index
int64 1
4.83k
| file_id
stringlengths 5
9
| content
stringlengths 167
16.5k
| repo
stringlengths 7
82
| path
stringlengths 8
164
| token_length
int64 72
4.23k
| original_comment
stringlengths 11
2.7k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 142
16.5k
| Inclusion
stringclasses 4
values | file-tokens-Qwen/Qwen2-7B
int64 64
3.93k
| comment-tokens-Qwen/Qwen2-7B
int64 4
972
| file-tokens-bigcode/starcoder2-7b
int64 74
3.98k
| comment-tokens-bigcode/starcoder2-7b
int64 4
959
| file-tokens-google/codegemma-7b
int64 56
3.99k
| comment-tokens-google/codegemma-7b
int64 3
953
| file-tokens-ibm-granite/granite-8b-code-base
int64 74
3.98k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 4
959
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 77
4.12k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 4
1.11k
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
963 | 17457_1 | package Week4.Opdracht11;
import java.io.File;
import java.io.FileWriter;
import java.util.*;
import java.io.FileNotFoundException;
import java.io.IOException;
//Het onderstaande tekstbestand bevat van een aantal artikelen de prijs in US Dollars.
// In de file staan de gegevens van één artikel op één regel. Op iedere regel staat een omschrijving van een artikel, dan een spatie, een dubbele punt, en weer een spatie, en dan de prijs van het artikel in dollars.
// Er moet nu een zelfde soort file worden gegenereerd maar dan met de prijs in euro's.
public class PrijsOmzetter {
private File bronBestand;
private File bestemmingBestand;
private double us_DollarWorthInEuro;
public String veranderDollarNaarEuro() {
List<String> txt = new ArrayList<>();
setBronBestand();
setBestemmingBestand();
setWaardeVanUSNaarEuro();
try {
Scanner reader = new Scanner(bronBestand);
while (reader.hasNextLine()) {
txt.add(reader.nextLine());
}
txt = dollarNaarEuro(txt);
try {
FileWriter writer = new FileWriter(bestemmingBestand);
for (int i = 0; i < txt.size(); i++) {
writer.write(txt.get(i)+"\n");
}
writer.close();
}catch (IOException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return("Geslaagd check: " + bestemmingBestand);
}
public List<String> dollarNaarEuro(List input){
String string = "";
String string2 = "";
ArrayList output = new ArrayList();
for (int i = 0; i < input.size(); i++) {
string = input.get(i).toString();
string = string.substring(string.indexOf(": "));
string = string.replaceAll("\\D+\\.?\\D+","");
//
double prijs = Double.parseDouble(string);
prijs = prijs * us_DollarWorthInEuro;
string =" "+"€"+String.format("%.2f", prijs);
//
string2 = input.get(i).toString();
int index = string2.indexOf(": ")+1;
string2 = string2.substring(0,index);
string2 += string;
output.add(string2);
}
return (output);
}
public void setBronBestand(){
Scanner st = new Scanner(System.in);
System.out.println("Enter bronbestand: ");
String in = "src/Week4/Opdracht11/"+st.nextLine();
File tempFile = new File(in);
if(tempFile.exists()){
this.bronBestand = new File(in);}
else{
System.out.println("Bestand niet gevonden. Probeer het opnieuw.");
setBronBestand();
}
}
public void setBestemmingBestand(){
Scanner st = new Scanner(System.in);
System.out.println("Enter bestemmingbestand: ");
String in = "src/Week4/Opdracht11/"+st.nextLine();
File tempFile = new File(in);
if(tempFile.exists()){
this.bestemmingBestand = new File(in);}
else{
System.out.println("Bestand niet gevonden. Probeer het opnieuw.");
setBestemmingBestand();}
}
public void setWaardeVanUSNaarEuro() {
Scanner st = new Scanner(System.in);
System.out.println("Enter waarde van 1 US dollar in Eurocent: ");
try {
this.us_DollarWorthInEuro = st.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Geen correcte waarde gevonden. Probeer het opnieuw.");
setWaardeVanUSNaarEuro();}
}}
| LegendWolf-Dev/OOP | src/Week4/Opdracht11/PrijsOmzetter.java | 1,119 | // In de file staan de gegevens van één artikel op één regel. Op iedere regel staat een omschrijving van een artikel, dan een spatie, een dubbele punt, en weer een spatie, en dan de prijs van het artikel in dollars. | line_comment | nl | package Week4.Opdracht11;
import java.io.File;
import java.io.FileWriter;
import java.util.*;
import java.io.FileNotFoundException;
import java.io.IOException;
//Het onderstaande tekstbestand bevat van een aantal artikelen de prijs in US Dollars.
// In de<SUF>
// Er moet nu een zelfde soort file worden gegenereerd maar dan met de prijs in euro's.
public class PrijsOmzetter {
private File bronBestand;
private File bestemmingBestand;
private double us_DollarWorthInEuro;
public String veranderDollarNaarEuro() {
List<String> txt = new ArrayList<>();
setBronBestand();
setBestemmingBestand();
setWaardeVanUSNaarEuro();
try {
Scanner reader = new Scanner(bronBestand);
while (reader.hasNextLine()) {
txt.add(reader.nextLine());
}
txt = dollarNaarEuro(txt);
try {
FileWriter writer = new FileWriter(bestemmingBestand);
for (int i = 0; i < txt.size(); i++) {
writer.write(txt.get(i)+"\n");
}
writer.close();
}catch (IOException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return("Geslaagd check: " + bestemmingBestand);
}
public List<String> dollarNaarEuro(List input){
String string = "";
String string2 = "";
ArrayList output = new ArrayList();
for (int i = 0; i < input.size(); i++) {
string = input.get(i).toString();
string = string.substring(string.indexOf(": "));
string = string.replaceAll("\\D+\\.?\\D+","");
//
double prijs = Double.parseDouble(string);
prijs = prijs * us_DollarWorthInEuro;
string =" "+"€"+String.format("%.2f", prijs);
//
string2 = input.get(i).toString();
int index = string2.indexOf(": ")+1;
string2 = string2.substring(0,index);
string2 += string;
output.add(string2);
}
return (output);
}
public void setBronBestand(){
Scanner st = new Scanner(System.in);
System.out.println("Enter bronbestand: ");
String in = "src/Week4/Opdracht11/"+st.nextLine();
File tempFile = new File(in);
if(tempFile.exists()){
this.bronBestand = new File(in);}
else{
System.out.println("Bestand niet gevonden. Probeer het opnieuw.");
setBronBestand();
}
}
public void setBestemmingBestand(){
Scanner st = new Scanner(System.in);
System.out.println("Enter bestemmingbestand: ");
String in = "src/Week4/Opdracht11/"+st.nextLine();
File tempFile = new File(in);
if(tempFile.exists()){
this.bestemmingBestand = new File(in);}
else{
System.out.println("Bestand niet gevonden. Probeer het opnieuw.");
setBestemmingBestand();}
}
public void setWaardeVanUSNaarEuro() {
Scanner st = new Scanner(System.in);
System.out.println("Enter waarde van 1 US dollar in Eurocent: ");
try {
this.us_DollarWorthInEuro = st.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Geen correcte waarde gevonden. Probeer het opnieuw.");
setWaardeVanUSNaarEuro();}
}}
| True | 864 | 62 | 1,001 | 71 | 983 | 52 | 1,001 | 71 | 1,118 | 67 | false | false | false | false | false | true |
3,930 | 19350_5 | package net.osmand.plus.configmap;
import android.animation.ValueAnimator;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import net.osmand.plus.R;
import net.osmand.plus.helpers.AndroidUiHelper;
import net.osmand.plus.utils.AndroidUtils;
import net.osmand.plus.utils.ColorUtilities;
import net.osmand.plus.widgets.ctxmenu.data.ContextMenuItem;
import java.util.HashMap;
import java.util.Map;
public class CategoryAnimator {
private static final Map<ContextMenuItem, ValueAnimator> runningAnimations = new HashMap<>();
private static final float MAX_ROTATION = 180;
private final Context ctx;
private final boolean isExpanding;
private final ContextMenuItem category;
private final View header;
private final ImageView ivIndicator;
private final TextView tvDescription;
private final View itemsContainer;
private final View divider;
// common parameters
private float descHeight;
private float minHeaderHeight;
private float maxHeaderHeight;
private int maxListHeight;
private int maxDuration;
private CategoryAnimator(@NonNull ContextMenuItem category, @NonNull View view, boolean isExpanding) {
this.category = category;
this.ctx = view.getContext();
this.isExpanding = isExpanding;
header = view.findViewById(R.id.button_container);
ivIndicator = view.findViewById(R.id.explicit_indicator);
tvDescription = view.findViewById(R.id.description);
itemsContainer = view.findViewById(R.id.items_container);
divider = view.findViewById(R.id.divider);
calculateCommonParameters();
}
private ValueAnimator startAnimation() {
onBeforeAnimation();
// Determine passed distance in current direction
float currentHeaderHeight = header.getHeight();
float wholeDistance = maxHeaderHeight - minHeaderHeight;
float leftDistance = isExpanding ? (currentHeaderHeight - minHeaderHeight) : (maxHeaderHeight - currentHeaderHeight);
float passedDistance = wholeDistance - leftDistance;
// Determine restrictions
int minValue = 0;
int maxValue = 100;
int startValue = (int) ((passedDistance / wholeDistance) * maxValue);
// Determine correct animation duration
int calculatedDuration = (int) ((float) maxDuration / maxValue * (maxValue - startValue));
int duration = Math.max(calculatedDuration, 0);
// Create animation
ValueAnimator animation = ValueAnimator.ofInt(startValue, maxValue);
animation.setDuration(duration);
animation.addUpdateListener(animator -> {
int val = (Integer) animator.getAnimatedValue();
onMainAnimationUpdate(val, minValue, maxValue);
if (val == maxValue) {
onMainAnimationFinished();
if (isExpanding) {
runningAnimations.remove(category);
} else {
onShowDescriptionAnimation(minValue, maxValue, duration);
}
}
});
animation.start();
return animation;
}
private void calculateCommonParameters() {
descHeight = getDimen(R.dimen.default_desc_line_height);
int titleHeight = getDimen(R.dimen.default_title_line_height);
int verticalMargin = getDimen(R.dimen.content_padding_small) * 2;
minHeaderHeight = titleHeight + verticalMargin - AndroidUtils.dpToPx(ctx, 3);
maxHeaderHeight = minHeaderHeight + descHeight;
itemsContainer.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
maxListHeight = itemsContainer.getMeasuredHeight();
maxDuration = getInteger(isExpanding ? android.R.integer.config_mediumAnimTime : android.R.integer.config_shortAnimTime);
}
private void onBeforeAnimation() {
// Make all views visible before animate them
tvDescription.setVisibility(View.VISIBLE);
itemsContainer.setVisibility(View.VISIBLE);
divider.setVisibility(View.VISIBLE);
// Description will be invisible until collapsing animation finished
boolean hasDescription = category.getDescription() != null;
tvDescription.setVisibility(hasDescription ? View.INVISIBLE : View.GONE);
}
private void onMainAnimationUpdate(int val, float minValue, float maxValue) {
// Set indicator rotation
float rotation = MAX_ROTATION / maxValue * val;
ivIndicator.setRotation(isExpanding ? -rotation : rotation);
// Set header height
float headerIncrement = descHeight / maxValue * val;
float headerHeight = isExpanding ? maxHeaderHeight - headerIncrement : minHeaderHeight + headerIncrement;
ViewGroup.LayoutParams layoutParams = header.getLayoutParams();
layoutParams.height = (int) headerHeight;
header.setLayoutParams(layoutParams);
// Set list alpha
float listAlpha = ColorUtilities.getProportionalAlpha(minValue, maxValue, val);
float listInverseAlpha = 1.0f - listAlpha;
itemsContainer.setAlpha(isExpanding ? listInverseAlpha : listAlpha);
// Set list height
float increment = (float) maxListHeight / maxValue * val;
float height = isExpanding ? increment : maxListHeight - increment;
ViewGroup.LayoutParams layoutParams1 = itemsContainer.getLayoutParams();
layoutParams1.height = (int) height;
itemsContainer.setLayoutParams(layoutParams1);
}
private void onMainAnimationFinished() {
// Set indicator icon and reset its rotation
int indicatorRes = isExpanding ? R.drawable.ic_action_arrow_up : R.drawable.ic_action_arrow_down;
ivIndicator.setRotation(0);
ivIndicator.setImageResource(indicatorRes);
boolean hasDescription = category.getDescription() != null;
// Update views visibility
AndroidUiHelper.updateVisibility(divider, isExpanding);
AndroidUiHelper.updateVisibility(tvDescription, !isExpanding && hasDescription);
AndroidUiHelper.updateVisibility(itemsContainer, isExpanding);
// Set items container height as WRAP_CONTENT
LayoutParams params = itemsContainer.getLayoutParams();
params.height = LayoutParams.WRAP_CONTENT;
itemsContainer.setLayoutParams(params);
}
private void onShowDescriptionAnimation(int minValue, int maxValue, int duration) {
ValueAnimator animator = ValueAnimator.ofInt(minValue, maxValue);
animator.setDuration(duration);
animator.addUpdateListener(animation -> {
int val = (Integer) animator.getAnimatedValue();
float alpha = ColorUtilities.getProportionalAlpha(minValue, maxValue, val);
tvDescription.setAlpha(1.0f - alpha);
if (maxValue == val) {
runningAnimations.remove(category);
}
});
animator.start();
}
private int getDimen(int id) {
return ctx.getResources().getDimensionPixelSize(id);
}
private int getInteger(int id) {
return ctx.getResources().getInteger(id);
}
public static void startCollapsing(@NonNull ContextMenuItem category, @NonNull View view) {
tryStartAnimation(category, view, false);
}
public static void startExpanding(@NonNull ContextMenuItem category, @NonNull View view) {
tryStartAnimation(category, view, true);
}
private static void tryStartAnimation(@NonNull ContextMenuItem category, @NonNull View view, boolean isExpanding) {
CategoryAnimator animator = new CategoryAnimator(category, view, isExpanding);
// Stop previous animation for the category
ValueAnimator runningAnimation = runningAnimations.remove(category);
if (runningAnimation != null && runningAnimation.isRunning()) {
runningAnimation.end();
}
// Create and run a new animation
runningAnimations.put(category, animator.startAnimation());
}
}
| osmandapp/OsmAnd | OsmAnd/src/net/osmand/plus/configmap/CategoryAnimator.java | 2,133 | // Set header height | line_comment | nl | package net.osmand.plus.configmap;
import android.animation.ValueAnimator;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import net.osmand.plus.R;
import net.osmand.plus.helpers.AndroidUiHelper;
import net.osmand.plus.utils.AndroidUtils;
import net.osmand.plus.utils.ColorUtilities;
import net.osmand.plus.widgets.ctxmenu.data.ContextMenuItem;
import java.util.HashMap;
import java.util.Map;
public class CategoryAnimator {
private static final Map<ContextMenuItem, ValueAnimator> runningAnimations = new HashMap<>();
private static final float MAX_ROTATION = 180;
private final Context ctx;
private final boolean isExpanding;
private final ContextMenuItem category;
private final View header;
private final ImageView ivIndicator;
private final TextView tvDescription;
private final View itemsContainer;
private final View divider;
// common parameters
private float descHeight;
private float minHeaderHeight;
private float maxHeaderHeight;
private int maxListHeight;
private int maxDuration;
private CategoryAnimator(@NonNull ContextMenuItem category, @NonNull View view, boolean isExpanding) {
this.category = category;
this.ctx = view.getContext();
this.isExpanding = isExpanding;
header = view.findViewById(R.id.button_container);
ivIndicator = view.findViewById(R.id.explicit_indicator);
tvDescription = view.findViewById(R.id.description);
itemsContainer = view.findViewById(R.id.items_container);
divider = view.findViewById(R.id.divider);
calculateCommonParameters();
}
private ValueAnimator startAnimation() {
onBeforeAnimation();
// Determine passed distance in current direction
float currentHeaderHeight = header.getHeight();
float wholeDistance = maxHeaderHeight - minHeaderHeight;
float leftDistance = isExpanding ? (currentHeaderHeight - minHeaderHeight) : (maxHeaderHeight - currentHeaderHeight);
float passedDistance = wholeDistance - leftDistance;
// Determine restrictions
int minValue = 0;
int maxValue = 100;
int startValue = (int) ((passedDistance / wholeDistance) * maxValue);
// Determine correct animation duration
int calculatedDuration = (int) ((float) maxDuration / maxValue * (maxValue - startValue));
int duration = Math.max(calculatedDuration, 0);
// Create animation
ValueAnimator animation = ValueAnimator.ofInt(startValue, maxValue);
animation.setDuration(duration);
animation.addUpdateListener(animator -> {
int val = (Integer) animator.getAnimatedValue();
onMainAnimationUpdate(val, minValue, maxValue);
if (val == maxValue) {
onMainAnimationFinished();
if (isExpanding) {
runningAnimations.remove(category);
} else {
onShowDescriptionAnimation(minValue, maxValue, duration);
}
}
});
animation.start();
return animation;
}
private void calculateCommonParameters() {
descHeight = getDimen(R.dimen.default_desc_line_height);
int titleHeight = getDimen(R.dimen.default_title_line_height);
int verticalMargin = getDimen(R.dimen.content_padding_small) * 2;
minHeaderHeight = titleHeight + verticalMargin - AndroidUtils.dpToPx(ctx, 3);
maxHeaderHeight = minHeaderHeight + descHeight;
itemsContainer.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
maxListHeight = itemsContainer.getMeasuredHeight();
maxDuration = getInteger(isExpanding ? android.R.integer.config_mediumAnimTime : android.R.integer.config_shortAnimTime);
}
private void onBeforeAnimation() {
// Make all views visible before animate them
tvDescription.setVisibility(View.VISIBLE);
itemsContainer.setVisibility(View.VISIBLE);
divider.setVisibility(View.VISIBLE);
// Description will be invisible until collapsing animation finished
boolean hasDescription = category.getDescription() != null;
tvDescription.setVisibility(hasDescription ? View.INVISIBLE : View.GONE);
}
private void onMainAnimationUpdate(int val, float minValue, float maxValue) {
// Set indicator rotation
float rotation = MAX_ROTATION / maxValue * val;
ivIndicator.setRotation(isExpanding ? -rotation : rotation);
// Set header<SUF>
float headerIncrement = descHeight / maxValue * val;
float headerHeight = isExpanding ? maxHeaderHeight - headerIncrement : minHeaderHeight + headerIncrement;
ViewGroup.LayoutParams layoutParams = header.getLayoutParams();
layoutParams.height = (int) headerHeight;
header.setLayoutParams(layoutParams);
// Set list alpha
float listAlpha = ColorUtilities.getProportionalAlpha(minValue, maxValue, val);
float listInverseAlpha = 1.0f - listAlpha;
itemsContainer.setAlpha(isExpanding ? listInverseAlpha : listAlpha);
// Set list height
float increment = (float) maxListHeight / maxValue * val;
float height = isExpanding ? increment : maxListHeight - increment;
ViewGroup.LayoutParams layoutParams1 = itemsContainer.getLayoutParams();
layoutParams1.height = (int) height;
itemsContainer.setLayoutParams(layoutParams1);
}
private void onMainAnimationFinished() {
// Set indicator icon and reset its rotation
int indicatorRes = isExpanding ? R.drawable.ic_action_arrow_up : R.drawable.ic_action_arrow_down;
ivIndicator.setRotation(0);
ivIndicator.setImageResource(indicatorRes);
boolean hasDescription = category.getDescription() != null;
// Update views visibility
AndroidUiHelper.updateVisibility(divider, isExpanding);
AndroidUiHelper.updateVisibility(tvDescription, !isExpanding && hasDescription);
AndroidUiHelper.updateVisibility(itemsContainer, isExpanding);
// Set items container height as WRAP_CONTENT
LayoutParams params = itemsContainer.getLayoutParams();
params.height = LayoutParams.WRAP_CONTENT;
itemsContainer.setLayoutParams(params);
}
private void onShowDescriptionAnimation(int minValue, int maxValue, int duration) {
ValueAnimator animator = ValueAnimator.ofInt(minValue, maxValue);
animator.setDuration(duration);
animator.addUpdateListener(animation -> {
int val = (Integer) animator.getAnimatedValue();
float alpha = ColorUtilities.getProportionalAlpha(minValue, maxValue, val);
tvDescription.setAlpha(1.0f - alpha);
if (maxValue == val) {
runningAnimations.remove(category);
}
});
animator.start();
}
private int getDimen(int id) {
return ctx.getResources().getDimensionPixelSize(id);
}
private int getInteger(int id) {
return ctx.getResources().getInteger(id);
}
public static void startCollapsing(@NonNull ContextMenuItem category, @NonNull View view) {
tryStartAnimation(category, view, false);
}
public static void startExpanding(@NonNull ContextMenuItem category, @NonNull View view) {
tryStartAnimation(category, view, true);
}
private static void tryStartAnimation(@NonNull ContextMenuItem category, @NonNull View view, boolean isExpanding) {
CategoryAnimator animator = new CategoryAnimator(category, view, isExpanding);
// Stop previous animation for the category
ValueAnimator runningAnimation = runningAnimations.remove(category);
if (runningAnimation != null && runningAnimation.isRunning()) {
runningAnimation.end();
}
// Create and run a new animation
runningAnimations.put(category, animator.startAnimation());
}
}
| False | 1,573 | 4 | 1,938 | 4 | 1,868 | 4 | 1,937 | 4 | 2,234 | 4 | false | false | false | false | false | true |
3,406 | 68315_2 | /*
* This file is part of verfluchter-android.
*
* verfluchter-android is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* verfluchter-android is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.xsolve.verfluchter.activities;
import android.app.ProgressDialog;
import android.content.*;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.common.base.Joiner;
import pl.xsolve.verfluchter.R;
import pl.xsolve.verfluchter.rest.RestResponse;
import pl.xsolve.verfluchter.services.WorkTimeNotifierService;
import pl.xsolve.verfluchter.tasks.ChangeWorkingStatusAsyncTask;
import pl.xsolve.verfluchter.tasks.ChangeWorkingStatusListener;
import pl.xsolve.verfluchter.tasks.RefreshDataAsyncTask;
import pl.xsolve.verfluchter.tasks.RefreshDataListener;
import pl.xsolve.verfluchter.tasks.general.CanDisplayErrorMessages;
import pl.xsolve.verfluchter.tasks.general.CanDisplayProgress;
import pl.xsolve.verfluchter.tools.*;
import roboguice.inject.InjectView;
import java.util.*;
import static pl.xsolve.verfluchter.tools.AutoSettings.USE_REMINDER_SERVICE_B;
import static pl.xsolve.verfluchter.tools.SoulTools.hasText;
import static pl.xsolve.verfluchter.tools.SoulTools.isTrue;
/**
* @author Konrad Ktoso Malawski
*/
public class VerfluchterActivity extends CommonViewActivity
implements RefreshDataListener, ChangeWorkingStatusListener,
CanDisplayErrorMessages, CanDisplayProgress {
//---------------------------- Fields ----------------------------------------------------------
// logger tag
private final static String TAG = VerfluchterActivity.class.getSimpleName();
// UI components
@InjectView(R.id.start_work_button)
Button startWorkButton;
@InjectView(R.id.stop_work_button)
Button stopWorkButton;
@InjectView(R.id.refresh_button)
ImageButton refreshButton;
@InjectView(R.id.hours_stats_textview)
TextView hoursStatsTextView;
@InjectView(R.id.work_time_today)
TextView workTimeToday;
@InjectView(R.id.work_time_today_label)
TextView workTimeTodayLabel;
@InjectView(R.id.currently_working_textview)
TextView currentlyWorking;
// other UI components (dialogs etc)
ProgressDialog progressDialog;
private Timer workTimeUpdaterTimer = new Timer();
// Global Broadcast Receiver
BroadcastReceiver broadcastReceiver;
// Need handler for callbacks to the UI thread
// http://developer.android.com/guide/appendix/faq/commontasks.html#threading
final Handler handler = new Handler();
List<String> dziennie = new LinkedList<String>();
List<String> tygodniowo = new LinkedList<String>();
List<String> miesiecznie = new LinkedList<String>();
static AutoSettings settingsForTasksReference;
//------------------------ Basic cache ----------------------------
// Loaded work hours data
static Date updatedAt;
// cache for our last fetched response
static String cachedPlainTextResponse;
//when did I click the start work button?
static HourMin workStartedAt = null;
//this pair represents the hours and mins worked today
static HourMin workHourMin = new HourMin(0, 0);
// am I currently working?
static boolean amICurrentlyWorking = false;
//---------------------------- Methods ---------------------------------------------------------
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settingsForTasksReference = autoSettings;
setContentView(R.layout.main);
// goto settings if it seems that the setup is incorrect etc...
if (!hasText(getSetting(AutoSettings.BASIC_AUTH_PASS_S, String.class))) {
startActivityForResult(new Intent(this, SettingsActivity.class), 0);
return;
}
initListeners();
if (isTrue(getSetting(USE_REMINDER_SERVICE_B, Boolean.class))) {
stopService(new Intent(this, WorkTimeNotifierService.class));
startService(new Intent(this, WorkTimeNotifierService.class));
}
if (updatedAt == null) {
new RefreshDataAsyncTask(this).execute();
} else if (cachedPlainTextResponse != null) {
updateWorkedToday(workHourMin);
setAmICurrentlyWorking(amICurrentlyWorking);
updateWorkedHoursStats(cachedPlainTextResponse);
}
restartWorkTimeUpdater();
}
/**
* Initialize all button listeners
*/
private void initListeners() {
// our global intent listener
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WorkTimeNotifierService.INTENT_HEY_STOP_WORKING.equals(action)) {
Log.d(TAG, "Received " + WorkTimeNotifierService.INTENT_HEY_STOP_WORKING);
showToast(getString(R.string.hey_stop_working_title));
}
// else if (RefreshService.INTENT_FRESH_DATA.equals(action)) {
// Log.d(TAG, "Received " + RefreshService.INTENT_FRESH_DATA);
// updateWorkedHoursStats(intent.getStringExtra("cachedPlainTextResponse"));
// }
}
};
// important global intent filter registration!
IntentFilter filter = new IntentFilter(WorkTimeNotifierService.INTENT_HEY_STOP_WORKING);
filter.addAction(WorkTimeNotifierService.INTENT_HEY_STOP_WORKING);
registerReceiver(broadcastReceiver, filter);
final VerfluchterActivity self = VerfluchterActivity.this;
refreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new RefreshDataAsyncTask(self).execute();
}
});
startWorkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new ChangeWorkingStatusAsyncTask(self, true).execute();
}
});
stopWorkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new ChangeWorkingStatusAsyncTask(self, false).execute();
}
});
}
private void setAmICurrentlyWorking(String plainTextResponse) {
if (plainTextResponse.contains("Rozpocznij")) {
setAmICurrentlyWorking(false);
} else if (plainTextResponse.contains("Zakończ")) {
setAmICurrentlyWorking(true);
}
}
private void setAmICurrentlyWorking(boolean amIWorking) {
amICurrentlyWorking = amIWorking;
String text = amIWorking ? getString(R.string.am_i_working_yes) : getString(R.string.am_i_working_no);
currentlyWorking.setText(text);
}
private void updateWorkedHoursStats(String plainTextResponse) {
boolean byloDziennie = false, byloTygodniowo = false, byloMiesiecznie = false;
// cache the response
updatedAt = new Date();
cachedPlainTextResponse = plainTextResponse;
// so we dont get into each others way
workTimeUpdaterTimer.cancel();
dziennie.clear();
tygodniowo.clear();
miesiecznie.clear();
for (String line : plainTextResponse.split("\n")) {
if (line.trim().equals("")) {
continue;
}
if (!byloDziennie) {
if (line.contains("Dziennie")) {
byloDziennie = true;
}
continue;
}
if (line.contains("Tygodniowo")) {
byloTygodniowo = true;
continue;
}
if (line.contains("Miesiecznie")) {
byloMiesiecznie = true;
continue;
}
if (!byloTygodniowo && !byloMiesiecznie) {
String[] strings = line.split(" ");
updateWorkedToday(SoulTools.convertTimeStringToHourMin(strings[1]));
strings[0] = strings[0].replaceAll(":", "");
dziennie.add(new StringBuilder(strings[0]).append(" ")
.append(SoulTools.getDisplayDay(strings[0]))
.append(": ")
.append(new HourMin(strings[1]).pretty())
.toString());
} else if (!byloMiesiecznie) {
tygodniowo.add(line);
} else {
if (!line.contains("Mantis")) {
miesiecznie.add(line);
} else {
break;
}
}
}
Collections.reverse(dziennie);
Collections.reverse(tygodniowo);
Collections.reverse(miesiecznie);
// update the "worked today|yesterday" stuff
String newestEntry = dziennie.get(0);
if (newestEntry.contains(SoulTools.getTodayDateString())) {
workTimeTodayLabel.setText(R.string.workedTodayLabel);
restartWorkTimeUpdater();
} else if (newestEntry.contains(SoulTools.getYesterdayString())) {
workTimeTodayLabel.setText(R.string.workedYesterdayLabel);
restartWorkTimeUpdater();
} else {
workTimeTodayLabel.setText(R.string.workedLastTimeLabel);
restartWorkTimeUpdater();
}
// update the long stats view
// todo make this better
hoursStatsTextView.setText(
getString(R.string.dailyHoursLabel) + "\n" + Joiner.on("\n").join(dziennie) + "\n\n"
+ getString(R.string.weeklyHoursLabel) + "\n" + Joiner.on("\n").join(tygodniowo) + "\n\n"
+ getString(R.string.monthlyHoursLabel) + "\n" + Joiner.on("\n").join(miesiecznie));
}
private void restartWorkTimeUpdater() {
workTimeUpdaterTimer.cancel();
workTimeUpdaterTimer = new Timer();
workTimeUpdaterTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// stop adding time if you've stopped working
if (!amICurrentlyWorking) {
this.cancel();
return;
}
handler.post(addOneMinuteWorkedTimeRunnable);
}
}, Constants.MINUTE, Constants.MINUTE);
}
private synchronized void updateWorkedToday(HourMin hourAndMin) {
workHourMin = hourAndMin;
workTimeToday.setText(hourAndMin.pretty());
}
public static AutoSettings getAutoSettings() {
return settingsForTasksReference;
}
public static boolean isCurrentlyWorking() {
return amICurrentlyWorking;
}
@Override
protected void onDestroy() {
super.onDestroy();
workTimeUpdaterTimer.cancel();
}
//--------------------------- Async Task handling ---------------------------------------------
@Override
public void afterRefreshData(final RestResponse restResponse) {
handler.post(new Runnable() {
public void run() {
progressDialog = ProgressDialog.show(VerfluchterActivity.this,
"",
"Trwa przetważanie odpowiedzi serwera. Jeszcze tylko chwilkę.",
true);
String responseMessage = restResponse.getResponse();
setAmICurrentlyWorking(responseMessage);
String plainTextResponse = Html.fromHtml(responseMessage).toString();
if (plainTextResponse != null) {
updateWorkedHoursStats(plainTextResponse);
}
progressDialog.dismiss();
}
});
}
@Override
public void afterChangeWorkingStatus(final RestResponse restResponse) {
handler.post(new Runnable() {
public void run() {
progressDialog = ProgressDialog.show(VerfluchterActivity.this,
"",
"Trwa przetwarzanie odpowiedi serwera. Jeszcze tylko momencik.",
true);
String responseMessage = restResponse.getResponse();
setAmICurrentlyWorking(responseMessage);
String plainTextResponse = Html.fromHtml(responseMessage).toString();
if (plainTextResponse != null) {
updateWorkedHoursStats(plainTextResponse);
}
progressDialog.dismiss();
}
});
}
/**
* This Runnable will be launched using handler.post()
* which returns us into the UI Thread and allows us to update the UI right away,
* even thought the initial call came from inside of an Timer instance.
*/
final Runnable addOneMinuteWorkedTimeRunnable = new Runnable() {
@Override
public void run() {
// if called using an handler => back in the UI Thread :-)
updateWorkedToday(workHourMin.addMin(1));
}
};
//---------------------------- Interface implementations ---------------------------------------
@Override
public void showProgressDialog(final String title, final String message, final boolean indeterminate) {
handler.post(new Runnable() {
public void run() {
progressDialog = ProgressDialog.show(VerfluchterActivity.this, title, message, indeterminate, true);
}
});
}
@Override
public void showProgressDialog(final String title, final String message, final boolean indeterminate, final boolean cancelable, final DialogInterface.OnCancelListener cancelListener) {
handler.post(new Runnable() {
public void run() {
progressDialog = ProgressDialog.show(VerfluchterActivity.this, title, message, indeterminate, cancelable, cancelListener);
}
});
}
@Override
public void hideProgressDialog() {
handler.post(new Runnable() {
public void run() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
});
}
@Override
public void showErrorMessage(final String error) {
handler.post(new Runnable() {
@Override
public void run() {
showToast(error, Toast.LENGTH_LONG);
}
});
}
} | ktoso/verfluchter-android | src/pl/xsolve/verfluchter/activities/VerfluchterActivity.java | 4,231 | //---------------------------- Fields ---------------------------------------------------------- | line_comment | nl | /*
* This file is part of verfluchter-android.
*
* verfluchter-android is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* verfluchter-android is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.xsolve.verfluchter.activities;
import android.app.ProgressDialog;
import android.content.*;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.common.base.Joiner;
import pl.xsolve.verfluchter.R;
import pl.xsolve.verfluchter.rest.RestResponse;
import pl.xsolve.verfluchter.services.WorkTimeNotifierService;
import pl.xsolve.verfluchter.tasks.ChangeWorkingStatusAsyncTask;
import pl.xsolve.verfluchter.tasks.ChangeWorkingStatusListener;
import pl.xsolve.verfluchter.tasks.RefreshDataAsyncTask;
import pl.xsolve.verfluchter.tasks.RefreshDataListener;
import pl.xsolve.verfluchter.tasks.general.CanDisplayErrorMessages;
import pl.xsolve.verfluchter.tasks.general.CanDisplayProgress;
import pl.xsolve.verfluchter.tools.*;
import roboguice.inject.InjectView;
import java.util.*;
import static pl.xsolve.verfluchter.tools.AutoSettings.USE_REMINDER_SERVICE_B;
import static pl.xsolve.verfluchter.tools.SoulTools.hasText;
import static pl.xsolve.verfluchter.tools.SoulTools.isTrue;
/**
* @author Konrad Ktoso Malawski
*/
public class VerfluchterActivity extends CommonViewActivity
implements RefreshDataListener, ChangeWorkingStatusListener,
CanDisplayErrorMessages, CanDisplayProgress {
//---------------------------- Fields<SUF>
// logger tag
private final static String TAG = VerfluchterActivity.class.getSimpleName();
// UI components
@InjectView(R.id.start_work_button)
Button startWorkButton;
@InjectView(R.id.stop_work_button)
Button stopWorkButton;
@InjectView(R.id.refresh_button)
ImageButton refreshButton;
@InjectView(R.id.hours_stats_textview)
TextView hoursStatsTextView;
@InjectView(R.id.work_time_today)
TextView workTimeToday;
@InjectView(R.id.work_time_today_label)
TextView workTimeTodayLabel;
@InjectView(R.id.currently_working_textview)
TextView currentlyWorking;
// other UI components (dialogs etc)
ProgressDialog progressDialog;
private Timer workTimeUpdaterTimer = new Timer();
// Global Broadcast Receiver
BroadcastReceiver broadcastReceiver;
// Need handler for callbacks to the UI thread
// http://developer.android.com/guide/appendix/faq/commontasks.html#threading
final Handler handler = new Handler();
List<String> dziennie = new LinkedList<String>();
List<String> tygodniowo = new LinkedList<String>();
List<String> miesiecznie = new LinkedList<String>();
static AutoSettings settingsForTasksReference;
//------------------------ Basic cache ----------------------------
// Loaded work hours data
static Date updatedAt;
// cache for our last fetched response
static String cachedPlainTextResponse;
//when did I click the start work button?
static HourMin workStartedAt = null;
//this pair represents the hours and mins worked today
static HourMin workHourMin = new HourMin(0, 0);
// am I currently working?
static boolean amICurrentlyWorking = false;
//---------------------------- Methods ---------------------------------------------------------
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settingsForTasksReference = autoSettings;
setContentView(R.layout.main);
// goto settings if it seems that the setup is incorrect etc...
if (!hasText(getSetting(AutoSettings.BASIC_AUTH_PASS_S, String.class))) {
startActivityForResult(new Intent(this, SettingsActivity.class), 0);
return;
}
initListeners();
if (isTrue(getSetting(USE_REMINDER_SERVICE_B, Boolean.class))) {
stopService(new Intent(this, WorkTimeNotifierService.class));
startService(new Intent(this, WorkTimeNotifierService.class));
}
if (updatedAt == null) {
new RefreshDataAsyncTask(this).execute();
} else if (cachedPlainTextResponse != null) {
updateWorkedToday(workHourMin);
setAmICurrentlyWorking(amICurrentlyWorking);
updateWorkedHoursStats(cachedPlainTextResponse);
}
restartWorkTimeUpdater();
}
/**
* Initialize all button listeners
*/
private void initListeners() {
// our global intent listener
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WorkTimeNotifierService.INTENT_HEY_STOP_WORKING.equals(action)) {
Log.d(TAG, "Received " + WorkTimeNotifierService.INTENT_HEY_STOP_WORKING);
showToast(getString(R.string.hey_stop_working_title));
}
// else if (RefreshService.INTENT_FRESH_DATA.equals(action)) {
// Log.d(TAG, "Received " + RefreshService.INTENT_FRESH_DATA);
// updateWorkedHoursStats(intent.getStringExtra("cachedPlainTextResponse"));
// }
}
};
// important global intent filter registration!
IntentFilter filter = new IntentFilter(WorkTimeNotifierService.INTENT_HEY_STOP_WORKING);
filter.addAction(WorkTimeNotifierService.INTENT_HEY_STOP_WORKING);
registerReceiver(broadcastReceiver, filter);
final VerfluchterActivity self = VerfluchterActivity.this;
refreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new RefreshDataAsyncTask(self).execute();
}
});
startWorkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new ChangeWorkingStatusAsyncTask(self, true).execute();
}
});
stopWorkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new ChangeWorkingStatusAsyncTask(self, false).execute();
}
});
}
private void setAmICurrentlyWorking(String plainTextResponse) {
if (plainTextResponse.contains("Rozpocznij")) {
setAmICurrentlyWorking(false);
} else if (plainTextResponse.contains("Zakończ")) {
setAmICurrentlyWorking(true);
}
}
private void setAmICurrentlyWorking(boolean amIWorking) {
amICurrentlyWorking = amIWorking;
String text = amIWorking ? getString(R.string.am_i_working_yes) : getString(R.string.am_i_working_no);
currentlyWorking.setText(text);
}
private void updateWorkedHoursStats(String plainTextResponse) {
boolean byloDziennie = false, byloTygodniowo = false, byloMiesiecznie = false;
// cache the response
updatedAt = new Date();
cachedPlainTextResponse = plainTextResponse;
// so we dont get into each others way
workTimeUpdaterTimer.cancel();
dziennie.clear();
tygodniowo.clear();
miesiecznie.clear();
for (String line : plainTextResponse.split("\n")) {
if (line.trim().equals("")) {
continue;
}
if (!byloDziennie) {
if (line.contains("Dziennie")) {
byloDziennie = true;
}
continue;
}
if (line.contains("Tygodniowo")) {
byloTygodniowo = true;
continue;
}
if (line.contains("Miesiecznie")) {
byloMiesiecznie = true;
continue;
}
if (!byloTygodniowo && !byloMiesiecznie) {
String[] strings = line.split(" ");
updateWorkedToday(SoulTools.convertTimeStringToHourMin(strings[1]));
strings[0] = strings[0].replaceAll(":", "");
dziennie.add(new StringBuilder(strings[0]).append(" ")
.append(SoulTools.getDisplayDay(strings[0]))
.append(": ")
.append(new HourMin(strings[1]).pretty())
.toString());
} else if (!byloMiesiecznie) {
tygodniowo.add(line);
} else {
if (!line.contains("Mantis")) {
miesiecznie.add(line);
} else {
break;
}
}
}
Collections.reverse(dziennie);
Collections.reverse(tygodniowo);
Collections.reverse(miesiecznie);
// update the "worked today|yesterday" stuff
String newestEntry = dziennie.get(0);
if (newestEntry.contains(SoulTools.getTodayDateString())) {
workTimeTodayLabel.setText(R.string.workedTodayLabel);
restartWorkTimeUpdater();
} else if (newestEntry.contains(SoulTools.getYesterdayString())) {
workTimeTodayLabel.setText(R.string.workedYesterdayLabel);
restartWorkTimeUpdater();
} else {
workTimeTodayLabel.setText(R.string.workedLastTimeLabel);
restartWorkTimeUpdater();
}
// update the long stats view
// todo make this better
hoursStatsTextView.setText(
getString(R.string.dailyHoursLabel) + "\n" + Joiner.on("\n").join(dziennie) + "\n\n"
+ getString(R.string.weeklyHoursLabel) + "\n" + Joiner.on("\n").join(tygodniowo) + "\n\n"
+ getString(R.string.monthlyHoursLabel) + "\n" + Joiner.on("\n").join(miesiecznie));
}
private void restartWorkTimeUpdater() {
workTimeUpdaterTimer.cancel();
workTimeUpdaterTimer = new Timer();
workTimeUpdaterTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// stop adding time if you've stopped working
if (!amICurrentlyWorking) {
this.cancel();
return;
}
handler.post(addOneMinuteWorkedTimeRunnable);
}
}, Constants.MINUTE, Constants.MINUTE);
}
private synchronized void updateWorkedToday(HourMin hourAndMin) {
workHourMin = hourAndMin;
workTimeToday.setText(hourAndMin.pretty());
}
public static AutoSettings getAutoSettings() {
return settingsForTasksReference;
}
public static boolean isCurrentlyWorking() {
return amICurrentlyWorking;
}
@Override
protected void onDestroy() {
super.onDestroy();
workTimeUpdaterTimer.cancel();
}
//--------------------------- Async Task handling ---------------------------------------------
@Override
public void afterRefreshData(final RestResponse restResponse) {
handler.post(new Runnable() {
public void run() {
progressDialog = ProgressDialog.show(VerfluchterActivity.this,
"",
"Trwa przetważanie odpowiedzi serwera. Jeszcze tylko chwilkę.",
true);
String responseMessage = restResponse.getResponse();
setAmICurrentlyWorking(responseMessage);
String plainTextResponse = Html.fromHtml(responseMessage).toString();
if (plainTextResponse != null) {
updateWorkedHoursStats(plainTextResponse);
}
progressDialog.dismiss();
}
});
}
@Override
public void afterChangeWorkingStatus(final RestResponse restResponse) {
handler.post(new Runnable() {
public void run() {
progressDialog = ProgressDialog.show(VerfluchterActivity.this,
"",
"Trwa przetwarzanie odpowiedi serwera. Jeszcze tylko momencik.",
true);
String responseMessage = restResponse.getResponse();
setAmICurrentlyWorking(responseMessage);
String plainTextResponse = Html.fromHtml(responseMessage).toString();
if (plainTextResponse != null) {
updateWorkedHoursStats(plainTextResponse);
}
progressDialog.dismiss();
}
});
}
/**
* This Runnable will be launched using handler.post()
* which returns us into the UI Thread and allows us to update the UI right away,
* even thought the initial call came from inside of an Timer instance.
*/
final Runnable addOneMinuteWorkedTimeRunnable = new Runnable() {
@Override
public void run() {
// if called using an handler => back in the UI Thread :-)
updateWorkedToday(workHourMin.addMin(1));
}
};
//---------------------------- Interface implementations ---------------------------------------
@Override
public void showProgressDialog(final String title, final String message, final boolean indeterminate) {
handler.post(new Runnable() {
public void run() {
progressDialog = ProgressDialog.show(VerfluchterActivity.this, title, message, indeterminate, true);
}
});
}
@Override
public void showProgressDialog(final String title, final String message, final boolean indeterminate, final boolean cancelable, final DialogInterface.OnCancelListener cancelListener) {
handler.post(new Runnable() {
public void run() {
progressDialog = ProgressDialog.show(VerfluchterActivity.this, title, message, indeterminate, cancelable, cancelListener);
}
});
}
@Override
public void hideProgressDialog() {
handler.post(new Runnable() {
public void run() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
});
}
@Override
public void showErrorMessage(final String error) {
handler.post(new Runnable() {
@Override
public void run() {
showToast(error, Toast.LENGTH_LONG);
}
});
}
} | False | 2,990 | 5 | 3,451 | 6 | 3,597 | 9 | 3,451 | 6 | 4,114 | 11 | false | false | false | false | false | true |
435 | 23563_1 | // Toelichting:
// Het aantal plaatsen en aantal rijen is public static want ik wil die attributen in de tests gebruiken. Ik ga ervan uit dat de aantallen vast blijven, maar mocht ze dan toch gewijzigd worden in de toekomst dan kloppen de tests nog.
package theater;
import java.util.ArrayList;
public class Theater {
public final static int AANTALTRIJEN = 15;
public final static int AANTALPERRIJ = 10;
private int hoogsteKlantnummer = 0;
private String naam;
private ArrayList<Klant> klanten = new ArrayList<>();
private Voorstelling voorstelling;
/**
* Constructor functie voor Theater.
*
* @param naam neemt alleen een naam als parameter
*/
public Theater(String naam) {
this.naam = naam;
}
private Klant zoekKlant(String naam, String telefoon) {
Klant klant = null;
for (Klant k : klanten) {
if (telefoon.equals(k.getTelefoon()) && naam.trim().toLowerCase().equals(k.getNaam().trim().toLowerCase())) {
klant = k;
break;
}
}
return klant;
}
/**
* Maakt een nieuwe voorstelling aan.
* Nu is er nog maar ruimte voor 1 voorstelling.
*
* @param naam naam van de voorstelling
* @param datum datum dat deze plaatsvindt
*/
public void nieuweVoorstelling(String naam, String datum) {
voorstelling = new Voorstelling(naam, datum);
}
/**
* Voegt een nieuwe klant toe aan de ArrayList van klanten van het theater, mits deze nog niet is toegevoegd.
*
* @param naam naam van de klant
* @param telefoon telefoonnummer van de klant
*/
public void nieuweKlant(String naam, String telefoon) {
if (zoekKlant(naam, telefoon) == null) {
klanten.add(new Klant(naam, hoogsteKlantnummer + 1, telefoon));
hoogsteKlantnummer++;
}
}
/**
* Reserveert een plaats voor een klant.
* Een gereserveerde plaats kan weer vrijgemaakt worden.
*
* @param rij nummer van de rij
* @param stoel nummer van de stoel
*/
public void reserveren(int rij, int stoel) {
if (voorstelling != null) {
voorstelling.reserveer(rij, stoel);
}
}
/**
* Als een klant plaatsen heeft gereserveerd kan deze worden geplaatst, waarna ze op bezet komen te staan.
* Dit kan niet meer gewijzigd worden.
*
* @param naam naam van de klant
* @param telefoon telefoonnummer van de klant
*/
public void plaatsen(String naam, String telefoon) {
Klant klant = zoekKlant(naam, telefoon);
if (voorstelling != null && klant != null) {
voorstelling.plaatsKlant(klant);
}
}
/**
* Als de klant uiteindelijk niet geplaatst wordt, moeten alle reserveringen weer reset worden.
*/
public void resetten() {
if (voorstelling != null) {
voorstelling.resetAlleReserveringen();
}
}
/**
* Geeft het aantal plaatsen van een bepaalde status terug.
*
* @param status geef de status mee die je zoekt
* @return geeft het aantal plaatsen met deze status terug
*/
public int getAantalPlaatsen(Plaats.Status status) {
int aantal = 0;
if (voorstelling != null) {
aantal = voorstelling.getPlaatsenStatus(status);
}
return aantal;
}
}
| DreamEmulator/ou_java | object_oriented_programming/opdracht_4/src/theater/Theater.java | 1,041 | /**
* Constructor functie voor Theater.
*
* @param naam neemt alleen een naam als parameter
*/ | block_comment | nl | // Toelichting:
// Het aantal plaatsen en aantal rijen is public static want ik wil die attributen in de tests gebruiken. Ik ga ervan uit dat de aantallen vast blijven, maar mocht ze dan toch gewijzigd worden in de toekomst dan kloppen de tests nog.
package theater;
import java.util.ArrayList;
public class Theater {
public final static int AANTALTRIJEN = 15;
public final static int AANTALPERRIJ = 10;
private int hoogsteKlantnummer = 0;
private String naam;
private ArrayList<Klant> klanten = new ArrayList<>();
private Voorstelling voorstelling;
/**
* Constructor functie voor<SUF>*/
public Theater(String naam) {
this.naam = naam;
}
private Klant zoekKlant(String naam, String telefoon) {
Klant klant = null;
for (Klant k : klanten) {
if (telefoon.equals(k.getTelefoon()) && naam.trim().toLowerCase().equals(k.getNaam().trim().toLowerCase())) {
klant = k;
break;
}
}
return klant;
}
/**
* Maakt een nieuwe voorstelling aan.
* Nu is er nog maar ruimte voor 1 voorstelling.
*
* @param naam naam van de voorstelling
* @param datum datum dat deze plaatsvindt
*/
public void nieuweVoorstelling(String naam, String datum) {
voorstelling = new Voorstelling(naam, datum);
}
/**
* Voegt een nieuwe klant toe aan de ArrayList van klanten van het theater, mits deze nog niet is toegevoegd.
*
* @param naam naam van de klant
* @param telefoon telefoonnummer van de klant
*/
public void nieuweKlant(String naam, String telefoon) {
if (zoekKlant(naam, telefoon) == null) {
klanten.add(new Klant(naam, hoogsteKlantnummer + 1, telefoon));
hoogsteKlantnummer++;
}
}
/**
* Reserveert een plaats voor een klant.
* Een gereserveerde plaats kan weer vrijgemaakt worden.
*
* @param rij nummer van de rij
* @param stoel nummer van de stoel
*/
public void reserveren(int rij, int stoel) {
if (voorstelling != null) {
voorstelling.reserveer(rij, stoel);
}
}
/**
* Als een klant plaatsen heeft gereserveerd kan deze worden geplaatst, waarna ze op bezet komen te staan.
* Dit kan niet meer gewijzigd worden.
*
* @param naam naam van de klant
* @param telefoon telefoonnummer van de klant
*/
public void plaatsen(String naam, String telefoon) {
Klant klant = zoekKlant(naam, telefoon);
if (voorstelling != null && klant != null) {
voorstelling.plaatsKlant(klant);
}
}
/**
* Als de klant uiteindelijk niet geplaatst wordt, moeten alle reserveringen weer reset worden.
*/
public void resetten() {
if (voorstelling != null) {
voorstelling.resetAlleReserveringen();
}
}
/**
* Geeft het aantal plaatsen van een bepaalde status terug.
*
* @param status geef de status mee die je zoekt
* @return geeft het aantal plaatsen met deze status terug
*/
public int getAantalPlaatsen(Plaats.Status status) {
int aantal = 0;
if (voorstelling != null) {
aantal = voorstelling.getPlaatsenStatus(status);
}
return aantal;
}
}
| True | 914 | 27 | 1,039 | 30 | 927 | 27 | 1,039 | 30 | 1,063 | 33 | false | false | false | false | false | true |
255 | 9244_10 | package org.bukkit;
import java.util.Map;
import com.google.common.collect.Maps;
import org.bukkit.block.BlockFace;
import org.bukkit.potion.Potion;
/**
* A list of effects that the server is able to send to players.
*/
public enum Effect {
/**
* An alternate click sound.
*/
CLICK2(1000, Type.SOUND),
/**
* A click sound.
*/
CLICK1(1001, Type.SOUND),
/**
* Sound of a bow firing.
*/
BOW_FIRE(1002, Type.SOUND),
/**
* Sound of a door opening/closing.
*/
DOOR_TOGGLE(1003, Type.SOUND),
/**
* Sound of fire being extinguished.
*/
EXTINGUISH(1004, Type.SOUND),
/**
* A song from a record. Needs the record item ID as additional info
*/
RECORD_PLAY(1005, Type.SOUND, Material.class),
/**
* Sound of ghast shrieking.
*/
GHAST_SHRIEK(1007, Type.SOUND),
/**
* Sound of ghast firing.
*/
GHAST_SHOOT(1008, Type.SOUND),
/**
* Sound of blaze firing.
*/
BLAZE_SHOOT(1009, Type.SOUND),
/**
* Sound of zombies chewing on wooden doors.
*/
ZOMBIE_CHEW_WOODEN_DOOR(1010, Type.SOUND),
/**
* Sound of zombies chewing on iron doors.
*/
ZOMBIE_CHEW_IRON_DOOR(1011, Type.SOUND),
/**
* Sound of zombies destroying a door.
*/
ZOMBIE_DESTROY_DOOR(1012, Type.SOUND),
/**
* A visual smoke effect. Needs direction as additional info.
*/
SMOKE(2000, Type.VISUAL, BlockFace.class),
/**
* Sound of a block breaking. Needs block ID as additional info.
*/
STEP_SOUND(2001, Type.SOUND, Material.class),
/**
* Visual effect of a splash potion breaking. Needs potion data value as
* additional info.
*/
POTION_BREAK(2002, Type.VISUAL, Potion.class),
/**
* An ender eye signal; a visual effect.
*/
ENDER_SIGNAL(2003, Type.VISUAL),
/**
* The flames seen on a mobspawner; a visual effect.
*/
MOBSPAWNER_FLAMES(2004, Type.VISUAL);
private final int id;
private final Type type;
private final Class<?> data;
private static final Map<Integer, Effect> BY_ID = Maps.newHashMap();
Effect(int id, Type type) {
this(id,type,null);
}
Effect(int id, Type type, Class<?> data) {
this.id = id;
this.type = type;
this.data = data;
}
/**
* Gets the ID for this effect.
*
* @return ID of this effect
* @deprecated Magic value
*/
@Deprecated
public int getId() {
return this.id;
}
/**
* @return The type of the effect.
*/
public Type getType() {
return this.type;
}
/**
* @return The class which represents data for this effect, or null if
* none
*/
public Class<?> getData() {
return this.data;
}
/**
* Gets the Effect associated with the given ID.
*
* @param id ID of the Effect to return
* @return Effect with the given ID
* @deprecated Magic value
*/
@Deprecated
public static Effect getById(int id) {
return BY_ID.get(id);
}
static {
for (Effect effect : values()) {
BY_ID.put(effect.id, effect);
}
}
/**
* Represents the type of an effect.
*/
public enum Type {SOUND, VISUAL}
}
| Bukkit/Bukkit | src/main/java/org/bukkit/Effect.java | 1,138 | /**
* Sound of zombies chewing on wooden doors.
*/ | block_comment | nl | package org.bukkit;
import java.util.Map;
import com.google.common.collect.Maps;
import org.bukkit.block.BlockFace;
import org.bukkit.potion.Potion;
/**
* A list of effects that the server is able to send to players.
*/
public enum Effect {
/**
* An alternate click sound.
*/
CLICK2(1000, Type.SOUND),
/**
* A click sound.
*/
CLICK1(1001, Type.SOUND),
/**
* Sound of a bow firing.
*/
BOW_FIRE(1002, Type.SOUND),
/**
* Sound of a door opening/closing.
*/
DOOR_TOGGLE(1003, Type.SOUND),
/**
* Sound of fire being extinguished.
*/
EXTINGUISH(1004, Type.SOUND),
/**
* A song from a record. Needs the record item ID as additional info
*/
RECORD_PLAY(1005, Type.SOUND, Material.class),
/**
* Sound of ghast shrieking.
*/
GHAST_SHRIEK(1007, Type.SOUND),
/**
* Sound of ghast firing.
*/
GHAST_SHOOT(1008, Type.SOUND),
/**
* Sound of blaze firing.
*/
BLAZE_SHOOT(1009, Type.SOUND),
/**
* Sound of zombies<SUF>*/
ZOMBIE_CHEW_WOODEN_DOOR(1010, Type.SOUND),
/**
* Sound of zombies chewing on iron doors.
*/
ZOMBIE_CHEW_IRON_DOOR(1011, Type.SOUND),
/**
* Sound of zombies destroying a door.
*/
ZOMBIE_DESTROY_DOOR(1012, Type.SOUND),
/**
* A visual smoke effect. Needs direction as additional info.
*/
SMOKE(2000, Type.VISUAL, BlockFace.class),
/**
* Sound of a block breaking. Needs block ID as additional info.
*/
STEP_SOUND(2001, Type.SOUND, Material.class),
/**
* Visual effect of a splash potion breaking. Needs potion data value as
* additional info.
*/
POTION_BREAK(2002, Type.VISUAL, Potion.class),
/**
* An ender eye signal; a visual effect.
*/
ENDER_SIGNAL(2003, Type.VISUAL),
/**
* The flames seen on a mobspawner; a visual effect.
*/
MOBSPAWNER_FLAMES(2004, Type.VISUAL);
private final int id;
private final Type type;
private final Class<?> data;
private static final Map<Integer, Effect> BY_ID = Maps.newHashMap();
Effect(int id, Type type) {
this(id,type,null);
}
Effect(int id, Type type, Class<?> data) {
this.id = id;
this.type = type;
this.data = data;
}
/**
* Gets the ID for this effect.
*
* @return ID of this effect
* @deprecated Magic value
*/
@Deprecated
public int getId() {
return this.id;
}
/**
* @return The type of the effect.
*/
public Type getType() {
return this.type;
}
/**
* @return The class which represents data for this effect, or null if
* none
*/
public Class<?> getData() {
return this.data;
}
/**
* Gets the Effect associated with the given ID.
*
* @param id ID of the Effect to return
* @return Effect with the given ID
* @deprecated Magic value
*/
@Deprecated
public static Effect getById(int id) {
return BY_ID.get(id);
}
static {
for (Effect effect : values()) {
BY_ID.put(effect.id, effect);
}
}
/**
* Represents the type of an effect.
*/
public enum Type {SOUND, VISUAL}
}
| False | 903 | 13 | 996 | 18 | 1,062 | 15 | 996 | 18 | 1,197 | 18 | false | false | false | false | false | true |
1,333 | 130715_15 | // Copyright (c) 2014, NVIDIA CORPORATION. All rights reserved.
package icera.DebugAgent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
public class ModemLogger extends Logger {
public static final String TAG = "ModemLog";
public static final String MODEM_LOGGING_DEV = "/dev/log_modem";
private static final String GENIE_TOOLS_DIRECTORY = "tools"; // System will
// add "app_"
// prefix
private static final String GENIE_IOS_TOOL = "genie-ios-arm";
private static final String GENIE_LOGGING_TOOL = "icera_log_serial_arm";
private static final String MODEM_DEBUG_DIRECTORY = "/data/rfs/data/debug";
private static final String IOS_FILE_NAME = "dyn_filter.ios";
private static final String TRACEGEN_FILE_NAME = "tracegen.ix";
private static final String FILTER_FILE_NAME = "icera_filter.tsf";
private static final String MODEM_LOGGING_PORT = "32768";
public Process mGenieProc = null;
private boolean hasNewFilter;
private String iosFilename = MODEM_DEBUG_DIRECTORY + File.separator + IOS_FILE_NAME;;
private String filterFilename = MODEM_DEBUG_DIRECTORY + File.separator + FILTER_FILE_NAME;
private long mLoggingSize;
protected int mNumOfLogSegments;
private boolean noLimitLogging;
private boolean mDeferred;
private int mDeferredTimeout;
private int mDeferredWatermark;
public ModemLogger(Context ctx) {
super(ctx);
noLimitLogging = mPrefs.getNoLimit();
mLoggingSize = mPrefs.getLoggingSize();
mDeferred = mPrefs.isDeferredLoggingEnabled();
mDeferredTimeout = mPrefs.getDeferredTimeoutPos();
mDeferredWatermark = mPrefs.getDeferredWatermarkPos();
if (noLimitLogging) {
long freeSpace;
if (onSDCard)
freeSpace = Environment.getExternalStorageDirectory().getFreeSpace();
else
freeSpace = Environment.getDataDirectory().getFreeSpace();
mLoggingSize = (int)(((freeSpace - LogUtil.FULL_COREDUMP_FILE_SIZE * 3 - SaveLogs.RESERVED_SPACE_SIZE * 1024 * 1024) / (1024 * 1024)) / SaveLogs.DEFAULT_IOM_SIZE)
* SaveLogs.DEFAULT_IOM_SIZE;
mNumOfLogSegments = (int)(mLoggingSize / SaveLogs.DEFAULT_IOM_SIZE);
} else
mNumOfLogSegments = 5; // TODO: allow user to customize?
hasNewFilter = new File(filterFilename).exists();
installGenieTools();
}
/**
* Copy modify filter tool into /data/data/icera.DebugAgent/app_tools
* directory
*
* @param bugReportService TODO
*/
void installGenieTools() {
InputStream in = null;
OutputStream out = null;
int size = 0;
// Create storage directory for tools
File toolsDir = mContext.getDir(GENIE_TOOLS_DIRECTORY, Context.MODE_WORLD_READABLE
| Context.MODE_WORLD_WRITEABLE);
try {
in = mContext.getResources().getAssets().open(GENIE_IOS_TOOL);
size = in.available();
// Read the entire resource into a local byte buffer
byte[] buffer = new byte[size];
in.read(buffer);
in.close();
out = new FileOutputStream(toolsDir.getAbsolutePath() + "/" + GENIE_IOS_TOOL);
out.write(buffer);
out.close();
Runtime.getRuntime().exec(
"chmod 777 data/data/icera.DebugAgent/app_tools/genie-ios-arm");
} catch (Exception e) {
e.printStackTrace();
}
}
void uninstallGenieTools() {
// TODO
}
boolean isGenieToolInstalled() {
// TODO
return true;
}
/*
* Retrieve tracegen.ix from the modem
*/
public void getTracegen() {
File port = new File(MODEM_LOGGING_DEV);
// File outputTracegen = new
// File("/data/data/icera.DebugAgent/files/tracegen.ix");
File outputTracegen = new File(mLoggingDir + File.separator + TRACEGEN_FILE_NAME);
String cmd = "icera_log_serial_arm -e" + outputTracegen.getAbsolutePath()
+ " -d/dev/log_modem";
if (port.exists()
&& (!outputTracegen.exists() || (outputTracegen.exists() && (outputTracegen
.length() < 500000)))) {
// stopAndClean();
try {
Runtime.getRuntime().exec(cmd);
Thread.sleep(2000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* For modem logger, we need to make sure there is no other instance
* running. and if there is filter file, we need to generate the ios file
* first. and always get tracegen first
* @see icera.DebugAgent.Logger#beforeStart()
*/
@Override
protected boolean beforeStart() {
// Call super to initialize the logging directory
if (!super.beforeStart())
return false;
// TODO: check if ios and logging tools are installed?
if (checkLoggingProcess()) {
Log.e(TAG, "icera_log_serial_arm already running!");
mLoggingDir.delete();
// TODO: kill the running processes?
return false;
}
if (!(new File(MODEM_LOGGING_DEV).exists())) {
Log.e(TAG, "Modem logging device not found!");
mLoggingDir.delete();
return false;
}
getTracegen();
ArrayList<String> progs = new ArrayList<String>();
if (hasNewFilter) {
progs.add("/data/data/icera.DebugAgent/app_tools/" + GENIE_IOS_TOOL);
progs.add(iosFilename);
//progs.add(mContext.getFilesDir().getAbsolutePath() + File.separator + TRACEGEN_FILE_NAME);
progs.add(new File(mLoggingDir + File.separator + TRACEGEN_FILE_NAME).getAbsolutePath());
progs.add(filterFilename);
try {
mGenieProc = Runtime.getRuntime().exec(progs.toArray(new String[0]));
} catch (IOException e) {
Log.e(TAG, "Failed to generate IOS file!");
mGenieProc = null;
e.printStackTrace();
return false;
}
}
return true;
}
@Override
protected void prepareProgram() {
mProgram.clear();
mProgram.add(GENIE_LOGGING_TOOL);
mProgram.add("-b");
mProgram.add("-d" + MODEM_LOGGING_DEV);
mProgram.add("-p" + MODEM_LOGGING_PORT);
mProgram.add("-f");
if (hasNewFilter)
mProgram.add("-s" + iosFilename);
if (!mPrefs.isBeanieVersionOld()){
if (mDeferred){
mProgram.add("-r1" + "," + mDeferredWatermark + "," + mDeferredTimeout);
}
else{
mProgram.add("-r0");
}
}
mProgram.add("-a" + mLoggingDir + "," + mLoggingSize + "," + mLoggingSize
/ mNumOfLogSegments);
}
public boolean checkLoggingProcess() {
BufferedReader br = null;
boolean proc_present = false;
String line = "";
try {
Process p = Runtime.getRuntime().exec(new String[] {
"ps"
});
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = br.readLine()) != null) {
if (line.contains("icera_log_serial_arm"))
proc_present = true;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return proc_present;
}
@Override
protected void updateLogList() {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(".iom") || filename.contentEquals("daemon.log")
|| filename.contentEquals("comment.txt")
|| filename.contentEquals("tracegen.ix"))
return true;
else
return false;
}
};
for (File file : mLoggingDir.listFiles(filter)) {
this.addToLogList(file);
}
/*
* File tracegen = new
* File("/data/data/icera.DebugAgent/files/tracegen.ix"); if
* (!tracegen.exists()) getTracegen(); addToLogList(tracegen);
*/
}
@Override
protected void setLoggerName() {
mLoggerName = "MDM";
}
}
| Project-Google-Tango/vendor_nvidia_jxd_src | tegra/icera/apps/ModemErrorReporter/src/icera/DebugAgent/ModemLogger.java | 2,686 | /*
* File tracegen = new
* File("/data/data/icera.DebugAgent/files/tracegen.ix"); if
* (!tracegen.exists()) getTracegen(); addToLogList(tracegen);
*/ | block_comment | nl | // Copyright (c) 2014, NVIDIA CORPORATION. All rights reserved.
package icera.DebugAgent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
public class ModemLogger extends Logger {
public static final String TAG = "ModemLog";
public static final String MODEM_LOGGING_DEV = "/dev/log_modem";
private static final String GENIE_TOOLS_DIRECTORY = "tools"; // System will
// add "app_"
// prefix
private static final String GENIE_IOS_TOOL = "genie-ios-arm";
private static final String GENIE_LOGGING_TOOL = "icera_log_serial_arm";
private static final String MODEM_DEBUG_DIRECTORY = "/data/rfs/data/debug";
private static final String IOS_FILE_NAME = "dyn_filter.ios";
private static final String TRACEGEN_FILE_NAME = "tracegen.ix";
private static final String FILTER_FILE_NAME = "icera_filter.tsf";
private static final String MODEM_LOGGING_PORT = "32768";
public Process mGenieProc = null;
private boolean hasNewFilter;
private String iosFilename = MODEM_DEBUG_DIRECTORY + File.separator + IOS_FILE_NAME;;
private String filterFilename = MODEM_DEBUG_DIRECTORY + File.separator + FILTER_FILE_NAME;
private long mLoggingSize;
protected int mNumOfLogSegments;
private boolean noLimitLogging;
private boolean mDeferred;
private int mDeferredTimeout;
private int mDeferredWatermark;
public ModemLogger(Context ctx) {
super(ctx);
noLimitLogging = mPrefs.getNoLimit();
mLoggingSize = mPrefs.getLoggingSize();
mDeferred = mPrefs.isDeferredLoggingEnabled();
mDeferredTimeout = mPrefs.getDeferredTimeoutPos();
mDeferredWatermark = mPrefs.getDeferredWatermarkPos();
if (noLimitLogging) {
long freeSpace;
if (onSDCard)
freeSpace = Environment.getExternalStorageDirectory().getFreeSpace();
else
freeSpace = Environment.getDataDirectory().getFreeSpace();
mLoggingSize = (int)(((freeSpace - LogUtil.FULL_COREDUMP_FILE_SIZE * 3 - SaveLogs.RESERVED_SPACE_SIZE * 1024 * 1024) / (1024 * 1024)) / SaveLogs.DEFAULT_IOM_SIZE)
* SaveLogs.DEFAULT_IOM_SIZE;
mNumOfLogSegments = (int)(mLoggingSize / SaveLogs.DEFAULT_IOM_SIZE);
} else
mNumOfLogSegments = 5; // TODO: allow user to customize?
hasNewFilter = new File(filterFilename).exists();
installGenieTools();
}
/**
* Copy modify filter tool into /data/data/icera.DebugAgent/app_tools
* directory
*
* @param bugReportService TODO
*/
void installGenieTools() {
InputStream in = null;
OutputStream out = null;
int size = 0;
// Create storage directory for tools
File toolsDir = mContext.getDir(GENIE_TOOLS_DIRECTORY, Context.MODE_WORLD_READABLE
| Context.MODE_WORLD_WRITEABLE);
try {
in = mContext.getResources().getAssets().open(GENIE_IOS_TOOL);
size = in.available();
// Read the entire resource into a local byte buffer
byte[] buffer = new byte[size];
in.read(buffer);
in.close();
out = new FileOutputStream(toolsDir.getAbsolutePath() + "/" + GENIE_IOS_TOOL);
out.write(buffer);
out.close();
Runtime.getRuntime().exec(
"chmod 777 data/data/icera.DebugAgent/app_tools/genie-ios-arm");
} catch (Exception e) {
e.printStackTrace();
}
}
void uninstallGenieTools() {
// TODO
}
boolean isGenieToolInstalled() {
// TODO
return true;
}
/*
* Retrieve tracegen.ix from the modem
*/
public void getTracegen() {
File port = new File(MODEM_LOGGING_DEV);
// File outputTracegen = new
// File("/data/data/icera.DebugAgent/files/tracegen.ix");
File outputTracegen = new File(mLoggingDir + File.separator + TRACEGEN_FILE_NAME);
String cmd = "icera_log_serial_arm -e" + outputTracegen.getAbsolutePath()
+ " -d/dev/log_modem";
if (port.exists()
&& (!outputTracegen.exists() || (outputTracegen.exists() && (outputTracegen
.length() < 500000)))) {
// stopAndClean();
try {
Runtime.getRuntime().exec(cmd);
Thread.sleep(2000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* For modem logger, we need to make sure there is no other instance
* running. and if there is filter file, we need to generate the ios file
* first. and always get tracegen first
* @see icera.DebugAgent.Logger#beforeStart()
*/
@Override
protected boolean beforeStart() {
// Call super to initialize the logging directory
if (!super.beforeStart())
return false;
// TODO: check if ios and logging tools are installed?
if (checkLoggingProcess()) {
Log.e(TAG, "icera_log_serial_arm already running!");
mLoggingDir.delete();
// TODO: kill the running processes?
return false;
}
if (!(new File(MODEM_LOGGING_DEV).exists())) {
Log.e(TAG, "Modem logging device not found!");
mLoggingDir.delete();
return false;
}
getTracegen();
ArrayList<String> progs = new ArrayList<String>();
if (hasNewFilter) {
progs.add("/data/data/icera.DebugAgent/app_tools/" + GENIE_IOS_TOOL);
progs.add(iosFilename);
//progs.add(mContext.getFilesDir().getAbsolutePath() + File.separator + TRACEGEN_FILE_NAME);
progs.add(new File(mLoggingDir + File.separator + TRACEGEN_FILE_NAME).getAbsolutePath());
progs.add(filterFilename);
try {
mGenieProc = Runtime.getRuntime().exec(progs.toArray(new String[0]));
} catch (IOException e) {
Log.e(TAG, "Failed to generate IOS file!");
mGenieProc = null;
e.printStackTrace();
return false;
}
}
return true;
}
@Override
protected void prepareProgram() {
mProgram.clear();
mProgram.add(GENIE_LOGGING_TOOL);
mProgram.add("-b");
mProgram.add("-d" + MODEM_LOGGING_DEV);
mProgram.add("-p" + MODEM_LOGGING_PORT);
mProgram.add("-f");
if (hasNewFilter)
mProgram.add("-s" + iosFilename);
if (!mPrefs.isBeanieVersionOld()){
if (mDeferred){
mProgram.add("-r1" + "," + mDeferredWatermark + "," + mDeferredTimeout);
}
else{
mProgram.add("-r0");
}
}
mProgram.add("-a" + mLoggingDir + "," + mLoggingSize + "," + mLoggingSize
/ mNumOfLogSegments);
}
public boolean checkLoggingProcess() {
BufferedReader br = null;
boolean proc_present = false;
String line = "";
try {
Process p = Runtime.getRuntime().exec(new String[] {
"ps"
});
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = br.readLine()) != null) {
if (line.contains("icera_log_serial_arm"))
proc_present = true;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return proc_present;
}
@Override
protected void updateLogList() {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
if (filename.endsWith(".iom") || filename.contentEquals("daemon.log")
|| filename.contentEquals("comment.txt")
|| filename.contentEquals("tracegen.ix"))
return true;
else
return false;
}
};
for (File file : mLoggingDir.listFiles(filter)) {
this.addToLogList(file);
}
/*
* File tracegen =<SUF>*/
}
@Override
protected void setLoggerName() {
mLoggerName = "MDM";
}
}
| False | 1,947 | 46 | 2,187 | 51 | 2,377 | 55 | 2,187 | 51 | 2,687 | 56 | false | false | false | false | false | true |
829 | 194208_6 | /*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.integration;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.delegate.ActivityDelegate;
import com.jess.arms.base.delegate.ActivityDelegateImpl;
import com.jess.arms.base.delegate.FragmentDelegate;
import com.jess.arms.base.delegate.IActivity;
import com.jess.arms.integration.cache.Cache;
import com.jess.arms.integration.cache.IntelligentCache;
import com.jess.arms.utils.Preconditions;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Lazy;
/**
* ================================================
* {@link Application.ActivityLifecycleCallbacks} 默认实现类
* 通过 {@link ActivityDelegate} 管理 {@link Activity}
*
* @see <a href="http://www.jianshu.com/p/75a5c24174b2">ActivityLifecycleCallbacks 分析文章</a>
* Created by JessYan on 21/02/2017 14:23
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
@Singleton
public class ActivityLifecycle implements Application.ActivityLifecycleCallbacks {
@Inject
AppManager mAppManager;
@Inject
Application mApplication;
@Inject
Cache<String, Object> mExtras;
@Inject
Lazy<FragmentManager.FragmentLifecycleCallbacks> mFragmentLifecycle;
@Inject
Lazy<List<FragmentManager.FragmentLifecycleCallbacks>> mFragmentLifecycles;
@Inject
public ActivityLifecycle() {
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//如果 intent 包含了此字段,并且为 true 说明不加入到 list 进行统一管理
boolean isNotAdd = false;
if (activity.getIntent() != null) {
isNotAdd = activity.getIntent().getBooleanExtra(AppManager.IS_NOT_ADD_ACTIVITY_LIST, false);
}
if (!isNotAdd) {
mAppManager.addActivity(activity);
}
//配置ActivityDelegate
if (activity instanceof IActivity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate == null) {
Cache<String, Object> cache = getCacheFromActivity((IActivity) activity);
activityDelegate = new ActivityDelegateImpl(activity);
//使用 IntelligentCache.KEY_KEEP 作为 key 的前缀, 可以使储存的数据永久存储在内存中
//否则存储在 LRU 算法的存储空间中, 前提是 Activity 使用的是 IntelligentCache (框架默认使用)
cache.put(IntelligentCache.getKeyOfKeep(ActivityDelegate.ACTIVITY_DELEGATE), activityDelegate);
}
activityDelegate.onCreate(savedInstanceState);
}
registerFragmentCallbacks(activity);
}
@Override
public void onActivityStarted(Activity activity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onStart();
}
}
@Override
public void onActivityResumed(Activity activity) {
mAppManager.setCurrentActivity(activity);
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onResume();
}
}
@Override
public void onActivityPaused(Activity activity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onPause();
}
}
@Override
public void onActivityStopped(Activity activity) {
if (mAppManager.getCurrentActivity() == activity) {
mAppManager.setCurrentActivity(null);
}
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onStop();
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onSaveInstanceState(outState);
}
}
@Override
public void onActivityDestroyed(Activity activity) {
mAppManager.removeActivity(activity);
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onDestroy();
getCacheFromActivity((IActivity) activity).clear();
}
}
/**
* 给每个 Activity 的所有 Fragment 设置监听其生命周期, Activity 可以通过 {@link IActivity#useFragment()}
* 设置是否使用监听,如果这个 Activity 返回 false 的话,这个 Activity 下面的所有 Fragment 将不能使用 {@link FragmentDelegate}
* 意味着 {@link BaseFragment} 也不能使用
*
* @param activity
*/
private void registerFragmentCallbacks(Activity activity) {
boolean useFragment = !(activity instanceof IActivity) || ((IActivity) activity).useFragment();
if (activity instanceof FragmentActivity && useFragment) {
//mFragmentLifecycle 为 Fragment 生命周期实现类, 用于框架内部对每个 Fragment 的必要操作, 如给每个 Fragment 配置 FragmentDelegate
//注册框架内部已实现的 Fragment 生命周期逻辑
((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(mFragmentLifecycle.get(), true);
if (mExtras.containsKey(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()))) {
@SuppressWarnings("unchecked")
List<ConfigModule> modules = (List<ConfigModule>) mExtras.get(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()));
if (modules != null) {
for (ConfigModule module : modules) {
module.injectFragmentLifecycle(mApplication, mFragmentLifecycles.get());
}
}
mExtras.remove(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()));
}
//注册框架外部, 开发者扩展的 Fragment 生命周期逻辑
for (FragmentManager.FragmentLifecycleCallbacks fragmentLifecycle : mFragmentLifecycles.get()) {
((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(fragmentLifecycle, true);
}
}
}
private ActivityDelegate fetchActivityDelegate(Activity activity) {
ActivityDelegate activityDelegate = null;
if (activity instanceof IActivity) {
Cache<String, Object> cache = getCacheFromActivity((IActivity) activity);
activityDelegate = (ActivityDelegate) cache.get(IntelligentCache.getKeyOfKeep(ActivityDelegate.ACTIVITY_DELEGATE));
}
return activityDelegate;
}
@NonNull
private Cache<String, Object> getCacheFromActivity(IActivity activity) {
Cache<String, Object> cache = activity.provideCache();
Preconditions.checkNotNull(cache, "%s cannot be null on Activity", Cache.class.getName());
return cache;
}
}
| JessYanCoding/MVPArms | arms/src/main/java/com/jess/arms/integration/ActivityLifecycle.java | 2,083 | //mFragmentLifecycle 为 Fragment 生命周期实现类, 用于框架内部对每个 Fragment 的必要操作, 如给每个 Fragment 配置 FragmentDelegate | line_comment | nl | /*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.integration;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.delegate.ActivityDelegate;
import com.jess.arms.base.delegate.ActivityDelegateImpl;
import com.jess.arms.base.delegate.FragmentDelegate;
import com.jess.arms.base.delegate.IActivity;
import com.jess.arms.integration.cache.Cache;
import com.jess.arms.integration.cache.IntelligentCache;
import com.jess.arms.utils.Preconditions;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Lazy;
/**
* ================================================
* {@link Application.ActivityLifecycleCallbacks} 默认实现类
* 通过 {@link ActivityDelegate} 管理 {@link Activity}
*
* @see <a href="http://www.jianshu.com/p/75a5c24174b2">ActivityLifecycleCallbacks 分析文章</a>
* Created by JessYan on 21/02/2017 14:23
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
@Singleton
public class ActivityLifecycle implements Application.ActivityLifecycleCallbacks {
@Inject
AppManager mAppManager;
@Inject
Application mApplication;
@Inject
Cache<String, Object> mExtras;
@Inject
Lazy<FragmentManager.FragmentLifecycleCallbacks> mFragmentLifecycle;
@Inject
Lazy<List<FragmentManager.FragmentLifecycleCallbacks>> mFragmentLifecycles;
@Inject
public ActivityLifecycle() {
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//如果 intent 包含了此字段,并且为 true 说明不加入到 list 进行统一管理
boolean isNotAdd = false;
if (activity.getIntent() != null) {
isNotAdd = activity.getIntent().getBooleanExtra(AppManager.IS_NOT_ADD_ACTIVITY_LIST, false);
}
if (!isNotAdd) {
mAppManager.addActivity(activity);
}
//配置ActivityDelegate
if (activity instanceof IActivity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate == null) {
Cache<String, Object> cache = getCacheFromActivity((IActivity) activity);
activityDelegate = new ActivityDelegateImpl(activity);
//使用 IntelligentCache.KEY_KEEP 作为 key 的前缀, 可以使储存的数据永久存储在内存中
//否则存储在 LRU 算法的存储空间中, 前提是 Activity 使用的是 IntelligentCache (框架默认使用)
cache.put(IntelligentCache.getKeyOfKeep(ActivityDelegate.ACTIVITY_DELEGATE), activityDelegate);
}
activityDelegate.onCreate(savedInstanceState);
}
registerFragmentCallbacks(activity);
}
@Override
public void onActivityStarted(Activity activity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onStart();
}
}
@Override
public void onActivityResumed(Activity activity) {
mAppManager.setCurrentActivity(activity);
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onResume();
}
}
@Override
public void onActivityPaused(Activity activity) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onPause();
}
}
@Override
public void onActivityStopped(Activity activity) {
if (mAppManager.getCurrentActivity() == activity) {
mAppManager.setCurrentActivity(null);
}
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onStop();
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onSaveInstanceState(outState);
}
}
@Override
public void onActivityDestroyed(Activity activity) {
mAppManager.removeActivity(activity);
ActivityDelegate activityDelegate = fetchActivityDelegate(activity);
if (activityDelegate != null) {
activityDelegate.onDestroy();
getCacheFromActivity((IActivity) activity).clear();
}
}
/**
* 给每个 Activity 的所有 Fragment 设置监听其生命周期, Activity 可以通过 {@link IActivity#useFragment()}
* 设置是否使用监听,如果这个 Activity 返回 false 的话,这个 Activity 下面的所有 Fragment 将不能使用 {@link FragmentDelegate}
* 意味着 {@link BaseFragment} 也不能使用
*
* @param activity
*/
private void registerFragmentCallbacks(Activity activity) {
boolean useFragment = !(activity instanceof IActivity) || ((IActivity) activity).useFragment();
if (activity instanceof FragmentActivity && useFragment) {
//mFragmentLifecycle 为<SUF>
//注册框架内部已实现的 Fragment 生命周期逻辑
((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(mFragmentLifecycle.get(), true);
if (mExtras.containsKey(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()))) {
@SuppressWarnings("unchecked")
List<ConfigModule> modules = (List<ConfigModule>) mExtras.get(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()));
if (modules != null) {
for (ConfigModule module : modules) {
module.injectFragmentLifecycle(mApplication, mFragmentLifecycles.get());
}
}
mExtras.remove(IntelligentCache.getKeyOfKeep(ConfigModule.class.getName()));
}
//注册框架外部, 开发者扩展的 Fragment 生命周期逻辑
for (FragmentManager.FragmentLifecycleCallbacks fragmentLifecycle : mFragmentLifecycles.get()) {
((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(fragmentLifecycle, true);
}
}
}
private ActivityDelegate fetchActivityDelegate(Activity activity) {
ActivityDelegate activityDelegate = null;
if (activity instanceof IActivity) {
Cache<String, Object> cache = getCacheFromActivity((IActivity) activity);
activityDelegate = (ActivityDelegate) cache.get(IntelligentCache.getKeyOfKeep(ActivityDelegate.ACTIVITY_DELEGATE));
}
return activityDelegate;
}
@NonNull
private Cache<String, Object> getCacheFromActivity(IActivity activity) {
Cache<String, Object> cache = activity.provideCache();
Preconditions.checkNotNull(cache, "%s cannot be null on Activity", Cache.class.getName());
return cache;
}
}
| False | 1,594 | 31 | 1,781 | 31 | 1,847 | 27 | 1,781 | 31 | 2,241 | 50 | false | false | false | false | false | true |
788 | 207160_1 | package com.jadonvb;
import org.knowm.xchart.*;
import org.knowm.xchart.style.Styler;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Voer een geheel getal in: ");
int startingNumber = scanner.nextInt();
List<Integer> xData = new ArrayList<>();
List<Integer> yData = new ArrayList<>();
int n = startingNumber;
int step = 0;
while (n != 1) {
xData.add(step);
yData.add(n);
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
step++;
}
xData.add(step);
yData.add(1);
// Tooltip-tekst genereren voor hele getallen
List<String> toolTips = new ArrayList<>();
for (int i = 0; i < xData.size(); i++) {
if (xData.get(i) % 1 == 0) {
toolTips.add("Step: " + xData.get(i) + ", Number: " + yData.get(i));
} else {
toolTips.add(""); // Geen tooltip voor niet-gehele getallen
}
}
// Grafiek maken
XYChart chart = new XYChartBuilder().width(800).height(600).title("Collatz Conjecture").xAxisTitle("Tijd").yAxisTitle("Getal").build();
// Data toevoegen
XYSeries series = chart.addSeries("Collatz", xData, yData);
// Tooltips instellen met aangepaste tooltip generator
chart.getStyler().setToolTipType(Styler.ToolTipType.yLabels);
chart.getStyler().setCursorEnabled(true);
chart.getStyler().setToolTipsEnabled(true);
chart.getStyler().setToolTipFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12));
chart.getStyler().setToolTipBackgroundColor(java.awt.Color.WHITE);
chart.getStyler().setToolTipBorderColor(java.awt.Color.BLACK);
// Laten zien
new SwingWrapper<>(chart).displayChart();
}
} | Ja90n/CollatzDisplayer | src/main/java/com/jadonvb/Main.java | 658 | // Geen tooltip voor niet-gehele getallen | line_comment | nl | package com.jadonvb;
import org.knowm.xchart.*;
import org.knowm.xchart.style.Styler;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Voer een geheel getal in: ");
int startingNumber = scanner.nextInt();
List<Integer> xData = new ArrayList<>();
List<Integer> yData = new ArrayList<>();
int n = startingNumber;
int step = 0;
while (n != 1) {
xData.add(step);
yData.add(n);
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
step++;
}
xData.add(step);
yData.add(1);
// Tooltip-tekst genereren voor hele getallen
List<String> toolTips = new ArrayList<>();
for (int i = 0; i < xData.size(); i++) {
if (xData.get(i) % 1 == 0) {
toolTips.add("Step: " + xData.get(i) + ", Number: " + yData.get(i));
} else {
toolTips.add(""); // Geen tooltip<SUF>
}
}
// Grafiek maken
XYChart chart = new XYChartBuilder().width(800).height(600).title("Collatz Conjecture").xAxisTitle("Tijd").yAxisTitle("Getal").build();
// Data toevoegen
XYSeries series = chart.addSeries("Collatz", xData, yData);
// Tooltips instellen met aangepaste tooltip generator
chart.getStyler().setToolTipType(Styler.ToolTipType.yLabels);
chart.getStyler().setCursorEnabled(true);
chart.getStyler().setToolTipsEnabled(true);
chart.getStyler().setToolTipFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12));
chart.getStyler().setToolTipBackgroundColor(java.awt.Color.WHITE);
chart.getStyler().setToolTipBorderColor(java.awt.Color.BLACK);
// Laten zien
new SwingWrapper<>(chart).displayChart();
}
} | True | 516 | 12 | 580 | 12 | 597 | 10 | 580 | 12 | 671 | 13 | false | false | false | false | false | true |
3,691 | 126342_3 | import java.io.*;
import java.util.*;
public class ceilAndFloor {
private static class Node {
int data;
ArrayList<Node> children = new ArrayList<>();
}
public static void display(Node node) {
String str = node.data + " -> ";
for (Node child : node.children) {
str += child.data + ", ";
}
str += ".";
System.out.println(str);
for (Node child : node.children) {
display(child);
}
}
public static Node construct(int[] arr) {
Node root = null;
Stack<Node> st = new Stack<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == -1) {
st.pop();
} else {
Node t = new Node();
t.data = arr[i];
if (st.size() > 0) {
st.peek().children.add(t);
} else {
root = t;
}
st.push(t);
}
}
return root;
}
static int ceil; // set at +infinity
static int floor; // set at -infinity
public static void ceilFloor(Node node, int data) {
if(node.data > data){
// potential ceil members enter
if(node.data < ceil){
ceil = node.data;
}
}
else if(node.data < data){
// potential floor members enters
if(node.data > floor){
floor = node.data;
}
}
// travel
for(Node child : node.children){
ceilFloor(child , data);
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] values = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(values[i]);
}
int data = Integer.parseInt(br.readLine());
Node root = construct(arr);
ceil = Integer.MAX_VALUE; // smallest among larger
floor = Integer.MIN_VALUE; // largest among smaller
ceilFloor(root, data);
System.out.println("CEIL = " + ceil);
System.out.println("FLOOR = " + floor);
}
} | mktintumon/DSA-Beginners | 13.GenericTree/ceilAndFloor.java | 682 | // potential floor members enters | line_comment | nl | import java.io.*;
import java.util.*;
public class ceilAndFloor {
private static class Node {
int data;
ArrayList<Node> children = new ArrayList<>();
}
public static void display(Node node) {
String str = node.data + " -> ";
for (Node child : node.children) {
str += child.data + ", ";
}
str += ".";
System.out.println(str);
for (Node child : node.children) {
display(child);
}
}
public static Node construct(int[] arr) {
Node root = null;
Stack<Node> st = new Stack<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == -1) {
st.pop();
} else {
Node t = new Node();
t.data = arr[i];
if (st.size() > 0) {
st.peek().children.add(t);
} else {
root = t;
}
st.push(t);
}
}
return root;
}
static int ceil; // set at +infinity
static int floor; // set at -infinity
public static void ceilFloor(Node node, int data) {
if(node.data > data){
// potential ceil members enter
if(node.data < ceil){
ceil = node.data;
}
}
else if(node.data < data){
// potential floor<SUF>
if(node.data > floor){
floor = node.data;
}
}
// travel
for(Node child : node.children){
ceilFloor(child , data);
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] values = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(values[i]);
}
int data = Integer.parseInt(br.readLine());
Node root = construct(arr);
ceil = Integer.MAX_VALUE; // smallest among larger
floor = Integer.MIN_VALUE; // largest among smaller
ceilFloor(root, data);
System.out.println("CEIL = " + ceil);
System.out.println("FLOOR = " + floor);
}
} | False | 501 | 5 | 565 | 6 | 635 | 5 | 565 | 6 | 680 | 5 | false | false | false | false | false | true |
3,943 | 107768_9 | /*
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright: 2007-2016 PagSeguro Internet Ltda.
* Licence: http://www.apache.org/licenses/LICENSE-2.0
*/
package br.com.uol.pagseguro.api.checkout;
import java.math.BigDecimal;
import java.util.List;
import br.com.uol.pagseguro.api.common.domain.*;
import br.com.uol.pagseguro.api.common.domain.PreApprovalRequest;
import br.com.uol.pagseguro.api.common.domain.enums.Currency;
/**
* Interface to make payments through payment API
*
* @author PagSeguro Internet Ltda.
*/
public interface CheckoutRegistration {
/**
* Define a code to refer to the payment.
* This code is associated with the transaction created by the payment and is useful
* to link PagSeguro transactions to sales registered on your system.
* Format: Free, with the 200-character limit.
*
* Optional
*
* @return Reference Code.
*/
String getReference();
/**
* Extra value. Specifies an extra value to be added or subtracted from the total amount of
* payment. This value may represent an extra fee to be charged in the payment or a discount to be
* granted if the value is negative. Format: Decimal (positive or negative), to two decimal places
* separated by a point (bp, or 1234.56 -1234.56), greater than or equal to -9999999.00 and less
* than or equal to 9999999.00. When negative, this value can not be greater than or equal to the
* sum of the values of the products.
*
* Optional
*
* @return Extra Amout
*/
BigDecimal getExtraAmount();
/**
* Indicates the currency in which payment will be made.
*
* Required
*
* @return Currency used
* @see Currency
*/
Currency getCurrency();
/**
* Shipping data
*
* @return Shipping
*
* Optional
* @see Shipping
*/
Shipping getShipping();
/**
* Sender data
*
* @return Sender Data
*
* Optional
* @see Sender
*/
Sender getSender();
/**
* List of items contained in the payment
*
* @return List of Payment Items
* @see PaymentItem
*/
List<? extends PaymentItem> getItems();
/**
* Pre Approval
*
* @return Pre Approval
* @see PreApprovalRequest
*/
PreApprovalRequest getPreApproval();
/**
* Get Parameters
*
* @return Parameters
* @see Parameter
*/
List<? extends Parameter> getParameters();
/**
* Used to include and exclude groups of means of payment and means of payment for a transaction
*
* @return Accepted Payment Methods
* @see AcceptedPaymentMethods
*/
AcceptedPaymentMethods getAcceptedPaymentMethods();
/**
* Configurations to payment methods.
*
* @return Configurations to payment methods.
*/
List<? extends PaymentMethodConfig> getPaymentMethodConfigs();
}
| pagseguro/pagseguro-sdk-java | source/src/main/java/br/com/uol/pagseguro/api/checkout/CheckoutRegistration.java | 994 | /**
* Get Parameters
*
* @return Parameters
* @see Parameter
*/ | block_comment | nl | /*
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright: 2007-2016 PagSeguro Internet Ltda.
* Licence: http://www.apache.org/licenses/LICENSE-2.0
*/
package br.com.uol.pagseguro.api.checkout;
import java.math.BigDecimal;
import java.util.List;
import br.com.uol.pagseguro.api.common.domain.*;
import br.com.uol.pagseguro.api.common.domain.PreApprovalRequest;
import br.com.uol.pagseguro.api.common.domain.enums.Currency;
/**
* Interface to make payments through payment API
*
* @author PagSeguro Internet Ltda.
*/
public interface CheckoutRegistration {
/**
* Define a code to refer to the payment.
* This code is associated with the transaction created by the payment and is useful
* to link PagSeguro transactions to sales registered on your system.
* Format: Free, with the 200-character limit.
*
* Optional
*
* @return Reference Code.
*/
String getReference();
/**
* Extra value. Specifies an extra value to be added or subtracted from the total amount of
* payment. This value may represent an extra fee to be charged in the payment or a discount to be
* granted if the value is negative. Format: Decimal (positive or negative), to two decimal places
* separated by a point (bp, or 1234.56 -1234.56), greater than or equal to -9999999.00 and less
* than or equal to 9999999.00. When negative, this value can not be greater than or equal to the
* sum of the values of the products.
*
* Optional
*
* @return Extra Amout
*/
BigDecimal getExtraAmount();
/**
* Indicates the currency in which payment will be made.
*
* Required
*
* @return Currency used
* @see Currency
*/
Currency getCurrency();
/**
* Shipping data
*
* @return Shipping
*
* Optional
* @see Shipping
*/
Shipping getShipping();
/**
* Sender data
*
* @return Sender Data
*
* Optional
* @see Sender
*/
Sender getSender();
/**
* List of items contained in the payment
*
* @return List of Payment Items
* @see PaymentItem
*/
List<? extends PaymentItem> getItems();
/**
* Pre Approval
*
* @return Pre Approval
* @see PreApprovalRequest
*/
PreApprovalRequest getPreApproval();
/**
* Get Parameters
<SUF>*/
List<? extends Parameter> getParameters();
/**
* Used to include and exclude groups of means of payment and means of payment for a transaction
*
* @return Accepted Payment Methods
* @see AcceptedPaymentMethods
*/
AcceptedPaymentMethods getAcceptedPaymentMethods();
/**
* Configurations to payment methods.
*
* @return Configurations to payment methods.
*/
List<? extends PaymentMethodConfig> getPaymentMethodConfigs();
}
| False | 845 | 22 | 895 | 19 | 945 | 24 | 895 | 19 | 1,076 | 26 | false | false | false | false | false | true |
3,729 | 197311_9 | package team2.abcbank.beans;_x000D_
_x000D_
import javax.ejb.EJB;_x000D_
import javax.faces.application.FacesMessage;_x000D_
import javax.faces.context.ExternalContext;_x000D_
import javax.naming.Context;_x000D_
import javax.naming.InitialContext;_x000D_
import javax.naming.NamingException;_x000D_
import javax.security.auth.login.LoginException;_x000D_
import javax.servlet.http.HttpSession;_x000D_
_x000D_
import org.jboss.security.SecurityAssociation;_x000D_
import org.jboss.security.auth.callback.CallbackHandlerPolicyContextHandler;_x000D_
import org.jboss.web.tomcat.security.login.WebAuthentication;_x000D_
_x000D_
import team2.abcbank.ejb.shared.AccountManagerIF;_x000D_
import team2.abcbank.ejb.shared.AccountOfficeIF;_x000D_
import team2.abcbank.ejb.shared.BankException;_x000D_
import team2.abcbank.ejb.shared.LoginBeanIF;_x000D_
import team2.abcbank.jaas.MyCallbackHandler;_x000D_
_x000D_
public class BankAccessBean extends EvenMoreCommonBean_x000D_
{_x000D_
private String username = null;_x000D_
private String password = null;_x000D_
private String captcha = null;_x000D_
_x000D_
protected LoginBeanIF loginBean = null;_x000D_
protected AccountManagerIF accountManager = null;_x000D_
protected AccountOfficeIF accountOffice = null;_x000D_
protected long accountNumber = -1;_x000D_
_x000D_
public BankAccessBean()_x000D_
{_x000D_
try_x000D_
{_x000D_
Context ctx = new InitialContext();_x000D_
loginBean = (LoginBeanIF) ctx.lookup("java:comp/env/LoginBeanRef");_x000D_
accountManager = (AccountManagerIF) ctx.lookup("java:comp/env/AccountManagerRef");_x000D_
accountOffice = (AccountOfficeIF) ctx.lookup("java:comp/env/AccountOfficeRef");_x000D_
}_x000D_
catch (NamingException e)_x000D_
{_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
_x000D_
public String getBankStatus()_x000D_
{_x000D_
System.out.println("BankAccessBean.getBankStatus()");_x000D_
String status = "database onbereikbaar";_x000D_
try_x000D_
{_x000D_
status = loginBean.getBankIsOpen() ? "bank is open" : "bank is closed";_x000D_
status += loginBean.getTransactionManagerIsIdle() ? " and idle" : " and busy";_x000D_
}_x000D_
catch (Throwable t)_x000D_
{_x000D_
t.printStackTrace();_x000D_
}_x000D_
return status;_x000D_
}_x000D_
_x000D_
public String logout()_x000D_
{_x000D_
System.out.println("BankAccessBean.logout()");_x000D_
// zie jboss-web.xml : flushOnSessionInvalidation_x000D_
// dat zorgt dat logout() op de loginmodules gecalled wordt_x000D_
// en alle rechten weer netjes ingetrokken worden_x000D_
if (false)_x000D_
{_x000D_
try_x000D_
{_x000D_
if (accountOffice.getPendingTransactions(accountNumber).length > 0)_x000D_
{_x000D_
addMessage(FacesMessage.SEVERITY_ERROR, "Kan niet uitloggen als er nog transacties open staan.");_x000D_
return "transactionLeft";_x000D_
}_x000D_
}_x000D_
catch (BankException e)_x000D_
{_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
HttpSession session = (HttpSession) getExternalContext().getSession(false);_x000D_
if (session != null)_x000D_
{_x000D_
session.invalidate();_x000D_
}_x000D_
return "logoutOutcome";_x000D_
}_x000D_
_x000D_
public String login()_x000D_
{_x000D_
System.out.println("BankAccessBean.login()");_x000D_
_x000D_
ExternalContext ec = getExternalContext();_x000D_
boolean error = false;_x000D_
// alleen maar inloggen als de user nog niet ingelogd is_x000D_
if (ec.getRemoteUser() == null)_x000D_
{_x000D_
try_x000D_
{_x000D_
// de callbackHandler die WebAuthentication opbouwt voor zijn username + credentials parameters_x000D_
// delegeert onbekende callbacks naar deze callbackHandler_x000D_
// zo kunnen we dus communiceren via de callbacks_x000D_
// doc: http://docs.jboss.org/jbossas/javadoc/4.0.5/security/org/jboss/security/auth/callback/CallbackHandlerPolicyContextHandler.html_x000D_
// doc: https://jira.jboss.org/jira/browse/JBAS-2345_x000D_
CallbackHandlerPolicyContextHandler.setCallbackHandler(new MyCallbackHandler(this));_x000D_
_x000D_
// doe de programmatic web logon:_x000D_
// doc: http://jboss.org/community/docs/DOC-12656_x000D_
// dit object doet zowel authentication als authorization_x000D_
WebAuthentication wa = new WebAuthentication();_x000D_
boolean success = wa.login(username, password);_x000D_
if (!success)_x000D_
{_x000D_
error = true;_x000D_
// gespecificeerd in:_x000D_
// https://jira.jboss.org/jira/browse/SECURITY-278?focusedCommentId=12433231#action_12433231_x000D_
Object o = SecurityAssociation.getContextInfo("org.jboss.security.exception");_x000D_
if (o instanceof LoginException)_x000D_
{_x000D_
LoginException le = (LoginException) o;_x000D_
addMessage(FacesMessage.SEVERITY_ERROR, "Login fout: " + le.getMessage());_x000D_
}_x000D_
else_x000D_
{_x000D_
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");_x000D_
}_x000D_
}_x000D_
}_x000D_
catch (Throwable t)_x000D_
{_x000D_
error = true;_x000D_
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");_x000D_
t.printStackTrace();_x000D_
}_x000D_
}_x000D_
_x000D_
// mogelijke outcomes voor redirection_x000D_
// zie JSF navigation rules in faces-config.xml_x000D_
if (error)_x000D_
return "loginError";_x000D_
if (ec.isUserInRole("AccountManager"))_x000D_
return "loggedInAsAccountManager";_x000D_
if (ec.isUserInRole("AccountOffice"))_x000D_
return "loggedInAsAccountOffice";_x000D_
_x000D_
// kom hier uit als JBoss iets geks doet:_x000D_
// de authenticatie is gelukt, maar de authorisatie is mislukt_x000D_
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");_x000D_
return "loginError";_x000D_
}_x000D_
_x000D_
public String getUsername()_x000D_
{_x000D_
return username;_x000D_
}_x000D_
_x000D_
public void setUsername(String username)_x000D_
{_x000D_
this.username = username;_x000D_
}_x000D_
_x000D_
public String getPassword()_x000D_
{_x000D_
return password;_x000D_
}_x000D_
_x000D_
public void setPassword(String password)_x000D_
{_x000D_
this.password = password;_x000D_
}_x000D_
_x000D_
public String getCaptcha()_x000D_
{_x000D_
return captcha;_x000D_
}_x000D_
_x000D_
public void setCaptcha(String captcha)_x000D_
{_x000D_
this.captcha = captcha;_x000D_
}_x000D_
_x000D_
/**_x000D_
* for jaas mycallbackhandler_x000D_
*/_x000D_
public LoginBeanIF getLoginBean()_x000D_
{_x000D_
return loginBean;_x000D_
}_x000D_
_x000D_
public AccountManagerIF getAccountManager()_x000D_
{_x000D_
return accountManager;_x000D_
}_x000D_
_x000D_
public AccountOfficeIF getAccountOffice()_x000D_
{_x000D_
return accountOffice;_x000D_
}_x000D_
_x000D_
public long getAccountNumber()_x000D_
{_x000D_
return accountNumber;_x000D_
}_x000D_
_x000D_
public void setAccountNumber(long accountNumber)_x000D_
{_x000D_
this.accountNumber = accountNumber;_x000D_
}_x000D_
} | mpkossen/fantajava | GDSY_project7/src/team2/abcbank/beans/BankAccessBean.java | 1,885 | // mogelijke outcomes voor redirection_x000D_ | line_comment | nl | package team2.abcbank.beans;_x000D_
_x000D_
import javax.ejb.EJB;_x000D_
import javax.faces.application.FacesMessage;_x000D_
import javax.faces.context.ExternalContext;_x000D_
import javax.naming.Context;_x000D_
import javax.naming.InitialContext;_x000D_
import javax.naming.NamingException;_x000D_
import javax.security.auth.login.LoginException;_x000D_
import javax.servlet.http.HttpSession;_x000D_
_x000D_
import org.jboss.security.SecurityAssociation;_x000D_
import org.jboss.security.auth.callback.CallbackHandlerPolicyContextHandler;_x000D_
import org.jboss.web.tomcat.security.login.WebAuthentication;_x000D_
_x000D_
import team2.abcbank.ejb.shared.AccountManagerIF;_x000D_
import team2.abcbank.ejb.shared.AccountOfficeIF;_x000D_
import team2.abcbank.ejb.shared.BankException;_x000D_
import team2.abcbank.ejb.shared.LoginBeanIF;_x000D_
import team2.abcbank.jaas.MyCallbackHandler;_x000D_
_x000D_
public class BankAccessBean extends EvenMoreCommonBean_x000D_
{_x000D_
private String username = null;_x000D_
private String password = null;_x000D_
private String captcha = null;_x000D_
_x000D_
protected LoginBeanIF loginBean = null;_x000D_
protected AccountManagerIF accountManager = null;_x000D_
protected AccountOfficeIF accountOffice = null;_x000D_
protected long accountNumber = -1;_x000D_
_x000D_
public BankAccessBean()_x000D_
{_x000D_
try_x000D_
{_x000D_
Context ctx = new InitialContext();_x000D_
loginBean = (LoginBeanIF) ctx.lookup("java:comp/env/LoginBeanRef");_x000D_
accountManager = (AccountManagerIF) ctx.lookup("java:comp/env/AccountManagerRef");_x000D_
accountOffice = (AccountOfficeIF) ctx.lookup("java:comp/env/AccountOfficeRef");_x000D_
}_x000D_
catch (NamingException e)_x000D_
{_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
_x000D_
public String getBankStatus()_x000D_
{_x000D_
System.out.println("BankAccessBean.getBankStatus()");_x000D_
String status = "database onbereikbaar";_x000D_
try_x000D_
{_x000D_
status = loginBean.getBankIsOpen() ? "bank is open" : "bank is closed";_x000D_
status += loginBean.getTransactionManagerIsIdle() ? " and idle" : " and busy";_x000D_
}_x000D_
catch (Throwable t)_x000D_
{_x000D_
t.printStackTrace();_x000D_
}_x000D_
return status;_x000D_
}_x000D_
_x000D_
public String logout()_x000D_
{_x000D_
System.out.println("BankAccessBean.logout()");_x000D_
// zie jboss-web.xml : flushOnSessionInvalidation_x000D_
// dat zorgt dat logout() op de loginmodules gecalled wordt_x000D_
// en alle rechten weer netjes ingetrokken worden_x000D_
if (false)_x000D_
{_x000D_
try_x000D_
{_x000D_
if (accountOffice.getPendingTransactions(accountNumber).length > 0)_x000D_
{_x000D_
addMessage(FacesMessage.SEVERITY_ERROR, "Kan niet uitloggen als er nog transacties open staan.");_x000D_
return "transactionLeft";_x000D_
}_x000D_
}_x000D_
catch (BankException e)_x000D_
{_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
HttpSession session = (HttpSession) getExternalContext().getSession(false);_x000D_
if (session != null)_x000D_
{_x000D_
session.invalidate();_x000D_
}_x000D_
return "logoutOutcome";_x000D_
}_x000D_
_x000D_
public String login()_x000D_
{_x000D_
System.out.println("BankAccessBean.login()");_x000D_
_x000D_
ExternalContext ec = getExternalContext();_x000D_
boolean error = false;_x000D_
// alleen maar inloggen als de user nog niet ingelogd is_x000D_
if (ec.getRemoteUser() == null)_x000D_
{_x000D_
try_x000D_
{_x000D_
// de callbackHandler die WebAuthentication opbouwt voor zijn username + credentials parameters_x000D_
// delegeert onbekende callbacks naar deze callbackHandler_x000D_
// zo kunnen we dus communiceren via de callbacks_x000D_
// doc: http://docs.jboss.org/jbossas/javadoc/4.0.5/security/org/jboss/security/auth/callback/CallbackHandlerPolicyContextHandler.html_x000D_
// doc: https://jira.jboss.org/jira/browse/JBAS-2345_x000D_
CallbackHandlerPolicyContextHandler.setCallbackHandler(new MyCallbackHandler(this));_x000D_
_x000D_
// doe de programmatic web logon:_x000D_
// doc: http://jboss.org/community/docs/DOC-12656_x000D_
// dit object doet zowel authentication als authorization_x000D_
WebAuthentication wa = new WebAuthentication();_x000D_
boolean success = wa.login(username, password);_x000D_
if (!success)_x000D_
{_x000D_
error = true;_x000D_
// gespecificeerd in:_x000D_
// https://jira.jboss.org/jira/browse/SECURITY-278?focusedCommentId=12433231#action_12433231_x000D_
Object o = SecurityAssociation.getContextInfo("org.jboss.security.exception");_x000D_
if (o instanceof LoginException)_x000D_
{_x000D_
LoginException le = (LoginException) o;_x000D_
addMessage(FacesMessage.SEVERITY_ERROR, "Login fout: " + le.getMessage());_x000D_
}_x000D_
else_x000D_
{_x000D_
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");_x000D_
}_x000D_
}_x000D_
}_x000D_
catch (Throwable t)_x000D_
{_x000D_
error = true;_x000D_
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");_x000D_
t.printStackTrace();_x000D_
}_x000D_
}_x000D_
_x000D_
// mogelijke outcomes<SUF>
// zie JSF navigation rules in faces-config.xml_x000D_
if (error)_x000D_
return "loginError";_x000D_
if (ec.isUserInRole("AccountManager"))_x000D_
return "loggedInAsAccountManager";_x000D_
if (ec.isUserInRole("AccountOffice"))_x000D_
return "loggedInAsAccountOffice";_x000D_
_x000D_
// kom hier uit als JBoss iets geks doet:_x000D_
// de authenticatie is gelukt, maar de authorisatie is mislukt_x000D_
addMessage(FacesMessage.SEVERITY_ERROR, "Systeem fout");_x000D_
return "loginError";_x000D_
}_x000D_
_x000D_
public String getUsername()_x000D_
{_x000D_
return username;_x000D_
}_x000D_
_x000D_
public void setUsername(String username)_x000D_
{_x000D_
this.username = username;_x000D_
}_x000D_
_x000D_
public String getPassword()_x000D_
{_x000D_
return password;_x000D_
}_x000D_
_x000D_
public void setPassword(String password)_x000D_
{_x000D_
this.password = password;_x000D_
}_x000D_
_x000D_
public String getCaptcha()_x000D_
{_x000D_
return captcha;_x000D_
}_x000D_
_x000D_
public void setCaptcha(String captcha)_x000D_
{_x000D_
this.captcha = captcha;_x000D_
}_x000D_
_x000D_
/**_x000D_
* for jaas mycallbackhandler_x000D_
*/_x000D_
public LoginBeanIF getLoginBean()_x000D_
{_x000D_
return loginBean;_x000D_
}_x000D_
_x000D_
public AccountManagerIF getAccountManager()_x000D_
{_x000D_
return accountManager;_x000D_
}_x000D_
_x000D_
public AccountOfficeIF getAccountOffice()_x000D_
{_x000D_
return accountOffice;_x000D_
}_x000D_
_x000D_
public long getAccountNumber()_x000D_
{_x000D_
return accountNumber;_x000D_
}_x000D_
_x000D_
public void setAccountNumber(long accountNumber)_x000D_
{_x000D_
this.accountNumber = accountNumber;_x000D_
}_x000D_
} | True | 2,743 | 12 | 3,112 | 16 | 3,051 | 13 | 3,112 | 16 | 3,439 | 15 | false | false | false | false | false | true |
2,785 | 177168_8 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.cat.csw20.impl;
import net.opengis.cat.csw20.Csw20Package;
import net.opengis.cat.csw20.EchoedRequestType;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.BasicFeatureMap;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Echoed Request Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link net.opengis.cat.csw20.impl.EchoedRequestTypeImpl#getAny <em>Any</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class EchoedRequestTypeImpl extends EObjectImpl implements EchoedRequestType {
/**
* The cached value of the '{@link #getAny() <em>Any</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAny()
* @generated
* @ordered
*/
protected FeatureMap any;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EchoedRequestTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Csw20Package.Literals.ECHOED_REQUEST_TYPE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public FeatureMap getAny() {
if (any == null) {
any = new BasicFeatureMap(this, Csw20Package.ECHOED_REQUEST_TYPE__ANY);
}
return any;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Csw20Package.ECHOED_REQUEST_TYPE__ANY:
return ((InternalEList<?>)getAny()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Csw20Package.ECHOED_REQUEST_TYPE__ANY:
if (coreType) return getAny();
return ((FeatureMap.Internal)getAny()).getWrapper();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Csw20Package.ECHOED_REQUEST_TYPE__ANY:
((FeatureMap.Internal)getAny()).set(newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Csw20Package.ECHOED_REQUEST_TYPE__ANY:
getAny().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Csw20Package.ECHOED_REQUEST_TYPE__ANY:
return any != null && !any.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (any: ");
result.append(any);
result.append(')');
return result.toString();
}
} //EchoedRequestTypeImpl
| geotools/geotools | modules/ogc/net.opengis.csw/src/net/opengis/cat/csw20/impl/EchoedRequestTypeImpl.java | 1,346 | /**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | block_comment | nl | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.cat.csw20.impl;
import net.opengis.cat.csw20.Csw20Package;
import net.opengis.cat.csw20.EchoedRequestType;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.BasicFeatureMap;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Echoed Request Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link net.opengis.cat.csw20.impl.EchoedRequestTypeImpl#getAny <em>Any</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class EchoedRequestTypeImpl extends EObjectImpl implements EchoedRequestType {
/**
* The cached value of the '{@link #getAny() <em>Any</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAny()
* @generated
* @ordered
*/
protected FeatureMap any;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EchoedRequestTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Csw20Package.Literals.ECHOED_REQUEST_TYPE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public FeatureMap getAny() {
if (any == null) {
any = new BasicFeatureMap(this, Csw20Package.ECHOED_REQUEST_TYPE__ANY);
}
return any;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Csw20Package.ECHOED_REQUEST_TYPE__ANY:
return ((InternalEList<?>)getAny()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Csw20Package.ECHOED_REQUEST_TYPE__ANY:
if (coreType) return getAny();
return ((FeatureMap.Internal)getAny()).getWrapper();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc --><SUF>*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Csw20Package.ECHOED_REQUEST_TYPE__ANY:
((FeatureMap.Internal)getAny()).set(newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Csw20Package.ECHOED_REQUEST_TYPE__ANY:
getAny().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Csw20Package.ECHOED_REQUEST_TYPE__ANY:
return any != null && !any.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (any: ");
result.append(any);
result.append(')');
return result.toString();
}
} //EchoedRequestTypeImpl
| False | 1,011 | 22 | 1,156 | 25 | 1,248 | 29 | 1,156 | 25 | 1,363 | 29 | false | false | false | false | false | true |
1,012 | 91775_3 | package database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Centraliseert gedeelde database bewerkingen
* @author Remi De Boer, Gerke de Boer, Michael Oosterhout
*/
public abstract class AbstractDAO {
protected DBaccess dBaccess;
protected PreparedStatement preparedStatement;
public AbstractDAO(DBaccess dBaccess) {
this.dBaccess = dBaccess;
}
/**
* Maakt een preparedStatement voor de sql string. Een DAO gebruikt dit om de parameters te vullen.
*
* @param sql,
* de SQl query
*/
protected void setupPreparedStatement(String sql) throws SQLException {
preparedStatement = dBaccess.getConnection().prepareStatement(sql);
}
/**
* Voert de preparedStatement uit zonder een ResultSet. Wordt gebruikt voor insert, update en
* delete statements.
*
*/
protected void executeManipulateStatement() throws SQLException {
preparedStatement.executeUpdate();
}
/**
* Voert de preparedStatement uit met een ResultSet. Wordt gebruikt voor select statements.
*
*/
protected ResultSet executeSelectStatement() throws SQLException {
return preparedStatement.executeQuery();
}
/**
* Maakt een preparedStatement voor de sql string, die een gegenereerde sleutel terug moet geven.
* @param sql,
* de SQL query
*/
protected void setupPreparedStatementWithKey(String sql) throws SQLException {
preparedStatement = dBaccess.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
}
/**
* Voert de prepared statement uit en geeft de gegenereerde sleutel terug.
* Wordt gebruikt voor een insert in een AutoIncrement tabel
*/
protected int executeInsertStatementWithKey() throws SQLException {
preparedStatement.executeUpdate();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
int gegenereerdeSleutel = 0;
while (resultSet.next()) {
gegenereerdeSleutel = resultSet.getInt(1);
}
return gegenereerdeSleutel;
}
}
| MIW-G-C6/Meetkunde | src/database/AbstractDAO.java | 613 | /**
* Voert de preparedStatement uit met een ResultSet. Wordt gebruikt voor select statements.
*
*/ | block_comment | nl | package database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Centraliseert gedeelde database bewerkingen
* @author Remi De Boer, Gerke de Boer, Michael Oosterhout
*/
public abstract class AbstractDAO {
protected DBaccess dBaccess;
protected PreparedStatement preparedStatement;
public AbstractDAO(DBaccess dBaccess) {
this.dBaccess = dBaccess;
}
/**
* Maakt een preparedStatement voor de sql string. Een DAO gebruikt dit om de parameters te vullen.
*
* @param sql,
* de SQl query
*/
protected void setupPreparedStatement(String sql) throws SQLException {
preparedStatement = dBaccess.getConnection().prepareStatement(sql);
}
/**
* Voert de preparedStatement uit zonder een ResultSet. Wordt gebruikt voor insert, update en
* delete statements.
*
*/
protected void executeManipulateStatement() throws SQLException {
preparedStatement.executeUpdate();
}
/**
* Voert de preparedStatement<SUF>*/
protected ResultSet executeSelectStatement() throws SQLException {
return preparedStatement.executeQuery();
}
/**
* Maakt een preparedStatement voor de sql string, die een gegenereerde sleutel terug moet geven.
* @param sql,
* de SQL query
*/
protected void setupPreparedStatementWithKey(String sql) throws SQLException {
preparedStatement = dBaccess.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
}
/**
* Voert de prepared statement uit en geeft de gegenereerde sleutel terug.
* Wordt gebruikt voor een insert in een AutoIncrement tabel
*/
protected int executeInsertStatementWithKey() throws SQLException {
preparedStatement.executeUpdate();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
int gegenereerdeSleutel = 0;
while (resultSet.next()) {
gegenereerdeSleutel = resultSet.getInt(1);
}
return gegenereerdeSleutel;
}
}
| True | 444 | 24 | 519 | 24 | 515 | 27 | 519 | 24 | 613 | 29 | false | false | false | false | false | true |
1,128 | 10277_0 | package ss.week7;_x000D_
_x000D_
import java.util.concurrent.locks.Lock;_x000D_
import java.util.concurrent.locks.ReentrantLock;_x000D_
_x000D_
public class ConcatThread extends Thread {_x000D_
private static String text = ""; // global variable_x000D_
private String toe; // niet static dus deze word nooit overschreven_x000D_
private static Lock l = new ReentrantLock();_x000D_
_x000D_
public ConcatThread(String toeArg) {_x000D_
this.toe = toeArg;_x000D_
}_x000D_
_x000D_
public void run() {_x000D_
l.lock();_x000D_
text = text.concat(toe); _x000D_
l.unlock();_x000D_
}_x000D_
_x000D_
public static void main(String[] args) {_x000D_
(new ConcatThread("one;")).start();_x000D_
(new ConcatThread("two;")).start();_x000D_
_x000D_
try {_x000D_
Thread.sleep(100);_x000D_
} catch (InterruptedException e) {_x000D_
e.getMessage();_x000D_
}_x000D_
System.out.println(text);_x000D_
_x000D_
}_x000D_
}_x000D_
| MinThaMie/Opdrachten | softwaresystems/src/ss/week7/ConcatThread.java | 253 | // niet static dus deze word nooit overschreven_x000D_ | line_comment | nl | package ss.week7;_x000D_
_x000D_
import java.util.concurrent.locks.Lock;_x000D_
import java.util.concurrent.locks.ReentrantLock;_x000D_
_x000D_
public class ConcatThread extends Thread {_x000D_
private static String text = ""; // global variable_x000D_
private String toe; // niet static<SUF>
private static Lock l = new ReentrantLock();_x000D_
_x000D_
public ConcatThread(String toeArg) {_x000D_
this.toe = toeArg;_x000D_
}_x000D_
_x000D_
public void run() {_x000D_
l.lock();_x000D_
text = text.concat(toe); _x000D_
l.unlock();_x000D_
}_x000D_
_x000D_
public static void main(String[] args) {_x000D_
(new ConcatThread("one;")).start();_x000D_
(new ConcatThread("two;")).start();_x000D_
_x000D_
try {_x000D_
Thread.sleep(100);_x000D_
} catch (InterruptedException e) {_x000D_
e.getMessage();_x000D_
}_x000D_
System.out.println(text);_x000D_
_x000D_
}_x000D_
}_x000D_
| True | 385 | 18 | 449 | 21 | 450 | 17 | 449 | 21 | 483 | 18 | false | false | false | false | false | true |
1,105 | 110005_5 | package husacct.validate.domain.factory.violationtype;
import husacct.validate.domain.configuration.ConfigurationServiceImpl;
import husacct.validate.domain.exception.ProgrammingLanguageNotFoundException;
import husacct.validate.domain.exception.RuleTypeNotFoundException;
import husacct.validate.domain.exception.SeverityNotFoundException;
import husacct.validate.domain.exception.ViolationTypeNotFoundException;
import husacct.validate.domain.validation.Severity;
import husacct.validate.domain.validation.ViolationType;
import husacct.validate.domain.validation.internaltransferobjects.CategoryKeySeverityDTO;
import husacct.validate.domain.validation.ruletype.RuleTypes;
import husacct.validate.domain.validation.violationtype.IViolationType;
import java.awt.Color;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
public abstract class AbstractViolationType {
private Logger logger = Logger.getLogger(AbstractViolationType.class);
private final ConfigurationServiceImpl configuration;
protected List<CategoryKeySeverityDTO> allViolationKeys;
protected String languageName;
public abstract List<ViolationType> createViolationTypesByRule(String key);
abstract List<IViolationType> createViolationTypesMetaData();
AbstractViolationType(ConfigurationServiceImpl configuration, String languageName) {
this.configuration = configuration;
this.languageName = languageName;
ViolationtypeGenerator generator = new ViolationtypeGenerator();
this.allViolationKeys = generator.getAllViolationTypes(createViolationTypesMetaData());
}
protected List<ViolationType> generateViolationTypes(String ruleTypeKey, EnumSet<?> enums) {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
for (Enum<?> enumValue : enums) {
ViolationType violationtype = generateViolationType(ruleTypeKey, enumValue);
violationtypes.add(violationtype);
}
return violationtypes;
}
public HashMap<String, List<ViolationType>> getAllViolationTypes() {
return getAllViolationTypes(allViolationKeys);
}
protected HashMap<String, List<ViolationType>> getAllViolationTypes(List<CategoryKeySeverityDTO> keyList) {
HashMap<String, List<ViolationType>> categoryViolations = new HashMap<String, List<ViolationType>>();
for (CategoryKeySeverityDTO dto : keyList) {
if (categoryViolations.containsKey(dto.getCategory())) {
List<ViolationType> violationtypes = categoryViolations.get(dto.getCategory());
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
} else {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
categoryViolations.put(dto.getCategory(), violationtypes);
}
}
return categoryViolations;
}
private ViolationType createViolationType(String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
final Severity severity = createSeverity(languageName, violationTypeKey);
return new ViolationType(violationTypeKey, severity);
} else {
logger.warn(String.format("Warning specified %s not found in the system", violationTypeKey));
}
throw new ViolationTypeNotFoundException();
}
public ViolationType createViolationType(String ruleTypeKey, String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
//System.err.println("ADD key: " + violationtype.getKey() + " - category: " + violationtype.getCategory());
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
//System.err.println("CREATE " + violationTypeKey.toLowerCase());
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
try {
//System.out.println("GIVEN ruleTypeKey: " + ruleTypeKey + " violationTypeKey: " + violationTypeKey);
final Severity severity = createSeverity(languageName, violationTypeKey);
boolean enabled = configuration.isViolationEnabled(languageName, ruleTypeKey, violationTypeKey);
return new ViolationType(violationTypeKey, enabled, severity);
} catch (ProgrammingLanguageNotFoundException e) {
logger.warn(String.format("ProgrammingLanguage %s not found", languageName));
} catch (RuleTypeNotFoundException e) {
logger.warn(String.format("RuleTypeKey: %s not found", ruleTypeKey));
} catch (ViolationTypeNotFoundException e) {
logger.warn(String.format("ViolationTypeKey: %s not found", violationTypeKey));
}
} else {
//logger.warn(String.format("Warning specified %s not found in the system and or configuration", violationTypeKey));
return new ViolationType("", false, new Severity("", Color.GREEN));
}
// //Verbeteren
//return new ViolationType("", false, new Severity("", Color.GREEN));
throw new ViolationTypeNotFoundException(); //TODO: Onaangekondige dependencyTypes ondersteunen (van team Define)
}
private ViolationType generateViolationType(String ruleTypeKey, Enum<?> enumValue) {
final Severity severity = createSeverity(languageName, enumValue.toString());
final boolean isEnabled = configuration.isViolationEnabled(languageName, ruleTypeKey, enumValue.toString());
return new ViolationType(enumValue.toString(), isEnabled, severity);
}
protected boolean isCategoryLegalityOfDependency(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.IS_ONLY_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_THE_ONLY_MODULE_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.MUST_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_BACK_CALL.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_SKIP_CALL.toString())) {
return true;
} else {
return false;
}
}
protected boolean isVisibilityConventionRule(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isNamingConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isInheritanceConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.INHERITANCE_CONVENTION)) {
return true;
} else {
return false;
}
}
private Severity createSeverity(String programmingLanguage, String violationKey) {
try {
return configuration.getSeverityFromKey(programmingLanguage, violationKey);
} catch (SeverityNotFoundException e) {
CategoryKeySeverityDTO violation = getCategoryKeySeverityDTO(violationKey);
if (violation != null) {
return configuration.getSeverityByName(violation.getDefaultSeverity().toString());
}
}
return null;
}
private CategoryKeySeverityDTO getCategoryKeySeverityDTO(String violationKey) {
for (CategoryKeySeverityDTO violation : allViolationKeys) {
if (violation.getKey().toLowerCase().equals(violationKey.toLowerCase())) {
return violation;
}
}
return null;
}
} | Mestway/Patl4J | examples/statistics/husacct/src/husacct/validate/domain/factory/violationtype/AbstractViolationType.java | 2,278 | //TODO: Onaangekondige dependencyTypes ondersteunen (van team Define) | line_comment | nl | package husacct.validate.domain.factory.violationtype;
import husacct.validate.domain.configuration.ConfigurationServiceImpl;
import husacct.validate.domain.exception.ProgrammingLanguageNotFoundException;
import husacct.validate.domain.exception.RuleTypeNotFoundException;
import husacct.validate.domain.exception.SeverityNotFoundException;
import husacct.validate.domain.exception.ViolationTypeNotFoundException;
import husacct.validate.domain.validation.Severity;
import husacct.validate.domain.validation.ViolationType;
import husacct.validate.domain.validation.internaltransferobjects.CategoryKeySeverityDTO;
import husacct.validate.domain.validation.ruletype.RuleTypes;
import husacct.validate.domain.validation.violationtype.IViolationType;
import java.awt.Color;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
public abstract class AbstractViolationType {
private Logger logger = Logger.getLogger(AbstractViolationType.class);
private final ConfigurationServiceImpl configuration;
protected List<CategoryKeySeverityDTO> allViolationKeys;
protected String languageName;
public abstract List<ViolationType> createViolationTypesByRule(String key);
abstract List<IViolationType> createViolationTypesMetaData();
AbstractViolationType(ConfigurationServiceImpl configuration, String languageName) {
this.configuration = configuration;
this.languageName = languageName;
ViolationtypeGenerator generator = new ViolationtypeGenerator();
this.allViolationKeys = generator.getAllViolationTypes(createViolationTypesMetaData());
}
protected List<ViolationType> generateViolationTypes(String ruleTypeKey, EnumSet<?> enums) {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
for (Enum<?> enumValue : enums) {
ViolationType violationtype = generateViolationType(ruleTypeKey, enumValue);
violationtypes.add(violationtype);
}
return violationtypes;
}
public HashMap<String, List<ViolationType>> getAllViolationTypes() {
return getAllViolationTypes(allViolationKeys);
}
protected HashMap<String, List<ViolationType>> getAllViolationTypes(List<CategoryKeySeverityDTO> keyList) {
HashMap<String, List<ViolationType>> categoryViolations = new HashMap<String, List<ViolationType>>();
for (CategoryKeySeverityDTO dto : keyList) {
if (categoryViolations.containsKey(dto.getCategory())) {
List<ViolationType> violationtypes = categoryViolations.get(dto.getCategory());
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
} else {
List<ViolationType> violationtypes = new ArrayList<ViolationType>();
ViolationType violationtype = createViolationType(dto.getKey());
violationtypes.add(violationtype);
categoryViolations.put(dto.getCategory(), violationtypes);
}
}
return categoryViolations;
}
private ViolationType createViolationType(String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
final Severity severity = createSeverity(languageName, violationTypeKey);
return new ViolationType(violationTypeKey, severity);
} else {
logger.warn(String.format("Warning specified %s not found in the system", violationTypeKey));
}
throw new ViolationTypeNotFoundException();
}
public ViolationType createViolationType(String ruleTypeKey, String violationTypeKey) {
List<String> violationKeysToLower = new ArrayList<String>();
for (CategoryKeySeverityDTO violationtype : allViolationKeys) {
//System.err.println("ADD key: " + violationtype.getKey() + " - category: " + violationtype.getCategory());
violationKeysToLower.add(violationtype.getKey().toLowerCase());
}
//System.err.println("CREATE " + violationTypeKey.toLowerCase());
if (violationKeysToLower.contains(violationTypeKey.toLowerCase())) {
try {
//System.out.println("GIVEN ruleTypeKey: " + ruleTypeKey + " violationTypeKey: " + violationTypeKey);
final Severity severity = createSeverity(languageName, violationTypeKey);
boolean enabled = configuration.isViolationEnabled(languageName, ruleTypeKey, violationTypeKey);
return new ViolationType(violationTypeKey, enabled, severity);
} catch (ProgrammingLanguageNotFoundException e) {
logger.warn(String.format("ProgrammingLanguage %s not found", languageName));
} catch (RuleTypeNotFoundException e) {
logger.warn(String.format("RuleTypeKey: %s not found", ruleTypeKey));
} catch (ViolationTypeNotFoundException e) {
logger.warn(String.format("ViolationTypeKey: %s not found", violationTypeKey));
}
} else {
//logger.warn(String.format("Warning specified %s not found in the system and or configuration", violationTypeKey));
return new ViolationType("", false, new Severity("", Color.GREEN));
}
// //Verbeteren
//return new ViolationType("", false, new Severity("", Color.GREEN));
throw new ViolationTypeNotFoundException(); //TODO: Onaangekondige<SUF>
}
private ViolationType generateViolationType(String ruleTypeKey, Enum<?> enumValue) {
final Severity severity = createSeverity(languageName, enumValue.toString());
final boolean isEnabled = configuration.isViolationEnabled(languageName, ruleTypeKey, enumValue.toString());
return new ViolationType(enumValue.toString(), isEnabled, severity);
}
protected boolean isCategoryLegalityOfDependency(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.IS_ONLY_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_THE_ONLY_MODULE_ALLOWED_TO_USE.toString()) || ruleTypeKey.equals(RuleTypes.MUST_USE.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_BACK_CALL.toString()) || ruleTypeKey.equals(RuleTypes.IS_NOT_ALLOWED_SKIP_CALL.toString())) {
return true;
} else {
return false;
}
}
protected boolean isVisibilityConventionRule(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.VISIBILITY_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isNamingConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION.toString()) || ruleTypeKey.equals(RuleTypes.NAMING_CONVENTION_EXCEPTION.toString())) {
return true;
} else {
return false;
}
}
protected boolean isInheritanceConvention(String ruleTypeKey) {
if (ruleTypeKey.equals(RuleTypes.INHERITANCE_CONVENTION)) {
return true;
} else {
return false;
}
}
private Severity createSeverity(String programmingLanguage, String violationKey) {
try {
return configuration.getSeverityFromKey(programmingLanguage, violationKey);
} catch (SeverityNotFoundException e) {
CategoryKeySeverityDTO violation = getCategoryKeySeverityDTO(violationKey);
if (violation != null) {
return configuration.getSeverityByName(violation.getDefaultSeverity().toString());
}
}
return null;
}
private CategoryKeySeverityDTO getCategoryKeySeverityDTO(String violationKey) {
for (CategoryKeySeverityDTO violation : allViolationKeys) {
if (violation.getKey().toLowerCase().equals(violationKey.toLowerCase())) {
return violation;
}
}
return null;
}
} | True | 1,682 | 20 | 2,005 | 19 | 1,971 | 16 | 2,005 | 19 | 2,531 | 21 | false | false | false | false | false | true |
3,950 | 200855_4 | // Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package com.twitter.intellij.pants.service.project.model;
import com.intellij.openapi.util.Condition;
import com.intellij.util.containers.ContainerUtil;
import com.twitter.intellij.pants.model.PantsSourceType;
import com.twitter.intellij.pants.model.TargetAddressInfo;
import com.twitter.intellij.pants.util.PantsScalaUtil;
import com.twitter.intellij.pants.util.PantsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class TargetInfo {
protected Set<TargetAddressInfo> addressInfos = Collections.emptySet();
/**
* List of libraries. Just names.
*/
protected Set<String> libraries = Collections.emptySet();
/**
* List of libraries. Just names.
*/
protected Set<String> excludes = Collections.emptySet();
/**
* List of dependencies.
*/
protected Set<String> targets = Collections.emptySet();
/**
* List of source roots.
*/
protected Set<ContentRoot> roots = Collections.emptySet();
public TargetInfo(TargetAddressInfo... addressInfos) {
setAddressInfos(ContainerUtil.newHashSet(addressInfos));
}
public TargetInfo(
Set<TargetAddressInfo> addressInfos,
Set<String> targets,
Set<String> libraries,
Set<String> excludes,
Set<ContentRoot> roots
) {
setAddressInfos(addressInfos);
setLibraries(libraries);
setExcludes(excludes);
setTargets(targets);
setRoots(roots);
}
public Set<TargetAddressInfo> getAddressInfos() {
return addressInfos;
}
public void setAddressInfos(Set<TargetAddressInfo> addressInfos) {
this.addressInfos = addressInfos;
}
@NotNull
public Set<String> getLibraries() {
return libraries;
}
public void setLibraries(Set<String> libraries) {
this.libraries = new TreeSet<>(libraries);
}
@NotNull
public Set<String> getExcludes() {
return excludes;
}
public void setExcludes(Set<String> excludes) {
this.excludes = new TreeSet<>(excludes);
}
@NotNull
public Set<String> getTargets() {
return targets;
}
public void setTargets(Set<String> targets) {
this.targets = new TreeSet<>(targets);
}
@NotNull
public Set<ContentRoot> getRoots() {
return roots;
}
public void setRoots(Set<ContentRoot> roots) {
this.roots = new TreeSet<>(roots);
}
public boolean isEmpty() {
return libraries.isEmpty() && targets.isEmpty() && roots.isEmpty() && addressInfos.isEmpty();
}
@Nullable
public String findScalaLibId() {
return ContainerUtil.find(
libraries,
new Condition<String>() {
@Override
public boolean value(String libraryId) {
return PantsScalaUtil.isScalaLibraryLib(libraryId);
}
}
);
}
public boolean isTest() {
return ContainerUtil.exists(
getAddressInfos(),
new Condition<TargetAddressInfo>() {
@Override
public boolean value(TargetAddressInfo info) {
return PantsUtil.getSourceTypeForTargetType(info.getTargetType(), info.isSynthetic()).toExternalSystemSourceType().isTest();
}
}
);
}
@NotNull
public PantsSourceType getSourcesType() {
// In the case where multiple targets get combined into one module,
// the type of common module should be in the order of
// source -> test source -> resource -> test resources. (like Ranked Value in Pants options)
// e.g. if source and resources get combined, the common module should be source type.
Set<PantsSourceType> allTypes = getAddressInfos().stream()
.map(s -> PantsUtil.getSourceTypeForTargetType(s.getTargetType(), s.isSynthetic()))
.collect(Collectors.toSet());
Optional<PantsSourceType> topRankedType = Arrays.stream(PantsSourceType.values())
.filter(allTypes::contains)
.findFirst();
if (topRankedType.isPresent()) {
return topRankedType.get();
}
return PantsSourceType.SOURCE;
}
public boolean isJarLibrary() {
return getAddressInfos().stream().allMatch(TargetAddressInfo::isJarLibrary);
}
public boolean isScalaTarget() {
return getAddressInfos().stream().anyMatch(TargetAddressInfo::isScala) ||
// TODO(yic): have Pants export `pants_target_type` correctly
// because `thrift-scala` also has the type `java_thrift_library`
getAddressInfos().stream().anyMatch(s -> s.getTargetAddress().endsWith("-scala"));
}
public boolean isPythonTarget() {
return getAddressInfos().stream().anyMatch(TargetAddressInfo::isPython);
}
public boolean dependOn(@NotNull String targetName) {
return targets.contains(targetName);
}
public void addDependency(@NotNull String targetName) {
if (targets.isEmpty()) {
targets = new HashSet<>(Collections.singletonList(targetName));
}
else {
targets.add(targetName);
}
}
public boolean removeDependency(@NotNull String targetName) {
return getTargets().remove(targetName);
}
public void replaceDependency(@NotNull String targetName, @NotNull String newTargetName) {
if (removeDependency(targetName)) {
addDependency(newTargetName);
}
}
public TargetInfo union(@NotNull TargetInfo other) {
return new TargetInfo(
ContainerUtil.union(getAddressInfos(), other.getAddressInfos()),
ContainerUtil.union(getTargets(), other.getTargets()),
ContainerUtil.union(getLibraries(), other.getLibraries()),
ContainerUtil.union(getExcludes(), other.getExcludes()),
ContainerUtil.union(getRoots(), other.getRoots())
);
}
@Override
public String toString() {
return "TargetInfo{" +
"libraries=" + libraries +
", excludes=" + excludes +
", targets=" + targets +
", roots=" + roots +
", addressInfos='" + addressInfos + '\'' +
'}';
}
}
| pantsbuild/intellij-pants-plugin | src/main/scala/com/twitter/intellij/pants/service/project/model/TargetInfo.java | 1,868 | /**
* List of dependencies.
*/ | block_comment | nl | // Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package com.twitter.intellij.pants.service.project.model;
import com.intellij.openapi.util.Condition;
import com.intellij.util.containers.ContainerUtil;
import com.twitter.intellij.pants.model.PantsSourceType;
import com.twitter.intellij.pants.model.TargetAddressInfo;
import com.twitter.intellij.pants.util.PantsScalaUtil;
import com.twitter.intellij.pants.util.PantsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class TargetInfo {
protected Set<TargetAddressInfo> addressInfos = Collections.emptySet();
/**
* List of libraries. Just names.
*/
protected Set<String> libraries = Collections.emptySet();
/**
* List of libraries. Just names.
*/
protected Set<String> excludes = Collections.emptySet();
/**
* List of dependencies.<SUF>*/
protected Set<String> targets = Collections.emptySet();
/**
* List of source roots.
*/
protected Set<ContentRoot> roots = Collections.emptySet();
public TargetInfo(TargetAddressInfo... addressInfos) {
setAddressInfos(ContainerUtil.newHashSet(addressInfos));
}
public TargetInfo(
Set<TargetAddressInfo> addressInfos,
Set<String> targets,
Set<String> libraries,
Set<String> excludes,
Set<ContentRoot> roots
) {
setAddressInfos(addressInfos);
setLibraries(libraries);
setExcludes(excludes);
setTargets(targets);
setRoots(roots);
}
public Set<TargetAddressInfo> getAddressInfos() {
return addressInfos;
}
public void setAddressInfos(Set<TargetAddressInfo> addressInfos) {
this.addressInfos = addressInfos;
}
@NotNull
public Set<String> getLibraries() {
return libraries;
}
public void setLibraries(Set<String> libraries) {
this.libraries = new TreeSet<>(libraries);
}
@NotNull
public Set<String> getExcludes() {
return excludes;
}
public void setExcludes(Set<String> excludes) {
this.excludes = new TreeSet<>(excludes);
}
@NotNull
public Set<String> getTargets() {
return targets;
}
public void setTargets(Set<String> targets) {
this.targets = new TreeSet<>(targets);
}
@NotNull
public Set<ContentRoot> getRoots() {
return roots;
}
public void setRoots(Set<ContentRoot> roots) {
this.roots = new TreeSet<>(roots);
}
public boolean isEmpty() {
return libraries.isEmpty() && targets.isEmpty() && roots.isEmpty() && addressInfos.isEmpty();
}
@Nullable
public String findScalaLibId() {
return ContainerUtil.find(
libraries,
new Condition<String>() {
@Override
public boolean value(String libraryId) {
return PantsScalaUtil.isScalaLibraryLib(libraryId);
}
}
);
}
public boolean isTest() {
return ContainerUtil.exists(
getAddressInfos(),
new Condition<TargetAddressInfo>() {
@Override
public boolean value(TargetAddressInfo info) {
return PantsUtil.getSourceTypeForTargetType(info.getTargetType(), info.isSynthetic()).toExternalSystemSourceType().isTest();
}
}
);
}
@NotNull
public PantsSourceType getSourcesType() {
// In the case where multiple targets get combined into one module,
// the type of common module should be in the order of
// source -> test source -> resource -> test resources. (like Ranked Value in Pants options)
// e.g. if source and resources get combined, the common module should be source type.
Set<PantsSourceType> allTypes = getAddressInfos().stream()
.map(s -> PantsUtil.getSourceTypeForTargetType(s.getTargetType(), s.isSynthetic()))
.collect(Collectors.toSet());
Optional<PantsSourceType> topRankedType = Arrays.stream(PantsSourceType.values())
.filter(allTypes::contains)
.findFirst();
if (topRankedType.isPresent()) {
return topRankedType.get();
}
return PantsSourceType.SOURCE;
}
public boolean isJarLibrary() {
return getAddressInfos().stream().allMatch(TargetAddressInfo::isJarLibrary);
}
public boolean isScalaTarget() {
return getAddressInfos().stream().anyMatch(TargetAddressInfo::isScala) ||
// TODO(yic): have Pants export `pants_target_type` correctly
// because `thrift-scala` also has the type `java_thrift_library`
getAddressInfos().stream().anyMatch(s -> s.getTargetAddress().endsWith("-scala"));
}
public boolean isPythonTarget() {
return getAddressInfos().stream().anyMatch(TargetAddressInfo::isPython);
}
public boolean dependOn(@NotNull String targetName) {
return targets.contains(targetName);
}
public void addDependency(@NotNull String targetName) {
if (targets.isEmpty()) {
targets = new HashSet<>(Collections.singletonList(targetName));
}
else {
targets.add(targetName);
}
}
public boolean removeDependency(@NotNull String targetName) {
return getTargets().remove(targetName);
}
public void replaceDependency(@NotNull String targetName, @NotNull String newTargetName) {
if (removeDependency(targetName)) {
addDependency(newTargetName);
}
}
public TargetInfo union(@NotNull TargetInfo other) {
return new TargetInfo(
ContainerUtil.union(getAddressInfos(), other.getAddressInfos()),
ContainerUtil.union(getTargets(), other.getTargets()),
ContainerUtil.union(getLibraries(), other.getLibraries()),
ContainerUtil.union(getExcludes(), other.getExcludes()),
ContainerUtil.union(getRoots(), other.getRoots())
);
}
@Override
public String toString() {
return "TargetInfo{" +
"libraries=" + libraries +
", excludes=" + excludes +
", targets=" + targets +
", roots=" + roots +
", addressInfos='" + addressInfos + '\'' +
'}';
}
}
| False | 1,333 | 9 | 1,525 | 9 | 1,629 | 11 | 1,525 | 9 | 1,865 | 11 | false | false | false | false | false | true |
398 | 135658_2 | package util;
public final class Constants{
public static final byte PLATFORM_INTEL = 0x01;
public static final byte PLATFORM_POWERPC = 0x02;
public static final byte PLATFORM_MACOSX = 0x03;
public static final byte PRODUCT_STARCRAFT = 0x01;
public static final byte PRODUCT_BROODWAR = 0x02;
public static final byte PRODUCT_WAR2BNE = 0x03;
public static final byte PRODUCT_DIABLO2 = 0x04;
public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05;
public static final byte PRODUCT_JAPANSTARCRAFT = 0x06;
public static final byte PRODUCT_WARCRAFT3 = 0x07;
public static final byte PRODUCT_THEFROZENTHRONE = 0x08;
public static final byte PRODUCT_DIABLO = 0x09;
public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A;
public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B;
public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"};
public static String[][] IX86files = {
{"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"},
{"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"},
{"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"},
{"IX86/D2DV/", "Game.exe", "NULL", "NULL", "D2DV.bin"},
{"IX86/D2XP/", "Game.exe", "NULL", "NULL", "D2XP.bin"},
{"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"},
{"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"},
{"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"},
{"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"},
{"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"},
{"IX86/SSHR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "SSHR.bin"}
};
public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1E, 0x1E, 0x2a, 0x2a, 0xa5};
public static String[] IX86versions = {"", "", "2.0.2.1", "1.14.3.71", "1.14.3.71", "", "", "", "2001, 5, 18, 1", "", ""};
public static String[] IX86certs = {"", "", "", "", "", "", "", "", "", "", ""};
public static String ArchivePath = "DLLs/";
public static String LogFilePath = "./Logs/";
public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)";
//public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)";
//public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)";
public static int maxThreads=500;
public static int BNLSPort=9367;
public static boolean requireAuthorization=false;
public static boolean trackStatistics=true;
public static int ipAuthStatus=1; //default is IPBans on
public static boolean displayPacketInfo=true;
public static boolean displayParseInfo=false;
public static boolean debugInfo=false;
public static boolean enableLogging = false;
public static int logKeepDuration = 7;
public static boolean RunAdmin = false;
public static String BotNetBotID = "";
public static String BotNetHubPW = "";
public static String BotNetDatabase = "";
public static String BotNetUsername = "";
public static String BotNetPassword = "";
public static String BotNetServer = "www.valhallalegends.com";
public static boolean LogStats = false;
public static String StatsUsername = "";
public static String StatsPassword = "";
public static String StatsDatabase = "";
public static String StatsServer = "localhost";
public static int StatsQueue = 10;
public static boolean StatsLogIps = false;
public static boolean StatsLogCRevs = true;
public static boolean StatsLogBotIDs = true;
public static boolean StatsLogConns = true;
public static boolean StatsCheckSchema = true;
public static String DownloadPath = "./";
public static boolean RunHTTP = true;
public static int HTTPPort = 81;
public static int lngServerVer=0x01;
public static int numOfNews=0;
public static String[] strNews={"", "", "", "", ""};
}
| Davnit/JBLS | util/Constants.java | 1,588 | //default is IPBans on | line_comment | nl | package util;
public final class Constants{
public static final byte PLATFORM_INTEL = 0x01;
public static final byte PLATFORM_POWERPC = 0x02;
public static final byte PLATFORM_MACOSX = 0x03;
public static final byte PRODUCT_STARCRAFT = 0x01;
public static final byte PRODUCT_BROODWAR = 0x02;
public static final byte PRODUCT_WAR2BNE = 0x03;
public static final byte PRODUCT_DIABLO2 = 0x04;
public static final byte PRODUCT_LORDOFDESTRUCTION = 0x05;
public static final byte PRODUCT_JAPANSTARCRAFT = 0x06;
public static final byte PRODUCT_WARCRAFT3 = 0x07;
public static final byte PRODUCT_THEFROZENTHRONE = 0x08;
public static final byte PRODUCT_DIABLO = 0x09;
public static final byte PRODUCT_DIABLOSHAREWARE = 0x0A;
public static final byte PRODUCT_STARCRAFTSHAREWARE= 0x0B;
public static String[] prods = {"STAR", "SEXP", "W2BN", "D2DV", "D2XP", "JSTR", "WAR3", "W3XP", "DRTL", "DSHR", "SSHR"};
public static String[][] IX86files = {
{"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"},
{"IX86/STAR/", "StarCraft.exe", "Storm.dll", "NULL", "STAR.bin"},
{"IX86/W2BN/", "Warcraft II BNE.exe", "Storm.dll", "Battle.snp", "W2BN.bin"},
{"IX86/D2DV/", "Game.exe", "NULL", "NULL", "D2DV.bin"},
{"IX86/D2XP/", "Game.exe", "NULL", "NULL", "D2XP.bin"},
{"IX86/JSTR/", "StarcraftJ.exe", "Storm.dll", "Battle.snp", "JSTR.bin"},
{"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"},
{"IX86/WAR3/", "Warcraft III.exe", "NULL", "NULL", "WAR3.bin"},
{"IX86/DRTL/", "Diablo.exe", "Storm.dll", "Battle.snp", "DRTL.bin"},
{"IX86/DSHR/", "Diablo_s.exe", "Storm.dll", "Battle.snp", "DSHR.bin"},
{"IX86/SSHR/", "Starcraft.exe", "Storm.dll", "Battle.snp", "SSHR.bin"}
};
public static int[] IX86verbytes = {0xD3, 0xD3, 0x4f, 0x0e, 0x0e, 0xa9, 0x1E, 0x1E, 0x2a, 0x2a, 0xa5};
public static String[] IX86versions = {"", "", "2.0.2.1", "1.14.3.71", "1.14.3.71", "", "", "", "2001, 5, 18, 1", "", ""};
public static String[] IX86certs = {"", "", "", "", "", "", "", "", "", "", ""};
public static String ArchivePath = "DLLs/";
public static String LogFilePath = "./Logs/";
public static String build="Build V3.1 Bug Fixes, SQL Stats tracking. (10-14-07)";
//public static String build="Build V3.0 BotNet Admin, Lockdown, Legacy Clients.(07-07-07)";
//public static String build="Build V2.9 Remote admin, extended admin commands w/ JSTR support.(01/18/06)";
public static int maxThreads=500;
public static int BNLSPort=9367;
public static boolean requireAuthorization=false;
public static boolean trackStatistics=true;
public static int ipAuthStatus=1; //default is<SUF>
public static boolean displayPacketInfo=true;
public static boolean displayParseInfo=false;
public static boolean debugInfo=false;
public static boolean enableLogging = false;
public static int logKeepDuration = 7;
public static boolean RunAdmin = false;
public static String BotNetBotID = "";
public static String BotNetHubPW = "";
public static String BotNetDatabase = "";
public static String BotNetUsername = "";
public static String BotNetPassword = "";
public static String BotNetServer = "www.valhallalegends.com";
public static boolean LogStats = false;
public static String StatsUsername = "";
public static String StatsPassword = "";
public static String StatsDatabase = "";
public static String StatsServer = "localhost";
public static int StatsQueue = 10;
public static boolean StatsLogIps = false;
public static boolean StatsLogCRevs = true;
public static boolean StatsLogBotIDs = true;
public static boolean StatsLogConns = true;
public static boolean StatsCheckSchema = true;
public static String DownloadPath = "./";
public static boolean RunHTTP = true;
public static int HTTPPort = 81;
public static int lngServerVer=0x01;
public static int numOfNews=0;
public static String[] strNews={"", "", "", "", ""};
}
| False | 1,317 | 7 | 1,379 | 7 | 1,455 | 6 | 1,379 | 7 | 1,628 | 7 | false | false | false | false | false | true |
3,513 | 202603_6 | /*
*
* .::::.
* .::::::::.
* ::::::::::: by [email protected]
* ..:::::::::::'
* '::::::::::::'
* .::::::::::
* '::::::::::::::..
* ..::::::::::::.
* ``::::::::::::::::
* ::::``:::::::::' .:::.
* ::::' ':::::' .::::::::.
* .::::' :::: .:::::::'::::.
* .:::' ::::: .:::::::::' ':::::.
* .::' :::::.:::::::::' ':::::.
* .::' ::::::::::::::' ``::::.
* ...::: ::::::::::::' ``::.
* ```` ':. ':::::::::' ::::..
* '.:::::' ':'````..
*
*/
package cn.qssq666.robot.ui;
import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
/**
* Created by 情随事迁([email protected]) on 2017/3/7. 虽然能解决左右平均分配问题但是不能解决4个item 中每一个item 宽度一致问题。
* 因此开发者还需要 写一个东西就是
* jingxuanHeadBinding.recyclerviewSinger.setPadding(spacingInPixels/2, 0, spacingInPixels/2, spacingInPixels/2);
*/
public class EqualDivierDecoration extends SpacesItemDecoration {
private boolean needTop;
/**
* 不包括顶部
* @param recyclerView
* @param space
*/
public EqualDivierDecoration(RecyclerView recyclerView, int space) {
super(space);
/**
* 顶部 下面实现了
*/
recyclerView.setPadding(getSpace() / 2, 0, getSpace() / 2, getSpace() / 2);
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight) {
this(recyclerView, space, needLeft, needRight, true);
/**
* 顶部 下面实现了
*/
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight, boolean isneddTop) {
super(space);
/**
* 顶部 下面实现了
*/
this.needTop = isneddTop;
recyclerView.setPadding(needLeft ? getSpace() / 2 : 0, isneddTop ? getSpace() / 2 : 0, needRight ? getSpace() / 2 : 0, getSpace() / 2);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// int itemCount = parent.getLayoutManager().getItemCount();
// int childAdapterPosition = parent.getChildAdapterPosition(view);
// GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
// int spanCount = layoutManager.getSpanCount();
// int result = childAdapterPosition % spanCount;
//左右必须等分 上下没关系。
if (needTop) {
outRect.top = getSpace() / 2;
}
outRect.left = getSpace() / 2;
outRect.right = getSpace() / 2;
outRect.bottom = getSpace() / 2;//底部的diy不给提供,只负责顶部
}
}
| lozn00/robot | app/src/main/java/cn/qssq666/robot/ui/EqualDivierDecoration.java | 932 | // int itemCount = parent.getLayoutManager().getItemCount(); | line_comment | nl | /*
*
* .::::.
* .::::::::.
* ::::::::::: by [email protected]
* ..:::::::::::'
* '::::::::::::'
* .::::::::::
* '::::::::::::::..
* ..::::::::::::.
* ``::::::::::::::::
* ::::``:::::::::' .:::.
* ::::' ':::::' .::::::::.
* .::::' :::: .:::::::'::::.
* .:::' ::::: .:::::::::' ':::::.
* .::' :::::.:::::::::' ':::::.
* .::' ::::::::::::::' ``::::.
* ...::: ::::::::::::' ``::.
* ```` ':. ':::::::::' ::::..
* '.:::::' ':'````..
*
*/
package cn.qssq666.robot.ui;
import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
/**
* Created by 情随事迁([email protected]) on 2017/3/7. 虽然能解决左右平均分配问题但是不能解决4个item 中每一个item 宽度一致问题。
* 因此开发者还需要 写一个东西就是
* jingxuanHeadBinding.recyclerviewSinger.setPadding(spacingInPixels/2, 0, spacingInPixels/2, spacingInPixels/2);
*/
public class EqualDivierDecoration extends SpacesItemDecoration {
private boolean needTop;
/**
* 不包括顶部
* @param recyclerView
* @param space
*/
public EqualDivierDecoration(RecyclerView recyclerView, int space) {
super(space);
/**
* 顶部 下面实现了
*/
recyclerView.setPadding(getSpace() / 2, 0, getSpace() / 2, getSpace() / 2);
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight) {
this(recyclerView, space, needLeft, needRight, true);
/**
* 顶部 下面实现了
*/
}
public EqualDivierDecoration(RecyclerView recyclerView, int space, boolean needLeft, boolean needRight, boolean isneddTop) {
super(space);
/**
* 顶部 下面实现了
*/
this.needTop = isneddTop;
recyclerView.setPadding(needLeft ? getSpace() / 2 : 0, isneddTop ? getSpace() / 2 : 0, needRight ? getSpace() / 2 : 0, getSpace() / 2);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// int itemCount<SUF>
// int childAdapterPosition = parent.getChildAdapterPosition(view);
// GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
// int spanCount = layoutManager.getSpanCount();
// int result = childAdapterPosition % spanCount;
//左右必须等分 上下没关系。
if (needTop) {
outRect.top = getSpace() / 2;
}
outRect.left = getSpace() / 2;
outRect.right = getSpace() / 2;
outRect.bottom = getSpace() / 2;//底部的diy不给提供,只负责顶部
}
}
| False | 748 | 12 | 830 | 14 | 823 | 14 | 830 | 14 | 1,070 | 16 | false | false | false | false | false | true |
4,469 | 44409_3 | package tjesmits.android.avans.nl.bolbrowser.api;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import tjesmits.android.avans.nl.bolbrowser.api.interfaces.OnProductAvailable;
import tjesmits.android.avans.nl.bolbrowser.domain.Product;
/**
* Created by Tom Smits on 9-3-2018.
*/
public class ProductTask extends AsyncTask<String, Void, String> {
// Callback
private OnProductAvailable listener = null;
// Statics
private static final String TAG = ProductTask.class.getSimpleName();
// Constructor, set listener
public ProductTask(OnProductAvailable listener) {
this.listener = listener;
}
/**
* doInBackground is de methode waarin de aanroep naar een service op
* het Internet gedaan wordt.
*
* @param params
* @return
*/
@Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
int responsCode = -1;
// De URL die we via de .execute() meegeleverd krijgen
String personUrl = params[0];
// Het resultaat dat we gaan retourneren
String response = "";
Log.i(TAG, "doInBackground - " + personUrl);
try {
// Maak een URL object
URL url = new URL(personUrl);
// Open een connection op de URL
URLConnection urlConnection = url.openConnection();
if (!(urlConnection instanceof HttpURLConnection)) {
return null;
}
// Initialiseer een HTTP connectie
HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
httpConnection.setAllowUserInteraction(false);
httpConnection.setInstanceFollowRedirects(true);
httpConnection.setRequestMethod("GET");
// Voer het request uit via de HTTP connectie op de URL
httpConnection.connect();
// Kijk of het gelukt is door de response code te checken
responsCode = httpConnection.getResponseCode();
if (responsCode == HttpURLConnection.HTTP_OK) {
inputStream = httpConnection.getInputStream();
response = getStringFromInputStream(inputStream);
// Log.i(TAG, "doInBackground response = " + response);
} else {
Log.e(TAG, "Error, invalid response");
}
} catch (MalformedURLException e) {
Log.e(TAG, "doInBackground MalformedURLEx " + e.getLocalizedMessage());
return null;
} catch (IOException e) {
Log.e("TAG", "doInBackground IOException " + e.getLocalizedMessage());
return null;
}
// Hier eindigt deze methode.
// Het resultaat gaat naar de onPostExecute methode.
return response;
}
/**
* onPostExecute verwerkt het resultaat uit de doInBackground methode.
*
* @param response
*/
protected void onPostExecute(String response) {
Log.i(TAG, "onPostExecute " + response);
// Check of er een response is
if(response == null || response == "") {
Log.e(TAG, "onPostExecute kreeg een lege response!");
return;
}
// Het resultaat is in ons geval een stuk tekst in JSON formaat.
// Daar moeten we de info die we willen tonen uit filteren (parsen).
// Dat kan met een JSONObject.
JSONObject jsonObject;
try {
// Top level json object
jsonObject = new JSONObject(response);
// Get all users and start looping
JSONArray productsArray = jsonObject.getJSONArray("products");
for(int idx = 0; idx < productsArray.length(); idx++) {
// array level objects and get user
JSONObject productObject = productsArray.getJSONObject(idx);
// Get title, first and last name
String id = productObject.getString("id");
String title = productObject.getString("title");
String tag = null;
if (productObject.has("summary")) {
tag = productObject.getString("summary");
}
else {
tag = productObject.getString("specsTag");
}
int rating = productObject.getInt("rating");
String description = productObject.getString("longDescription");
// Get the price of product and formats text.
String price = productObject.getJSONObject("offerData").getJSONArray("offers").getJSONObject(0).getString("price");
String finalPrice = null;
if (price.endsWith(".0")) {
finalPrice = price.replace(".0", ",-");
}
else if (price.matches("(?i).*.*"))
{
finalPrice = price.replace(".", ",");
}
Log.i(TAG, "Got product " + id + " " + title);
// Get image url
String imageThumbURL = productObject.getJSONArray("images").getJSONObject(0).getString("url");
String imageURL = productObject.getJSONArray("images").getJSONObject(1).getString("url");
Log.i(TAG, imageURL);
// Create new Product object
// Builder Design Pattern
Product product = new Product.ProductBuilder(title, tag, rating, finalPrice)
.setID(id)
.setDescription(description)
.setImageURL(imageThumbURL, imageURL)
.build();
//
// call back with new product data
//
listener.OnProductAvailable(product);
}
} catch( JSONException ex) {
Log.e(TAG, "onPostExecute JSONException " + ex.getLocalizedMessage());
}
}
//
// convert InputStream to String
//
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
} | teumaas/BolBrowser | app/src/main/java/tjesmits/android/avans/nl/bolbrowser/api/ProductTask.java | 1,784 | // De URL die we via de .execute() meegeleverd krijgen | line_comment | nl | package tjesmits.android.avans.nl.bolbrowser.api;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import tjesmits.android.avans.nl.bolbrowser.api.interfaces.OnProductAvailable;
import tjesmits.android.avans.nl.bolbrowser.domain.Product;
/**
* Created by Tom Smits on 9-3-2018.
*/
public class ProductTask extends AsyncTask<String, Void, String> {
// Callback
private OnProductAvailable listener = null;
// Statics
private static final String TAG = ProductTask.class.getSimpleName();
// Constructor, set listener
public ProductTask(OnProductAvailable listener) {
this.listener = listener;
}
/**
* doInBackground is de methode waarin de aanroep naar een service op
* het Internet gedaan wordt.
*
* @param params
* @return
*/
@Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
int responsCode = -1;
// De URL<SUF>
String personUrl = params[0];
// Het resultaat dat we gaan retourneren
String response = "";
Log.i(TAG, "doInBackground - " + personUrl);
try {
// Maak een URL object
URL url = new URL(personUrl);
// Open een connection op de URL
URLConnection urlConnection = url.openConnection();
if (!(urlConnection instanceof HttpURLConnection)) {
return null;
}
// Initialiseer een HTTP connectie
HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
httpConnection.setAllowUserInteraction(false);
httpConnection.setInstanceFollowRedirects(true);
httpConnection.setRequestMethod("GET");
// Voer het request uit via de HTTP connectie op de URL
httpConnection.connect();
// Kijk of het gelukt is door de response code te checken
responsCode = httpConnection.getResponseCode();
if (responsCode == HttpURLConnection.HTTP_OK) {
inputStream = httpConnection.getInputStream();
response = getStringFromInputStream(inputStream);
// Log.i(TAG, "doInBackground response = " + response);
} else {
Log.e(TAG, "Error, invalid response");
}
} catch (MalformedURLException e) {
Log.e(TAG, "doInBackground MalformedURLEx " + e.getLocalizedMessage());
return null;
} catch (IOException e) {
Log.e("TAG", "doInBackground IOException " + e.getLocalizedMessage());
return null;
}
// Hier eindigt deze methode.
// Het resultaat gaat naar de onPostExecute methode.
return response;
}
/**
* onPostExecute verwerkt het resultaat uit de doInBackground methode.
*
* @param response
*/
protected void onPostExecute(String response) {
Log.i(TAG, "onPostExecute " + response);
// Check of er een response is
if(response == null || response == "") {
Log.e(TAG, "onPostExecute kreeg een lege response!");
return;
}
// Het resultaat is in ons geval een stuk tekst in JSON formaat.
// Daar moeten we de info die we willen tonen uit filteren (parsen).
// Dat kan met een JSONObject.
JSONObject jsonObject;
try {
// Top level json object
jsonObject = new JSONObject(response);
// Get all users and start looping
JSONArray productsArray = jsonObject.getJSONArray("products");
for(int idx = 0; idx < productsArray.length(); idx++) {
// array level objects and get user
JSONObject productObject = productsArray.getJSONObject(idx);
// Get title, first and last name
String id = productObject.getString("id");
String title = productObject.getString("title");
String tag = null;
if (productObject.has("summary")) {
tag = productObject.getString("summary");
}
else {
tag = productObject.getString("specsTag");
}
int rating = productObject.getInt("rating");
String description = productObject.getString("longDescription");
// Get the price of product and formats text.
String price = productObject.getJSONObject("offerData").getJSONArray("offers").getJSONObject(0).getString("price");
String finalPrice = null;
if (price.endsWith(".0")) {
finalPrice = price.replace(".0", ",-");
}
else if (price.matches("(?i).*.*"))
{
finalPrice = price.replace(".", ",");
}
Log.i(TAG, "Got product " + id + " " + title);
// Get image url
String imageThumbURL = productObject.getJSONArray("images").getJSONObject(0).getString("url");
String imageURL = productObject.getJSONArray("images").getJSONObject(1).getString("url");
Log.i(TAG, imageURL);
// Create new Product object
// Builder Design Pattern
Product product = new Product.ProductBuilder(title, tag, rating, finalPrice)
.setID(id)
.setDescription(description)
.setImageURL(imageThumbURL, imageURL)
.build();
//
// call back with new product data
//
listener.OnProductAvailable(product);
}
} catch( JSONException ex) {
Log.e(TAG, "onPostExecute JSONException " + ex.getLocalizedMessage());
}
}
//
// convert InputStream to String
//
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
} | True | 1,320 | 16 | 1,496 | 19 | 1,566 | 14 | 1,496 | 19 | 1,762 | 18 | false | false | false | false | false | true |
3,638 | 147399_1 | import sofia.micro.*;
//-------------------------------------------------------------------------
/**
* this class houses all the subclasses of ants
*
* @author Mykayla Fernandes (mkaykay1)
* @version 2015.10.22
*/
public class Ant extends Timer
{
//~ Fields ................................................................
/**
* @param health equals health
*/
public int health;
/**
* @param cost equals cost to add ant to world
*/
public int cost;
/**
* @param sting equals 40
* turns passed before bee stings
*/
public int sting = 40;
//~ Constructor ...........................................................
// ----------------------------------------------------------
/**
* Creates a new Ant object.
*/
public Ant()
{
super();
}
//~ Methods ...............................................................
/**
* @return equals the ant's current health
*/
public int getHealth()
{
return health;
}
/**
* reduces the ant's health by the provided amount.
* when the ant's health reaches zero,
* it should remove itself from the colony
* @param n equals amount it gets injured
*/
public void injure(int n)
{
if (health == 0)
{
this.remove();
}
else
{
health = health - n;
}
}
/**
* gets injured when a bee makes contact with it
* waits 40 turns before stinging begins
*/
public void beeSting()
{
if (this.getIntersectingObjects(Bee.class).size() > 0)
{
if (sting == 0)
{
this.injure(1);
}
else
{
sting = sting - 1;
}
}
}
/**
* indicates how many food units are necessary to
* be added to the colony
* @return the food cost
*/
public int getFoodCost()
{
return cost;
}
/**
* executes methods which
* give this actor it's unique behavior
*/
public void act()
{
this.beeSting();
this.getFoodCost();
this.getHealth();
}
}
| mfcecilia/cs1114_program04-ants-vs-somebees | Ant.java | 611 | //~ Fields ................................................................ | line_comment | nl | import sofia.micro.*;
//-------------------------------------------------------------------------
/**
* this class houses all the subclasses of ants
*
* @author Mykayla Fernandes (mkaykay1)
* @version 2015.10.22
*/
public class Ant extends Timer
{
//~ Fields<SUF>
/**
* @param health equals health
*/
public int health;
/**
* @param cost equals cost to add ant to world
*/
public int cost;
/**
* @param sting equals 40
* turns passed before bee stings
*/
public int sting = 40;
//~ Constructor ...........................................................
// ----------------------------------------------------------
/**
* Creates a new Ant object.
*/
public Ant()
{
super();
}
//~ Methods ...............................................................
/**
* @return equals the ant's current health
*/
public int getHealth()
{
return health;
}
/**
* reduces the ant's health by the provided amount.
* when the ant's health reaches zero,
* it should remove itself from the colony
* @param n equals amount it gets injured
*/
public void injure(int n)
{
if (health == 0)
{
this.remove();
}
else
{
health = health - n;
}
}
/**
* gets injured when a bee makes contact with it
* waits 40 turns before stinging begins
*/
public void beeSting()
{
if (this.getIntersectingObjects(Bee.class).size() > 0)
{
if (sting == 0)
{
this.injure(1);
}
else
{
sting = sting - 1;
}
}
}
/**
* indicates how many food units are necessary to
* be added to the colony
* @return the food cost
*/
public int getFoodCost()
{
return cost;
}
/**
* executes methods which
* give this actor it's unique behavior
*/
public void act()
{
this.beeSting();
this.getFoodCost();
this.getHealth();
}
}
| False | 487 | 4 | 510 | 5 | 580 | 7 | 510 | 5 | 632 | 9 | false | false | false | false | false | true |
2,756 | 20446_16 | package io.gameoftrades.model.markt.actie;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import io.gameoftrades.model.Wereld;
import io.gameoftrades.model.kaart.Coordinaat;
import io.gameoftrades.model.kaart.Richting;
import io.gameoftrades.model.kaart.Stad;
import io.gameoftrades.model.kaart.Terrein;
import io.gameoftrades.model.markt.Handelswaar;
import io.gameoftrades.util.Assert;
/**
* De HandelsPositie bevat de de huidige situatie van de Handelaar.
* <p>
* Dat wil zeggen, zijn huidige locatie, zijn kapitaal, de beschikbare ruimte en de voorraad.
* </p>
* <p>
* Deze klasse biedt een aantal methoden aan die samen met de verschillende Acties er voor
* zorgen dat de Handelaar zijn positie kan verbeteren door te Bewegen, Kopen en Verkopen.
* </p>
*/
public final class HandelsPositie {
private Stad stad;
private Coordinaat coordinaat;
private int kapitaal;
private int ruimte;
private Map<Handelswaar, Integer> voorraad;
private Wereld wereld;
private int maxActie;
private boolean gestopt;
private int totaalActie;
private int totaalWinst;
private Set<Handelswaar> uniekeGoederen;
private List<Stad> bezochteSteden;
private int totaalGebruikteRuimte;
/**
* maakt een nieuwe handels positie na het bewegen van een stad naar een andere stad.
* Deze actie slaat voor het gemak de gedetailleerde routering over en gebruikt een
* van te voren berekend aantal bewegingspunten.
* @param org de originele handels positie.
* @param van de stad waarvan vertrokken wordt.
* @param naar de stad waar naartoe genavigeerd wordt.
* @param bw het aantal bewegingspunten.
* @return de nieuwe handelspositie.
*/
static HandelsPositie beweeg(HandelsPositie org, Stad van, Stad naar, int bw) {
HandelsPositie copy = new HandelsPositie(org);
if (!copy.stad.equals(van)) {
throw new IllegalArgumentException("De huidige locatie is " + org.stad + " en niet " + van);
}
copy.stad = naar;
copy.bezochteSteden.add(naar);
copy.totaalActie += bw;
copy.coordinaat = naar.getCoordinaat();
return copy;
}
/**
* maakt de nieuwe handels positie na een navigatie (het gedetailleerd over de kaart bewegen).
* @param org de originele positie.
* @param van het coordinaat waarvan vertrokken wordt.
* @param richting de richting waarheen bewogen wordt.
* @return de nieuwe handels positie.
*/
static HandelsPositie navigeer(HandelsPositie org, Coordinaat van, Richting richting) {
if (!org.coordinaat.equals(van)) {
throw new IllegalArgumentException("Niet op positie " + van + " maar op " + org.coordinaat);
}
HandelsPositie copy = new HandelsPositie(org);
Terrein terrein = org.wereld.getKaart().getTerreinOp(org.coordinaat);
copy.coordinaat = org.wereld.getKaart().kijk(terrein, richting).getCoordinaat();
copy.stad = null;
copy.totaalActie += terrein.getTerreinType().getBewegingspunten();
for (Stad stad : org.wereld.getSteden()) {
if (stad.getCoordinaat().equals(copy.coordinaat)) {
copy.stad = stad;
copy.bezochteSteden.add(stad);
}
}
return copy;
}
/**
* maakt een nieuwe handelspositie na het kopen van handelswaar.
* @param org de originele handelspositie.
* @param aantal het aantal stuks Handelswaar dat gekocht wordt.
* @param hw de handelswaar.
* @param geld de totale hoeveelheid geld dat voor de handelswaar betaald wordt.
* @return de nieuwe positie.
*/
static HandelsPositie koop(HandelsPositie org, int aantal, Handelswaar hw, int geld) {
HandelsPositie copy = new HandelsPositie(org);
if (org.ruimte - aantal < 0) {
throw new IllegalArgumentException("Onvoldoende ruimte om " + aantal + " te kunnen kopen. Er is maar " + org.ruimte + " beschikbaar.");
}
if (org.kapitaal - geld < 0) {
throw new IllegalArgumentException("Onvoldoende kapitaal.");
}
copy.ruimte = copy.ruimte - aantal;
copy.kapitaal = org.kapitaal - geld;
copy.totaalWinst = org.totaalWinst - geld;
copy.totaalGebruikteRuimte = copy.totaalGebruikteRuimte + aantal;
copy.totaalActie += 1;
if (copy.voorraad.containsKey(hw)) {
copy.voorraad.put(hw, copy.voorraad.get(hw) + aantal);
} else {
copy.voorraad.put(hw, aantal);
}
return copy;
}
/**
* maakt een nieuwe handelspositie na het verkopen van handelswaar.
* @param org de originele positie.
* @param aantal het aantal stuks handelswaar dat verkocht gaat worden.
* @param hw de handelswaar.
* @param geld de totale hoeveelheid geld die ontvangen wordt voor de handelswaar.
* @return de nieuwe positie.
*/
static HandelsPositie verkoop(HandelsPositie org, int aantal, Handelswaar hw, int geld) {
HandelsPositie copy = new HandelsPositie(org);
if (!org.voorraad.containsKey(hw)) {
throw new IllegalArgumentException("Geen " + hw + " op voorraad.");
}
if (aantal > org.voorraad.get(hw)) {
throw new IllegalArgumentException("Onvoldoende " + hw + " op voorraad.");
}
copy.ruimte = copy.ruimte + aantal;
copy.kapitaal = org.kapitaal + geld;
copy.totaalWinst = org.totaalWinst + geld;
copy.totaalActie += 1;
copy.voorraad.put(hw, copy.voorraad.get(hw) - aantal);
copy.uniekeGoederen.add(hw);
if (copy.voorraad.get(hw) == 0) {
copy.voorraad.remove(hw);
}
return copy;
}
static HandelsPositie stop(HandelsPositie org) {
HandelsPositie copy = new HandelsPositie(org);
if (org.gestopt) {
throw new IllegalArgumentException("Alreeds gestopt!");
}
copy.gestopt = true;
return copy;
}
/**
* maakt een nieuwe initieele handelspositie.
* @param wereld de wereld waarin gehandeld gaat worden.
* @param stad de stad waarin gestart wordt.
* @param kapitaal het begin kapitaal.
* @param ruimte de hoeveelheid ruimte in de voorraad.
* @param maxActie het maximum aantal bewegingspunten dat verbruikt mag worden.
*/
public HandelsPositie(Wereld wereld, Stad stad, int kapitaal, int ruimte, int maxActie) {
Assert.notNull(wereld);
Assert.notNull(stad);
this.wereld = wereld;
this.stad = stad;
this.maxActie = maxActie;
this.coordinaat = stad.getCoordinaat();
this.kapitaal = kapitaal;
this.ruimte = ruimte;
this.voorraad = new TreeMap<>();
this.uniekeGoederen = new TreeSet<>();
this.bezochteSteden = new ArrayList<>();
this.totaalGebruikteRuimte = 0;
}
/**
* maakt een kopie van de gegeven handelspositie.
* @param pos de positie.
*/
protected HandelsPositie(HandelsPositie pos) {
Assert.notNull(pos);
this.wereld = pos.wereld;
this.stad = pos.stad;
this.kapitaal = pos.kapitaal;
this.ruimte = pos.ruimte;
this.voorraad = new TreeMap<>(pos.voorraad);
this.coordinaat = pos.coordinaat;
this.totaalActie = pos.totaalActie;
this.totaalWinst = pos.totaalWinst;
this.maxActie = pos.maxActie;
this.gestopt = pos.gestopt;
this.uniekeGoederen = new TreeSet<>(pos.uniekeGoederen);
this.bezochteSteden = new ArrayList<>(pos.bezochteSteden);
this.totaalGebruikteRuimte = pos.totaalGebruikteRuimte;
}
/**
* @return de huidige stad of null.
*/
public Stad getStad() {
return stad;
}
/**
* @return het huidige coordinaat van de handelaar.
*/
public Coordinaat getCoordinaat() {
return coordinaat;
}
/**
* @return totaal beschikbaar kapitaal.
*/
public int getKapitaal() {
return kapitaal;
}
/**
* @return totaal beschikbare ruimte.
*/
public int getRuimte() {
return ruimte;
}
/**
* @return de voorraad.
*/
public Map<Handelswaar, Integer> getVoorraad() {
return Collections.unmodifiableMap(voorraad);
}
/**
* @return het totaal verbruikte actie punten.
*/
public int getTotaalActie() {
return totaalActie;
}
/**
* @return de gemaakte winst.
*/
public int getTotaalWinst() {
return totaalWinst;
}
/**
* @return het maximaal te gebruiken acties.
*/
public int getMaxActie() {
return maxActie;
}
/**
* @return de lijst van bezochte steden.
*/
public List<Stad> getBezochteSteden() {
return Collections.unmodifiableList(bezochteSteden);
}
/**
* @return totale hoeveelheid gebruikte ruimte over het spel heen.
*/
public int getTotaalGebruikteRuimte() {
return totaalGebruikteRuimte;
}
/**
* @return alle unieke goederen waarin gedurende het spel in gehandeld is.
*/
public Set<Handelswaar> getUniekeGoederen() {
return Collections.unmodifiableSet(uniekeGoederen);
}
/**
* @return true wanneer het handelen gestopt is met een StopActie.
*/
public boolean isGestopt() {
return gestopt;
}
/**
* Geeft true terug wanneer er gestopt is of dat er geen actie punten meer zijn.
* @return true wanneer het handelen klaar is.
*/
public boolean isKlaar() {
return gestopt || getTotaalActie() >= getMaxActie();
}
/**
* @param actie het aantal actie punten dat verbruikt moet gaan worden.
* @return true wanneer er nog voldoende punten beschikbaar zijn (en er nog niet is gestopt).
*/
public boolean isActieBeschikbaar(int actie) {
return !gestopt && getTotaalActie() + actie <= getMaxActie();
}
@Override
public String toString() {
return "HandelsPositie(" + getCoordinaat() + ",$" + kapitaal + ",R:" + ruimte + ",A:" + getTotaalActie() + ",W:" + getTotaalWinst() + ")";
}
}
| gameoftrades/gameoftrades-library | src/main/java/io/gameoftrades/model/markt/actie/HandelsPositie.java | 3,525 | /**
* @return totale hoeveelheid gebruikte ruimte over het spel heen.
*/ | block_comment | nl | package io.gameoftrades.model.markt.actie;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import io.gameoftrades.model.Wereld;
import io.gameoftrades.model.kaart.Coordinaat;
import io.gameoftrades.model.kaart.Richting;
import io.gameoftrades.model.kaart.Stad;
import io.gameoftrades.model.kaart.Terrein;
import io.gameoftrades.model.markt.Handelswaar;
import io.gameoftrades.util.Assert;
/**
* De HandelsPositie bevat de de huidige situatie van de Handelaar.
* <p>
* Dat wil zeggen, zijn huidige locatie, zijn kapitaal, de beschikbare ruimte en de voorraad.
* </p>
* <p>
* Deze klasse biedt een aantal methoden aan die samen met de verschillende Acties er voor
* zorgen dat de Handelaar zijn positie kan verbeteren door te Bewegen, Kopen en Verkopen.
* </p>
*/
public final class HandelsPositie {
private Stad stad;
private Coordinaat coordinaat;
private int kapitaal;
private int ruimte;
private Map<Handelswaar, Integer> voorraad;
private Wereld wereld;
private int maxActie;
private boolean gestopt;
private int totaalActie;
private int totaalWinst;
private Set<Handelswaar> uniekeGoederen;
private List<Stad> bezochteSteden;
private int totaalGebruikteRuimte;
/**
* maakt een nieuwe handels positie na het bewegen van een stad naar een andere stad.
* Deze actie slaat voor het gemak de gedetailleerde routering over en gebruikt een
* van te voren berekend aantal bewegingspunten.
* @param org de originele handels positie.
* @param van de stad waarvan vertrokken wordt.
* @param naar de stad waar naartoe genavigeerd wordt.
* @param bw het aantal bewegingspunten.
* @return de nieuwe handelspositie.
*/
static HandelsPositie beweeg(HandelsPositie org, Stad van, Stad naar, int bw) {
HandelsPositie copy = new HandelsPositie(org);
if (!copy.stad.equals(van)) {
throw new IllegalArgumentException("De huidige locatie is " + org.stad + " en niet " + van);
}
copy.stad = naar;
copy.bezochteSteden.add(naar);
copy.totaalActie += bw;
copy.coordinaat = naar.getCoordinaat();
return copy;
}
/**
* maakt de nieuwe handels positie na een navigatie (het gedetailleerd over de kaart bewegen).
* @param org de originele positie.
* @param van het coordinaat waarvan vertrokken wordt.
* @param richting de richting waarheen bewogen wordt.
* @return de nieuwe handels positie.
*/
static HandelsPositie navigeer(HandelsPositie org, Coordinaat van, Richting richting) {
if (!org.coordinaat.equals(van)) {
throw new IllegalArgumentException("Niet op positie " + van + " maar op " + org.coordinaat);
}
HandelsPositie copy = new HandelsPositie(org);
Terrein terrein = org.wereld.getKaart().getTerreinOp(org.coordinaat);
copy.coordinaat = org.wereld.getKaart().kijk(terrein, richting).getCoordinaat();
copy.stad = null;
copy.totaalActie += terrein.getTerreinType().getBewegingspunten();
for (Stad stad : org.wereld.getSteden()) {
if (stad.getCoordinaat().equals(copy.coordinaat)) {
copy.stad = stad;
copy.bezochteSteden.add(stad);
}
}
return copy;
}
/**
* maakt een nieuwe handelspositie na het kopen van handelswaar.
* @param org de originele handelspositie.
* @param aantal het aantal stuks Handelswaar dat gekocht wordt.
* @param hw de handelswaar.
* @param geld de totale hoeveelheid geld dat voor de handelswaar betaald wordt.
* @return de nieuwe positie.
*/
static HandelsPositie koop(HandelsPositie org, int aantal, Handelswaar hw, int geld) {
HandelsPositie copy = new HandelsPositie(org);
if (org.ruimte - aantal < 0) {
throw new IllegalArgumentException("Onvoldoende ruimte om " + aantal + " te kunnen kopen. Er is maar " + org.ruimte + " beschikbaar.");
}
if (org.kapitaal - geld < 0) {
throw new IllegalArgumentException("Onvoldoende kapitaal.");
}
copy.ruimte = copy.ruimte - aantal;
copy.kapitaal = org.kapitaal - geld;
copy.totaalWinst = org.totaalWinst - geld;
copy.totaalGebruikteRuimte = copy.totaalGebruikteRuimte + aantal;
copy.totaalActie += 1;
if (copy.voorraad.containsKey(hw)) {
copy.voorraad.put(hw, copy.voorraad.get(hw) + aantal);
} else {
copy.voorraad.put(hw, aantal);
}
return copy;
}
/**
* maakt een nieuwe handelspositie na het verkopen van handelswaar.
* @param org de originele positie.
* @param aantal het aantal stuks handelswaar dat verkocht gaat worden.
* @param hw de handelswaar.
* @param geld de totale hoeveelheid geld die ontvangen wordt voor de handelswaar.
* @return de nieuwe positie.
*/
static HandelsPositie verkoop(HandelsPositie org, int aantal, Handelswaar hw, int geld) {
HandelsPositie copy = new HandelsPositie(org);
if (!org.voorraad.containsKey(hw)) {
throw new IllegalArgumentException("Geen " + hw + " op voorraad.");
}
if (aantal > org.voorraad.get(hw)) {
throw new IllegalArgumentException("Onvoldoende " + hw + " op voorraad.");
}
copy.ruimte = copy.ruimte + aantal;
copy.kapitaal = org.kapitaal + geld;
copy.totaalWinst = org.totaalWinst + geld;
copy.totaalActie += 1;
copy.voorraad.put(hw, copy.voorraad.get(hw) - aantal);
copy.uniekeGoederen.add(hw);
if (copy.voorraad.get(hw) == 0) {
copy.voorraad.remove(hw);
}
return copy;
}
static HandelsPositie stop(HandelsPositie org) {
HandelsPositie copy = new HandelsPositie(org);
if (org.gestopt) {
throw new IllegalArgumentException("Alreeds gestopt!");
}
copy.gestopt = true;
return copy;
}
/**
* maakt een nieuwe initieele handelspositie.
* @param wereld de wereld waarin gehandeld gaat worden.
* @param stad de stad waarin gestart wordt.
* @param kapitaal het begin kapitaal.
* @param ruimte de hoeveelheid ruimte in de voorraad.
* @param maxActie het maximum aantal bewegingspunten dat verbruikt mag worden.
*/
public HandelsPositie(Wereld wereld, Stad stad, int kapitaal, int ruimte, int maxActie) {
Assert.notNull(wereld);
Assert.notNull(stad);
this.wereld = wereld;
this.stad = stad;
this.maxActie = maxActie;
this.coordinaat = stad.getCoordinaat();
this.kapitaal = kapitaal;
this.ruimte = ruimte;
this.voorraad = new TreeMap<>();
this.uniekeGoederen = new TreeSet<>();
this.bezochteSteden = new ArrayList<>();
this.totaalGebruikteRuimte = 0;
}
/**
* maakt een kopie van de gegeven handelspositie.
* @param pos de positie.
*/
protected HandelsPositie(HandelsPositie pos) {
Assert.notNull(pos);
this.wereld = pos.wereld;
this.stad = pos.stad;
this.kapitaal = pos.kapitaal;
this.ruimte = pos.ruimte;
this.voorraad = new TreeMap<>(pos.voorraad);
this.coordinaat = pos.coordinaat;
this.totaalActie = pos.totaalActie;
this.totaalWinst = pos.totaalWinst;
this.maxActie = pos.maxActie;
this.gestopt = pos.gestopt;
this.uniekeGoederen = new TreeSet<>(pos.uniekeGoederen);
this.bezochteSteden = new ArrayList<>(pos.bezochteSteden);
this.totaalGebruikteRuimte = pos.totaalGebruikteRuimte;
}
/**
* @return de huidige stad of null.
*/
public Stad getStad() {
return stad;
}
/**
* @return het huidige coordinaat van de handelaar.
*/
public Coordinaat getCoordinaat() {
return coordinaat;
}
/**
* @return totaal beschikbaar kapitaal.
*/
public int getKapitaal() {
return kapitaal;
}
/**
* @return totaal beschikbare ruimte.
*/
public int getRuimte() {
return ruimte;
}
/**
* @return de voorraad.
*/
public Map<Handelswaar, Integer> getVoorraad() {
return Collections.unmodifiableMap(voorraad);
}
/**
* @return het totaal verbruikte actie punten.
*/
public int getTotaalActie() {
return totaalActie;
}
/**
* @return de gemaakte winst.
*/
public int getTotaalWinst() {
return totaalWinst;
}
/**
* @return het maximaal te gebruiken acties.
*/
public int getMaxActie() {
return maxActie;
}
/**
* @return de lijst van bezochte steden.
*/
public List<Stad> getBezochteSteden() {
return Collections.unmodifiableList(bezochteSteden);
}
/**
* @return totale hoeveelheid<SUF>*/
public int getTotaalGebruikteRuimte() {
return totaalGebruikteRuimte;
}
/**
* @return alle unieke goederen waarin gedurende het spel in gehandeld is.
*/
public Set<Handelswaar> getUniekeGoederen() {
return Collections.unmodifiableSet(uniekeGoederen);
}
/**
* @return true wanneer het handelen gestopt is met een StopActie.
*/
public boolean isGestopt() {
return gestopt;
}
/**
* Geeft true terug wanneer er gestopt is of dat er geen actie punten meer zijn.
* @return true wanneer het handelen klaar is.
*/
public boolean isKlaar() {
return gestopt || getTotaalActie() >= getMaxActie();
}
/**
* @param actie het aantal actie punten dat verbruikt moet gaan worden.
* @return true wanneer er nog voldoende punten beschikbaar zijn (en er nog niet is gestopt).
*/
public boolean isActieBeschikbaar(int actie) {
return !gestopt && getTotaalActie() + actie <= getMaxActie();
}
@Override
public String toString() {
return "HandelsPositie(" + getCoordinaat() + ",$" + kapitaal + ",R:" + ruimte + ",A:" + getTotaalActie() + ",W:" + getTotaalWinst() + ")";
}
}
| True | 2,974 | 24 | 3,314 | 27 | 2,991 | 20 | 3,316 | 27 | 3,485 | 27 | false | false | false | false | false | true |
4,448 | 44514_7 | /*
* Copyright (C) 2016 Luca Corbatto
*
* This file is part of the hsReisePlugin.
*
* The hsReisePlugin is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The hsReisePlugin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package reiseplugin.data;
import java.util.Observable;
/**
* Contains all information of a {@link reiseplugin.data.Rast Rast}.
* @author Luca Corbatto {@literal <[email protected]>}
*/
public class Rast extends Observable {
private int start;
private int ende;
private int erschöpfungProStunde;
private int überanstrengungProStunde;
/**
* Creates a new {@link reiseplugin.data.Rast Rast} with the given parameters.
* If you give start = 12 and ende = 14 that results in a {@link reiseplugin.data.Rast Rast} from
* 12:00 - 14:00.
* @param start The start hour.
* @param ende The end hour.
* @param erschöpfungProStunde The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param überanstrengungProStunde The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public Rast(int start, int ende, int erschöpfungProStunde, int überanstrengungProStunde) {
if(start < 0 || start > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(ende < 0 || ende > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(erschöpfungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(überanstrengungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
this.start = start;
this.ende = ende;
this.erschöpfungProStunde = erschöpfungProStunde;
this.überanstrengungProStunde = überanstrengungProStunde;
}
/**
* Returns the start hour.
* @return The start hour.
*/
public int getStart() {
return start;
}
/**
* Sets the start hour.
* @param start The start hour.
*/
public void setStart(int start) {
if(start < 0 || start > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(this.start != start) {
this.start = start;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the end hour.
* @return The end hour.
*/
public int getEnde() {
return ende;
}
/**
* Sets the end hour.
* @param ende The end hour.
*/
public void setEnde(int ende) {
if(ende < 0 || ende > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(this.ende != ende) {
this.ende = ende;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @return The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public int getErschöpfungProStunde() {
return erschöpfungProStunde;
}
/**
* Sets the Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param erschöpfungProStunde The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public void setErschöpfungProStunde(int erschöpfungProStunde) {
if(erschöpfungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(this.erschöpfungProStunde != erschöpfungProStunde) {
this.erschöpfungProStunde = erschöpfungProStunde;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @return The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public int getÜberanstrengungProStunde() {
return überanstrengungProStunde;
}
/**
* Sets the Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param überanstrengungProStunde The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public void setÜberanstrengungProStunde(int überanstrengungProStunde) {
if(überanstrengungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(this.überanstrengungProStunde != überanstrengungProStunde) {
this.überanstrengungProStunde = überanstrengungProStunde;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns true if the given hour is within this {@link reiseplugin.data.Rast Rast}en start and end.
* @param st The hour to test.
* @return true if the given hour is within this {@link reiseplugin.data.Rast Rast}en start and end.
*/
public boolean matchStunde(int st) {
if(this.start > this.ende) {
// über nacht
return this.start <= st || st < this.ende;
} else {
// über tag
return this.start <= st && st < this.ende;
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "Rast{" + "start=" + this.start + ", ende=" + this.ende + ", ersch\u00f6pfungProStunde=" + this.erschöpfungProStunde + ", \u00fcberanstrengungProStunde=" + this.überanstrengungProStunde + '}';
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = 3;
hash = 37 * hash + this.start;
hash = 37 * hash + this.ende;
hash = 37 * hash + this.erschöpfungProStunde;
hash = 37 * hash + this.überanstrengungProStunde;
return hash;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Rast other = (Rast) obj;
if (this.start != other.start) {
return false;
}
if (this.ende != other.ende) {
return false;
}
if (this.erschöpfungProStunde != other.erschöpfungProStunde) {
return false;
}
if (this.überanstrengungProStunde != other.überanstrengungProStunde) {
return false;
}
return true;
}
} | targodan/hsReisePlugin | src/main/java/reiseplugin/data/Rast.java | 2,258 | /**
* Returns the Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @return The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/ | block_comment | nl | /*
* Copyright (C) 2016 Luca Corbatto
*
* This file is part of the hsReisePlugin.
*
* The hsReisePlugin is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The hsReisePlugin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package reiseplugin.data;
import java.util.Observable;
/**
* Contains all information of a {@link reiseplugin.data.Rast Rast}.
* @author Luca Corbatto {@literal <[email protected]>}
*/
public class Rast extends Observable {
private int start;
private int ende;
private int erschöpfungProStunde;
private int überanstrengungProStunde;
/**
* Creates a new {@link reiseplugin.data.Rast Rast} with the given parameters.
* If you give start = 12 and ende = 14 that results in a {@link reiseplugin.data.Rast Rast} from
* 12:00 - 14:00.
* @param start The start hour.
* @param ende The end hour.
* @param erschöpfungProStunde The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param überanstrengungProStunde The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public Rast(int start, int ende, int erschöpfungProStunde, int überanstrengungProStunde) {
if(start < 0 || start > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(ende < 0 || ende > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(erschöpfungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(überanstrengungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
this.start = start;
this.ende = ende;
this.erschöpfungProStunde = erschöpfungProStunde;
this.überanstrengungProStunde = überanstrengungProStunde;
}
/**
* Returns the start hour.
* @return The start hour.
*/
public int getStart() {
return start;
}
/**
* Sets the start hour.
* @param start The start hour.
*/
public void setStart(int start) {
if(start < 0 || start > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(this.start != start) {
this.start = start;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the end hour.
* @return The end hour.
*/
public int getEnde() {
return ende;
}
/**
* Sets the end hour.
* @param ende The end hour.
*/
public void setEnde(int ende) {
if(ende < 0 || ende > 23) {
throw new IllegalArgumentException("The time must be between 0 and 23.");
}
if(this.ende != ende) {
this.ende = ende;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the Erschöpfung<SUF>*/
public int getErschöpfungProStunde() {
return erschöpfungProStunde;
}
/**
* Sets the Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param erschöpfungProStunde The Erschöpfung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public void setErschöpfungProStunde(int erschöpfungProStunde) {
if(erschöpfungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(this.erschöpfungProStunde != erschöpfungProStunde) {
this.erschöpfungProStunde = erschöpfungProStunde;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns the Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @return The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public int getÜberanstrengungProStunde() {
return überanstrengungProStunde;
}
/**
* Sets the Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
* @param überanstrengungProStunde The Überanstrengung the {@link reiseplugin.data.Held Held}en regenerate per hour.
*/
public void setÜberanstrengungProStunde(int überanstrengungProStunde) {
if(überanstrengungProStunde < 0) {
throw new IllegalArgumentException("ErschöpfungProStunde may not be less than 0.");
}
if(this.überanstrengungProStunde != überanstrengungProStunde) {
this.überanstrengungProStunde = überanstrengungProStunde;
this.setChanged();
this.notifyObservers();
}
}
/**
* Returns true if the given hour is within this {@link reiseplugin.data.Rast Rast}en start and end.
* @param st The hour to test.
* @return true if the given hour is within this {@link reiseplugin.data.Rast Rast}en start and end.
*/
public boolean matchStunde(int st) {
if(this.start > this.ende) {
// über nacht
return this.start <= st || st < this.ende;
} else {
// über tag
return this.start <= st && st < this.ende;
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "Rast{" + "start=" + this.start + ", ende=" + this.ende + ", ersch\u00f6pfungProStunde=" + this.erschöpfungProStunde + ", \u00fcberanstrengungProStunde=" + this.überanstrengungProStunde + '}';
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
int hash = 3;
hash = 37 * hash + this.start;
hash = 37 * hash + this.ende;
hash = 37 * hash + this.erschöpfungProStunde;
hash = 37 * hash + this.überanstrengungProStunde;
return hash;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Rast other = (Rast) obj;
if (this.start != other.start) {
return false;
}
if (this.ende != other.ende) {
return false;
}
if (this.erschöpfungProStunde != other.erschöpfungProStunde) {
return false;
}
if (this.überanstrengungProStunde != other.überanstrengungProStunde) {
return false;
}
return true;
}
} | False | 1,961 | 56 | 2,105 | 64 | 2,095 | 55 | 2,105 | 64 | 2,326 | 67 | false | false | false | false | false | true |
3,909 | 80895_10 | /*
* Created on 21-feb-2006
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package microdev.db;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author andrea
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class QueryExecutor {
private Log log = LogFactory.getLog(QueryExecutor.class);
private Connection conn = null;
/** TODO */
public void execute(String query) {
// TODO
}
public List executeQuery(String query) {
return executeQuery(query, null);
}
public List executeQuery(String query, QueryTips tips) {
// aggrega temporaneamente i risultati
ArrayList vect = new ArrayList();
String order_query = "";
String limit_query = "";
if ( tips != null ) {
order_query = tips.getOrderQuery();
limit_query = tips.getLimitQuery();
}
String final_query = query + order_query + limit_query;
Statement stmt = null;
ResultSet rs = null;
try {
conn = ConnectionUtil.currentConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
//log.debug("executing query: " + final_query);
rs = stmt.executeQuery(final_query);
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
//ResultRecord rec = new ResultRecord();
Map rec = new LinkedHashMap();
for ( int i=1; i <= meta.getColumnCount(); i++ ) {
// log.debug("meta.getColumnLabel(i):" + meta.getColumnLabel(i));
// log.debug("meta.getColumnClassName(i):" + meta.getColumnClassName(i));
// log.debug("meta.getColumnType(i):" + meta.getColumnType(i));
// log.debug("meta.getColumnTypeName(i):" + meta.getColumnTypeName(i));
//
// log.debug("rs.getObject(i):" + rs.getObject(i));
// log.debug("rs.getObject(i).getClass():" + rs.getObject(i).getClass());
rec.put(meta.getColumnLabel(i),rs.getObject(i));
}
//log.debug("added record: " + rec);
vect.add(rec);
}
rs.close();
} catch (Exception e) {
log.error("",e);
} finally {
if (stmt != null) {
try { stmt.close(); } catch (SQLException ignore) {}
stmt = null;
}
//In realt� la connessione dovrebbe essere chiusa dal ConnectionFilter
//In questo caso sarebbe meglio chiedere la connessione ad ibatis e lasciarla
//chiudere a lui.
//Per motivi di tempo � stato utilizzato un workaround ovvero si � deciso
//di bypassare il connection filter e di fare il post processing alla fine di questo metodo.
//Per due motivi: il primo � che non avrebbe senso aggiungere il connection filter di
//questo modulo al web.xml, il secondo � che si ha bisogno di una soluzione immediata
//La soluzione migliore � quella iniziale
ConnectionUtil.closeConnection();
}
if ( vect.size() > 0 ) {
//return (ResultRecord[]) vect.toArray(new ResultRecord[vect.size()]);
return vect;
}
return null;
}
public List executeQueryTyped(String query, Class type, QueryTips tips){
// aggrega temporaneamente i risultati
ArrayList vect = new ArrayList();
String order_query = "";
String limit_query = "";
if ( tips != null ) {
order_query = tips.getOrderQuery();
limit_query = tips.getLimitQuery();
log.debug("order query:" + order_query);
log.debug("limit query:" + limit_query);
}
String final_query = query + order_query + limit_query;
Statement stmt = null;
ResultSet rs = null;
try {
conn = ConnectionUtil.currentConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
log.debug(final_query);
rs = stmt.executeQuery(final_query);
while (rs.next()) {
BasicRowProcessor proc = new BasicRowProcessor();
Object obj = proc.toBean(rs, type);
//log.debug("added object: " + obj);
vect.add(obj);
}
rs.close();
} catch (Exception e) {
log.error("",e);
} finally {
if (stmt != null) {
try { stmt.close(); } catch (SQLException ignore) {}
stmt = null;
}
//In realt� la connessione dovrebbe essere chiusa dal ConnectionFilter
//In questo caso sarebbe meglio chiedere la connessione ad ibatis e lasciarla
//chiudere a lui.
//Per motivi di tempo � stato utilizzato un workaround ovvero si � deciso
//di bypassare il connection filter e di fare il post processing alla fine di questo metodo.
//Per due motivi: il primo � che non avrebbe senso aggiungere il connection filter di
//questo modulo al web.xml, il secondo � che si ha bisogno di una soluzione immediata
//La soluzione migliore � quella iniziale
ConnectionUtil.closeConnection();
}
if ( vect.size() > 0 ) {
//return (ResultRecord[]) vect.toArray(new ResultRecord[vect.size()]);
return vect;
}
return null;
}
}
| openrecordz/openrecordz-server | src/main/java/microdev/db/QueryExecutor.java | 1,713 | // log.debug("rs.getObject(i).getClass():" + rs.getObject(i).getClass()); | line_comment | nl | /*
* Created on 21-feb-2006
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package microdev.db;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author andrea
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class QueryExecutor {
private Log log = LogFactory.getLog(QueryExecutor.class);
private Connection conn = null;
/** TODO */
public void execute(String query) {
// TODO
}
public List executeQuery(String query) {
return executeQuery(query, null);
}
public List executeQuery(String query, QueryTips tips) {
// aggrega temporaneamente i risultati
ArrayList vect = new ArrayList();
String order_query = "";
String limit_query = "";
if ( tips != null ) {
order_query = tips.getOrderQuery();
limit_query = tips.getLimitQuery();
}
String final_query = query + order_query + limit_query;
Statement stmt = null;
ResultSet rs = null;
try {
conn = ConnectionUtil.currentConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
//log.debug("executing query: " + final_query);
rs = stmt.executeQuery(final_query);
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
//ResultRecord rec = new ResultRecord();
Map rec = new LinkedHashMap();
for ( int i=1; i <= meta.getColumnCount(); i++ ) {
// log.debug("meta.getColumnLabel(i):" + meta.getColumnLabel(i));
// log.debug("meta.getColumnClassName(i):" + meta.getColumnClassName(i));
// log.debug("meta.getColumnType(i):" + meta.getColumnType(i));
// log.debug("meta.getColumnTypeName(i):" + meta.getColumnTypeName(i));
//
// log.debug("rs.getObject(i):" + rs.getObject(i));
// log.debug("rs.getObject(i).getClass():" +<SUF>
rec.put(meta.getColumnLabel(i),rs.getObject(i));
}
//log.debug("added record: " + rec);
vect.add(rec);
}
rs.close();
} catch (Exception e) {
log.error("",e);
} finally {
if (stmt != null) {
try { stmt.close(); } catch (SQLException ignore) {}
stmt = null;
}
//In realt� la connessione dovrebbe essere chiusa dal ConnectionFilter
//In questo caso sarebbe meglio chiedere la connessione ad ibatis e lasciarla
//chiudere a lui.
//Per motivi di tempo � stato utilizzato un workaround ovvero si � deciso
//di bypassare il connection filter e di fare il post processing alla fine di questo metodo.
//Per due motivi: il primo � che non avrebbe senso aggiungere il connection filter di
//questo modulo al web.xml, il secondo � che si ha bisogno di una soluzione immediata
//La soluzione migliore � quella iniziale
ConnectionUtil.closeConnection();
}
if ( vect.size() > 0 ) {
//return (ResultRecord[]) vect.toArray(new ResultRecord[vect.size()]);
return vect;
}
return null;
}
public List executeQueryTyped(String query, Class type, QueryTips tips){
// aggrega temporaneamente i risultati
ArrayList vect = new ArrayList();
String order_query = "";
String limit_query = "";
if ( tips != null ) {
order_query = tips.getOrderQuery();
limit_query = tips.getLimitQuery();
log.debug("order query:" + order_query);
log.debug("limit query:" + limit_query);
}
String final_query = query + order_query + limit_query;
Statement stmt = null;
ResultSet rs = null;
try {
conn = ConnectionUtil.currentConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
log.debug(final_query);
rs = stmt.executeQuery(final_query);
while (rs.next()) {
BasicRowProcessor proc = new BasicRowProcessor();
Object obj = proc.toBean(rs, type);
//log.debug("added object: " + obj);
vect.add(obj);
}
rs.close();
} catch (Exception e) {
log.error("",e);
} finally {
if (stmt != null) {
try { stmt.close(); } catch (SQLException ignore) {}
stmt = null;
}
//In realt� la connessione dovrebbe essere chiusa dal ConnectionFilter
//In questo caso sarebbe meglio chiedere la connessione ad ibatis e lasciarla
//chiudere a lui.
//Per motivi di tempo � stato utilizzato un workaround ovvero si � deciso
//di bypassare il connection filter e di fare il post processing alla fine di questo metodo.
//Per due motivi: il primo � che non avrebbe senso aggiungere il connection filter di
//questo modulo al web.xml, il secondo � che si ha bisogno di una soluzione immediata
//La soluzione migliore � quella iniziale
ConnectionUtil.closeConnection();
}
if ( vect.size() > 0 ) {
//return (ResultRecord[]) vect.toArray(new ResultRecord[vect.size()]);
return vect;
}
return null;
}
}
| False | 1,326 | 19 | 1,601 | 25 | 1,517 | 24 | 1,601 | 25 | 1,938 | 32 | false | false | false | false | false | true |
2,842 | 73282_6 | /* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
import java.nio.ByteBuffer;
/**
* Transformations on dictionary words.
*
* Transform descriptor is a triplet: {prefix, operator, suffix}.
* "prefix" and "suffix" are short strings inserted before and after transformed dictionary word.
* "operator" is applied to dictionary word itself.
*
* Some operators has "built-in" parameters, i.e. parameter is defined by operator ordinal. Other
* operators have "external" parameters, supplied via additional table encoded in shared dictionary.
*
* Operators:
* - IDENTITY (0): dictionary word is inserted "as is"
* - OMIT_LAST_N (1 - 9): last N octets of dictionary word are not inserted; N == ordinal
* - OMIT_FIRST_M (12-20): first M octets of dictionary word are not inserted; M == ordinal - 11
* - UPPERCASE_FIRST (10): first "scalar" is XOR'ed with number 32
* - UPPERCASE_ALL (11): all "scalars" are XOR'ed with number 32
* - SHIFT_FIRST (21): first "scalar" is shifted by number form parameter table
* - SHIFT_ALL (22): all "scalar" is shifted by number form parameter table
*
* Here "scalar" is a variable length character coding similar to UTF-8 encoding.
* UPPERCASE_XXX / SHIFT_XXX operators were designed to change the case of UTF-8 encoded characters.
* While UPPERCASE_XXX works well only on ASCII charset, SHIFT is much more generic and could be
* used for most (all?) alphabets.
*/
final class Transform {
static final class Transforms {
final int numTransforms;
final int[] triplets;
final byte[] prefixSuffixStorage;
final int[] prefixSuffixHeads;
final short[] params;
Transforms(int numTransforms, int prefixSuffixLen, int prefixSuffixCount) {
this.numTransforms = numTransforms;
this.triplets = new int[numTransforms * 3];
this.params = new short[numTransforms];
this.prefixSuffixStorage = new byte[prefixSuffixLen];
this.prefixSuffixHeads = new int[prefixSuffixCount + 1];
}
}
static final int NUM_RFC_TRANSFORMS = 121;
static final Transforms RFC_TRANSFORMS = new Transforms(NUM_RFC_TRANSFORMS, 167, 50);
private static final int OMIT_FIRST_LAST_LIMIT = 9;
private static final int IDENTITY = 0;
private static final int OMIT_LAST_BASE = IDENTITY + 1 - 1; // there is no OMIT_LAST_0.
private static final int UPPERCASE_FIRST = OMIT_LAST_BASE + OMIT_FIRST_LAST_LIMIT + 1;
private static final int UPPERCASE_ALL = UPPERCASE_FIRST + 1;
private static final int OMIT_FIRST_BASE = UPPERCASE_ALL + 1 - 1; // there is no OMIT_FIRST_0.
private static final int SHIFT_FIRST = OMIT_FIRST_BASE + OMIT_FIRST_LAST_LIMIT + 1;
private static final int SHIFT_ALL = SHIFT_FIRST + 1;
// Bundle of 0-terminated strings.
private static final String PREFIX_SUFFIX_SRC = "# #s #, #e #.# the #.com/#\u00C2\u00A0# of # and"
+ " # in # to #\"#\">#\n#]# for # a # that #. # with #'# from # by #. The # on # as # is #ing"
+ " #\n\t#:#ed #(# at #ly #=\"# of the #. This #,# not #er #al #='#ful #ive #less #est #ize #"
+ "ous #";
private static final String TRANSFORMS_SRC = " !! ! , *! &! \" ! ) * * - ! # ! #!*! "
+ "+ ,$ ! - % . / # 0 1 . \" 2 3!* 4% ! # / 5 6 7 8 0 1 & $ 9 + : "
+ " ; < ' != > ?! 4 @ 4 2 & A *# ( B C& ) % ) !*# *-% A +! *. D! %' & E *6 F "
+ " G% ! *A *% H! D I!+! J!+ K +- *4! A L!*4 M N +6 O!*% +.! K *G P +%( ! G *D +D "
+ " Q +# *K!*G!+D!+# +G +A +4!+% +K!+4!*D!+K!*K";
private static void unpackTransforms(byte[] prefixSuffix,
int[] prefixSuffixHeads, int[] transforms, String prefixSuffixSrc, String transformsSrc) {
final int n = prefixSuffixSrc.length();
int index = 1;
int j = 0;
for (int i = 0; i < n; ++i) {
final int c = (int) prefixSuffixSrc.charAt(i);
if (c == 35) { // == #
prefixSuffixHeads[index++] = j;
} else {
prefixSuffix[j++] = (byte) c;
}
}
for (int i = 0; i < NUM_RFC_TRANSFORMS * 3; ++i) {
transforms[i] = (int) transformsSrc.charAt(i) - 32;
}
}
static {
unpackTransforms(RFC_TRANSFORMS.prefixSuffixStorage, RFC_TRANSFORMS.prefixSuffixHeads,
RFC_TRANSFORMS.triplets, PREFIX_SUFFIX_SRC, TRANSFORMS_SRC);
}
static int transformDictionaryWord(byte[] dst, int dstOffset, ByteBuffer src, int srcOffset,
int wordLen, Transforms transforms, int transformIndex) {
int offset = dstOffset;
final int[] triplets = transforms.triplets;
final byte[] prefixSuffixStorage = transforms.prefixSuffixStorage;
final int[] prefixSuffixHeads = transforms.prefixSuffixHeads;
final int transformOffset = 3 * transformIndex;
final int prefixIdx = triplets[transformOffset];
final int transformType = triplets[transformOffset + 1];
final int suffixIdx = triplets[transformOffset + 2];
int prefix = prefixSuffixHeads[prefixIdx];
final int prefixEnd = prefixSuffixHeads[prefixIdx + 1];
int suffix = prefixSuffixHeads[suffixIdx];
final int suffixEnd = prefixSuffixHeads[suffixIdx + 1];
int omitFirst = transformType - OMIT_FIRST_BASE;
int omitLast = transformType - OMIT_LAST_BASE;
if (omitFirst < 1 || omitFirst > OMIT_FIRST_LAST_LIMIT) {
omitFirst = 0;
}
if (omitLast < 1 || omitLast > OMIT_FIRST_LAST_LIMIT) {
omitLast = 0;
}
// Copy prefix.
while (prefix != prefixEnd) {
dst[offset++] = prefixSuffixStorage[prefix++];
}
int len = wordLen;
// Copy trimmed word.
if (omitFirst > len) {
omitFirst = len;
}
int dictOffset = srcOffset + omitFirst;
len -= omitFirst;
len -= omitLast;
int i = len;
while (i > 0) {
dst[offset++] = src.get(dictOffset++);
i--;
}
// Ferment.
if (transformType == UPPERCASE_FIRST || transformType == UPPERCASE_ALL) {
int uppercaseOffset = offset - len;
if (transformType == UPPERCASE_FIRST) {
len = 1;
}
while (len > 0) {
final int c0 = (int) dst[uppercaseOffset] & 0xFF;
if (c0 < 0xC0) {
if (c0 >= 97 && c0 <= 122) { // in [a..z] range
dst[uppercaseOffset] = (byte) ((int) dst[uppercaseOffset] ^ 32);
}
uppercaseOffset += 1;
len -= 1;
} else if (c0 < 0xE0) {
dst[uppercaseOffset + 1] = (byte) ((int) dst[uppercaseOffset + 1] ^ 32);
uppercaseOffset += 2;
len -= 2;
} else {
dst[uppercaseOffset + 2] = (byte) ((int) dst[uppercaseOffset + 2] ^ 5);
uppercaseOffset += 3;
len -= 3;
}
}
} else if (transformType == SHIFT_FIRST || transformType == SHIFT_ALL) {
int shiftOffset = offset - len;
final int param = (int) transforms.params[transformIndex];
/* Limited sign extension: scalar < (1 << 24). */
int scalar = (param & 0x7FFF) + (0x1000000 - (param & 0x8000));
while (len > 0) {
int step = 1;
final int c0 = (int) dst[shiftOffset] & 0xFF;
if (c0 < 0x80) {
/* 1-byte rune / 0sssssss / 7 bit scalar (ASCII). */
scalar += c0;
dst[shiftOffset] = (byte) (scalar & 0x7F);
} else if (c0 < 0xC0) {
/* Continuation / 10AAAAAA. */
} else if (c0 < 0xE0) {
/* 2-byte rune / 110sssss AAssssss / 11 bit scalar. */
if (len >= 2) {
final int c1 = (int) dst[shiftOffset + 1];
scalar += (c1 & 0x3F) | ((c0 & 0x1F) << 6);
dst[shiftOffset] = (byte) (0xC0 | ((scalar >> 6) & 0x1F));
dst[shiftOffset + 1] = (byte) ((c1 & 0xC0) | (scalar & 0x3F));
step = 2;
} else {
step = len;
}
} else if (c0 < 0xF0) {
/* 3-byte rune / 1110ssss AAssssss BBssssss / 16 bit scalar. */
if (len >= 3) {
final int c1 = (int) dst[shiftOffset + 1];
final int c2 = (int) dst[shiftOffset + 2];
scalar += (c2 & 0x3F) | ((c1 & 0x3F) << 6) | ((c0 & 0x0F) << 12);
dst[shiftOffset] = (byte) (0xE0 | ((scalar >> 12) & 0x0F));
dst[shiftOffset + 1] = (byte) ((c1 & 0xC0) | ((scalar >> 6) & 0x3F));
dst[shiftOffset + 2] = (byte) ((c2 & 0xC0) | (scalar & 0x3F));
step = 3;
} else {
step = len;
}
} else if (c0 < 0xF8) {
/* 4-byte rune / 11110sss AAssssss BBssssss CCssssss / 21 bit scalar. */
if (len >= 4) {
final int c1 = (int) dst[shiftOffset + 1];
final int c2 = (int) dst[shiftOffset + 2];
final int c3 = (int) dst[shiftOffset + 3];
scalar += (c3 & 0x3F) | ((c2 & 0x3F) << 6) | ((c1 & 0x3F) << 12) | ((c0 & 0x07) << 18);
dst[shiftOffset] = (byte) (0xF0 | ((scalar >> 18) & 0x07));
dst[shiftOffset + 1] = (byte) ((c1 & 0xC0) | ((scalar >> 12) & 0x3F));
dst[shiftOffset + 2] = (byte) ((c2 & 0xC0) | ((scalar >> 6) & 0x3F));
dst[shiftOffset + 3] = (byte) ((c3 & 0xC0) | (scalar & 0x3F));
step = 4;
} else {
step = len;
}
}
shiftOffset += step;
len -= step;
if (transformType == SHIFT_FIRST) {
len = 0;
}
}
}
// Copy suffix.
while (suffix != suffixEnd) {
dst[offset++] = prefixSuffixStorage[suffix++];
}
return offset - dstOffset;
}
}
| google/brotli | java/org/brotli/dec/Transform.java | 3,692 | // in [a..z] range | line_comment | nl | /* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
package org.brotli.dec;
import java.nio.ByteBuffer;
/**
* Transformations on dictionary words.
*
* Transform descriptor is a triplet: {prefix, operator, suffix}.
* "prefix" and "suffix" are short strings inserted before and after transformed dictionary word.
* "operator" is applied to dictionary word itself.
*
* Some operators has "built-in" parameters, i.e. parameter is defined by operator ordinal. Other
* operators have "external" parameters, supplied via additional table encoded in shared dictionary.
*
* Operators:
* - IDENTITY (0): dictionary word is inserted "as is"
* - OMIT_LAST_N (1 - 9): last N octets of dictionary word are not inserted; N == ordinal
* - OMIT_FIRST_M (12-20): first M octets of dictionary word are not inserted; M == ordinal - 11
* - UPPERCASE_FIRST (10): first "scalar" is XOR'ed with number 32
* - UPPERCASE_ALL (11): all "scalars" are XOR'ed with number 32
* - SHIFT_FIRST (21): first "scalar" is shifted by number form parameter table
* - SHIFT_ALL (22): all "scalar" is shifted by number form parameter table
*
* Here "scalar" is a variable length character coding similar to UTF-8 encoding.
* UPPERCASE_XXX / SHIFT_XXX operators were designed to change the case of UTF-8 encoded characters.
* While UPPERCASE_XXX works well only on ASCII charset, SHIFT is much more generic and could be
* used for most (all?) alphabets.
*/
final class Transform {
static final class Transforms {
final int numTransforms;
final int[] triplets;
final byte[] prefixSuffixStorage;
final int[] prefixSuffixHeads;
final short[] params;
Transforms(int numTransforms, int prefixSuffixLen, int prefixSuffixCount) {
this.numTransforms = numTransforms;
this.triplets = new int[numTransforms * 3];
this.params = new short[numTransforms];
this.prefixSuffixStorage = new byte[prefixSuffixLen];
this.prefixSuffixHeads = new int[prefixSuffixCount + 1];
}
}
static final int NUM_RFC_TRANSFORMS = 121;
static final Transforms RFC_TRANSFORMS = new Transforms(NUM_RFC_TRANSFORMS, 167, 50);
private static final int OMIT_FIRST_LAST_LIMIT = 9;
private static final int IDENTITY = 0;
private static final int OMIT_LAST_BASE = IDENTITY + 1 - 1; // there is no OMIT_LAST_0.
private static final int UPPERCASE_FIRST = OMIT_LAST_BASE + OMIT_FIRST_LAST_LIMIT + 1;
private static final int UPPERCASE_ALL = UPPERCASE_FIRST + 1;
private static final int OMIT_FIRST_BASE = UPPERCASE_ALL + 1 - 1; // there is no OMIT_FIRST_0.
private static final int SHIFT_FIRST = OMIT_FIRST_BASE + OMIT_FIRST_LAST_LIMIT + 1;
private static final int SHIFT_ALL = SHIFT_FIRST + 1;
// Bundle of 0-terminated strings.
private static final String PREFIX_SUFFIX_SRC = "# #s #, #e #.# the #.com/#\u00C2\u00A0# of # and"
+ " # in # to #\"#\">#\n#]# for # a # that #. # with #'# from # by #. The # on # as # is #ing"
+ " #\n\t#:#ed #(# at #ly #=\"# of the #. This #,# not #er #al #='#ful #ive #less #est #ize #"
+ "ous #";
private static final String TRANSFORMS_SRC = " !! ! , *! &! \" ! ) * * - ! # ! #!*! "
+ "+ ,$ ! - % . / # 0 1 . \" 2 3!* 4% ! # / 5 6 7 8 0 1 & $ 9 + : "
+ " ; < ' != > ?! 4 @ 4 2 & A *# ( B C& ) % ) !*# *-% A +! *. D! %' & E *6 F "
+ " G% ! *A *% H! D I!+! J!+ K +- *4! A L!*4 M N +6 O!*% +.! K *G P +%( ! G *D +D "
+ " Q +# *K!*G!+D!+# +G +A +4!+% +K!+4!*D!+K!*K";
private static void unpackTransforms(byte[] prefixSuffix,
int[] prefixSuffixHeads, int[] transforms, String prefixSuffixSrc, String transformsSrc) {
final int n = prefixSuffixSrc.length();
int index = 1;
int j = 0;
for (int i = 0; i < n; ++i) {
final int c = (int) prefixSuffixSrc.charAt(i);
if (c == 35) { // == #
prefixSuffixHeads[index++] = j;
} else {
prefixSuffix[j++] = (byte) c;
}
}
for (int i = 0; i < NUM_RFC_TRANSFORMS * 3; ++i) {
transforms[i] = (int) transformsSrc.charAt(i) - 32;
}
}
static {
unpackTransforms(RFC_TRANSFORMS.prefixSuffixStorage, RFC_TRANSFORMS.prefixSuffixHeads,
RFC_TRANSFORMS.triplets, PREFIX_SUFFIX_SRC, TRANSFORMS_SRC);
}
static int transformDictionaryWord(byte[] dst, int dstOffset, ByteBuffer src, int srcOffset,
int wordLen, Transforms transforms, int transformIndex) {
int offset = dstOffset;
final int[] triplets = transforms.triplets;
final byte[] prefixSuffixStorage = transforms.prefixSuffixStorage;
final int[] prefixSuffixHeads = transforms.prefixSuffixHeads;
final int transformOffset = 3 * transformIndex;
final int prefixIdx = triplets[transformOffset];
final int transformType = triplets[transformOffset + 1];
final int suffixIdx = triplets[transformOffset + 2];
int prefix = prefixSuffixHeads[prefixIdx];
final int prefixEnd = prefixSuffixHeads[prefixIdx + 1];
int suffix = prefixSuffixHeads[suffixIdx];
final int suffixEnd = prefixSuffixHeads[suffixIdx + 1];
int omitFirst = transformType - OMIT_FIRST_BASE;
int omitLast = transformType - OMIT_LAST_BASE;
if (omitFirst < 1 || omitFirst > OMIT_FIRST_LAST_LIMIT) {
omitFirst = 0;
}
if (omitLast < 1 || omitLast > OMIT_FIRST_LAST_LIMIT) {
omitLast = 0;
}
// Copy prefix.
while (prefix != prefixEnd) {
dst[offset++] = prefixSuffixStorage[prefix++];
}
int len = wordLen;
// Copy trimmed word.
if (omitFirst > len) {
omitFirst = len;
}
int dictOffset = srcOffset + omitFirst;
len -= omitFirst;
len -= omitLast;
int i = len;
while (i > 0) {
dst[offset++] = src.get(dictOffset++);
i--;
}
// Ferment.
if (transformType == UPPERCASE_FIRST || transformType == UPPERCASE_ALL) {
int uppercaseOffset = offset - len;
if (transformType == UPPERCASE_FIRST) {
len = 1;
}
while (len > 0) {
final int c0 = (int) dst[uppercaseOffset] & 0xFF;
if (c0 < 0xC0) {
if (c0 >= 97 && c0 <= 122) { // in [a..z]<SUF>
dst[uppercaseOffset] = (byte) ((int) dst[uppercaseOffset] ^ 32);
}
uppercaseOffset += 1;
len -= 1;
} else if (c0 < 0xE0) {
dst[uppercaseOffset + 1] = (byte) ((int) dst[uppercaseOffset + 1] ^ 32);
uppercaseOffset += 2;
len -= 2;
} else {
dst[uppercaseOffset + 2] = (byte) ((int) dst[uppercaseOffset + 2] ^ 5);
uppercaseOffset += 3;
len -= 3;
}
}
} else if (transformType == SHIFT_FIRST || transformType == SHIFT_ALL) {
int shiftOffset = offset - len;
final int param = (int) transforms.params[transformIndex];
/* Limited sign extension: scalar < (1 << 24). */
int scalar = (param & 0x7FFF) + (0x1000000 - (param & 0x8000));
while (len > 0) {
int step = 1;
final int c0 = (int) dst[shiftOffset] & 0xFF;
if (c0 < 0x80) {
/* 1-byte rune / 0sssssss / 7 bit scalar (ASCII). */
scalar += c0;
dst[shiftOffset] = (byte) (scalar & 0x7F);
} else if (c0 < 0xC0) {
/* Continuation / 10AAAAAA. */
} else if (c0 < 0xE0) {
/* 2-byte rune / 110sssss AAssssss / 11 bit scalar. */
if (len >= 2) {
final int c1 = (int) dst[shiftOffset + 1];
scalar += (c1 & 0x3F) | ((c0 & 0x1F) << 6);
dst[shiftOffset] = (byte) (0xC0 | ((scalar >> 6) & 0x1F));
dst[shiftOffset + 1] = (byte) ((c1 & 0xC0) | (scalar & 0x3F));
step = 2;
} else {
step = len;
}
} else if (c0 < 0xF0) {
/* 3-byte rune / 1110ssss AAssssss BBssssss / 16 bit scalar. */
if (len >= 3) {
final int c1 = (int) dst[shiftOffset + 1];
final int c2 = (int) dst[shiftOffset + 2];
scalar += (c2 & 0x3F) | ((c1 & 0x3F) << 6) | ((c0 & 0x0F) << 12);
dst[shiftOffset] = (byte) (0xE0 | ((scalar >> 12) & 0x0F));
dst[shiftOffset + 1] = (byte) ((c1 & 0xC0) | ((scalar >> 6) & 0x3F));
dst[shiftOffset + 2] = (byte) ((c2 & 0xC0) | (scalar & 0x3F));
step = 3;
} else {
step = len;
}
} else if (c0 < 0xF8) {
/* 4-byte rune / 11110sss AAssssss BBssssss CCssssss / 21 bit scalar. */
if (len >= 4) {
final int c1 = (int) dst[shiftOffset + 1];
final int c2 = (int) dst[shiftOffset + 2];
final int c3 = (int) dst[shiftOffset + 3];
scalar += (c3 & 0x3F) | ((c2 & 0x3F) << 6) | ((c1 & 0x3F) << 12) | ((c0 & 0x07) << 18);
dst[shiftOffset] = (byte) (0xF0 | ((scalar >> 18) & 0x07));
dst[shiftOffset + 1] = (byte) ((c1 & 0xC0) | ((scalar >> 12) & 0x3F));
dst[shiftOffset + 2] = (byte) ((c2 & 0xC0) | ((scalar >> 6) & 0x3F));
dst[shiftOffset + 3] = (byte) ((c3 & 0xC0) | (scalar & 0x3F));
step = 4;
} else {
step = len;
}
}
shiftOffset += step;
len -= step;
if (transformType == SHIFT_FIRST) {
len = 0;
}
}
}
// Copy suffix.
while (suffix != suffixEnd) {
dst[offset++] = prefixSuffixStorage[suffix++];
}
return offset - dstOffset;
}
}
| False | 3,022 | 8 | 3,139 | 8 | 3,257 | 8 | 3,139 | 8 | 3,677 | 8 | false | false | false | false | false | true |
1,792 | 44439_2 | package test.view;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumWorksWellTest {
private WebDriver driver;
@Before
public void setUp() throws Exception {
// pas aan indien nodig
//System.setProperty("webdriver.chrome.driver", "/Users/grjon/Desktop/web3/chromedriver");
// windows: gebruik dubbele \\ om pad aan te geven
// hint: zoek een werkende test op van web 2 maar houd er rekening mee dat Chrome wellicht een upgrade kreeg
System.setProperty("webdriver.chrome.driver", "/Applications/chromedriver");
driver = new ChromeDriver();
driver.get("https://nl.wikipedia.org/wiki/Hoofdpagina");
}
@After
public void clean(){
driver.quit();
}
@Test
public void browserVindtWikipedia() {
assertEquals("Wikipedia, de vrije encyclopedie", driver.getTitle());
}
@Test
public void wikipediaVindtSelenium() {
WebElement field = driver.findElement(By.id("searchInput"));
field.clear();
field.sendKeys("selenium");
WebElement link = driver.findElement(By.id("searchButton"));
link.click();
assertEquals("Selenium - Wikipedia", driver.getTitle());
assertEquals("Selenium", driver.findElement(By.tagName("h1")).getText());
}
}
| UCLLWebontwikkeling3-1920/week01_labo1_opgave | test/test/view/SeleniumWorksWellTest.java | 468 | // hint: zoek een werkende test op van web 2 maar houd er rekening mee dat Chrome wellicht een upgrade kreeg | line_comment | nl | package test.view;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumWorksWellTest {
private WebDriver driver;
@Before
public void setUp() throws Exception {
// pas aan indien nodig
//System.setProperty("webdriver.chrome.driver", "/Users/grjon/Desktop/web3/chromedriver");
// windows: gebruik dubbele \\ om pad aan te geven
// hint: zoek<SUF>
System.setProperty("webdriver.chrome.driver", "/Applications/chromedriver");
driver = new ChromeDriver();
driver.get("https://nl.wikipedia.org/wiki/Hoofdpagina");
}
@After
public void clean(){
driver.quit();
}
@Test
public void browserVindtWikipedia() {
assertEquals("Wikipedia, de vrije encyclopedie", driver.getTitle());
}
@Test
public void wikipediaVindtSelenium() {
WebElement field = driver.findElement(By.id("searchInput"));
field.clear();
field.sendKeys("selenium");
WebElement link = driver.findElement(By.id("searchButton"));
link.click();
assertEquals("Selenium - Wikipedia", driver.getTitle());
assertEquals("Selenium", driver.findElement(By.tagName("h1")).getText());
}
}
| True | 336 | 29 | 424 | 34 | 390 | 25 | 424 | 34 | 508 | 31 | false | false | false | false | false | true |
177 | 181879_15 | /*
* B3P Kaartenbalie is a OGC WMS/WFS proxy that adds functionality
* for authentication/authorization, pricing and usage reporting.
*
* Copyright 2006, 2007, 2008 B3Partners BV
*
* This file is part of B3P Kaartenbalie.
*
* B3P Kaartenbalie is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B3P Kaartenbalie is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B3P Kaartenbalie. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.kaartenbalie.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import nl.b3p.wms.capabilities.Layer;
import nl.b3p.wms.capabilities.SrsBoundingBox;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Roy
*/
public class LayerValidator {
private static final Log log = LogFactory.getLog(LayerValidator.class);
private Set layers;
/** Creates a new Instance of LayerValidator with the given layers
*/
public LayerValidator(Set layers) {
setLayers(layers);
}
/* Getters and setters */
public Set getLayers() {
return layers;
}
public void setLayers(Set layers) {
this.layers = layers;
Iterator it = layers.iterator();
while (it.hasNext()) {
Layer l = (Layer) it.next();
Set srsbb = l.getSrsbb();
if (srsbb == null) {
log.debug("Layer: " + l.getUniqueName() + " does not have a SRS");
}
}
}
public boolean validate() {
return this.validateSRS().length > 0;
}
public SrsBoundingBox validateLatLonBoundingBox() {
Iterator it = layers.iterator();
ArrayList supportedLLBB = new ArrayList();
while (it.hasNext()) {
addLayerSupportedLLBB((Layer) it.next(), supportedLLBB);
}
//nu hebben we een lijst met alle LLBB's
//van deze LLBB's moet nu per item bekeken worden welke de uiterste waarden
//heeft voor de minx, miny, maxx, maxy
// volgende waarden geinitialiseerd op extreme omgekeerde waarde
double minx = 180.0, miny = 90.0, maxx = -180.0, maxy = -90.0;
it = supportedLLBB.iterator();
while (it.hasNext()) {
SrsBoundingBox llbb = (SrsBoundingBox) it.next();
double xmin = Double.parseDouble(llbb.getMinx());
double ymin = Double.parseDouble(llbb.getMiny());
double xmax = Double.parseDouble(llbb.getMaxx());
double ymax = Double.parseDouble(llbb.getMaxy());
if (xmin < minx) {
minx = xmin;
}
if (ymin < miny) {
miny = ymin;
}
if (xmax > maxx) {
maxx = xmax;
}
if (ymax > maxy) {
maxy = ymax;
}
}
SrsBoundingBox llbb = new SrsBoundingBox();
llbb.setMinx(Double.toString(minx));
llbb.setMiny(Double.toString(miny));
llbb.setMaxx(Double.toString(maxx));
llbb.setMaxy(Double.toString(maxy));
return llbb;
}
/**
* Checks wether or not a layer has a LatLonBoundingBox. If so this LatLonBoundingBox is added to the supported hashmap
*/
// <editor-fold defaultstate="" desc="default DescribeLayerRequestHandler() constructor">
private void addLayerSupportedLLBB(Layer layer, ArrayList supported) {
Set srsen = layer.getSrsbb();
if (srsen == null) {
return;
}
Iterator it = srsen.iterator();
while (it.hasNext()) {
SrsBoundingBox srsbb = (SrsBoundingBox) it.next();
String type = srsbb.getType();
if (type != null) {
if (type.equalsIgnoreCase("LatLonBoundingBox")) {
supported.add(srsbb);
}
}
}
if (layer.getParent() != null) {
addLayerSupportedLLBB(layer.getParent(), supported);
}
}
// </editor-fold>
/** add a srs supported by this layer or a parent of the layer to the supported hashmap
*/
public void addLayerSupportedSRS(Layer l, HashMap supported) {
Set srsen = l.getSrsbb();
if (srsen == null) {
return;
}
Iterator i = srsen.iterator();
while (i.hasNext()) {
SrsBoundingBox srsbb = (SrsBoundingBox) i.next();
if (srsbb.getSrs() != null) {
// alleen srs zonder boundingbox coords
if (srsbb.getMinx() == null && srsbb.getMiny() == null && srsbb.getMaxx() == null && srsbb.getMaxy() == null) {
supported.put(srsbb.getSrs(), srsbb.getSrs());
}
}
}
if (l.getParent() != null) {
addLayerSupportedSRS(l.getParent(), supported);
}
}
/** Returns the combined srs's that all layers given supports
*
* Every Layer shall have at least one <SRS> element that is either stated explicitly or
* inherited from a parent Layer (Section 7.1.4.6). The root <Layer> element shall include a
* sequence of zero or more SRS elements listing all SRSes that are common to all
* subsidiary layers. Use a single SRS element with empty content (like so: "<SRS></SRS>") if
* there is no common SRS. Layers may optionally add to the global SRS list, or to the list
* inherited from a parent layer. Any duplication shall be ignored by clients.
*/
public String[] validateSRS() {
HashMap hm = new HashMap();
Iterator lit = layers.iterator();
//Een teller die alle layers telt die een SRS hebben.
int tellerMeeTellendeLayers = 0;
//doorloop de layers
while (lit.hasNext()) {
HashMap supportedByLayer = new HashMap();
addLayerSupportedSRS((Layer) lit.next(), supportedByLayer);
if (supportedByLayer.size() > 0) {
tellerMeeTellendeLayers++;
Iterator i = supportedByLayer.values().iterator();
while (i.hasNext()) {
String srs = (String) i.next();
addSrsCount(hm, srs);
}
}
}
ArrayList supportedSrsen = new ArrayList();
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
int i = ((Integer) entry.getValue()).intValue();
if (i >= tellerMeeTellendeLayers) {
supportedSrsen.add((String) entry.getKey());
}
}
//Voeg lege srs toe indien geen overeenkomstige gevonden
if (supportedSrsen.isEmpty()) {
supportedSrsen.add("");
}
String[] returnValue = new String[supportedSrsen.size()];
for (int i = 0; i < returnValue.length; i++) {
if (supportedSrsen.get(i) != null) {
returnValue[i] = (String) supportedSrsen.get(i);
}
}
return returnValue;
}
/** Methode that counts the different SRS's
* @parameter hm The hashmap that contains the counted srsen
* @parameter srs The srs to add to the count.
*/
private void addSrsCount(HashMap hm, String srs) {
if (hm.containsKey(srs)) {
int i = ((Integer) hm.get(srs)).intValue() + 1;
hm.put(srs, new Integer(i));
} else {
hm.put(srs, new Integer("1"));
}
}
}
| B3Partners/kaartenbalie | src/main/java/nl/b3p/kaartenbalie/service/LayerValidator.java | 2,392 | //Voeg lege srs toe indien geen overeenkomstige gevonden | line_comment | nl | /*
* B3P Kaartenbalie is a OGC WMS/WFS proxy that adds functionality
* for authentication/authorization, pricing and usage reporting.
*
* Copyright 2006, 2007, 2008 B3Partners BV
*
* This file is part of B3P Kaartenbalie.
*
* B3P Kaartenbalie is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* B3P Kaartenbalie is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with B3P Kaartenbalie. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.kaartenbalie.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import nl.b3p.wms.capabilities.Layer;
import nl.b3p.wms.capabilities.SrsBoundingBox;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Roy
*/
public class LayerValidator {
private static final Log log = LogFactory.getLog(LayerValidator.class);
private Set layers;
/** Creates a new Instance of LayerValidator with the given layers
*/
public LayerValidator(Set layers) {
setLayers(layers);
}
/* Getters and setters */
public Set getLayers() {
return layers;
}
public void setLayers(Set layers) {
this.layers = layers;
Iterator it = layers.iterator();
while (it.hasNext()) {
Layer l = (Layer) it.next();
Set srsbb = l.getSrsbb();
if (srsbb == null) {
log.debug("Layer: " + l.getUniqueName() + " does not have a SRS");
}
}
}
public boolean validate() {
return this.validateSRS().length > 0;
}
public SrsBoundingBox validateLatLonBoundingBox() {
Iterator it = layers.iterator();
ArrayList supportedLLBB = new ArrayList();
while (it.hasNext()) {
addLayerSupportedLLBB((Layer) it.next(), supportedLLBB);
}
//nu hebben we een lijst met alle LLBB's
//van deze LLBB's moet nu per item bekeken worden welke de uiterste waarden
//heeft voor de minx, miny, maxx, maxy
// volgende waarden geinitialiseerd op extreme omgekeerde waarde
double minx = 180.0, miny = 90.0, maxx = -180.0, maxy = -90.0;
it = supportedLLBB.iterator();
while (it.hasNext()) {
SrsBoundingBox llbb = (SrsBoundingBox) it.next();
double xmin = Double.parseDouble(llbb.getMinx());
double ymin = Double.parseDouble(llbb.getMiny());
double xmax = Double.parseDouble(llbb.getMaxx());
double ymax = Double.parseDouble(llbb.getMaxy());
if (xmin < minx) {
minx = xmin;
}
if (ymin < miny) {
miny = ymin;
}
if (xmax > maxx) {
maxx = xmax;
}
if (ymax > maxy) {
maxy = ymax;
}
}
SrsBoundingBox llbb = new SrsBoundingBox();
llbb.setMinx(Double.toString(minx));
llbb.setMiny(Double.toString(miny));
llbb.setMaxx(Double.toString(maxx));
llbb.setMaxy(Double.toString(maxy));
return llbb;
}
/**
* Checks wether or not a layer has a LatLonBoundingBox. If so this LatLonBoundingBox is added to the supported hashmap
*/
// <editor-fold defaultstate="" desc="default DescribeLayerRequestHandler() constructor">
private void addLayerSupportedLLBB(Layer layer, ArrayList supported) {
Set srsen = layer.getSrsbb();
if (srsen == null) {
return;
}
Iterator it = srsen.iterator();
while (it.hasNext()) {
SrsBoundingBox srsbb = (SrsBoundingBox) it.next();
String type = srsbb.getType();
if (type != null) {
if (type.equalsIgnoreCase("LatLonBoundingBox")) {
supported.add(srsbb);
}
}
}
if (layer.getParent() != null) {
addLayerSupportedLLBB(layer.getParent(), supported);
}
}
// </editor-fold>
/** add a srs supported by this layer or a parent of the layer to the supported hashmap
*/
public void addLayerSupportedSRS(Layer l, HashMap supported) {
Set srsen = l.getSrsbb();
if (srsen == null) {
return;
}
Iterator i = srsen.iterator();
while (i.hasNext()) {
SrsBoundingBox srsbb = (SrsBoundingBox) i.next();
if (srsbb.getSrs() != null) {
// alleen srs zonder boundingbox coords
if (srsbb.getMinx() == null && srsbb.getMiny() == null && srsbb.getMaxx() == null && srsbb.getMaxy() == null) {
supported.put(srsbb.getSrs(), srsbb.getSrs());
}
}
}
if (l.getParent() != null) {
addLayerSupportedSRS(l.getParent(), supported);
}
}
/** Returns the combined srs's that all layers given supports
*
* Every Layer shall have at least one <SRS> element that is either stated explicitly or
* inherited from a parent Layer (Section 7.1.4.6). The root <Layer> element shall include a
* sequence of zero or more SRS elements listing all SRSes that are common to all
* subsidiary layers. Use a single SRS element with empty content (like so: "<SRS></SRS>") if
* there is no common SRS. Layers may optionally add to the global SRS list, or to the list
* inherited from a parent layer. Any duplication shall be ignored by clients.
*/
public String[] validateSRS() {
HashMap hm = new HashMap();
Iterator lit = layers.iterator();
//Een teller die alle layers telt die een SRS hebben.
int tellerMeeTellendeLayers = 0;
//doorloop de layers
while (lit.hasNext()) {
HashMap supportedByLayer = new HashMap();
addLayerSupportedSRS((Layer) lit.next(), supportedByLayer);
if (supportedByLayer.size() > 0) {
tellerMeeTellendeLayers++;
Iterator i = supportedByLayer.values().iterator();
while (i.hasNext()) {
String srs = (String) i.next();
addSrsCount(hm, srs);
}
}
}
ArrayList supportedSrsen = new ArrayList();
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
int i = ((Integer) entry.getValue()).intValue();
if (i >= tellerMeeTellendeLayers) {
supportedSrsen.add((String) entry.getKey());
}
}
//Voeg lege<SUF>
if (supportedSrsen.isEmpty()) {
supportedSrsen.add("");
}
String[] returnValue = new String[supportedSrsen.size()];
for (int i = 0; i < returnValue.length; i++) {
if (supportedSrsen.get(i) != null) {
returnValue[i] = (String) supportedSrsen.get(i);
}
}
return returnValue;
}
/** Methode that counts the different SRS's
* @parameter hm The hashmap that contains the counted srsen
* @parameter srs The srs to add to the count.
*/
private void addSrsCount(HashMap hm, String srs) {
if (hm.containsKey(srs)) {
int i = ((Integer) hm.get(srs)).intValue() + 1;
hm.put(srs, new Integer(i));
} else {
hm.put(srs, new Integer("1"));
}
}
}
| True | 1,896 | 18 | 2,047 | 22 | 2,134 | 13 | 2,047 | 22 | 2,448 | 20 | false | false | false | false | false | true |
2,117 | 25068_4 | /*
* MicroMulti.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import com.foundationdb.*;
import com.foundationdb.async.Function;
import com.foundationdb.async.Future;
import com.foundationdb.subspace.Subspace;
import com.foundationdb.tuple.Tuple;
public class MicroMulti {
private static final FDB fdb;
private static final Database db;
private static final Subspace multi;
private static final int N = 100;
static {
fdb = FDB.selectAPIVersion(300);
db = fdb.open();
multi = new Subspace(Tuple.from("M"));
}
// TODO These two methods (addHelp and getLong) are used by the methods
// that are definitely in the book.
private static void addHelp(TransactionContext tcx, final byte[] key, final long amount){
tcx.run(new Function<Transaction,Void>() {
public Void apply(Transaction tr){
ByteBuffer b = ByteBuffer.allocate(8);
b.order(ByteOrder.LITTLE_ENDIAN);
b.putLong(amount);
tr.mutate(MutationType.ADD, key, b.array());
return null;
}
});
}
private static long getLong(byte[] val){
ByteBuffer b = ByteBuffer.allocate(8);
b.order(ByteOrder.LITTLE_ENDIAN);
b.put(val);
return b.getLong(0);
}
// TODO These five methods are definitely in the recipe book
// (add, subtract, get, getCounts, and isElement).
public static void add(TransactionContext tcx, final String index,
final Object value){
tcx.run(new Function<Transaction,Void>() {
public Void apply(Transaction tr){
addHelp(tr, multi.subspace(Tuple.from(index,value)).getKey(),1l);
return null;
}
});
}
public static void subtract(TransactionContext tcx, final String index,
final Object value){
tcx.run(new Function<Transaction,Void>() {
public Void apply(Transaction tr){
Future<byte[]> v = tr.get(multi.subspace(
Tuple.from(index,value)).getKey());
if(v.get() != null && getLong(v.get()) > 1l){
addHelp(tr, multi.subspace(Tuple.from(index,value)).getKey(), -1l);
} else {
tr.clear(multi.subspace(Tuple.from(index,value)).getKey());
}
return null;
}
});
}
public static ArrayList<Object> get(TransactionContext tcx, final String index){
return tcx.run(new Function<Transaction,ArrayList<Object> >() {
public ArrayList<Object> apply(Transaction tr){
ArrayList<Object> vals = new ArrayList<Object>();
for(KeyValue kv : tr.getRange(multi.subspace(
Tuple.from(index)).range())){
vals.add(multi.unpack(kv.getKey()).get(1));
}
return vals;
}
});
}
public static HashMap<Object,Long> getCounts(TransactionContext tcx,
final String index){
return tcx.run(new Function<Transaction,HashMap<Object,Long> >() {
public HashMap<Object,Long> apply(Transaction tr){
HashMap<Object,Long> vals = new HashMap<Object,Long>();
for(KeyValue kv : tr.getRange(multi.subspace(
Tuple.from(index)).range())){
vals.put(multi.unpack(kv.getKey()).get(1),
getLong(kv.getValue()));
}
return vals;
}
});
}
public static boolean isElement(TransactionContext tcx, final String index,
final Object value){
return tcx.run(new Function<Transaction,Boolean>() {
public Boolean apply(Transaction tr){
return tr.get(multi.subspace(
Tuple.from(index, value)).getKey()).get() != null;
}
});
}
public static void clearSubspace(TransactionContext tcx, final Subspace s){
tcx.run(new Function<Transaction,Void>() {
public Void apply(Transaction tr){
tr.clear(s.range());
return null;
}
});
}
public static void main(String[] args) {
clearSubspace(db, multi);
for(int i = 0; i < N; i++){
add(db, "foo", "bar");
if(i % 100 == 0){
System.out.println(i);
}
}
for(int i = 0; i < N/10; i++){
add(db,"foo","bear");
add(db,"foo","boar");
add(db,"fu","kung");
}
add(db,"fu","barre");
subtract(db,"fu","barre");
for(int i = 0; i < N/10; i++){
subtract(db,"foo","bar");
if(i % 100 == 0){
System.out.println(i);
}
}
System.out.println(isElement(db, "foo", "bar"));
System.out.println(isElement(db, "foo", "bor"));
System.out.println(isElement(db, "fu", "kung"));
HashMap<Object,Long> map = getCounts(db,"foo");
for(Entry<Object, Long> kv : map.entrySet()){
System.out.println(kv);
}
map = getCounts(db,"fu");
for(Entry<Object,Long> kv : map.entrySet()){
System.out.println(kv);
}
}
}
| apple/foundationdb | recipes/java-recipes/MicroMulti.java | 1,762 | // (add, subtract, get, getCounts, and isElement). | line_comment | nl | /*
* MicroMulti.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import com.foundationdb.*;
import com.foundationdb.async.Function;
import com.foundationdb.async.Future;
import com.foundationdb.subspace.Subspace;
import com.foundationdb.tuple.Tuple;
public class MicroMulti {
private static final FDB fdb;
private static final Database db;
private static final Subspace multi;
private static final int N = 100;
static {
fdb = FDB.selectAPIVersion(300);
db = fdb.open();
multi = new Subspace(Tuple.from("M"));
}
// TODO These two methods (addHelp and getLong) are used by the methods
// that are definitely in the book.
private static void addHelp(TransactionContext tcx, final byte[] key, final long amount){
tcx.run(new Function<Transaction,Void>() {
public Void apply(Transaction tr){
ByteBuffer b = ByteBuffer.allocate(8);
b.order(ByteOrder.LITTLE_ENDIAN);
b.putLong(amount);
tr.mutate(MutationType.ADD, key, b.array());
return null;
}
});
}
private static long getLong(byte[] val){
ByteBuffer b = ByteBuffer.allocate(8);
b.order(ByteOrder.LITTLE_ENDIAN);
b.put(val);
return b.getLong(0);
}
// TODO These five methods are definitely in the recipe book
// (add, subtract,<SUF>
public static void add(TransactionContext tcx, final String index,
final Object value){
tcx.run(new Function<Transaction,Void>() {
public Void apply(Transaction tr){
addHelp(tr, multi.subspace(Tuple.from(index,value)).getKey(),1l);
return null;
}
});
}
public static void subtract(TransactionContext tcx, final String index,
final Object value){
tcx.run(new Function<Transaction,Void>() {
public Void apply(Transaction tr){
Future<byte[]> v = tr.get(multi.subspace(
Tuple.from(index,value)).getKey());
if(v.get() != null && getLong(v.get()) > 1l){
addHelp(tr, multi.subspace(Tuple.from(index,value)).getKey(), -1l);
} else {
tr.clear(multi.subspace(Tuple.from(index,value)).getKey());
}
return null;
}
});
}
public static ArrayList<Object> get(TransactionContext tcx, final String index){
return tcx.run(new Function<Transaction,ArrayList<Object> >() {
public ArrayList<Object> apply(Transaction tr){
ArrayList<Object> vals = new ArrayList<Object>();
for(KeyValue kv : tr.getRange(multi.subspace(
Tuple.from(index)).range())){
vals.add(multi.unpack(kv.getKey()).get(1));
}
return vals;
}
});
}
public static HashMap<Object,Long> getCounts(TransactionContext tcx,
final String index){
return tcx.run(new Function<Transaction,HashMap<Object,Long> >() {
public HashMap<Object,Long> apply(Transaction tr){
HashMap<Object,Long> vals = new HashMap<Object,Long>();
for(KeyValue kv : tr.getRange(multi.subspace(
Tuple.from(index)).range())){
vals.put(multi.unpack(kv.getKey()).get(1),
getLong(kv.getValue()));
}
return vals;
}
});
}
public static boolean isElement(TransactionContext tcx, final String index,
final Object value){
return tcx.run(new Function<Transaction,Boolean>() {
public Boolean apply(Transaction tr){
return tr.get(multi.subspace(
Tuple.from(index, value)).getKey()).get() != null;
}
});
}
public static void clearSubspace(TransactionContext tcx, final Subspace s){
tcx.run(new Function<Transaction,Void>() {
public Void apply(Transaction tr){
tr.clear(s.range());
return null;
}
});
}
public static void main(String[] args) {
clearSubspace(db, multi);
for(int i = 0; i < N; i++){
add(db, "foo", "bar");
if(i % 100 == 0){
System.out.println(i);
}
}
for(int i = 0; i < N/10; i++){
add(db,"foo","bear");
add(db,"foo","boar");
add(db,"fu","kung");
}
add(db,"fu","barre");
subtract(db,"fu","barre");
for(int i = 0; i < N/10; i++){
subtract(db,"foo","bar");
if(i % 100 == 0){
System.out.println(i);
}
}
System.out.println(isElement(db, "foo", "bar"));
System.out.println(isElement(db, "foo", "bor"));
System.out.println(isElement(db, "fu", "kung"));
HashMap<Object,Long> map = getCounts(db,"foo");
for(Entry<Object, Long> kv : map.entrySet()){
System.out.println(kv);
}
map = getCounts(db,"fu");
for(Entry<Object,Long> kv : map.entrySet()){
System.out.println(kv);
}
}
}
| False | 1,326 | 15 | 1,643 | 15 | 1,631 | 15 | 1,643 | 15 | 2,006 | 16 | false | false | false | false | false | true |
3,044 | 99659_2 | package edu.ap.be.backend.models;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import javax.persistence.*;
import org.springframework.data.annotation.Transient;
import java.util.List;
@Entity
@Table(name = "roles")
// @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
// property = "id")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(insertable = false, updatable = false)
private Long id;
// meer aandachtt hieraan later
@Transient
@Enumerated(EnumType.STRING)
@Column(insertable = false, updatable = false)
private RoleType role;
@JsonManagedReference
// @JoinColumn("users", insertable=false, updatable=false)
@OneToMany(mappedBy = "role", cascade = CascadeType.REMOVE)
@Column(insertable = false, updatable = false)
private List<User> users;
// private List<Roles> roles = new ArrayList<>();
/*
* public Role(String name){
* this.rol = Roles.valueOf(name.toUpperCase(Locale.ROOT));
* }
*/
public Role(RoleType role) {
this.role = role;
}
public Role() {
}
public Role(String role) {
this.role = RoleType.valueOf(role.toUpperCase());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public RoleType getRole() {
return role;
}
public void setRole(RoleType role) {
this.role = role;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public void add(RoleType role) {
this.role = role;
}
}
| iDeebSee/project-informatica | backend/src/main/java/edu/ap/be/backend/models/Role.java | 613 | // meer aandachtt hieraan later | line_comment | nl | package edu.ap.be.backend.models;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import javax.persistence.*;
import org.springframework.data.annotation.Transient;
import java.util.List;
@Entity
@Table(name = "roles")
// @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
// property = "id")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(insertable = false, updatable = false)
private Long id;
// meer aandachtt<SUF>
@Transient
@Enumerated(EnumType.STRING)
@Column(insertable = false, updatable = false)
private RoleType role;
@JsonManagedReference
// @JoinColumn("users", insertable=false, updatable=false)
@OneToMany(mappedBy = "role", cascade = CascadeType.REMOVE)
@Column(insertable = false, updatable = false)
private List<User> users;
// private List<Roles> roles = new ArrayList<>();
/*
* public Role(String name){
* this.rol = Roles.valueOf(name.toUpperCase(Locale.ROOT));
* }
*/
public Role(RoleType role) {
this.role = role;
}
public Role() {
}
public Role(String role) {
this.role = RoleType.valueOf(role.toUpperCase());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public RoleType getRole() {
return role;
}
public void setRole(RoleType role) {
this.role = role;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public void add(RoleType role) {
this.role = role;
}
}
| True | 423 | 9 | 510 | 9 | 545 | 8 | 510 | 9 | 629 | 10 | false | false | false | false | false | true |
3,582 | 58650_9 | /**
* Copyright 2002 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
*
* This file is part of MARY TTS.
*
* MARY TTS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package marytts.language.de.postlex;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* The rules for the postlexical phonological processes module.
*
* @author Marc Schröder
*/
public class PhonologicalRules {
// Rules as regular expressions with substitution patterns:
// The first string is a regular expression pattern, the three others are
// substitution patterns for PRECISE, NORMAL and SLOPPY pronunciation
// respectively. They may contain bracket references $1, $2, ...
// as in the example below:
// {"([bdg])@(n)", "$1@$2", "$1@$2", "$1@$2"}
private static final String[][] _rules = {
// @-Elision mit -en, -el, -em
{ "([dlrszSt])@n", "$1@n", "$1@n", "$1@n" },
// warning: mbrola de1/2 don't have Z-n diphone
// @Elision mit -en, -el, -em; Assimilation
{ "f@n", "f@n", "f@n", "f@n" },
{ "g@n", "g@n", "g@n", "g@n" }, // warning: mbrola de1 doesn't have g-N diphone
{ "k@n", "k@n", "k@n", "k@n" },// warning: mbrola de1 doesn't have k-N diphone
{ "p@n", "p@n", "p@n", "p@n" },
{ "x@n", "x@n", "x@n", "x@n" },// warning: mbrola de1/2 don't have x-N diphone
// @-Elision mit -en, -el, -em; Assimilation und Geminatenreduktion
{ "b@n", "b@n", "b@n", "b@n" },// warning: mbrola de1 doesn't have b-m diphone
{ "m@n", "m@n", "m@n", "m@n" },
{ "n@n", "n@n", "n@n", "n@n" },
// bei Geminatenreduktion wird der uebrigbleibende Laut eigentlich gelaengt.
// Da es jedoch noch kein Symbol und keine Semantik fuer Laengung gibt,
// soll an dieser Stelle nur darauf hingewiesen werden.
// Assimilation der Artikulationsart
{ "g-n", "g-n", "g-n", "g-n" },
// Assimilation und Geminatenreduktion
{ "m-b", "m-b", "m-b", "m-b" },
{ "t-t", "t-t", "t-t", "t-t" },
// bei Geminatenreduktion wird der uebrigbleibende Laut eigentlich gelaengt.
// Da es jedoch noch kein Symbol und keine Semantik fuer Laengung gibt,
// soll an dieser Stelle nur darauf hingewiesen werden.
// glottal stop removal:
{ "\\?(aI|OY|aU|[iIyYe\\{E29uUoOaA])", "?$1", "?$1", "?$1" },
// Reduce E6 -> 6 in unstressed syllables only:
// {"^([^'-]*)E6", "$16", "$16", "$16"},
// {"-([^'-]*)E6", "-$16", "-$16", "-$16"},
// be more specific: reduce fE6 -> f6 in unstressed syllables only
{ "^([^'-]*)fE6", "$1f6", "$1f6", "$1f6" },
{ "-([^'-]*)fE6", "-$1f6", "-$1f6", "-$1f6" },
// Replace ?6 with ?E6 wordinitial
{ "\\?6", "\\?E6", "\\?E6", "\\?E6" },
// !! Translate the old MARY SAMPA to the new MARY SAMPA:
{ "O~:", "a~", "a~", "a~" }, { "o~:", "o~", "o~", "o~" }, { "9~:", "9~", "9~", "9~" }, { "E~:", "e~", "e~", "e~" },
{ "O~", "a~", "a~", "a~" }, { "o~", "o~", "o~", "o~" }, { "9~", "9~", "9~", "9~" }, { "E~", "e~", "e~", "e~" },
{ "\\{", "E", "E", "E" },
// {"r", "R", "R", "R"}
};
private static final List<PhonologicalRules> rules = initialiseRules();
private static List<PhonologicalRules> initialiseRules() {
List<PhonologicalRules> r = new ArrayList<PhonologicalRules>();
for (int i = 0; i < _rules.length; i++) {
r.add(new PhonologicalRules(_rules[i]));
}
return r;
}
public static List<PhonologicalRules> getRules() {
return rules;
}
public static final int PRECISE = 1;
public static final int NORMAL = 2;
public static final int SLOPPY = 3;
private Pattern key;
private String precise;
private String normal;
private String sloppy;
public PhonologicalRules(String[] data) {
try {
key = Pattern.compile(data[0]);
} catch (PatternSyntaxException e) {
System.err.println("Cannot compile regular expression `" + data[0] + "':");
e.printStackTrace();
}
precise = data[1];
normal = data[2];
sloppy = data[3];
}
public boolean matches(String input) {
return key.matcher(input).find();
}
public String apply(String input, int precision) {
String repl = normal;
if (precision == PRECISE)
repl = precise;
else if (precision == SLOPPY)
repl = sloppy;
return key.matcher(input).replaceAll(repl);
}
}
| marytts/marytts | marytts-languages/marytts-lang-de/src/main/java/marytts/language/de/postlex/PhonologicalRules.java | 1,875 | // warning: mbrola de1/2 don't have Z-n diphone | line_comment | nl | /**
* Copyright 2002 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
*
* This file is part of MARY TTS.
*
* MARY TTS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package marytts.language.de.postlex;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* The rules for the postlexical phonological processes module.
*
* @author Marc Schröder
*/
public class PhonologicalRules {
// Rules as regular expressions with substitution patterns:
// The first string is a regular expression pattern, the three others are
// substitution patterns for PRECISE, NORMAL and SLOPPY pronunciation
// respectively. They may contain bracket references $1, $2, ...
// as in the example below:
// {"([bdg])@(n)", "$1@$2", "$1@$2", "$1@$2"}
private static final String[][] _rules = {
// @-Elision mit -en, -el, -em
{ "([dlrszSt])@n", "$1@n", "$1@n", "$1@n" },
// warning: mbrola<SUF>
// @Elision mit -en, -el, -em; Assimilation
{ "f@n", "f@n", "f@n", "f@n" },
{ "g@n", "g@n", "g@n", "g@n" }, // warning: mbrola de1 doesn't have g-N diphone
{ "k@n", "k@n", "k@n", "k@n" },// warning: mbrola de1 doesn't have k-N diphone
{ "p@n", "p@n", "p@n", "p@n" },
{ "x@n", "x@n", "x@n", "x@n" },// warning: mbrola de1/2 don't have x-N diphone
// @-Elision mit -en, -el, -em; Assimilation und Geminatenreduktion
{ "b@n", "b@n", "b@n", "b@n" },// warning: mbrola de1 doesn't have b-m diphone
{ "m@n", "m@n", "m@n", "m@n" },
{ "n@n", "n@n", "n@n", "n@n" },
// bei Geminatenreduktion wird der uebrigbleibende Laut eigentlich gelaengt.
// Da es jedoch noch kein Symbol und keine Semantik fuer Laengung gibt,
// soll an dieser Stelle nur darauf hingewiesen werden.
// Assimilation der Artikulationsart
{ "g-n", "g-n", "g-n", "g-n" },
// Assimilation und Geminatenreduktion
{ "m-b", "m-b", "m-b", "m-b" },
{ "t-t", "t-t", "t-t", "t-t" },
// bei Geminatenreduktion wird der uebrigbleibende Laut eigentlich gelaengt.
// Da es jedoch noch kein Symbol und keine Semantik fuer Laengung gibt,
// soll an dieser Stelle nur darauf hingewiesen werden.
// glottal stop removal:
{ "\\?(aI|OY|aU|[iIyYe\\{E29uUoOaA])", "?$1", "?$1", "?$1" },
// Reduce E6 -> 6 in unstressed syllables only:
// {"^([^'-]*)E6", "$16", "$16", "$16"},
// {"-([^'-]*)E6", "-$16", "-$16", "-$16"},
// be more specific: reduce fE6 -> f6 in unstressed syllables only
{ "^([^'-]*)fE6", "$1f6", "$1f6", "$1f6" },
{ "-([^'-]*)fE6", "-$1f6", "-$1f6", "-$1f6" },
// Replace ?6 with ?E6 wordinitial
{ "\\?6", "\\?E6", "\\?E6", "\\?E6" },
// !! Translate the old MARY SAMPA to the new MARY SAMPA:
{ "O~:", "a~", "a~", "a~" }, { "o~:", "o~", "o~", "o~" }, { "9~:", "9~", "9~", "9~" }, { "E~:", "e~", "e~", "e~" },
{ "O~", "a~", "a~", "a~" }, { "o~", "o~", "o~", "o~" }, { "9~", "9~", "9~", "9~" }, { "E~", "e~", "e~", "e~" },
{ "\\{", "E", "E", "E" },
// {"r", "R", "R", "R"}
};
private static final List<PhonologicalRules> rules = initialiseRules();
private static List<PhonologicalRules> initialiseRules() {
List<PhonologicalRules> r = new ArrayList<PhonologicalRules>();
for (int i = 0; i < _rules.length; i++) {
r.add(new PhonologicalRules(_rules[i]));
}
return r;
}
public static List<PhonologicalRules> getRules() {
return rules;
}
public static final int PRECISE = 1;
public static final int NORMAL = 2;
public static final int SLOPPY = 3;
private Pattern key;
private String precise;
private String normal;
private String sloppy;
public PhonologicalRules(String[] data) {
try {
key = Pattern.compile(data[0]);
} catch (PatternSyntaxException e) {
System.err.println("Cannot compile regular expression `" + data[0] + "':");
e.printStackTrace();
}
precise = data[1];
normal = data[2];
sloppy = data[3];
}
public boolean matches(String input) {
return key.matcher(input).find();
}
public String apply(String input, int precision) {
String repl = normal;
if (precision == PRECISE)
repl = precise;
else if (precision == SLOPPY)
repl = sloppy;
return key.matcher(input).replaceAll(repl);
}
}
| False | 1,667 | 17 | 1,821 | 18 | 1,740 | 19 | 1,821 | 18 | 2,029 | 19 | false | false | false | false | false | true |
525 | 53445_0 | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class RunFromFile {
private static final String IP_ADDRESS = "192.168.43.1";
private static BufferedReader br;
private static DatagramSocket datagramSocket;
private static int i = 0;
public static void main(String[] args) throws InterruptedException, IOException {
initFile();
byte[] tempBytes;
datagramSocket = new DatagramSocket(9000);
tempBytes = getLine();
while (tempBytes != null) {
System.out.println("Sending Packet..");
System.out.println();
sendPacket(tempBytes);
//receivePacket();
Thread.sleep(100);
tempBytes = getLine();
}
}
public static void initFile() throws FileNotFoundException {
br = new BufferedReader(new FileReader("engine_data.txt"));
}
public static byte[] getLine() throws IOException {
String line;
if ((line = br.readLine()) != null) {
byte[] bytearray = new byte[10];
for (int i = 0; i < 20; i += 2) {
byte byte1 = (byte) (Integer.parseInt(line.substring(i, i + 2), 16) & 0xff);
bytearray[i / 2] = byte1;
}
return bytearray;
} else {
br.close();
return null;
}
}
public static String bytArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder();
for (byte b : a)
sb.append(String.format("%02x ", b & 0xff));
return sb.toString();
}
public static void sendPacket(byte[] stream) throws IOException {
InetAddress address = InetAddress.getByName(IP_ADDRESS); // IP-adres van de ontvanger hier zetten
DatagramPacket packet = new DatagramPacket(stream, stream.length, address, 9000);
DatagramSocket datagramSocket = new DatagramSocket();
datagramSocket.send(packet);
}
public static void receivePacket() throws IOException {
Thread thread = new Thread() {
public void run() {
i++;
System.out.println("Receiving packet..");
byte[] buffer2 = new byte[10];
try {
DatagramPacket packet = new DatagramPacket(buffer2, buffer2.length);
datagramSocket.receive(packet);
buffer2 = packet.getData();
if (buffer2 != null) {
System.out.println("UDP Packet " + i + ": " + bytArrayToHex(buffer2));
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
// Generate data is een functie om een custom ID en een integer value om te zetten naar bytes. Heb je niet echt nodig maar hebben het in het project laten staan.
public static byte[] generateData(int id, int value) {
byte[] array1 = new byte[10];
array1[0] = (byte) id;
ByteBuffer b = ByteBuffer.allocate(8);
b.order(ByteOrder.nativeOrder());
b.putInt(value);
for (int i = 0; i < 8; i++) {
array1[i + 2] = b.array()[7 - i];
}
return array1;
}
}
| FezzFest/FastradaTI | Mock Data/src/main/java/RunFromFile.java | 955 | // IP-adres van de ontvanger hier zetten | line_comment | nl | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class RunFromFile {
private static final String IP_ADDRESS = "192.168.43.1";
private static BufferedReader br;
private static DatagramSocket datagramSocket;
private static int i = 0;
public static void main(String[] args) throws InterruptedException, IOException {
initFile();
byte[] tempBytes;
datagramSocket = new DatagramSocket(9000);
tempBytes = getLine();
while (tempBytes != null) {
System.out.println("Sending Packet..");
System.out.println();
sendPacket(tempBytes);
//receivePacket();
Thread.sleep(100);
tempBytes = getLine();
}
}
public static void initFile() throws FileNotFoundException {
br = new BufferedReader(new FileReader("engine_data.txt"));
}
public static byte[] getLine() throws IOException {
String line;
if ((line = br.readLine()) != null) {
byte[] bytearray = new byte[10];
for (int i = 0; i < 20; i += 2) {
byte byte1 = (byte) (Integer.parseInt(line.substring(i, i + 2), 16) & 0xff);
bytearray[i / 2] = byte1;
}
return bytearray;
} else {
br.close();
return null;
}
}
public static String bytArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder();
for (byte b : a)
sb.append(String.format("%02x ", b & 0xff));
return sb.toString();
}
public static void sendPacket(byte[] stream) throws IOException {
InetAddress address = InetAddress.getByName(IP_ADDRESS); // IP-adres van<SUF>
DatagramPacket packet = new DatagramPacket(stream, stream.length, address, 9000);
DatagramSocket datagramSocket = new DatagramSocket();
datagramSocket.send(packet);
}
public static void receivePacket() throws IOException {
Thread thread = new Thread() {
public void run() {
i++;
System.out.println("Receiving packet..");
byte[] buffer2 = new byte[10];
try {
DatagramPacket packet = new DatagramPacket(buffer2, buffer2.length);
datagramSocket.receive(packet);
buffer2 = packet.getData();
if (buffer2 != null) {
System.out.println("UDP Packet " + i + ": " + bytArrayToHex(buffer2));
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
// Generate data is een functie om een custom ID en een integer value om te zetten naar bytes. Heb je niet echt nodig maar hebben het in het project laten staan.
public static byte[] generateData(int id, int value) {
byte[] array1 = new byte[10];
array1[0] = (byte) id;
ByteBuffer b = ByteBuffer.allocate(8);
b.order(ByteOrder.nativeOrder());
b.putInt(value);
for (int i = 0; i < 8; i++) {
array1[i + 2] = b.array()[7 - i];
}
return array1;
}
}
| True | 739 | 12 | 835 | 14 | 892 | 11 | 835 | 14 | 969 | 13 | false | false | false | false | false | true |
3,338 | 116140_6 | /**_x000D_
* <copyright>_x000D_
* </copyright>_x000D_
*_x000D_
* $Id$_x000D_
*/_x000D_
package RefOntoUML.impl;_x000D_
_x000D_
import RefOntoUML.Characterization;_x000D_
import RefOntoUML.Classifier;_x000D_
import RefOntoUML.Property;_x000D_
import RefOntoUML.RefOntoUMLPackage;_x000D_
_x000D_
import org.eclipse.emf.ecore.EAnnotation;_x000D_
import org.eclipse.emf.ecore.EClass;_x000D_
import org.eclipse.emf.ecore.EClassifier;_x000D_
import org.eclipse.emf.ecore.EOperation;_x000D_
_x000D_
import org.eclipse.ocl.ParserException;_x000D_
import org.eclipse.ocl.Query;_x000D_
_x000D_
import org.eclipse.ocl.ecore.OCL;_x000D_
_x000D_
import org.eclipse.ocl.expressions.OCLExpression;_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* An implementation of the model object '<em><b>Characterization</b></em>'._x000D_
* <!-- end-user-doc -->_x000D_
* <p>_x000D_
* </p>_x000D_
*_x000D_
* @generated_x000D_
*/_x000D_
public class CharacterizationImpl extends DependencyRelationshipImpl implements Characterization {_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
protected CharacterizationImpl() {_x000D_
super();_x000D_
}_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
@Override_x000D_
protected EClass eStaticClass() {_x000D_
return RefOntoUMLPackage.eINSTANCE.getCharacterization();_x000D_
}_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
public Property characterizingEnd() {_x000D_
if (characterizingEndBodyOCL == null) {_x000D_
EOperation eOperation = RefOntoUMLPackage.eINSTANCE.getCharacterization().getEOperations().get(0);_x000D_
OCL.Helper helper = OCL_ENV.createOCLHelper();_x000D_
helper.setOperationContext(RefOntoUMLPackage.eINSTANCE.getCharacterization(), eOperation);_x000D_
EAnnotation ocl = eOperation.getEAnnotation(OCL_ANNOTATION_SOURCE);_x000D_
String body = ocl.getDetails().get("body");_x000D_
_x000D_
try {_x000D_
characterizingEndBodyOCL = helper.createQuery(body);_x000D_
} catch (ParserException e) {_x000D_
throw new UnsupportedOperationException(e.getLocalizedMessage());_x000D_
}_x000D_
}_x000D_
_x000D_
Query<EClassifier, ?, ?> query = OCL_ENV.createQuery(characterizingEndBodyOCL);_x000D_
_x000D_
return (Property) query.evaluate(this);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
public Property characterizedEnd() {_x000D_
if (characterizedEndBodyOCL == null) {_x000D_
EOperation eOperation = RefOntoUMLPackage.eINSTANCE.getCharacterization().getEOperations().get(1);_x000D_
OCL.Helper helper = OCL_ENV.createOCLHelper();_x000D_
helper.setOperationContext(RefOntoUMLPackage.eINSTANCE.getCharacterization(), eOperation);_x000D_
EAnnotation ocl = eOperation.getEAnnotation(OCL_ANNOTATION_SOURCE);_x000D_
String body = ocl.getDetails().get("body");_x000D_
_x000D_
try {_x000D_
characterizedEndBodyOCL = helper.createQuery(body);_x000D_
} catch (ParserException e) {_x000D_
throw new UnsupportedOperationException(e.getLocalizedMessage());_x000D_
}_x000D_
}_x000D_
_x000D_
Query<EClassifier, ?, ?> query = OCL_ENV.createQuery(characterizedEndBodyOCL);_x000D_
_x000D_
return (Property) query.evaluate(this);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
public Classifier characterizing() {_x000D_
if (characterizingBodyOCL == null) {_x000D_
EOperation eOperation = RefOntoUMLPackage.eINSTANCE.getCharacterization().getEOperations().get(2);_x000D_
OCL.Helper helper = OCL_ENV.createOCLHelper();_x000D_
helper.setOperationContext(RefOntoUMLPackage.eINSTANCE.getCharacterization(), eOperation);_x000D_
EAnnotation ocl = eOperation.getEAnnotation(OCL_ANNOTATION_SOURCE);_x000D_
String body = ocl.getDetails().get("body");_x000D_
_x000D_
try {_x000D_
characterizingBodyOCL = helper.createQuery(body);_x000D_
} catch (ParserException e) {_x000D_
throw new UnsupportedOperationException(e.getLocalizedMessage());_x000D_
}_x000D_
}_x000D_
_x000D_
Query<EClassifier, ?, ?> query = OCL_ENV.createQuery(characterizingBodyOCL);_x000D_
_x000D_
return (Classifier) query.evaluate(this);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
public Classifier characterized() {_x000D_
if (characterizedBodyOCL == null) {_x000D_
EOperation eOperation = RefOntoUMLPackage.eINSTANCE.getCharacterization().getEOperations().get(3);_x000D_
OCL.Helper helper = OCL_ENV.createOCLHelper();_x000D_
helper.setOperationContext(RefOntoUMLPackage.eINSTANCE.getCharacterization(), eOperation);_x000D_
EAnnotation ocl = eOperation.getEAnnotation(OCL_ANNOTATION_SOURCE);_x000D_
String body = ocl.getDetails().get("body");_x000D_
_x000D_
try {_x000D_
characterizedBodyOCL = helper.createQuery(body);_x000D_
} catch (ParserException e) {_x000D_
throw new UnsupportedOperationException(e.getLocalizedMessage());_x000D_
}_x000D_
}_x000D_
_x000D_
Query<EClassifier, ?, ?> query = OCL_ENV.createQuery(characterizedBodyOCL);_x000D_
_x000D_
return (Classifier) query.evaluate(this);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* The parsed OCL expression for the body of the '{@link #characterizingEnd <em>Characterizing End</em>}' operation._x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @see #characterizingEnd_x000D_
* @generated_x000D_
*/_x000D_
private static OCLExpression<EClassifier> characterizingEndBodyOCL;_x000D_
_x000D_
/**_x000D_
* The parsed OCL expression for the body of the '{@link #characterizedEnd <em>Characterized End</em>}' operation._x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @see #characterizedEnd_x000D_
* @generated_x000D_
*/_x000D_
private static OCLExpression<EClassifier> characterizedEndBodyOCL;_x000D_
_x000D_
/**_x000D_
* The parsed OCL expression for the body of the '{@link #characterizing <em>Characterizing</em>}' operation._x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @see #characterizing_x000D_
* @generated_x000D_
*/_x000D_
private static OCLExpression<EClassifier> characterizingBodyOCL;_x000D_
_x000D_
/**_x000D_
* The parsed OCL expression for the body of the '{@link #characterized <em>Characterized</em>}' operation._x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @see #characterized_x000D_
* @generated_x000D_
*/_x000D_
private static OCLExpression<EClassifier> characterizedBodyOCL;_x000D_
_x000D_
private static final String OCL_ANNOTATION_SOURCE = "http://www.eclipse.org/ocl/examples/OCL";_x000D_
_x000D_
private static final OCL OCL_ENV = OCL.newInstance();_x000D_
} //CharacterizationImpl_x000D_
| kbss-cvut/menthor-editor | net.menthor.ontouml/src/RefOntoUML/impl/CharacterizationImpl.java | 2,034 | /**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/ | block_comment | nl | /**_x000D_
* <copyright>_x000D_
* </copyright>_x000D_
*_x000D_
* $Id$_x000D_
*/_x000D_
package RefOntoUML.impl;_x000D_
_x000D_
import RefOntoUML.Characterization;_x000D_
import RefOntoUML.Classifier;_x000D_
import RefOntoUML.Property;_x000D_
import RefOntoUML.RefOntoUMLPackage;_x000D_
_x000D_
import org.eclipse.emf.ecore.EAnnotation;_x000D_
import org.eclipse.emf.ecore.EClass;_x000D_
import org.eclipse.emf.ecore.EClassifier;_x000D_
import org.eclipse.emf.ecore.EOperation;_x000D_
_x000D_
import org.eclipse.ocl.ParserException;_x000D_
import org.eclipse.ocl.Query;_x000D_
_x000D_
import org.eclipse.ocl.ecore.OCL;_x000D_
_x000D_
import org.eclipse.ocl.expressions.OCLExpression;_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* An implementation of the model object '<em><b>Characterization</b></em>'._x000D_
* <!-- end-user-doc -->_x000D_
* <p>_x000D_
* </p>_x000D_
*_x000D_
* @generated_x000D_
*/_x000D_
public class CharacterizationImpl extends DependencyRelationshipImpl implements Characterization {_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
protected CharacterizationImpl() {_x000D_
super();_x000D_
}_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
@Override_x000D_
protected EClass eStaticClass() {_x000D_
return RefOntoUMLPackage.eINSTANCE.getCharacterization();_x000D_
}_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
public Property characterizingEnd() {_x000D_
if (characterizingEndBodyOCL == null) {_x000D_
EOperation eOperation = RefOntoUMLPackage.eINSTANCE.getCharacterization().getEOperations().get(0);_x000D_
OCL.Helper helper = OCL_ENV.createOCLHelper();_x000D_
helper.setOperationContext(RefOntoUMLPackage.eINSTANCE.getCharacterization(), eOperation);_x000D_
EAnnotation ocl = eOperation.getEAnnotation(OCL_ANNOTATION_SOURCE);_x000D_
String body = ocl.getDetails().get("body");_x000D_
_x000D_
try {_x000D_
characterizingEndBodyOCL = helper.createQuery(body);_x000D_
} catch (ParserException e) {_x000D_
throw new UnsupportedOperationException(e.getLocalizedMessage());_x000D_
}_x000D_
}_x000D_
_x000D_
Query<EClassifier, ?, ?> query = OCL_ENV.createQuery(characterizingEndBodyOCL);_x000D_
_x000D_
return (Property) query.evaluate(this);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
public Property characterizedEnd() {_x000D_
if (characterizedEndBodyOCL == null) {_x000D_
EOperation eOperation = RefOntoUMLPackage.eINSTANCE.getCharacterization().getEOperations().get(1);_x000D_
OCL.Helper helper = OCL_ENV.createOCLHelper();_x000D_
helper.setOperationContext(RefOntoUMLPackage.eINSTANCE.getCharacterization(), eOperation);_x000D_
EAnnotation ocl = eOperation.getEAnnotation(OCL_ANNOTATION_SOURCE);_x000D_
String body = ocl.getDetails().get("body");_x000D_
_x000D_
try {_x000D_
characterizedEndBodyOCL = helper.createQuery(body);_x000D_
} catch (ParserException e) {_x000D_
throw new UnsupportedOperationException(e.getLocalizedMessage());_x000D_
}_x000D_
}_x000D_
_x000D_
Query<EClassifier, ?, ?> query = OCL_ENV.createQuery(characterizedEndBodyOCL);_x000D_
_x000D_
return (Property) query.evaluate(this);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_<SUF>*/_x000D_
public Classifier characterizing() {_x000D_
if (characterizingBodyOCL == null) {_x000D_
EOperation eOperation = RefOntoUMLPackage.eINSTANCE.getCharacterization().getEOperations().get(2);_x000D_
OCL.Helper helper = OCL_ENV.createOCLHelper();_x000D_
helper.setOperationContext(RefOntoUMLPackage.eINSTANCE.getCharacterization(), eOperation);_x000D_
EAnnotation ocl = eOperation.getEAnnotation(OCL_ANNOTATION_SOURCE);_x000D_
String body = ocl.getDetails().get("body");_x000D_
_x000D_
try {_x000D_
characterizingBodyOCL = helper.createQuery(body);_x000D_
} catch (ParserException e) {_x000D_
throw new UnsupportedOperationException(e.getLocalizedMessage());_x000D_
}_x000D_
}_x000D_
_x000D_
Query<EClassifier, ?, ?> query = OCL_ENV.createQuery(characterizingBodyOCL);_x000D_
_x000D_
return (Classifier) query.evaluate(this);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @generated_x000D_
*/_x000D_
public Classifier characterized() {_x000D_
if (characterizedBodyOCL == null) {_x000D_
EOperation eOperation = RefOntoUMLPackage.eINSTANCE.getCharacterization().getEOperations().get(3);_x000D_
OCL.Helper helper = OCL_ENV.createOCLHelper();_x000D_
helper.setOperationContext(RefOntoUMLPackage.eINSTANCE.getCharacterization(), eOperation);_x000D_
EAnnotation ocl = eOperation.getEAnnotation(OCL_ANNOTATION_SOURCE);_x000D_
String body = ocl.getDetails().get("body");_x000D_
_x000D_
try {_x000D_
characterizedBodyOCL = helper.createQuery(body);_x000D_
} catch (ParserException e) {_x000D_
throw new UnsupportedOperationException(e.getLocalizedMessage());_x000D_
}_x000D_
}_x000D_
_x000D_
Query<EClassifier, ?, ?> query = OCL_ENV.createQuery(characterizedBodyOCL);_x000D_
_x000D_
return (Classifier) query.evaluate(this);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* The parsed OCL expression for the body of the '{@link #characterizingEnd <em>Characterizing End</em>}' operation._x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @see #characterizingEnd_x000D_
* @generated_x000D_
*/_x000D_
private static OCLExpression<EClassifier> characterizingEndBodyOCL;_x000D_
_x000D_
/**_x000D_
* The parsed OCL expression for the body of the '{@link #characterizedEnd <em>Characterized End</em>}' operation._x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @see #characterizedEnd_x000D_
* @generated_x000D_
*/_x000D_
private static OCLExpression<EClassifier> characterizedEndBodyOCL;_x000D_
_x000D_
/**_x000D_
* The parsed OCL expression for the body of the '{@link #characterizing <em>Characterizing</em>}' operation._x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @see #characterizing_x000D_
* @generated_x000D_
*/_x000D_
private static OCLExpression<EClassifier> characterizingBodyOCL;_x000D_
_x000D_
/**_x000D_
* The parsed OCL expression for the body of the '{@link #characterized <em>Characterized</em>}' operation._x000D_
* <!-- begin-user-doc -->_x000D_
* <!-- end-user-doc -->_x000D_
* @see #characterized_x000D_
* @generated_x000D_
*/_x000D_
private static OCLExpression<EClassifier> characterizedBodyOCL;_x000D_
_x000D_
private static final String OCL_ANNOTATION_SOURCE = "http://www.eclipse.org/ocl/examples/OCL";_x000D_
_x000D_
private static final OCL OCL_ENV = OCL.newInstance();_x000D_
} //CharacterizationImpl_x000D_
| False | 2,730 | 48 | 3,075 | 53 | 3,118 | 57 | 3,075 | 53 | 3,386 | 57 | false | false | false | false | false | true |
1,253 | 30787_2 | /**
* AODA - Aspect Oriented Debugging Architecture
* Copyright (C) 2007-2009 Wouter De Borger
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package adb;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.sun.jdi.AbsentInformationException;
import com.sun.jdi.VMMismatchException;
import com.sun.jdi.VirtualMachine;
import adb.backend.FilterManager;
import adb.tools.Converter;
import adb.tools.InterList;
import ajdi.ClassLoaderReference;
import ajdi.ClassObjectReference;
import ajdi.Field;
import ajdi.Location;
import ajdi.Method;
import ajdi.ObjectReference;
import ajdi.ReferenceType;
import ajdi.Shadow;
import ajdi.Value;
//TODO field locations bij allLineLocations en LocationForLine
public abstract class AbstractReferenceTypeImpl<T extends com.sun.jdi.ReferenceType>
implements ReferenceTypeImpl {
private T base;
protected ShadowMaster master;
public AbstractReferenceTypeImpl(T base, ShadowMaster master) {
super();
this.base = base;
this.master = master;
}
public List<Field> allFields() {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Field, Field>(fm.filterFields(unwrap().allFields()),
getFieldConverter());
}
public List<Location> allLineLocations() throws AbsentInformationException {
return new InterList<com.sun.jdi.Location, Location>(unwrap()
.allLineLocations(), master.getLocationConverter());
}
public abstract List<Method> allMethods();
public Field fieldByName(String fieldName) {
return wrap(unwrap().fieldByName(fieldName));
}
public List<Field> fields() {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Field, Field>(fm.filterFields(unwrap().fields()),
getFieldConverter());
}
public Value getValue(Field field) {
return master.wrap(unwrap().getValue(unwrap(field)));
}
public Map<Field, Value> getValues(List<Field> fields) {
Map<Field, Value> map = new TreeMap<Field, Value>();
for (Field field : fields) {
map.put(field, getValue(field));
}
return map;
}
public List<Location> locationsOfLine(int lineNumber)
throws AbsentInformationException {
return new InterList<com.sun.jdi.Location, Location>(unwrap()
.locationsOfLine(lineNumber), master.getLocationConverter());
}
public List<Method> methods() {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Method, Method>(fm.filterMethods(unwrap().methods()),getMethodConverter());
}
public List<Method> methodsByName(String name) {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Method, Method>(fm.filterMethods(unwrap().methodsByName(name)),getMethodConverter());
}
public List<Method> methodsByName(String name, String signature) {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Method, Method>(fm.filterMethods(unwrap().methodsByName(name, signature)),getMethodConverter());
}
public List<ReferenceType> nestedTypes() {
return new InterList<com.sun.jdi.ReferenceType, ReferenceType>(unwrap().nestedTypes(),master.getReferenceTypeConverter());
}
public List<Field> visibleFields() {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Field, Field>(fm.filterFields(unwrap().visibleFields()),getFieldConverter());
}
public List<Method> visibleMethods() {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Method, Method>(fm.filterMethods(unwrap().visibleMethods()),getMethodConverter());
}
public ClassLoaderReference classLoader() {
return (ClassLoaderReference) shadowMaster().wrap(unwrap().classLoader());
}
private ajdi.ClassObjectReference classo;
public ajdi.ClassObjectReference classObject() {
if(classo == null)
classo = master.wrap(unwrap().classObject());
return classo;
}
public boolean failedToInitialize() {
return unwrap().failedToInitialize();
}
public String genericSignature() {
return unwrap().genericSignature();
}
public boolean isAbstract() {
return unwrap().isAbstract();
}
public boolean isFinal() {
return unwrap().isFinal();
}
public boolean isInitialized() {
return unwrap().isInitialized();
}
public boolean isPrepared() {
return unwrap().isPrepared();
}
public boolean isStatic() {
return unwrap().isStatic();
}
public boolean isVerified() {
return unwrap().isVerified();
}
public String sourceName() throws AbsentInformationException {
return unwrap().sourceName();
}
public String name() {
return unwrap().name();
}
public String signature() {
return unwrap().signature();
}
public VirtualMachine virtualMachine() {
return unwrap().virtualMachine();
}
public boolean isPackagePrivate() {
return unwrap().isPackagePrivate();
}
public boolean isPrivate() {
return unwrap().isPrivate();
}
public boolean isProtected() {
return unwrap().isProtected();
}
public boolean isPublic() {
return unwrap().isPublic();
}
public int modifiers() {
return unwrap().modifiers();
}
//Iterne keuken
// cache alles, zo dicht mogelijk bij de consumer
com.sun.jdi.Method unwrap(Method method) {
checkMaster(method);
return ((MethodImpl)method).getBase();
}
private final Map<com.sun.jdi.Method, MethodImpl> methodsExt = new HashMap<com.sun.jdi.Method, MethodImpl>();
//private final Map<Method, com.sun.jdi.Method> methodsInt = new HashMap<Method, com.sun.jdi.Method>();
public MethodImpl wrap(com.sun.jdi.Method method) {
if(!method.declaringType().equals(unwrap()))
return master.wrap(method.declaringType()).wrap(method);
MethodImpl meth = methodsExt.get(method);
if(meth == null){
meth = master.createMethod(this,method);
if(meth != null)
methodsExt.put(method, meth);
}
return meth;
}
private final Converter<com.sun.jdi.Method, Method> methodConverter = new Converter<com.sun.jdi.Method, Method>(){
public Method convert(com.sun.jdi.Method source) {
return wrap(source);
}};
private Converter<com.sun.jdi.Method, Method> getMethodConverter() {
return methodConverter;
}
private final Map<com.sun.jdi.Field,Field> fieldsExt = new HashMap<com.sun.jdi.Field, Field>();
// private final Map<Field,com.sun.jdi.Field> fieldsInt = new HashMap<Field, com.sun.jdi.Field>();
//moet public door inheritance, eigenlijk protected
public Field wrap(com.sun.jdi.Field field) {
if(!field.declaringType().equals(unwrap()))
return master.wrap(field.declaringType()).wrap(field);
Field f = fieldsExt.get(field);
if(f == null){
f = master.createField(this,field);
if(field != null)
fieldsExt.put(field, f);
// fieldsInt.put(f, field);
}
return f;
}
protected com.sun.jdi.Field unwrap(Field field) {
return ((FieldImpl)field).base;
}
private final Converter<com.sun.jdi.Field, Field> fieldConverter = new Converter<com.sun.jdi.Field, Field>(){
public Field convert(com.sun.jdi.Field source) {
return wrap(source);
}};
private Converter<com.sun.jdi.Field, Field> getFieldConverter() {
return fieldConverter;
}
private void checkMaster(Shadow other) {
if(other.shadowMaster() != master)
throw new VMMismatchException("object came form different master");
}
public ShadowMaster shadowMaster(){
return master;
}
T unwrap() {
return base;
}
public String toString(){
return name();
}
}
| OpenUniversity/AOP-Awesome-Legacy | awesome.ajdi/adb/AbstractReferenceTypeImpl.java | 2,515 | // cache alles, zo dicht mogelijk bij de consumer | line_comment | nl | /**
* AODA - Aspect Oriented Debugging Architecture
* Copyright (C) 2007-2009 Wouter De Borger
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package adb;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.sun.jdi.AbsentInformationException;
import com.sun.jdi.VMMismatchException;
import com.sun.jdi.VirtualMachine;
import adb.backend.FilterManager;
import adb.tools.Converter;
import adb.tools.InterList;
import ajdi.ClassLoaderReference;
import ajdi.ClassObjectReference;
import ajdi.Field;
import ajdi.Location;
import ajdi.Method;
import ajdi.ObjectReference;
import ajdi.ReferenceType;
import ajdi.Shadow;
import ajdi.Value;
//TODO field locations bij allLineLocations en LocationForLine
public abstract class AbstractReferenceTypeImpl<T extends com.sun.jdi.ReferenceType>
implements ReferenceTypeImpl {
private T base;
protected ShadowMaster master;
public AbstractReferenceTypeImpl(T base, ShadowMaster master) {
super();
this.base = base;
this.master = master;
}
public List<Field> allFields() {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Field, Field>(fm.filterFields(unwrap().allFields()),
getFieldConverter());
}
public List<Location> allLineLocations() throws AbsentInformationException {
return new InterList<com.sun.jdi.Location, Location>(unwrap()
.allLineLocations(), master.getLocationConverter());
}
public abstract List<Method> allMethods();
public Field fieldByName(String fieldName) {
return wrap(unwrap().fieldByName(fieldName));
}
public List<Field> fields() {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Field, Field>(fm.filterFields(unwrap().fields()),
getFieldConverter());
}
public Value getValue(Field field) {
return master.wrap(unwrap().getValue(unwrap(field)));
}
public Map<Field, Value> getValues(List<Field> fields) {
Map<Field, Value> map = new TreeMap<Field, Value>();
for (Field field : fields) {
map.put(field, getValue(field));
}
return map;
}
public List<Location> locationsOfLine(int lineNumber)
throws AbsentInformationException {
return new InterList<com.sun.jdi.Location, Location>(unwrap()
.locationsOfLine(lineNumber), master.getLocationConverter());
}
public List<Method> methods() {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Method, Method>(fm.filterMethods(unwrap().methods()),getMethodConverter());
}
public List<Method> methodsByName(String name) {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Method, Method>(fm.filterMethods(unwrap().methodsByName(name)),getMethodConverter());
}
public List<Method> methodsByName(String name, String signature) {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Method, Method>(fm.filterMethods(unwrap().methodsByName(name, signature)),getMethodConverter());
}
public List<ReferenceType> nestedTypes() {
return new InterList<com.sun.jdi.ReferenceType, ReferenceType>(unwrap().nestedTypes(),master.getReferenceTypeConverter());
}
public List<Field> visibleFields() {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Field, Field>(fm.filterFields(unwrap().visibleFields()),getFieldConverter());
}
public List<Method> visibleMethods() {
FilterManager fm = shadowMaster().getFilterManager();
return new InterList<com.sun.jdi.Method, Method>(fm.filterMethods(unwrap().visibleMethods()),getMethodConverter());
}
public ClassLoaderReference classLoader() {
return (ClassLoaderReference) shadowMaster().wrap(unwrap().classLoader());
}
private ajdi.ClassObjectReference classo;
public ajdi.ClassObjectReference classObject() {
if(classo == null)
classo = master.wrap(unwrap().classObject());
return classo;
}
public boolean failedToInitialize() {
return unwrap().failedToInitialize();
}
public String genericSignature() {
return unwrap().genericSignature();
}
public boolean isAbstract() {
return unwrap().isAbstract();
}
public boolean isFinal() {
return unwrap().isFinal();
}
public boolean isInitialized() {
return unwrap().isInitialized();
}
public boolean isPrepared() {
return unwrap().isPrepared();
}
public boolean isStatic() {
return unwrap().isStatic();
}
public boolean isVerified() {
return unwrap().isVerified();
}
public String sourceName() throws AbsentInformationException {
return unwrap().sourceName();
}
public String name() {
return unwrap().name();
}
public String signature() {
return unwrap().signature();
}
public VirtualMachine virtualMachine() {
return unwrap().virtualMachine();
}
public boolean isPackagePrivate() {
return unwrap().isPackagePrivate();
}
public boolean isPrivate() {
return unwrap().isPrivate();
}
public boolean isProtected() {
return unwrap().isProtected();
}
public boolean isPublic() {
return unwrap().isPublic();
}
public int modifiers() {
return unwrap().modifiers();
}
//Iterne keuken
// cache alles,<SUF>
com.sun.jdi.Method unwrap(Method method) {
checkMaster(method);
return ((MethodImpl)method).getBase();
}
private final Map<com.sun.jdi.Method, MethodImpl> methodsExt = new HashMap<com.sun.jdi.Method, MethodImpl>();
//private final Map<Method, com.sun.jdi.Method> methodsInt = new HashMap<Method, com.sun.jdi.Method>();
public MethodImpl wrap(com.sun.jdi.Method method) {
if(!method.declaringType().equals(unwrap()))
return master.wrap(method.declaringType()).wrap(method);
MethodImpl meth = methodsExt.get(method);
if(meth == null){
meth = master.createMethod(this,method);
if(meth != null)
methodsExt.put(method, meth);
}
return meth;
}
private final Converter<com.sun.jdi.Method, Method> methodConverter = new Converter<com.sun.jdi.Method, Method>(){
public Method convert(com.sun.jdi.Method source) {
return wrap(source);
}};
private Converter<com.sun.jdi.Method, Method> getMethodConverter() {
return methodConverter;
}
private final Map<com.sun.jdi.Field,Field> fieldsExt = new HashMap<com.sun.jdi.Field, Field>();
// private final Map<Field,com.sun.jdi.Field> fieldsInt = new HashMap<Field, com.sun.jdi.Field>();
//moet public door inheritance, eigenlijk protected
public Field wrap(com.sun.jdi.Field field) {
if(!field.declaringType().equals(unwrap()))
return master.wrap(field.declaringType()).wrap(field);
Field f = fieldsExt.get(field);
if(f == null){
f = master.createField(this,field);
if(field != null)
fieldsExt.put(field, f);
// fieldsInt.put(f, field);
}
return f;
}
protected com.sun.jdi.Field unwrap(Field field) {
return ((FieldImpl)field).base;
}
private final Converter<com.sun.jdi.Field, Field> fieldConverter = new Converter<com.sun.jdi.Field, Field>(){
public Field convert(com.sun.jdi.Field source) {
return wrap(source);
}};
private Converter<com.sun.jdi.Field, Field> getFieldConverter() {
return fieldConverter;
}
private void checkMaster(Shadow other) {
if(other.shadowMaster() != master)
throw new VMMismatchException("object came form different master");
}
public ShadowMaster shadowMaster(){
return master;
}
T unwrap() {
return base;
}
public String toString(){
return name();
}
}
| True | 1,906 | 11 | 2,350 | 14 | 2,383 | 10 | 2,351 | 14 | 2,688 | 12 | false | false | false | false | false | true |
3,957 | 5102_1 | package library.wavelets.lift;_x000D_
_x000D_
/**_x000D_
<p>_x000D_
Haar (flat line) wavelet._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
As with all Lifting scheme wavelet transform functions, the_x000D_
first stage of a transform step is the split stage. The_x000D_
split step moves the even element to the first half of an_x000D_
N element region and the odd elements to the second half of the N_x000D_
element region._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
The Lifting Scheme version of the Haar transform uses a wavelet_x000D_
function (predict stage) that "predicts" that an odd element will_x000D_
have the same value as it preceeding even element. Stated another_x000D_
way, the odd element is "predicted" to be on a flat (zero slope_x000D_
line) shared with the even point. The difference between this_x000D_
"prediction" and the actual odd value replaces the odd element._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
The wavelet scaling function (a.k.a. smoothing function) used_x000D_
in the update stage calculates the average between an even and_x000D_
an odd element._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
The merge stage at the end of the inverse transform interleaves_x000D_
odd and even elements from the two halves of the array_x000D_
(e.g., ordering them even<sub>0</sub>, odd<sub>0</sub>,_x000D_
even<sub>1</sub>, odd<sub>1</sub>, ...)_x000D_
</p>_x000D_
_x000D_
<h4>_x000D_
Copyright and Use_x000D_
</h4>_x000D_
_x000D_
<p>_x000D_
You may use this source code without limitation and without_x000D_
fee as long as you include:_x000D_
</p>_x000D_
<blockquote>_x000D_
This software was written and is copyrighted by Ian Kaplan, Bear_x000D_
Products International, www.bearcave.com, 2001._x000D_
</blockquote>_x000D_
<p>_x000D_
This software is provided "as is", without any warrenty or_x000D_
claim as to its usefulness. Anyone who uses this source code_x000D_
uses it at their own risk. Nor is any support provided by_x000D_
Ian Kaplan and Bear Products International._x000D_
<p>_x000D_
Please send any bug fixes or suggested source changes to:_x000D_
<pre>_x000D_
[email protected]_x000D_
</pre>_x000D_
_x000D_
@author Ian Kaplan_x000D_
_x000D_
*/_x000D_
public class Haar extends Liftbase {_x000D_
_x000D_
/**_x000D_
Haar predict step_x000D_
*/_x000D_
protected void predict(double[] vec, int N, int direction) {_x000D_
int half = N >> 1;_x000D_
_x000D_
for (int i = 0; i < half; i++) {_x000D_
double predictVal = vec[i];_x000D_
int j = i + half;_x000D_
_x000D_
if (direction == forward) {_x000D_
vec[j] = vec[j] - predictVal;_x000D_
} else if (direction == inverse) {_x000D_
vec[j] = vec[j] + predictVal;_x000D_
} else {_x000D_
System.out.println("haar::predict: bad direction value");_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
<p>_x000D_
Update step of the Haar wavelet transform._x000D_
</p>_x000D_
<p>_x000D_
The wavelet transform calculates a set of detail or_x000D_
difference coefficients in the predict step. These_x000D_
are stored in the upper half of the array. The update step_x000D_
calculates an average from the even-odd element pairs._x000D_
The averages will replace the even elements in the _x000D_
lower half of the array._x000D_
</p>_x000D_
<p>_x000D_
The Haar wavelet calculation used in the Lifting Scheme_x000D_
is_x000D_
</p>_x000D_
<pre>_x000D_
d<sub>j+1, i</sub> = odd<sub>j+1, i</sub> = odd<sub>j, i</sub> - even<sub>j, i</sub>_x000D_
a<sub>j+1, i</sub> = even<sub>j, i</sub> = (even<sub>j, i</sub> + odd<sub>j, i</sub>)/2_x000D_
</pre>_x000D_
<p>_x000D_
Note that the Lifting Scheme uses an in-place algorithm. The odd_x000D_
elements have been replaced by the detail coefficients in the_x000D_
predict step. With a little algebra we can substitute the_x000D_
coefficient calculation into the average calculation, which_x000D_
gives us_x000D_
</p>_x000D_
<pre>_x000D_
a<sub>j+1, i</sub> = even<sub>j, i</sub> = even<sub>j, i</sub> + (odd<sub>j, i</sub>/2)_x000D_
</pre>_x000D_
*/_x000D_
protected void update(double[] vec, int N, int direction) {_x000D_
int half = N >> 1;_x000D_
_x000D_
for (int i = 0; i < half; i++) {_x000D_
int j = i + half;_x000D_
double updateVal = vec[j] / 2.0;_x000D_
_x000D_
if (direction == forward) {_x000D_
vec[i] = vec[i] + updateVal;_x000D_
} else if (direction == inverse) {_x000D_
vec[i] = vec[i] - updateVal;_x000D_
} else {_x000D_
System.out.println("update: bad direction value");_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
} // haar_x000D_
| patrickzib/SFA | src/main/java/library/wavelets/lift/Haar.java | 1,282 | /**_x000D_
Haar predict step_x000D_
*/ | block_comment | nl | package library.wavelets.lift;_x000D_
_x000D_
/**_x000D_
<p>_x000D_
Haar (flat line) wavelet._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
As with all Lifting scheme wavelet transform functions, the_x000D_
first stage of a transform step is the split stage. The_x000D_
split step moves the even element to the first half of an_x000D_
N element region and the odd elements to the second half of the N_x000D_
element region._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
The Lifting Scheme version of the Haar transform uses a wavelet_x000D_
function (predict stage) that "predicts" that an odd element will_x000D_
have the same value as it preceeding even element. Stated another_x000D_
way, the odd element is "predicted" to be on a flat (zero slope_x000D_
line) shared with the even point. The difference between this_x000D_
"prediction" and the actual odd value replaces the odd element._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
The wavelet scaling function (a.k.a. smoothing function) used_x000D_
in the update stage calculates the average between an even and_x000D_
an odd element._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
The merge stage at the end of the inverse transform interleaves_x000D_
odd and even elements from the two halves of the array_x000D_
(e.g., ordering them even<sub>0</sub>, odd<sub>0</sub>,_x000D_
even<sub>1</sub>, odd<sub>1</sub>, ...)_x000D_
</p>_x000D_
_x000D_
<h4>_x000D_
Copyright and Use_x000D_
</h4>_x000D_
_x000D_
<p>_x000D_
You may use this source code without limitation and without_x000D_
fee as long as you include:_x000D_
</p>_x000D_
<blockquote>_x000D_
This software was written and is copyrighted by Ian Kaplan, Bear_x000D_
Products International, www.bearcave.com, 2001._x000D_
</blockquote>_x000D_
<p>_x000D_
This software is provided "as is", without any warrenty or_x000D_
claim as to its usefulness. Anyone who uses this source code_x000D_
uses it at their own risk. Nor is any support provided by_x000D_
Ian Kaplan and Bear Products International._x000D_
<p>_x000D_
Please send any bug fixes or suggested source changes to:_x000D_
<pre>_x000D_
[email protected]_x000D_
</pre>_x000D_
_x000D_
@author Ian Kaplan_x000D_
_x000D_
*/_x000D_
public class Haar extends Liftbase {_x000D_
_x000D_
/**_x000D_
Haar predict step_x000D_<SUF>*/_x000D_
protected void predict(double[] vec, int N, int direction) {_x000D_
int half = N >> 1;_x000D_
_x000D_
for (int i = 0; i < half; i++) {_x000D_
double predictVal = vec[i];_x000D_
int j = i + half;_x000D_
_x000D_
if (direction == forward) {_x000D_
vec[j] = vec[j] - predictVal;_x000D_
} else if (direction == inverse) {_x000D_
vec[j] = vec[j] + predictVal;_x000D_
} else {_x000D_
System.out.println("haar::predict: bad direction value");_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
<p>_x000D_
Update step of the Haar wavelet transform._x000D_
</p>_x000D_
<p>_x000D_
The wavelet transform calculates a set of detail or_x000D_
difference coefficients in the predict step. These_x000D_
are stored in the upper half of the array. The update step_x000D_
calculates an average from the even-odd element pairs._x000D_
The averages will replace the even elements in the _x000D_
lower half of the array._x000D_
</p>_x000D_
<p>_x000D_
The Haar wavelet calculation used in the Lifting Scheme_x000D_
is_x000D_
</p>_x000D_
<pre>_x000D_
d<sub>j+1, i</sub> = odd<sub>j+1, i</sub> = odd<sub>j, i</sub> - even<sub>j, i</sub>_x000D_
a<sub>j+1, i</sub> = even<sub>j, i</sub> = (even<sub>j, i</sub> + odd<sub>j, i</sub>)/2_x000D_
</pre>_x000D_
<p>_x000D_
Note that the Lifting Scheme uses an in-place algorithm. The odd_x000D_
elements have been replaced by the detail coefficients in the_x000D_
predict step. With a little algebra we can substitute the_x000D_
coefficient calculation into the average calculation, which_x000D_
gives us_x000D_
</p>_x000D_
<pre>_x000D_
a<sub>j+1, i</sub> = even<sub>j, i</sub> = even<sub>j, i</sub> + (odd<sub>j, i</sub>/2)_x000D_
</pre>_x000D_
*/_x000D_
protected void update(double[] vec, int N, int direction) {_x000D_
int half = N >> 1;_x000D_
_x000D_
for (int i = 0; i < half; i++) {_x000D_
int j = i + half;_x000D_
double updateVal = vec[j] / 2.0;_x000D_
_x000D_
if (direction == forward) {_x000D_
vec[i] = vec[i] + updateVal;_x000D_
} else if (direction == inverse) {_x000D_
vec[i] = vec[i] - updateVal;_x000D_
} else {_x000D_
System.out.println("update: bad direction value");_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
} // haar_x000D_
| True | 1,858 | 21 | 2,019 | 22 | 1,991 | 23 | 2,019 | 22 | 2,151 | 24 | false | false | false | false | false | true |
1,771 | 209134_1 | package com.example.opt3_tristan;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.function.Supplier;
public class HoofdmenuController extends SwitchableScene implements Initializable {
@FXML
private Label ingelogdeMederwerkerLabel;
@FXML
private ListView<Medewerker> ingelogdeGebruikersListView;
@FXML
private TabPane mainPane;
public ObservableList<HuurItem> huurItems = FXCollections.observableArrayList();
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
ingelogdeMederwerkerLabel.setText(Medewerker.huidigeMedewerker.getUsername());
for (Medewerker medewerker : Medewerker.IngelogdeMedewerkers) {
ingelogdeGebruikersListView.getItems().add(medewerker);
}
//3 hardcoded personenauto's
HuurItem auto1 = new Personenauto("Toyota", 1200, "Een comfortabele personenauto");
huurItems.add(auto1);
HuurItem auto2 = new Personenauto("Volvo", 2500, "Een veilige personenauto");
huurItems.add(auto2);
HuurItem auto3 = new Personenauto("Porsche", 1500, "Een vrij snelle personenauto");
huurItems.add(auto3);
//3 hardcoded vrachtwagens
HuurItem vrachtwagen1 = new Vrachtwagen(20000, 18000,"Een wat kleinere vrachtwagen met 2 assen");
huurItems.add(vrachtwagen1);
HuurItem vrachtwagen2 = new Vrachtwagen(30000, 25000,"Een middelgrote vrachtwagen met 3 assen");
huurItems.add(vrachtwagen2);
HuurItem vrachtwagen3 = new Vrachtwagen(32000, 30000,"Een grote vrachtwagen met 4 assen");
huurItems.add(vrachtwagen3);
//3 hardcoded Boormachines
HuurItem boormachine1 = new Boormachine("Makita","HP457DWE accu schroef en klopboormachine","een veelzijdige schroefboormachine die ook als klopboor kan functioneren");
huurItems.add(boormachine1);
HuurItem boormachine2 = new Boormachine("Bosch","EasyDrill","Een comfortabele en veelzijdige boormachine");
huurItems.add(boormachine2);
HuurItem boormachine3 = new Boormachine("Einhell","TE-CD","een krachtige alleskunner");
huurItems.add(boormachine3);
}
public void wisselVanGebruiker(){
Medewerker selectedItem = ingelogdeGebruikersListView.getSelectionModel().getSelectedItem();
if (selectedItem != null) {
System.out.println("Gewisseld naar: "+selectedItem);
Medewerker.huidigeMedewerker = ingelogdeGebruikersListView.getSelectionModel().getSelectedItem();
ingelogdeMederwerkerLabel.setText(Medewerker.huidigeMedewerker.getUsername());
}
}
public void openOverzicht() {
Tab overzichtTab = new Tab();
overzichtTab.setText("Overzicht");
overzichtTab.setClosable(true);
ListView<HuurItem> producten = new ListView<>();
producten.setItems(huurItems);
TextArea textArea = new TextArea();
textArea.setVisible(false);
producten.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
textArea.setText(newValue.getInformatie());
textArea.setVisible(true);
}
});
BorderPane borderPane = new BorderPane();
borderPane.setLeft(producten);
borderPane.setRight(textArea);
Label bottomLabel = new Label("Ingelogde medewerker: " + Medewerker.huidigeMedewerker.getUsername());
borderPane.setBottom(bottomLabel);
BorderPane.setAlignment(bottomLabel, javafx.geometry.Pos.BOTTOM_LEFT);
overzichtTab.setContent(borderPane);
mainPane.getTabs().add(overzichtTab);
}
public void openBeheer() {
Tab beheerTab = createBeheerTab("Beheer", huurItems);
ComboBox<String> itemTypeComboBox = (ComboBox<String>) beheerTab.getContent().lookup(".combo-box");
ListView<HuurItem> producten = (ListView<HuurItem>) beheerTab.getContent().lookup(".list-view");
Label messageLabel = new Label();
VBox creationBox = new VBox();
setupItemTypeComboBoxAction(itemTypeComboBox, creationBox, messageLabel, producten);
TextArea textArea = createTextArea(producten);
BorderPane borderPane = createMainBorderPane(itemTypeComboBox, creationBox, messageLabel, producten, textArea);
beheerTab.setContent(borderPane);
mainPane.getTabs().add(beheerTab);
}
private Tab createBeheerTab(String tabText, ObservableList<HuurItem> items) {
Tab tab = new Tab();
tab.setText(tabText);
tab.setClosable(true);
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().addAll("Personenauto", "Vrachtwagen", "Boormachine");
ListView<HuurItem> listView = new ListView<>();
listView.setItems(items);
VBox vbox = new VBox(comboBox, listView);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(vbox);
tab.setContent(borderPane);
return tab;
}
private void setupItemTypeComboBoxAction(ComboBox<String> itemTypeComboBox, VBox creationBox, Label messageLabel, ListView<HuurItem> producten) {
itemTypeComboBox.setPromptText("Toevoegen");
Map<String, Supplier<ItemCreationTemplate>> creationSuppliers = new HashMap<>();
creationSuppliers.put("Personenauto", () -> new PersonenautoCreation(creationBox, messageLabel, producten, huurItems));
creationSuppliers.put("Vrachtwagen", () -> new VrachtwagenCreation(creationBox, messageLabel, producten, huurItems));
creationSuppliers.put("Boormachine", () -> new BoormachineCreation(creationBox, messageLabel, producten, huurItems));
itemTypeComboBox.setOnAction(e -> {
creationBox.getChildren().clear();
messageLabel.setText("");
Supplier<ItemCreationTemplate> supplier = creationSuppliers.get(itemTypeComboBox.getValue());
if (supplier != null) {
ItemCreationTemplate creationTemplate = supplier.get();
creationTemplate.setupItemCreation();
}
});
}
private TextArea createTextArea(ListView<HuurItem> producten) {
TextArea textArea = new TextArea();
textArea.setVisible(false);
producten.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
textArea.setText(newValue.getInformatie());
textArea.setVisible(true);
}
});
return textArea;
}
private BorderPane createMainBorderPane(ComboBox<String> itemTypeComboBox, VBox creationBox, Label messageLabel, ListView<HuurItem> producten, TextArea textArea) {
BorderPane borderPane = new BorderPane();
borderPane.setLeft(producten);
borderPane.setRight(textArea);
borderPane.setTop(new VBox(itemTypeComboBox, creationBox, messageLabel));
Label bottomLabel = new Label("Ingelogde medewerker: " + Medewerker.huidigeMedewerker.getUsername());
borderPane.setBottom(bottomLabel);
BorderPane.setAlignment(bottomLabel, javafx.geometry.Pos.BOTTOM_LEFT);
return borderPane;
}
public void loguit(ActionEvent event){
Medewerker.IngelogdeMedewerkers.remove(Medewerker.huidigeMedewerker);
System.out.println(Medewerker.huidigeMedewerker.getUsername() + " has been logged out.");
Medewerker.huidigeMedewerker = null;
super.switchScene(event,"login.fxml");
}
public void login(ActionEvent event){
super.switchScene(event,"login.fxml");
}
}
| Triistan/Opt3 | Opt3_Tristan/src/main/java/com/example/opt3_tristan/HoofdmenuController.java | 2,482 | //3 hardcoded vrachtwagens | line_comment | nl | package com.example.opt3_tristan;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.function.Supplier;
public class HoofdmenuController extends SwitchableScene implements Initializable {
@FXML
private Label ingelogdeMederwerkerLabel;
@FXML
private ListView<Medewerker> ingelogdeGebruikersListView;
@FXML
private TabPane mainPane;
public ObservableList<HuurItem> huurItems = FXCollections.observableArrayList();
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
ingelogdeMederwerkerLabel.setText(Medewerker.huidigeMedewerker.getUsername());
for (Medewerker medewerker : Medewerker.IngelogdeMedewerkers) {
ingelogdeGebruikersListView.getItems().add(medewerker);
}
//3 hardcoded personenauto's
HuurItem auto1 = new Personenauto("Toyota", 1200, "Een comfortabele personenauto");
huurItems.add(auto1);
HuurItem auto2 = new Personenauto("Volvo", 2500, "Een veilige personenauto");
huurItems.add(auto2);
HuurItem auto3 = new Personenauto("Porsche", 1500, "Een vrij snelle personenauto");
huurItems.add(auto3);
//3 hardcoded<SUF>
HuurItem vrachtwagen1 = new Vrachtwagen(20000, 18000,"Een wat kleinere vrachtwagen met 2 assen");
huurItems.add(vrachtwagen1);
HuurItem vrachtwagen2 = new Vrachtwagen(30000, 25000,"Een middelgrote vrachtwagen met 3 assen");
huurItems.add(vrachtwagen2);
HuurItem vrachtwagen3 = new Vrachtwagen(32000, 30000,"Een grote vrachtwagen met 4 assen");
huurItems.add(vrachtwagen3);
//3 hardcoded Boormachines
HuurItem boormachine1 = new Boormachine("Makita","HP457DWE accu schroef en klopboormachine","een veelzijdige schroefboormachine die ook als klopboor kan functioneren");
huurItems.add(boormachine1);
HuurItem boormachine2 = new Boormachine("Bosch","EasyDrill","Een comfortabele en veelzijdige boormachine");
huurItems.add(boormachine2);
HuurItem boormachine3 = new Boormachine("Einhell","TE-CD","een krachtige alleskunner");
huurItems.add(boormachine3);
}
public void wisselVanGebruiker(){
Medewerker selectedItem = ingelogdeGebruikersListView.getSelectionModel().getSelectedItem();
if (selectedItem != null) {
System.out.println("Gewisseld naar: "+selectedItem);
Medewerker.huidigeMedewerker = ingelogdeGebruikersListView.getSelectionModel().getSelectedItem();
ingelogdeMederwerkerLabel.setText(Medewerker.huidigeMedewerker.getUsername());
}
}
public void openOverzicht() {
Tab overzichtTab = new Tab();
overzichtTab.setText("Overzicht");
overzichtTab.setClosable(true);
ListView<HuurItem> producten = new ListView<>();
producten.setItems(huurItems);
TextArea textArea = new TextArea();
textArea.setVisible(false);
producten.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
textArea.setText(newValue.getInformatie());
textArea.setVisible(true);
}
});
BorderPane borderPane = new BorderPane();
borderPane.setLeft(producten);
borderPane.setRight(textArea);
Label bottomLabel = new Label("Ingelogde medewerker: " + Medewerker.huidigeMedewerker.getUsername());
borderPane.setBottom(bottomLabel);
BorderPane.setAlignment(bottomLabel, javafx.geometry.Pos.BOTTOM_LEFT);
overzichtTab.setContent(borderPane);
mainPane.getTabs().add(overzichtTab);
}
public void openBeheer() {
Tab beheerTab = createBeheerTab("Beheer", huurItems);
ComboBox<String> itemTypeComboBox = (ComboBox<String>) beheerTab.getContent().lookup(".combo-box");
ListView<HuurItem> producten = (ListView<HuurItem>) beheerTab.getContent().lookup(".list-view");
Label messageLabel = new Label();
VBox creationBox = new VBox();
setupItemTypeComboBoxAction(itemTypeComboBox, creationBox, messageLabel, producten);
TextArea textArea = createTextArea(producten);
BorderPane borderPane = createMainBorderPane(itemTypeComboBox, creationBox, messageLabel, producten, textArea);
beheerTab.setContent(borderPane);
mainPane.getTabs().add(beheerTab);
}
private Tab createBeheerTab(String tabText, ObservableList<HuurItem> items) {
Tab tab = new Tab();
tab.setText(tabText);
tab.setClosable(true);
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().addAll("Personenauto", "Vrachtwagen", "Boormachine");
ListView<HuurItem> listView = new ListView<>();
listView.setItems(items);
VBox vbox = new VBox(comboBox, listView);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(vbox);
tab.setContent(borderPane);
return tab;
}
private void setupItemTypeComboBoxAction(ComboBox<String> itemTypeComboBox, VBox creationBox, Label messageLabel, ListView<HuurItem> producten) {
itemTypeComboBox.setPromptText("Toevoegen");
Map<String, Supplier<ItemCreationTemplate>> creationSuppliers = new HashMap<>();
creationSuppliers.put("Personenauto", () -> new PersonenautoCreation(creationBox, messageLabel, producten, huurItems));
creationSuppliers.put("Vrachtwagen", () -> new VrachtwagenCreation(creationBox, messageLabel, producten, huurItems));
creationSuppliers.put("Boormachine", () -> new BoormachineCreation(creationBox, messageLabel, producten, huurItems));
itemTypeComboBox.setOnAction(e -> {
creationBox.getChildren().clear();
messageLabel.setText("");
Supplier<ItemCreationTemplate> supplier = creationSuppliers.get(itemTypeComboBox.getValue());
if (supplier != null) {
ItemCreationTemplate creationTemplate = supplier.get();
creationTemplate.setupItemCreation();
}
});
}
private TextArea createTextArea(ListView<HuurItem> producten) {
TextArea textArea = new TextArea();
textArea.setVisible(false);
producten.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
textArea.setText(newValue.getInformatie());
textArea.setVisible(true);
}
});
return textArea;
}
private BorderPane createMainBorderPane(ComboBox<String> itemTypeComboBox, VBox creationBox, Label messageLabel, ListView<HuurItem> producten, TextArea textArea) {
BorderPane borderPane = new BorderPane();
borderPane.setLeft(producten);
borderPane.setRight(textArea);
borderPane.setTop(new VBox(itemTypeComboBox, creationBox, messageLabel));
Label bottomLabel = new Label("Ingelogde medewerker: " + Medewerker.huidigeMedewerker.getUsername());
borderPane.setBottom(bottomLabel);
BorderPane.setAlignment(bottomLabel, javafx.geometry.Pos.BOTTOM_LEFT);
return borderPane;
}
public void loguit(ActionEvent event){
Medewerker.IngelogdeMedewerkers.remove(Medewerker.huidigeMedewerker);
System.out.println(Medewerker.huidigeMedewerker.getUsername() + " has been logged out.");
Medewerker.huidigeMedewerker = null;
super.switchScene(event,"login.fxml");
}
public void login(ActionEvent event){
super.switchScene(event,"login.fxml");
}
}
| True | 1,899 | 7 | 2,155 | 7 | 2,073 | 8 | 2,155 | 7 | 2,400 | 8 | false | false | false | false | false | true |
321 | 52212_2 | package com.hogent.ti3g05.ti3_g05_joetzapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.InflateException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.ParseUser;
import java.util.Arrays;
import java.util.List;
//Geeft de mogelijkheid om naar de detailpagina van een vorming te gaan
public class VormingDetail extends Activity {
String titel;
String locatie;
String betalingswijze;
String criteriaDeelnemer;
String korteBeschrijving;
String prijs;
String tips;
String websiteLocatie;
String inbegrepenInPrijs;
String objectId;
List<String> periodes;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha);
try
{
setContentView(R.layout.vorming_detail);
}catch (OutOfMemoryError e)
{
Intent intent1 = new Intent(this, navBarMainScreen.class);
intent1.putExtra("naarfrag", "vorming");
intent1.putExtra("herladen", "nee");
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Toast.makeText(getApplicationContext(), getString(R.string.error_generalException), Toast.LENGTH_SHORT).show();
startActivity(intent1);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
}
catch (InflateException ex)
{
Intent intent1 = new Intent(this, navBarMainScreen.class);
intent1.putExtra("naarfrag", "vorming");
intent1.putExtra("herladen", "nee");
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT).show();
startActivity(intent1);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
}
Intent i = getIntent();
titel = i.getStringExtra("titel");
locatie = i.getStringExtra("locatie");
betalingswijze = i.getStringExtra("betalingswijze");
criteriaDeelnemer = i.getStringExtra("criteriaDeelnemers");
korteBeschrijving = i.getStringExtra("korteBeschrijving");
tips = i.getStringExtra("tips");
prijs = i.getStringExtra("prijs");
inbegrepenInPrijs = i.getStringExtra("inbegrepenInPrijs");
objectId = i.getStringExtra("objectId");
websiteLocatie = i.getStringExtra("websiteLocatie");
String[] voorlopigePeriodes = i.getStringArrayExtra("periodes");
periodes = Arrays.asList(voorlopigePeriodes);
setTitle(titel);
TextView txtTitel = (TextView) findViewById(R.id.titelVD);
TextView txtLocatie = (TextView) findViewById(R.id.locatieVD);
TextView txtbetalingswijze = (TextView) findViewById(R.id.betalingswijzeVD);
TextView txtCriteriaDeelnemer = (TextView)findViewById(R.id.criteriaDeelnemerVD);
TextView txtkorteBeschrijving = (TextView)findViewById(R.id.beschrijvingVD);
TextView txtTips = (TextView)findViewById(R.id.tipsVD);
TextView txtPrijs = (TextView) findViewById(R.id.prijs);
TextView txtInbegrepenInPrijs = (TextView) findViewById(R.id.inbegrepenInPrijs);
TextView txtWebsite = (TextView) findViewById(R.id.websiteLocatieVD);
TextView txtPeriodes = (TextView) findViewById(R.id.periodesVD);
txtTitel.setText(titel);
txtLocatie.setText(locatie);
txtbetalingswijze.setText(betalingswijze);
txtCriteriaDeelnemer.setText(criteriaDeelnemer);
txtkorteBeschrijving.setText(korteBeschrijving);
txtTips.setText(tips);
txtPrijs.setText("€ " + prijs);
txtInbegrepenInPrijs.setText(inbegrepenInPrijs);
txtWebsite.setText(websiteLocatie);
StringBuilder periodesBuilder = new StringBuilder();
for (String obj : periodes){
periodesBuilder.append(obj + "\n");
}
txtPeriodes.setText(periodesBuilder.toString());
final Button inschrijven = (Button) findViewById(R.id.btnInschrijvenVorming);
//Enkel een monitor kan zich inschrijven, anders verberg je de knop
if(ParseUser.getCurrentUser().get("soort").toString().toLowerCase().equals("administrator"))
{
inschrijven.setVisibility(View.GONE);
}
else
{
inschrijven.setVisibility(View.VISIBLE);
}
inschrijven.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
inschrijven.startAnimation(animAlpha);
//Bij klikken op de knop stuur de gebruiker met de nodige gegevens door naar de inschrijvingpagina
Intent inte = new Intent(getApplicationContext(), VormingInschrijven.class);
inte.putExtra("periodes", periodes.toArray(new String[periodes.size()]));
inte.putExtra("objectId", objectId);
startActivity(inte);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.back, menu);
menu.findItem(R.id.menu_load).setVisible(false);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.backMenu) {
Intent intent1 = new Intent(this, navBarMainScreen.class);
intent1.putExtra("naarfrag", "vorming");
intent1.putExtra("herladen", "nee");
startActivity(intent1);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
Intent setIntent = new Intent(VormingDetail.this, navBarMainScreen.class);
setIntent.putExtra("naarfrag","vorming");
setIntent.putExtra("herladen","nee");
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
} | CharlotteErpels1993/TI3_GC05_Project | Android/TI3_G05_JoetzApp2/app/src/main/java/com/hogent/ti3g05/ti3_g05_joetzapp/VormingDetail.java | 2,069 | //Bij klikken op de knop stuur de gebruiker met de nodige gegevens door naar de inschrijvingpagina | line_comment | nl | package com.hogent.ti3g05.ti3_g05_joetzapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.InflateException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.ParseUser;
import java.util.Arrays;
import java.util.List;
//Geeft de mogelijkheid om naar de detailpagina van een vorming te gaan
public class VormingDetail extends Activity {
String titel;
String locatie;
String betalingswijze;
String criteriaDeelnemer;
String korteBeschrijving;
String prijs;
String tips;
String websiteLocatie;
String inbegrepenInPrijs;
String objectId;
List<String> periodes;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.alpha);
try
{
setContentView(R.layout.vorming_detail);
}catch (OutOfMemoryError e)
{
Intent intent1 = new Intent(this, navBarMainScreen.class);
intent1.putExtra("naarfrag", "vorming");
intent1.putExtra("herladen", "nee");
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Toast.makeText(getApplicationContext(), getString(R.string.error_generalException), Toast.LENGTH_SHORT).show();
startActivity(intent1);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
}
catch (InflateException ex)
{
Intent intent1 = new Intent(this, navBarMainScreen.class);
intent1.putExtra("naarfrag", "vorming");
intent1.putExtra("herladen", "nee");
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Toast.makeText(getApplicationContext(),getString(R.string.error_generalException),Toast.LENGTH_SHORT).show();
startActivity(intent1);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
}
Intent i = getIntent();
titel = i.getStringExtra("titel");
locatie = i.getStringExtra("locatie");
betalingswijze = i.getStringExtra("betalingswijze");
criteriaDeelnemer = i.getStringExtra("criteriaDeelnemers");
korteBeschrijving = i.getStringExtra("korteBeschrijving");
tips = i.getStringExtra("tips");
prijs = i.getStringExtra("prijs");
inbegrepenInPrijs = i.getStringExtra("inbegrepenInPrijs");
objectId = i.getStringExtra("objectId");
websiteLocatie = i.getStringExtra("websiteLocatie");
String[] voorlopigePeriodes = i.getStringArrayExtra("periodes");
periodes = Arrays.asList(voorlopigePeriodes);
setTitle(titel);
TextView txtTitel = (TextView) findViewById(R.id.titelVD);
TextView txtLocatie = (TextView) findViewById(R.id.locatieVD);
TextView txtbetalingswijze = (TextView) findViewById(R.id.betalingswijzeVD);
TextView txtCriteriaDeelnemer = (TextView)findViewById(R.id.criteriaDeelnemerVD);
TextView txtkorteBeschrijving = (TextView)findViewById(R.id.beschrijvingVD);
TextView txtTips = (TextView)findViewById(R.id.tipsVD);
TextView txtPrijs = (TextView) findViewById(R.id.prijs);
TextView txtInbegrepenInPrijs = (TextView) findViewById(R.id.inbegrepenInPrijs);
TextView txtWebsite = (TextView) findViewById(R.id.websiteLocatieVD);
TextView txtPeriodes = (TextView) findViewById(R.id.periodesVD);
txtTitel.setText(titel);
txtLocatie.setText(locatie);
txtbetalingswijze.setText(betalingswijze);
txtCriteriaDeelnemer.setText(criteriaDeelnemer);
txtkorteBeschrijving.setText(korteBeschrijving);
txtTips.setText(tips);
txtPrijs.setText("€ " + prijs);
txtInbegrepenInPrijs.setText(inbegrepenInPrijs);
txtWebsite.setText(websiteLocatie);
StringBuilder periodesBuilder = new StringBuilder();
for (String obj : periodes){
periodesBuilder.append(obj + "\n");
}
txtPeriodes.setText(periodesBuilder.toString());
final Button inschrijven = (Button) findViewById(R.id.btnInschrijvenVorming);
//Enkel een monitor kan zich inschrijven, anders verberg je de knop
if(ParseUser.getCurrentUser().get("soort").toString().toLowerCase().equals("administrator"))
{
inschrijven.setVisibility(View.GONE);
}
else
{
inschrijven.setVisibility(View.VISIBLE);
}
inschrijven.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
inschrijven.startAnimation(animAlpha);
//Bij klikken<SUF>
Intent inte = new Intent(getApplicationContext(), VormingInschrijven.class);
inte.putExtra("periodes", periodes.toArray(new String[periodes.size()]));
inte.putExtra("objectId", objectId);
startActivity(inte);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.back, menu);
menu.findItem(R.id.menu_load).setVisible(false);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.backMenu) {
Intent intent1 = new Intent(this, navBarMainScreen.class);
intent1.putExtra("naarfrag", "vorming");
intent1.putExtra("herladen", "nee");
startActivity(intent1);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
Intent setIntent = new Intent(VormingDetail.this, navBarMainScreen.class);
setIntent.putExtra("naarfrag","vorming");
setIntent.putExtra("herladen","nee");
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
} | True | 1,398 | 29 | 1,690 | 29 | 1,654 | 23 | 1,692 | 29 | 1,927 | 31 | false | false | false | false | false | true |
664 | 197785_3 | package net.fe.overworldStage;
import org.newdawn.slick.opengl.Texture;
import chu.engine.anim.Renderer;
import chu.engine.anim.Transform;
import net.fe.FEResources;
import net.fe.fightStage.FightStage;
import net.fe.unit.Unit;
// TODO: Auto-generated Javadoc
/**
* The Class TradeMenu.
*/
public class TradeMenu extends InventoryMenu {
/** The mug. */
private Texture mug;
/** The flip. */
private boolean flip;
/**
* Instantiates a new trade menu.
*
* @param u the u
* @param x the x
* @param y the y
* @param flip the flip
*/
public TradeMenu(Unit u, float x, float y, boolean flip) {
super(u,x,y);
mug = FEResources.getTexture(u.name.toLowerCase()+"_mugshot");
this.flip = flip;
}
/* (non-Javadoc)
* @see net.fe.overworldStage.Menu#render()
*/
public void render(){
int imageW = mug.getImageWidth();
int imageH = mug.getImageHeight();
int menuW = this.getWidth();
Transform t = new Transform();
if(flip)
t.flipHorizontal();
Renderer.render(mug, 0, 0, 1, 1,
x+menuW/2-imageW/2, y-imageH, x+menuW/2+imageW/2, y, renderDepth, t);
super.render();
}
}
| HamaIndustries/FEMultiPlayer-V2 | src/net/fe/overworldStage/TradeMenu.java | 448 | /* (non-Javadoc)
* @see net.fe.overworldStage.Menu#render()
*/ | block_comment | nl | package net.fe.overworldStage;
import org.newdawn.slick.opengl.Texture;
import chu.engine.anim.Renderer;
import chu.engine.anim.Transform;
import net.fe.FEResources;
import net.fe.fightStage.FightStage;
import net.fe.unit.Unit;
// TODO: Auto-generated Javadoc
/**
* The Class TradeMenu.
*/
public class TradeMenu extends InventoryMenu {
/** The mug. */
private Texture mug;
/** The flip. */
private boolean flip;
/**
* Instantiates a new trade menu.
*
* @param u the u
* @param x the x
* @param y the y
* @param flip the flip
*/
public TradeMenu(Unit u, float x, float y, boolean flip) {
super(u,x,y);
mug = FEResources.getTexture(u.name.toLowerCase()+"_mugshot");
this.flip = flip;
}
/* (non-Javadoc)
<SUF>*/
public void render(){
int imageW = mug.getImageWidth();
int imageH = mug.getImageHeight();
int menuW = this.getWidth();
Transform t = new Transform();
if(flip)
t.flipHorizontal();
Renderer.render(mug, 0, 0, 1, 1,
x+menuW/2-imageW/2, y-imageH, x+menuW/2+imageW/2, y, renderDepth, t);
super.render();
}
}
| False | 330 | 20 | 404 | 24 | 412 | 26 | 404 | 24 | 472 | 29 | false | false | false | false | false | true |
4,325 | 64970_4 | package prefuse.controls;_x000D_
_x000D_
import java.awt.Cursor;_x000D_
import java.awt.event.MouseEvent;_x000D_
import java.awt.geom.Point2D;_x000D_
_x000D_
import prefuse.Display;_x000D_
import prefuse.util.ui.UILib;_x000D_
import prefuse.visual.VisualItem;_x000D_
_x000D_
_x000D_
/**_x000D_
* Zooms the display, changing the scale of the viewable region. By default,_x000D_
* zooming is achieved by pressing the right mouse button on the background_x000D_
* of the visualization and dragging the mouse up or down. Moving the mouse up_x000D_
* zooms out the display around the spot the mouse was originally pressed._x000D_
* Moving the mouse down similarly zooms in the display, making items_x000D_
* larger._x000D_
*_x000D_
* @author <a href="http://jheer.org">jeffrey heer</a>_x000D_
*/_x000D_
public class ZoomControl extends AbstractZoomControl {_x000D_
_x000D_
private int yLast;_x000D_
private Point2D down = new Point2D.Float();_x000D_
private int button = RIGHT_MOUSE_BUTTON; _x000D_
_x000D_
/**_x000D_
* Create a new zoom control._x000D_
*/_x000D_
public ZoomControl() {_x000D_
// do nothing_x000D_
}_x000D_
_x000D_
/**_x000D_
* Create a new zoom control._x000D_
* @param mouseButton the mouse button that should initiate a zoom. One of_x000D_
* {@link Control#LEFT_MOUSE_BUTTON}, {@link Control#MIDDLE_MOUSE_BUTTON},_x000D_
* or {@link Control#RIGHT_MOUSE_BUTTON}._x000D_
*/_x000D_
public ZoomControl(int mouseButton) {_x000D_
button = mouseButton;_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void mousePressed(MouseEvent e) {_x000D_
if ( UILib.isButtonPressed(e, button) ) {_x000D_
Display display = (Display)e.getComponent();_x000D_
if (display.isTranformInProgress()) {_x000D_
yLast = -1;_x000D_
System.err.println("can't move");_x000D_
return;_x000D_
}_x000D_
display.setCursor(_x000D_
Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));_x000D_
display.getAbsoluteCoordinate(e.getPoint(), down);_x000D_
yLast = e.getY();_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void mouseDragged(MouseEvent e) {_x000D_
if ( UILib.isButtonPressed(e, button) ) {_x000D_
Display display = (Display)e.getComponent();_x000D_
if (display.isTranformInProgress() || yLast == -1) {_x000D_
yLast = -1;_x000D_
return;_x000D_
}_x000D_
_x000D_
int y = e.getY();_x000D_
int dy = y-yLast;_x000D_
double zoom = 1 + ((double)dy) / 100;_x000D_
_x000D_
int status = zoom(display, down, zoom, true);_x000D_
int cursor = Cursor.N_RESIZE_CURSOR;_x000D_
if ( status == NO_ZOOM )_x000D_
cursor = Cursor.WAIT_CURSOR;_x000D_
display.setCursor(Cursor.getPredefinedCursor(cursor));_x000D_
_x000D_
yLast = y;_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void mouseReleased(MouseEvent e) {_x000D_
if ( UILib.isButtonPressed(e, button) ) {_x000D_
e.getComponent().setCursor(Cursor.getDefaultCursor());_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see prefuse.controls.Control#itemPressed(prefuse.visual.VisualItem, java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void itemPressed(VisualItem item, MouseEvent e) {_x000D_
if ( m_zoomOverItem )_x000D_
mousePressed(e);_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see prefuse.controls.Control#itemDragged(prefuse.visual.VisualItem, java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void itemDragged(VisualItem item, MouseEvent e) {_x000D_
if ( m_zoomOverItem )_x000D_
mouseDragged(e);_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see prefuse.controls.Control#itemReleased(prefuse.visual.VisualItem, java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void itemReleased(VisualItem item, MouseEvent e) {_x000D_
if ( m_zoomOverItem )_x000D_
mouseReleased(e);_x000D_
}_x000D_
_x000D_
} // end of class ZoomControl_x000D_
| siyengar/Prefuse | src/prefuse/controls/ZoomControl.java | 1,244 | /**_x000D_
* @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)_x000D_
*/ | block_comment | nl | package prefuse.controls;_x000D_
_x000D_
import java.awt.Cursor;_x000D_
import java.awt.event.MouseEvent;_x000D_
import java.awt.geom.Point2D;_x000D_
_x000D_
import prefuse.Display;_x000D_
import prefuse.util.ui.UILib;_x000D_
import prefuse.visual.VisualItem;_x000D_
_x000D_
_x000D_
/**_x000D_
* Zooms the display, changing the scale of the viewable region. By default,_x000D_
* zooming is achieved by pressing the right mouse button on the background_x000D_
* of the visualization and dragging the mouse up or down. Moving the mouse up_x000D_
* zooms out the display around the spot the mouse was originally pressed._x000D_
* Moving the mouse down similarly zooms in the display, making items_x000D_
* larger._x000D_
*_x000D_
* @author <a href="http://jheer.org">jeffrey heer</a>_x000D_
*/_x000D_
public class ZoomControl extends AbstractZoomControl {_x000D_
_x000D_
private int yLast;_x000D_
private Point2D down = new Point2D.Float();_x000D_
private int button = RIGHT_MOUSE_BUTTON; _x000D_
_x000D_
/**_x000D_
* Create a new zoom control._x000D_
*/_x000D_
public ZoomControl() {_x000D_
// do nothing_x000D_
}_x000D_
_x000D_
/**_x000D_
* Create a new zoom control._x000D_
* @param mouseButton the mouse button that should initiate a zoom. One of_x000D_
* {@link Control#LEFT_MOUSE_BUTTON}, {@link Control#MIDDLE_MOUSE_BUTTON},_x000D_
* or {@link Control#RIGHT_MOUSE_BUTTON}._x000D_
*/_x000D_
public ZoomControl(int mouseButton) {_x000D_
button = mouseButton;_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void mousePressed(MouseEvent e) {_x000D_
if ( UILib.isButtonPressed(e, button) ) {_x000D_
Display display = (Display)e.getComponent();_x000D_
if (display.isTranformInProgress()) {_x000D_
yLast = -1;_x000D_
System.err.println("can't move");_x000D_
return;_x000D_
}_x000D_
display.setCursor(_x000D_
Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));_x000D_
display.getAbsoluteCoordinate(e.getPoint(), down);_x000D_
yLast = e.getY();_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)_x000D_
<SUF>*/_x000D_
public void mouseDragged(MouseEvent e) {_x000D_
if ( UILib.isButtonPressed(e, button) ) {_x000D_
Display display = (Display)e.getComponent();_x000D_
if (display.isTranformInProgress() || yLast == -1) {_x000D_
yLast = -1;_x000D_
return;_x000D_
}_x000D_
_x000D_
int y = e.getY();_x000D_
int dy = y-yLast;_x000D_
double zoom = 1 + ((double)dy) / 100;_x000D_
_x000D_
int status = zoom(display, down, zoom, true);_x000D_
int cursor = Cursor.N_RESIZE_CURSOR;_x000D_
if ( status == NO_ZOOM )_x000D_
cursor = Cursor.WAIT_CURSOR;_x000D_
display.setCursor(Cursor.getPredefinedCursor(cursor));_x000D_
_x000D_
yLast = y;_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void mouseReleased(MouseEvent e) {_x000D_
if ( UILib.isButtonPressed(e, button) ) {_x000D_
e.getComponent().setCursor(Cursor.getDefaultCursor());_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see prefuse.controls.Control#itemPressed(prefuse.visual.VisualItem, java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void itemPressed(VisualItem item, MouseEvent e) {_x000D_
if ( m_zoomOverItem )_x000D_
mousePressed(e);_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see prefuse.controls.Control#itemDragged(prefuse.visual.VisualItem, java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void itemDragged(VisualItem item, MouseEvent e) {_x000D_
if ( m_zoomOverItem )_x000D_
mouseDragged(e);_x000D_
}_x000D_
_x000D_
/**_x000D_
* @see prefuse.controls.Control#itemReleased(prefuse.visual.VisualItem, java.awt.event.MouseEvent)_x000D_
*/_x000D_
public void itemReleased(VisualItem item, MouseEvent e) {_x000D_
if ( m_zoomOverItem )_x000D_
mouseReleased(e);_x000D_
}_x000D_
_x000D_
} // end of class ZoomControl_x000D_
| False | 1,643 | 35 | 1,781 | 42 | 1,865 | 43 | 1,781 | 42 | 1,995 | 46 | false | false | false | false | false | true |
332 | 21174_2 | /*
* Licensed under the EUPL, Version 1.2.
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*/
package net.dries007.tfc.network;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.commons.lang3.mutable.MutableInt;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;
import net.dries007.tfc.common.capabilities.food.FoodCapability;
import net.dries007.tfc.common.capabilities.heat.HeatCapability;
import net.dries007.tfc.common.capabilities.size.ItemSizeManager;
import net.dries007.tfc.util.*;
public final class PacketHandler
{
private static final String VERSION = Integer.toString(1);
private static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel(Helpers.identifier("network"), () -> VERSION, VERSION::equals, VERSION::equals);
private static final MutableInt ID = new MutableInt(0);
public static void send(PacketDistributor.PacketTarget target, Object message)
{
CHANNEL.send(target, message);
}
public static void init()
{
// Server -> Client
register(ChunkWatchPacket.class, ChunkWatchPacket::encode, ChunkWatchPacket::new, ChunkWatchPacket::handle);
register(ChunkUnwatchPacket.class, ChunkUnwatchPacket::encode, ChunkUnwatchPacket::new, ChunkUnwatchPacket::handle);
register(CalendarUpdatePacket.class, CalendarUpdatePacket::encode, CalendarUpdatePacket::new, CalendarUpdatePacket::handle);
register(FoodDataReplacePacket.class, FoodDataReplacePacket::new, FoodDataReplacePacket::handle);
register(FoodDataUpdatePacket.class, FoodDataUpdatePacket::encode, FoodDataUpdatePacket::new, FoodDataUpdatePacket::handle);
register(PlayerDataUpdatePacket.class, PlayerDataUpdatePacket::encode, PlayerDataUpdatePacket::new, PlayerDataUpdatePacket::handle);
register(ProspectedPacket.class, ProspectedPacket::encode, ProspectedPacket::new, ProspectedPacket::handle);
register(ClimateSettingsUpdatePacket.class, ClimateSettingsUpdatePacket::encode, ClimateSettingsUpdatePacket::new, ClimateSettingsUpdatePacket::handle);
register(EffectExpirePacket.class, EffectExpirePacket::encode, EffectExpirePacket::new, EffectExpirePacket::handle);
registerDataManager(DataManagerSyncPacket.TMetal.class, Metal.MANAGER);
registerDataManager(DataManagerSyncPacket.TFuel.class, Fuel.MANAGER);
registerDataManager(DataManagerSyncPacket.TFertilizer.class, Fertilizer.MANAGER);
registerDataManager(DataManagerSyncPacket.TFoodDefinition.class, FoodCapability.MANAGER);
registerDataManager(DataManagerSyncPacket.THeatDefinition.class, HeatCapability.MANAGER);
registerDataManager(DataManagerSyncPacket.TItemSizeDefinition.class, ItemSizeManager.MANAGER);
// Client -> Server
register(SwitchInventoryTabPacket.class, SwitchInventoryTabPacket::encode, SwitchInventoryTabPacket::new, SwitchInventoryTabPacket::handle);
register(PlaceBlockSpecialPacket.class, PlaceBlockSpecialPacket::new, PlaceBlockSpecialPacket::handle);
register(ScreenButtonPacket.class, ScreenButtonPacket::encode, ScreenButtonPacket::new, ScreenButtonPacket::handle);
register(PlayerDrinkPacket.class, PlayerDrinkPacket::new, PlayerDrinkPacket::handle);
}
@SuppressWarnings("unchecked")
private static <T extends DataManagerSyncPacket<E>, E> void registerDataManager(Class<T> cls, DataManager<E> manager)
{
CHANNEL.registerMessage(ID.getAndIncrement(), cls,
(packet, buffer) -> packet.encode(manager, buffer),
buffer -> {
final T packet = (T) manager.createEmptyPacket();
packet.decode(manager, buffer);
return packet;
},
(packet, context) -> {
context.get().setPacketHandled(true);
context.get().enqueueWork(() -> packet.handle(manager));
});
}
private static <T> void register(Class<T> cls, BiConsumer<T, FriendlyByteBuf> encoder, Function<FriendlyByteBuf, T> decoder, BiConsumer<T, NetworkEvent.Context> handler)
{
CHANNEL.registerMessage(ID.getAndIncrement(), cls, encoder, decoder, (packet, context) -> {
context.get().setPacketHandled(true);
handler.accept(packet, context.get());
});
}
private static <T> void register(Class<T> cls, Supplier<T> factory, BiConsumer<T, NetworkEvent.Context> handler)
{
CHANNEL.registerMessage(ID.getAndIncrement(), cls, (packet, buffer) -> {}, buffer -> factory.get(), (packet, context) -> {
context.get().setPacketHandled(true);
handler.accept(packet, context.get());
});
}
} | CleanroomMC/TerraFirmaCraft | src/main/java/net/dries007/tfc/network/PacketHandler.java | 1,398 | // Client -> Server | line_comment | nl | /*
* Licensed under the EUPL, Version 1.2.
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*/
package net.dries007.tfc.network;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.commons.lang3.mutable.MutableInt;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;
import net.dries007.tfc.common.capabilities.food.FoodCapability;
import net.dries007.tfc.common.capabilities.heat.HeatCapability;
import net.dries007.tfc.common.capabilities.size.ItemSizeManager;
import net.dries007.tfc.util.*;
public final class PacketHandler
{
private static final String VERSION = Integer.toString(1);
private static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel(Helpers.identifier("network"), () -> VERSION, VERSION::equals, VERSION::equals);
private static final MutableInt ID = new MutableInt(0);
public static void send(PacketDistributor.PacketTarget target, Object message)
{
CHANNEL.send(target, message);
}
public static void init()
{
// Server -> Client
register(ChunkWatchPacket.class, ChunkWatchPacket::encode, ChunkWatchPacket::new, ChunkWatchPacket::handle);
register(ChunkUnwatchPacket.class, ChunkUnwatchPacket::encode, ChunkUnwatchPacket::new, ChunkUnwatchPacket::handle);
register(CalendarUpdatePacket.class, CalendarUpdatePacket::encode, CalendarUpdatePacket::new, CalendarUpdatePacket::handle);
register(FoodDataReplacePacket.class, FoodDataReplacePacket::new, FoodDataReplacePacket::handle);
register(FoodDataUpdatePacket.class, FoodDataUpdatePacket::encode, FoodDataUpdatePacket::new, FoodDataUpdatePacket::handle);
register(PlayerDataUpdatePacket.class, PlayerDataUpdatePacket::encode, PlayerDataUpdatePacket::new, PlayerDataUpdatePacket::handle);
register(ProspectedPacket.class, ProspectedPacket::encode, ProspectedPacket::new, ProspectedPacket::handle);
register(ClimateSettingsUpdatePacket.class, ClimateSettingsUpdatePacket::encode, ClimateSettingsUpdatePacket::new, ClimateSettingsUpdatePacket::handle);
register(EffectExpirePacket.class, EffectExpirePacket::encode, EffectExpirePacket::new, EffectExpirePacket::handle);
registerDataManager(DataManagerSyncPacket.TMetal.class, Metal.MANAGER);
registerDataManager(DataManagerSyncPacket.TFuel.class, Fuel.MANAGER);
registerDataManager(DataManagerSyncPacket.TFertilizer.class, Fertilizer.MANAGER);
registerDataManager(DataManagerSyncPacket.TFoodDefinition.class, FoodCapability.MANAGER);
registerDataManager(DataManagerSyncPacket.THeatDefinition.class, HeatCapability.MANAGER);
registerDataManager(DataManagerSyncPacket.TItemSizeDefinition.class, ItemSizeManager.MANAGER);
// Client -><SUF>
register(SwitchInventoryTabPacket.class, SwitchInventoryTabPacket::encode, SwitchInventoryTabPacket::new, SwitchInventoryTabPacket::handle);
register(PlaceBlockSpecialPacket.class, PlaceBlockSpecialPacket::new, PlaceBlockSpecialPacket::handle);
register(ScreenButtonPacket.class, ScreenButtonPacket::encode, ScreenButtonPacket::new, ScreenButtonPacket::handle);
register(PlayerDrinkPacket.class, PlayerDrinkPacket::new, PlayerDrinkPacket::handle);
}
@SuppressWarnings("unchecked")
private static <T extends DataManagerSyncPacket<E>, E> void registerDataManager(Class<T> cls, DataManager<E> manager)
{
CHANNEL.registerMessage(ID.getAndIncrement(), cls,
(packet, buffer) -> packet.encode(manager, buffer),
buffer -> {
final T packet = (T) manager.createEmptyPacket();
packet.decode(manager, buffer);
return packet;
},
(packet, context) -> {
context.get().setPacketHandled(true);
context.get().enqueueWork(() -> packet.handle(manager));
});
}
private static <T> void register(Class<T> cls, BiConsumer<T, FriendlyByteBuf> encoder, Function<FriendlyByteBuf, T> decoder, BiConsumer<T, NetworkEvent.Context> handler)
{
CHANNEL.registerMessage(ID.getAndIncrement(), cls, encoder, decoder, (packet, context) -> {
context.get().setPacketHandled(true);
handler.accept(packet, context.get());
});
}
private static <T> void register(Class<T> cls, Supplier<T> factory, BiConsumer<T, NetworkEvent.Context> handler)
{
CHANNEL.registerMessage(ID.getAndIncrement(), cls, (packet, buffer) -> {}, buffer -> factory.get(), (packet, context) -> {
context.get().setPacketHandled(true);
handler.accept(packet, context.get());
});
}
} | False | 1,052 | 4 | 1,221 | 4 | 1,248 | 4 | 1,221 | 4 | 1,481 | 4 | false | false | false | false | false | true |
2,849 | 3794_13 | /*
* Copyright (C) 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.internal.aop;
import static com.google.inject.internal.aop.ClassDefining.hasPackageAccess;
import static java.lang.reflect.Modifier.FINAL;
import static java.lang.reflect.Modifier.PRIVATE;
import static java.lang.reflect.Modifier.PROTECTED;
import static java.lang.reflect.Modifier.PUBLIC;
import static java.lang.reflect.Modifier.STATIC;
import com.google.inject.TypeLiteral;
import com.google.inject.internal.BytecodeGen;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Entry-point for building enhanced classes and 'fast-class' invocation.
*
* @author [email protected] (Stuart McCulloch)
*/
public final class ClassBuilding {
private ClassBuilding() {}
private static final Method[] OVERRIDABLE_OBJECT_METHODS = getOverridableObjectMethods();
/** Minimum signature needed to disambiguate constructors from the same host class. */
public static String signature(Constructor<?> constructor) {
return signature("<init>", constructor.getParameterTypes());
}
/** Minimum signature needed to disambiguate methods from the same host class. */
public static String signature(Method method) {
return signature(method.getName(), method.getParameterTypes());
}
/** Appends a semicolon-separated list of parameter types to the given name. */
private static String signature(String name, Class<?>[] parameterTypes) {
StringBuilder signature = new StringBuilder(name);
for (Class<?> type : parameterTypes) {
signature.append(';').append(type.getName());
}
return signature.toString();
}
/** Returns true if the given member can be enhanced using bytecode. */
public static boolean canEnhance(Executable member) {
return canAccess(member, hasPackageAccess());
}
/** Builder of enhancers that provide method interception via bytecode generation. */
public static BytecodeGen.EnhancerBuilder buildEnhancerBuilder(Class<?> hostClass) {
Map<String, Object> methodPartitions = new HashMap<>();
visitMethodHierarchy(
hostClass,
method -> {
// exclude static methods, but keep final methods for bridge analysis
if ((method.getModifiers() & STATIC) == 0) {
partitionMethod(method, methodPartitions);
}
});
Map<String, Method> enhanceableMethods = new TreeMap<>();
Map<Method, Method> bridgeDelegates = new HashMap<>();
TypeLiteral<?> hostType = TypeLiteral.get(hostClass);
for (Object partition : methodPartitions.values()) {
if (partition instanceof Method) {
// common case, partition is just one method; exclude if it turns out to be final
Method method = (Method) partition;
if ((method.getModifiers() & FINAL) == 0) {
enhanceableMethods.put(signature(method), method);
}
} else {
((MethodPartition) partition)
.collectEnhanceableMethods(
hostType,
method -> enhanceableMethods.put(signature(method), method),
bridgeDelegates);
}
}
return new EnhancerBuilderImpl(hostClass, enhanceableMethods.values(), bridgeDelegates);
}
/**
* Methods are partitioned by name and parameter count. This helps focus the search for bridge
* delegates that involve type-erasure of generic parameter types, since the parameter count will
* be the same for the bridge method and its delegate.
*/
private static void partitionMethod(Method method, Map<String, Object> partitions) {
String partitionKey = method.getName() + '/' + method.getParameterCount();
partitions.merge(partitionKey, method, ClassBuilding::mergeMethods);
}
/** Add the new method to an existing partition or create a new one. */
private static Object mergeMethods(Object existing, Object added) {
Method newMethod = (Method) added;
if (existing instanceof Method) {
return new MethodPartition((Method) existing, newMethod);
}
return ((MethodPartition) existing).addCandidate(newMethod);
}
/** Visit the method hierarchy for the host class. */
private static void visitMethodHierarchy(Class<?> hostClass, Consumer<Method> visitor) {
// this is an iterative form of the following recursive search:
// 1. visit declared methods
// 2. recursively visit superclass
// 3. visit declared interfaces
// stack of interface declarations, from host class (bottom) to superclass (top)
Deque<Class<?>[]> interfaceStack = new ArrayDeque<>();
// only try to match package-private methods if the class-definer has package-access
String hostPackage = hasPackageAccess() ? packageName(hostClass.getName()) : null;
for (Class<?> clazz = hostClass;
clazz != Object.class && clazz != null;
clazz = clazz.getSuperclass()) {
// optionally visit package-private methods matching the same package as the host
boolean samePackage = hostPackage != null && hostPackage.equals(packageName(clazz.getName()));
visitMembers(clazz.getDeclaredMethods(), samePackage, visitor);
pushInterfaces(interfaceStack, clazz.getInterfaces());
}
for (Method method : OVERRIDABLE_OBJECT_METHODS) {
visitor.accept(method);
}
// work our way back down the class hierarchy, merging and flattening interfaces into a list
List<Class<?>> interfaces = new ArrayList<>();
while (!interfaceStack.isEmpty()) {
for (Class<?> intf : interfaceStack.pop()) {
if (mergeInterface(interfaces, intf)) {
pushInterfaces(interfaceStack, intf.getInterfaces());
}
}
}
// finally visit the methods declared in the flattened interface hierarchy
for (Class<?> intf : interfaces) {
visitMembers(intf.getDeclaredMethods(), false, visitor);
}
}
/** Pushes the interface declaration onto the stack if it's not empty. */
private static void pushInterfaces(Deque<Class<?>[]> interfaceStack, Class<?>[] interfaces) {
if (interfaces.length > 0) {
interfaceStack.push(interfaces);
}
}
/** Attempts to merge the interface with the current flattened hierarchy. */
private static boolean mergeInterface(List<Class<?>> interfaces, Class<?> candidate) {
// work along the flattened hierarchy to find the appropriate merge point
for (int i = 0, len = interfaces.size(); i < len; i++) {
Class<?> existingInterface = interfaces.get(i);
if (existingInterface == candidate) {
// already seen this interface, skip further processing
return false;
} else if (existingInterface.isAssignableFrom(candidate)) {
// extends existing interface, insert just before it in the flattened hierarchy
interfaces.add(i, candidate);
return true;
}
}
// unrelated or a superinterface, in both cases append to the flattened hierarchy
return interfaces.add(candidate);
}
/** Extract the package name from a class name. */
private static String packageName(String className) {
return className.substring(0, className.lastIndexOf('.') + 1);
}
/** Cache common overridable Object methods. */
private static Method[] getOverridableObjectMethods() {
List<Method> objectMethods = new ArrayList<>();
visitMembers(
Object.class.getDeclaredMethods(),
false, // no package-level access
method -> {
// skip methods that can't/shouldn't be overridden
if ((method.getModifiers() & (STATIC | FINAL)) == 0
&& !"finalize".equals(method.getName())) {
objectMethods.add(method);
}
});
return objectMethods.toArray(new Method[0]);
}
/** Returns true if the given member can be fast-invoked. */
public static boolean canFastInvoke(Executable member) {
int modifiers = member.getModifiers() & (PUBLIC | PRIVATE);
if (hasPackageAccess()) {
// can fast-invoke anything except private members
return modifiers != PRIVATE;
}
// can fast-invoke public members in public types whose parameters are all public
boolean visible = (modifiers == PUBLIC) && isPublic(member.getDeclaringClass());
if (visible) {
for (Class<?> type : member.getParameterTypes()) {
if (!isPublic(type)) {
return false;
}
}
}
return visible;
}
private static boolean isPublic(Class<?> clazz) {
return (clazz.getModifiers() & PUBLIC) != 0;
}
/** Builds a 'fast-class' invoker that uses bytecode generation in place of reflection. */
public static Function<String, BiFunction<Object, Object[], Object>> buildFastClass(
Class<?> hostClass) {
NavigableMap<String, Executable> glueMap = new TreeMap<>();
visitFastConstructors(hostClass, ctor -> glueMap.put(signature(ctor), ctor));
visitFastMethods(hostClass, method -> glueMap.put(signature(method), method));
return new FastClass(hostClass).glue(glueMap);
}
/** Visit all constructors for the host class that can be fast-invoked. */
private static void visitFastConstructors(Class<?> hostClass, Consumer<Constructor<?>> visitor) {
if (hasPackageAccess()) {
// can fast-invoke all non-private constructors
visitMembers(hostClass.getDeclaredConstructors(), true, visitor);
} else {
// can only fast-invoke public constructors
for (Constructor<?> constructor : hostClass.getConstructors()) {
visitor.accept(constructor);
}
}
}
/** Visit all methods declared by the host class that can be fast-invoked. */
private static void visitFastMethods(Class<?> hostClass, Consumer<Method> visitor) {
if (hasPackageAccess()) {
// can fast-invoke all non-private methods declared by the class
visitMembers(hostClass.getDeclaredMethods(), true, visitor);
} else {
// can only fast-invoke public methods
for (Method method : hostClass.getMethods()) {
// limit to those declared by this class; inherited methods have their own fast-class
if (hostClass == method.getDeclaringClass()) {
visitor.accept(method);
}
}
}
}
/** Visit all subclass accessible members in the given array. */
static <T extends Executable> void visitMembers(
T[] members, boolean samePackage, Consumer<T> visitor) {
for (T member : members) {
if (canAccess(member, samePackage)) {
visitor.accept(member);
}
}
}
/** Can we access this member from a subclass which may be in the same package? */
private static boolean canAccess(Executable member, boolean samePackage) {
int modifiers = member.getModifiers();
// public and protected members are always ok, non-private also ok if in the same package
return (modifiers & (PUBLIC | PROTECTED)) != 0 || (samePackage && (modifiers & PRIVATE) == 0);
}
}
| google/guice | core/src/com/google/inject/internal/aop/ClassBuilding.java | 3,242 | // 1. visit declared methods | line_comment | nl | /*
* Copyright (C) 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.internal.aop;
import static com.google.inject.internal.aop.ClassDefining.hasPackageAccess;
import static java.lang.reflect.Modifier.FINAL;
import static java.lang.reflect.Modifier.PRIVATE;
import static java.lang.reflect.Modifier.PROTECTED;
import static java.lang.reflect.Modifier.PUBLIC;
import static java.lang.reflect.Modifier.STATIC;
import com.google.inject.TypeLiteral;
import com.google.inject.internal.BytecodeGen;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Entry-point for building enhanced classes and 'fast-class' invocation.
*
* @author [email protected] (Stuart McCulloch)
*/
public final class ClassBuilding {
private ClassBuilding() {}
private static final Method[] OVERRIDABLE_OBJECT_METHODS = getOverridableObjectMethods();
/** Minimum signature needed to disambiguate constructors from the same host class. */
public static String signature(Constructor<?> constructor) {
return signature("<init>", constructor.getParameterTypes());
}
/** Minimum signature needed to disambiguate methods from the same host class. */
public static String signature(Method method) {
return signature(method.getName(), method.getParameterTypes());
}
/** Appends a semicolon-separated list of parameter types to the given name. */
private static String signature(String name, Class<?>[] parameterTypes) {
StringBuilder signature = new StringBuilder(name);
for (Class<?> type : parameterTypes) {
signature.append(';').append(type.getName());
}
return signature.toString();
}
/** Returns true if the given member can be enhanced using bytecode. */
public static boolean canEnhance(Executable member) {
return canAccess(member, hasPackageAccess());
}
/** Builder of enhancers that provide method interception via bytecode generation. */
public static BytecodeGen.EnhancerBuilder buildEnhancerBuilder(Class<?> hostClass) {
Map<String, Object> methodPartitions = new HashMap<>();
visitMethodHierarchy(
hostClass,
method -> {
// exclude static methods, but keep final methods for bridge analysis
if ((method.getModifiers() & STATIC) == 0) {
partitionMethod(method, methodPartitions);
}
});
Map<String, Method> enhanceableMethods = new TreeMap<>();
Map<Method, Method> bridgeDelegates = new HashMap<>();
TypeLiteral<?> hostType = TypeLiteral.get(hostClass);
for (Object partition : methodPartitions.values()) {
if (partition instanceof Method) {
// common case, partition is just one method; exclude if it turns out to be final
Method method = (Method) partition;
if ((method.getModifiers() & FINAL) == 0) {
enhanceableMethods.put(signature(method), method);
}
} else {
((MethodPartition) partition)
.collectEnhanceableMethods(
hostType,
method -> enhanceableMethods.put(signature(method), method),
bridgeDelegates);
}
}
return new EnhancerBuilderImpl(hostClass, enhanceableMethods.values(), bridgeDelegates);
}
/**
* Methods are partitioned by name and parameter count. This helps focus the search for bridge
* delegates that involve type-erasure of generic parameter types, since the parameter count will
* be the same for the bridge method and its delegate.
*/
private static void partitionMethod(Method method, Map<String, Object> partitions) {
String partitionKey = method.getName() + '/' + method.getParameterCount();
partitions.merge(partitionKey, method, ClassBuilding::mergeMethods);
}
/** Add the new method to an existing partition or create a new one. */
private static Object mergeMethods(Object existing, Object added) {
Method newMethod = (Method) added;
if (existing instanceof Method) {
return new MethodPartition((Method) existing, newMethod);
}
return ((MethodPartition) existing).addCandidate(newMethod);
}
/** Visit the method hierarchy for the host class. */
private static void visitMethodHierarchy(Class<?> hostClass, Consumer<Method> visitor) {
// this is an iterative form of the following recursive search:
// 1. visit<SUF>
// 2. recursively visit superclass
// 3. visit declared interfaces
// stack of interface declarations, from host class (bottom) to superclass (top)
Deque<Class<?>[]> interfaceStack = new ArrayDeque<>();
// only try to match package-private methods if the class-definer has package-access
String hostPackage = hasPackageAccess() ? packageName(hostClass.getName()) : null;
for (Class<?> clazz = hostClass;
clazz != Object.class && clazz != null;
clazz = clazz.getSuperclass()) {
// optionally visit package-private methods matching the same package as the host
boolean samePackage = hostPackage != null && hostPackage.equals(packageName(clazz.getName()));
visitMembers(clazz.getDeclaredMethods(), samePackage, visitor);
pushInterfaces(interfaceStack, clazz.getInterfaces());
}
for (Method method : OVERRIDABLE_OBJECT_METHODS) {
visitor.accept(method);
}
// work our way back down the class hierarchy, merging and flattening interfaces into a list
List<Class<?>> interfaces = new ArrayList<>();
while (!interfaceStack.isEmpty()) {
for (Class<?> intf : interfaceStack.pop()) {
if (mergeInterface(interfaces, intf)) {
pushInterfaces(interfaceStack, intf.getInterfaces());
}
}
}
// finally visit the methods declared in the flattened interface hierarchy
for (Class<?> intf : interfaces) {
visitMembers(intf.getDeclaredMethods(), false, visitor);
}
}
/** Pushes the interface declaration onto the stack if it's not empty. */
private static void pushInterfaces(Deque<Class<?>[]> interfaceStack, Class<?>[] interfaces) {
if (interfaces.length > 0) {
interfaceStack.push(interfaces);
}
}
/** Attempts to merge the interface with the current flattened hierarchy. */
private static boolean mergeInterface(List<Class<?>> interfaces, Class<?> candidate) {
// work along the flattened hierarchy to find the appropriate merge point
for (int i = 0, len = interfaces.size(); i < len; i++) {
Class<?> existingInterface = interfaces.get(i);
if (existingInterface == candidate) {
// already seen this interface, skip further processing
return false;
} else if (existingInterface.isAssignableFrom(candidate)) {
// extends existing interface, insert just before it in the flattened hierarchy
interfaces.add(i, candidate);
return true;
}
}
// unrelated or a superinterface, in both cases append to the flattened hierarchy
return interfaces.add(candidate);
}
/** Extract the package name from a class name. */
private static String packageName(String className) {
return className.substring(0, className.lastIndexOf('.') + 1);
}
/** Cache common overridable Object methods. */
private static Method[] getOverridableObjectMethods() {
List<Method> objectMethods = new ArrayList<>();
visitMembers(
Object.class.getDeclaredMethods(),
false, // no package-level access
method -> {
// skip methods that can't/shouldn't be overridden
if ((method.getModifiers() & (STATIC | FINAL)) == 0
&& !"finalize".equals(method.getName())) {
objectMethods.add(method);
}
});
return objectMethods.toArray(new Method[0]);
}
/** Returns true if the given member can be fast-invoked. */
public static boolean canFastInvoke(Executable member) {
int modifiers = member.getModifiers() & (PUBLIC | PRIVATE);
if (hasPackageAccess()) {
// can fast-invoke anything except private members
return modifiers != PRIVATE;
}
// can fast-invoke public members in public types whose parameters are all public
boolean visible = (modifiers == PUBLIC) && isPublic(member.getDeclaringClass());
if (visible) {
for (Class<?> type : member.getParameterTypes()) {
if (!isPublic(type)) {
return false;
}
}
}
return visible;
}
private static boolean isPublic(Class<?> clazz) {
return (clazz.getModifiers() & PUBLIC) != 0;
}
/** Builds a 'fast-class' invoker that uses bytecode generation in place of reflection. */
public static Function<String, BiFunction<Object, Object[], Object>> buildFastClass(
Class<?> hostClass) {
NavigableMap<String, Executable> glueMap = new TreeMap<>();
visitFastConstructors(hostClass, ctor -> glueMap.put(signature(ctor), ctor));
visitFastMethods(hostClass, method -> glueMap.put(signature(method), method));
return new FastClass(hostClass).glue(glueMap);
}
/** Visit all constructors for the host class that can be fast-invoked. */
private static void visitFastConstructors(Class<?> hostClass, Consumer<Constructor<?>> visitor) {
if (hasPackageAccess()) {
// can fast-invoke all non-private constructors
visitMembers(hostClass.getDeclaredConstructors(), true, visitor);
} else {
// can only fast-invoke public constructors
for (Constructor<?> constructor : hostClass.getConstructors()) {
visitor.accept(constructor);
}
}
}
/** Visit all methods declared by the host class that can be fast-invoked. */
private static void visitFastMethods(Class<?> hostClass, Consumer<Method> visitor) {
if (hasPackageAccess()) {
// can fast-invoke all non-private methods declared by the class
visitMembers(hostClass.getDeclaredMethods(), true, visitor);
} else {
// can only fast-invoke public methods
for (Method method : hostClass.getMethods()) {
// limit to those declared by this class; inherited methods have their own fast-class
if (hostClass == method.getDeclaringClass()) {
visitor.accept(method);
}
}
}
}
/** Visit all subclass accessible members in the given array. */
static <T extends Executable> void visitMembers(
T[] members, boolean samePackage, Consumer<T> visitor) {
for (T member : members) {
if (canAccess(member, samePackage)) {
visitor.accept(member);
}
}
}
/** Can we access this member from a subclass which may be in the same package? */
private static boolean canAccess(Executable member, boolean samePackage) {
int modifiers = member.getModifiers();
// public and protected members are always ok, non-private also ok if in the same package
return (modifiers & (PUBLIC | PROTECTED)) != 0 || (samePackage && (modifiers & PRIVATE) == 0);
}
}
| False | 2,470 | 7 | 2,704 | 7 | 2,888 | 7 | 2,704 | 7 | 3,240 | 7 | false | false | false | false | false | true |
3,899 | 198063_11 | /*
* Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.lwawt.macosx;
import sun.awt.SunToolkit;
import sun.lwawt.LWWindowPeer;
import sun.lwawt.PlatformEventNotifier;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.KeyEvent;
import java.util.Locale;
/**
* Translates NSEvents/NPCocoaEvents into AWT events.
*/
final class CPlatformResponder {
private final PlatformEventNotifier eventNotifier;
private final boolean isNpapiCallback;
private int lastKeyPressCode = KeyEvent.VK_UNDEFINED;
private final DeltaAccumulator deltaAccumulatorX = new DeltaAccumulator();
private final DeltaAccumulator deltaAccumulatorY = new DeltaAccumulator();
CPlatformResponder(final PlatformEventNotifier eventNotifier,
final boolean isNpapiCallback) {
this.eventNotifier = eventNotifier;
this.isNpapiCallback = isNpapiCallback;
}
/**
* Handles mouse events.
*/
void handleMouseEvent(int eventType, int modifierFlags, int buttonNumber,
int clickCount, int x, int y, int absX, int absY) {
final SunToolkit tk = (SunToolkit)Toolkit.getDefaultToolkit();
if ((buttonNumber > 2 && !tk.areExtraMouseButtonsEnabled())
|| buttonNumber > tk.getNumberOfButtons() - 1) {
return;
}
int jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
int jbuttonNumber = MouseEvent.NOBUTTON;
int jclickCount = 0;
if (jeventType != MouseEvent.MOUSE_MOVED &&
jeventType != MouseEvent.MOUSE_ENTERED &&
jeventType != MouseEvent.MOUSE_EXITED)
{
jbuttonNumber = NSEvent.nsToJavaButton(buttonNumber);
jclickCount = clickCount;
}
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
if ((jeventType == MouseEvent.MOUSE_PRESSED) && (jbuttonNumber > MouseEvent.NOBUTTON)) {
// 8294426: NSEvent.nsToJavaModifiers returns 0 on M2 MacBooks if the event is generated
// via tapping (not pressing) on a trackpad
// (System Preferences -> Trackpad -> Tap to click must be turned on).
// So let's set the modifiers manually.
jmodifiers |= MouseEvent.getMaskForButton(jbuttonNumber);
}
boolean jpopupTrigger = NSEvent.isPopupTrigger(jmodifiers);
eventNotifier.notifyMouseEvent(jeventType, System.currentTimeMillis(), jbuttonNumber,
x, y, absX, absY, jmodifiers, jclickCount,
jpopupTrigger, null);
}
/**
* Handles scroll events.
*/
void handleScrollEvent(final int x, final int y, final int absX,
final int absY, final int modifierFlags,
final double deltaX, final double deltaY,
final int scrollPhase) {
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
final boolean isShift = (jmodifiers & InputEvent.SHIFT_DOWN_MASK) != 0;
int roundDeltaX = deltaAccumulatorX.getRoundedDelta(deltaX, scrollPhase);
int roundDeltaY = deltaAccumulatorY.getRoundedDelta(deltaY, scrollPhase);
// Vertical scroll.
if (!isShift && (deltaY != 0.0 || roundDeltaY != 0)) {
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDeltaY, deltaY);
}
// Horizontal scroll or shirt+vertical scroll.
final double delta = isShift && deltaY != 0.0 ? deltaY : deltaX;
final int roundDelta = isShift && roundDeltaY != 0 ? roundDeltaY : roundDeltaX;
if (delta != 0.0 || roundDelta != 0) {
jmodifiers |= InputEvent.SHIFT_DOWN_MASK;
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDelta, delta);
}
}
private void dispatchScrollEvent(final int x, final int y, final int absX,
final int absY, final int modifiers,
final int roundDelta, final double delta) {
final long when = System.currentTimeMillis();
final int scrollType = MouseWheelEvent.WHEEL_UNIT_SCROLL;
final int scrollAmount = 1;
// invert the wheelRotation for the peer
eventNotifier.notifyMouseWheelEvent(when, x, y, absX, absY, modifiers,
scrollType, scrollAmount,
-roundDelta, -delta, null);
}
/**
* Handles key events.
*/
void handleKeyEvent(int eventType, int modifierFlags, String chars, String charsIgnoringModifiers,
short keyCode, boolean needsKeyTyped, boolean needsKeyReleased) {
boolean isFlagsChangedEvent =
isNpapiCallback ? (eventType == CocoaConstants.NPCocoaEventFlagsChanged) :
(eventType == CocoaConstants.NSEventTypeFlagsChanged);
int jeventType = KeyEvent.KEY_PRESSED;
int jkeyCode = KeyEvent.VK_UNDEFINED;
int jextendedkeyCode = -1;
int jkeyLocation = KeyEvent.KEY_LOCATION_UNKNOWN;
boolean postsTyped = false;
boolean spaceKeyTyped = false;
char testChar = KeyEvent.CHAR_UNDEFINED;
boolean isDeadChar = (chars!= null && chars.length() == 0);
if (isFlagsChangedEvent) {
int[] in = new int[] {modifierFlags, keyCode};
int[] out = new int[3]; // [jkeyCode, jkeyLocation, jkeyType]
NSEvent.nsKeyModifiersToJavaKeyInfo(in, out);
jkeyCode = out[0];
jkeyLocation = out[1];
jeventType = out[2];
} else {
if (chars != null && chars.length() > 0) {
testChar = chars.charAt(0);
//Check if String chars contains SPACE character.
if (chars.trim().isEmpty()) {
spaceKeyTyped = true;
}
}
char testCharIgnoringModifiers = charsIgnoringModifiers != null && charsIgnoringModifiers.length() > 0 ?
charsIgnoringModifiers.charAt(0) : KeyEvent.CHAR_UNDEFINED;
int[] in = new int[] {testCharIgnoringModifiers, isDeadChar ? 1 : 0, modifierFlags, keyCode};
int[] out = new int[4]; // [jkeyCode, jkeyLocation, deadChar, extendedKeyCode]
postsTyped = NSEvent.nsToJavaKeyInfo(in, out);
if (!postsTyped) {
testChar = KeyEvent.CHAR_UNDEFINED;
}
if(isDeadChar){
testChar = (char) out[2];
if(testChar == 0){
return;
}
}
// If Pinyin Simplified input method is selected, CAPS_LOCK key is supposed to switch
// input to latin letters.
// It is necessary to use testCharIgnoringModifiers instead of testChar for event
// generation in such case to avoid uppercase letters in text components.
LWCToolkit lwcToolkit = (LWCToolkit)Toolkit.getDefaultToolkit();
if ((lwcToolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK) &&
Locale.SIMPLIFIED_CHINESE.equals(lwcToolkit.getDefaultKeyboardLocale())) ||
(LWCToolkit.isLocaleUSInternationalPC(lwcToolkit.getDefaultKeyboardLocale()) &&
LWCToolkit.isCharModifierKeyInUSInternationalPC(testChar) &&
(testChar != testCharIgnoringModifiers))) {
testChar = testCharIgnoringModifiers;
}
jkeyCode = out[0];
jextendedkeyCode = out[3];
jkeyLocation = out[1];
jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
}
char javaChar = NSEvent.nsToJavaChar(testChar, modifierFlags, spaceKeyTyped);
// Some keys may generate a KEY_TYPED, but we can't determine
// what that character is. That's likely a bug, but for now we
// just check for CHAR_UNDEFINED.
if (javaChar == KeyEvent.CHAR_UNDEFINED) {
postsTyped = false;
}
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
long when = System.currentTimeMillis();
if (jeventType == KeyEvent.KEY_PRESSED) {
lastKeyPressCode = jkeyCode;
}
eventNotifier.notifyKeyEvent(jeventType, when, jmodifiers,
jkeyCode, javaChar, jkeyLocation, jextendedkeyCode);
// Current browser may be sending input events, so don't
// post the KEY_TYPED here.
postsTyped &= needsKeyTyped;
// That's the reaction on the PRESSED (not RELEASED) event as it comes to
// appear in MacOSX.
// Modifier keys (shift, etc) don't want to send TYPED events.
// On the other hand we don't want to generate keyTyped events
// for clipboard related shortcuts like Meta + [CVX]
if (jeventType == KeyEvent.KEY_PRESSED && postsTyped &&
(jmodifiers & KeyEvent.META_DOWN_MASK) == 0) {
// Enter and Space keys finish the input method processing,
// KEY_TYPED and KEY_RELEASED events for them are synthesized in handleInputEvent.
if (needsKeyReleased && (jkeyCode == KeyEvent.VK_ENTER || jkeyCode == KeyEvent.VK_SPACE)) {
return;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED, when, jmodifiers,
KeyEvent.VK_UNDEFINED, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN, jextendedkeyCode);
//If events come from Firefox, released events should also be generated.
if (needsKeyReleased) {
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED, when, jmodifiers,
jkeyCode, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN, jextendedkeyCode);
}
}
}
void handleInputEvent(String text) {
if (text != null) {
int index = 0, length = text.length();
char c = 0;
while (index < length) {
c = text.charAt(index);
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED,
System.currentTimeMillis(),
0, KeyEvent.VK_UNDEFINED, c,
KeyEvent.KEY_LOCATION_UNKNOWN, -1);
index++;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED,
System.currentTimeMillis(),
0, lastKeyPressCode, c,
KeyEvent.KEY_LOCATION_UNKNOWN, -1);
}
}
void handleWindowFocusEvent(boolean gained, LWWindowPeer opposite) {
eventNotifier.notifyActivation(gained, opposite);
}
static class DeltaAccumulator {
double accumulatedDelta;
boolean accumulate;
int getRoundedDelta(double delta, int scrollPhase) {
int roundDelta = (int) Math.round(delta);
if (scrollPhase == NSEvent.SCROLL_PHASE_UNSUPPORTED) { // mouse wheel
if (roundDelta == 0 && delta != 0) {
roundDelta = delta > 0 ? 1 : -1;
}
} else { // trackpad
if (scrollPhase == NSEvent.SCROLL_PHASE_BEGAN) {
accumulatedDelta = 0;
accumulate = true;
}
else if (scrollPhase == NSEvent.SCROLL_PHASE_MOMENTUM_BEGAN) {
accumulate = true;
}
if (accumulate) {
accumulatedDelta += delta;
roundDelta = (int) Math.round(accumulatedDelta);
accumulatedDelta -= roundDelta;
if (scrollPhase == NSEvent.SCROLL_PHASE_ENDED) {
accumulate = false;
}
}
}
return roundDelta;
}
}
}
| openjdk/jdk | src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java | 3,870 | // [jkeyCode, jkeyLocation, jkeyType] | line_comment | nl | /*
* Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.lwawt.macosx;
import sun.awt.SunToolkit;
import sun.lwawt.LWWindowPeer;
import sun.lwawt.PlatformEventNotifier;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.KeyEvent;
import java.util.Locale;
/**
* Translates NSEvents/NPCocoaEvents into AWT events.
*/
final class CPlatformResponder {
private final PlatformEventNotifier eventNotifier;
private final boolean isNpapiCallback;
private int lastKeyPressCode = KeyEvent.VK_UNDEFINED;
private final DeltaAccumulator deltaAccumulatorX = new DeltaAccumulator();
private final DeltaAccumulator deltaAccumulatorY = new DeltaAccumulator();
CPlatformResponder(final PlatformEventNotifier eventNotifier,
final boolean isNpapiCallback) {
this.eventNotifier = eventNotifier;
this.isNpapiCallback = isNpapiCallback;
}
/**
* Handles mouse events.
*/
void handleMouseEvent(int eventType, int modifierFlags, int buttonNumber,
int clickCount, int x, int y, int absX, int absY) {
final SunToolkit tk = (SunToolkit)Toolkit.getDefaultToolkit();
if ((buttonNumber > 2 && !tk.areExtraMouseButtonsEnabled())
|| buttonNumber > tk.getNumberOfButtons() - 1) {
return;
}
int jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
int jbuttonNumber = MouseEvent.NOBUTTON;
int jclickCount = 0;
if (jeventType != MouseEvent.MOUSE_MOVED &&
jeventType != MouseEvent.MOUSE_ENTERED &&
jeventType != MouseEvent.MOUSE_EXITED)
{
jbuttonNumber = NSEvent.nsToJavaButton(buttonNumber);
jclickCount = clickCount;
}
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
if ((jeventType == MouseEvent.MOUSE_PRESSED) && (jbuttonNumber > MouseEvent.NOBUTTON)) {
// 8294426: NSEvent.nsToJavaModifiers returns 0 on M2 MacBooks if the event is generated
// via tapping (not pressing) on a trackpad
// (System Preferences -> Trackpad -> Tap to click must be turned on).
// So let's set the modifiers manually.
jmodifiers |= MouseEvent.getMaskForButton(jbuttonNumber);
}
boolean jpopupTrigger = NSEvent.isPopupTrigger(jmodifiers);
eventNotifier.notifyMouseEvent(jeventType, System.currentTimeMillis(), jbuttonNumber,
x, y, absX, absY, jmodifiers, jclickCount,
jpopupTrigger, null);
}
/**
* Handles scroll events.
*/
void handleScrollEvent(final int x, final int y, final int absX,
final int absY, final int modifierFlags,
final double deltaX, final double deltaY,
final int scrollPhase) {
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
final boolean isShift = (jmodifiers & InputEvent.SHIFT_DOWN_MASK) != 0;
int roundDeltaX = deltaAccumulatorX.getRoundedDelta(deltaX, scrollPhase);
int roundDeltaY = deltaAccumulatorY.getRoundedDelta(deltaY, scrollPhase);
// Vertical scroll.
if (!isShift && (deltaY != 0.0 || roundDeltaY != 0)) {
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDeltaY, deltaY);
}
// Horizontal scroll or shirt+vertical scroll.
final double delta = isShift && deltaY != 0.0 ? deltaY : deltaX;
final int roundDelta = isShift && roundDeltaY != 0 ? roundDeltaY : roundDeltaX;
if (delta != 0.0 || roundDelta != 0) {
jmodifiers |= InputEvent.SHIFT_DOWN_MASK;
dispatchScrollEvent(x, y, absX, absY, jmodifiers, roundDelta, delta);
}
}
private void dispatchScrollEvent(final int x, final int y, final int absX,
final int absY, final int modifiers,
final int roundDelta, final double delta) {
final long when = System.currentTimeMillis();
final int scrollType = MouseWheelEvent.WHEEL_UNIT_SCROLL;
final int scrollAmount = 1;
// invert the wheelRotation for the peer
eventNotifier.notifyMouseWheelEvent(when, x, y, absX, absY, modifiers,
scrollType, scrollAmount,
-roundDelta, -delta, null);
}
/**
* Handles key events.
*/
void handleKeyEvent(int eventType, int modifierFlags, String chars, String charsIgnoringModifiers,
short keyCode, boolean needsKeyTyped, boolean needsKeyReleased) {
boolean isFlagsChangedEvent =
isNpapiCallback ? (eventType == CocoaConstants.NPCocoaEventFlagsChanged) :
(eventType == CocoaConstants.NSEventTypeFlagsChanged);
int jeventType = KeyEvent.KEY_PRESSED;
int jkeyCode = KeyEvent.VK_UNDEFINED;
int jextendedkeyCode = -1;
int jkeyLocation = KeyEvent.KEY_LOCATION_UNKNOWN;
boolean postsTyped = false;
boolean spaceKeyTyped = false;
char testChar = KeyEvent.CHAR_UNDEFINED;
boolean isDeadChar = (chars!= null && chars.length() == 0);
if (isFlagsChangedEvent) {
int[] in = new int[] {modifierFlags, keyCode};
int[] out = new int[3]; // [jkeyCode, jkeyLocation,<SUF>
NSEvent.nsKeyModifiersToJavaKeyInfo(in, out);
jkeyCode = out[0];
jkeyLocation = out[1];
jeventType = out[2];
} else {
if (chars != null && chars.length() > 0) {
testChar = chars.charAt(0);
//Check if String chars contains SPACE character.
if (chars.trim().isEmpty()) {
spaceKeyTyped = true;
}
}
char testCharIgnoringModifiers = charsIgnoringModifiers != null && charsIgnoringModifiers.length() > 0 ?
charsIgnoringModifiers.charAt(0) : KeyEvent.CHAR_UNDEFINED;
int[] in = new int[] {testCharIgnoringModifiers, isDeadChar ? 1 : 0, modifierFlags, keyCode};
int[] out = new int[4]; // [jkeyCode, jkeyLocation, deadChar, extendedKeyCode]
postsTyped = NSEvent.nsToJavaKeyInfo(in, out);
if (!postsTyped) {
testChar = KeyEvent.CHAR_UNDEFINED;
}
if(isDeadChar){
testChar = (char) out[2];
if(testChar == 0){
return;
}
}
// If Pinyin Simplified input method is selected, CAPS_LOCK key is supposed to switch
// input to latin letters.
// It is necessary to use testCharIgnoringModifiers instead of testChar for event
// generation in such case to avoid uppercase letters in text components.
LWCToolkit lwcToolkit = (LWCToolkit)Toolkit.getDefaultToolkit();
if ((lwcToolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK) &&
Locale.SIMPLIFIED_CHINESE.equals(lwcToolkit.getDefaultKeyboardLocale())) ||
(LWCToolkit.isLocaleUSInternationalPC(lwcToolkit.getDefaultKeyboardLocale()) &&
LWCToolkit.isCharModifierKeyInUSInternationalPC(testChar) &&
(testChar != testCharIgnoringModifiers))) {
testChar = testCharIgnoringModifiers;
}
jkeyCode = out[0];
jextendedkeyCode = out[3];
jkeyLocation = out[1];
jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
NSEvent.nsToJavaEventType(eventType);
}
char javaChar = NSEvent.nsToJavaChar(testChar, modifierFlags, spaceKeyTyped);
// Some keys may generate a KEY_TYPED, but we can't determine
// what that character is. That's likely a bug, but for now we
// just check for CHAR_UNDEFINED.
if (javaChar == KeyEvent.CHAR_UNDEFINED) {
postsTyped = false;
}
int jmodifiers = NSEvent.nsToJavaModifiers(modifierFlags);
long when = System.currentTimeMillis();
if (jeventType == KeyEvent.KEY_PRESSED) {
lastKeyPressCode = jkeyCode;
}
eventNotifier.notifyKeyEvent(jeventType, when, jmodifiers,
jkeyCode, javaChar, jkeyLocation, jextendedkeyCode);
// Current browser may be sending input events, so don't
// post the KEY_TYPED here.
postsTyped &= needsKeyTyped;
// That's the reaction on the PRESSED (not RELEASED) event as it comes to
// appear in MacOSX.
// Modifier keys (shift, etc) don't want to send TYPED events.
// On the other hand we don't want to generate keyTyped events
// for clipboard related shortcuts like Meta + [CVX]
if (jeventType == KeyEvent.KEY_PRESSED && postsTyped &&
(jmodifiers & KeyEvent.META_DOWN_MASK) == 0) {
// Enter and Space keys finish the input method processing,
// KEY_TYPED and KEY_RELEASED events for them are synthesized in handleInputEvent.
if (needsKeyReleased && (jkeyCode == KeyEvent.VK_ENTER || jkeyCode == KeyEvent.VK_SPACE)) {
return;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED, when, jmodifiers,
KeyEvent.VK_UNDEFINED, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN, jextendedkeyCode);
//If events come from Firefox, released events should also be generated.
if (needsKeyReleased) {
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED, when, jmodifiers,
jkeyCode, javaChar,
KeyEvent.KEY_LOCATION_UNKNOWN, jextendedkeyCode);
}
}
}
void handleInputEvent(String text) {
if (text != null) {
int index = 0, length = text.length();
char c = 0;
while (index < length) {
c = text.charAt(index);
eventNotifier.notifyKeyEvent(KeyEvent.KEY_TYPED,
System.currentTimeMillis(),
0, KeyEvent.VK_UNDEFINED, c,
KeyEvent.KEY_LOCATION_UNKNOWN, -1);
index++;
}
eventNotifier.notifyKeyEvent(KeyEvent.KEY_RELEASED,
System.currentTimeMillis(),
0, lastKeyPressCode, c,
KeyEvent.KEY_LOCATION_UNKNOWN, -1);
}
}
void handleWindowFocusEvent(boolean gained, LWWindowPeer opposite) {
eventNotifier.notifyActivation(gained, opposite);
}
static class DeltaAccumulator {
double accumulatedDelta;
boolean accumulate;
int getRoundedDelta(double delta, int scrollPhase) {
int roundDelta = (int) Math.round(delta);
if (scrollPhase == NSEvent.SCROLL_PHASE_UNSUPPORTED) { // mouse wheel
if (roundDelta == 0 && delta != 0) {
roundDelta = delta > 0 ? 1 : -1;
}
} else { // trackpad
if (scrollPhase == NSEvent.SCROLL_PHASE_BEGAN) {
accumulatedDelta = 0;
accumulate = true;
}
else if (scrollPhase == NSEvent.SCROLL_PHASE_MOMENTUM_BEGAN) {
accumulate = true;
}
if (accumulate) {
accumulatedDelta += delta;
roundDelta = (int) Math.round(accumulatedDelta);
accumulatedDelta -= roundDelta;
if (scrollPhase == NSEvent.SCROLL_PHASE_ENDED) {
accumulate = false;
}
}
}
return roundDelta;
}
}
}
| False | 2,842 | 13 | 3,039 | 13 | 3,247 | 13 | 3,038 | 13 | 3,853 | 14 | false | false | false | false | false | true |
1,995 | 8399_0 | package com.unasat;_x000D_
_x000D_
import com.unasat.service.*;_x000D_
import com.unasat.utility.Messages;_x000D_
_x000D_
import java.sql.SQLException;_x000D_
import java.util.Scanner;_x000D_
_x000D_
import static com.unasat.utility.UtilityMethods.isInputNotCorrect;_x000D_
import static com.unasat.utility.UtilityMethods.isOptionCorrect;_x000D_
_x000D_
public class Main {_x000D_
_x000D_
/**_x000D_
* @Developer: Akhsaykumar Bhoendie_x000D_
* @Project: Mildred's Kookschool_x000D_
* @Description: De applicatie is gebouwd voor registratie van dagelijkse activiteiten voor de kookschool._x000D_
* Verschillende zaken worden bijgehouden nl.:_x000D_
* - Inschrijvingen_x000D_
* - Kook cursussen_x000D_
* - prestaties_x000D_
* - Klantenbestand_x000D_
* - Openstaande rekeningen_x000D_
* @Instructies: Om gebruik te kunnen maken van de applicatie moeten de volgende zaken eerst in orde gemaakt worden:_x000D_
* - Maak een database connectie met een database genoemd "kookschool"_x000D_
* - Navigeer naar de DatabaseConnection class en geef de credentials mee_x000D_
* - Navigeer naar de SQL folder in de root directory en draai de sql script in Heidi of ander database management system_x000D_
* - De mysql Java Connector zit in de applicatie structuur en kan gebruikt worden voor configuratie in geval nodig_x000D_
* - Run de main app_x000D_
* <p>_x000D_
* #@ENJOY!_x000D_
*/_x000D_
_x000D_
public static void main(String[] args) throws SQLException {_x000D_
_x000D_
Messages.startApplication();_x000D_
boolean cannotProceed = true;_x000D_
Scanner scanner = new Scanner(System.in);_x000D_
String input;_x000D_
_x000D_
while (cannotProceed) {_x000D_
Messages.hoofdMenu();_x000D_
input = scanner.nextLine();_x000D_
_x000D_
if (isInputNotCorrect(input) || !isOptionCorrect(input)) {_x000D_
Messages.error1();_x000D_
} else {_x000D_
if (input.trim().equalsIgnoreCase("1")) {_x000D_
cannotProceed = false;_x000D_
Messages.goodbye();_x000D_
break;_x000D_
} else if (input.trim().equalsIgnoreCase("2")) {_x000D_
//kookcursus_x000D_
KookCursusService kookCursusService = new KookCursusService();_x000D_
kookCursusService.perform(scanner);_x000D_
} else if (input.trim().equalsIgnoreCase("3")) {_x000D_
//inschrijven_x000D_
DeelnemersService deelnemersService = new DeelnemersService();_x000D_
deelnemersService.perform(scanner);_x000D_
} else if (input.trim().equalsIgnoreCase("4")) {_x000D_
//klanten bestand_x000D_
KlantenBestandService klantenBestandService = new KlantenBestandService();_x000D_
klantenBestandService.perform(scanner);_x000D_
} else if (input.trim().equalsIgnoreCase("5")) {_x000D_
//prestaties_x000D_
PrestatieService prestatieService = new PrestatieService();_x000D_
prestatieService.perform(scanner);_x000D_
} else if (input.trim().equalsIgnoreCase("6")) {_x000D_
//schulden_x000D_
SchuldenService schuldenService = new SchuldenService();_x000D_
schuldenService.perform(scanner);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
scanner.reset();_x000D_
scanner.close();_x000D_
Messages.finished();_x000D_
_x000D_
}_x000D_
}_x000D_
| akshaybhoendie/mildred-is-cooking | src/com/unasat/Main.java | 920 | /**_x000D_
* @Developer: Akhsaykumar Bhoendie_x000D_
* @Project: Mildred's Kookschool_x000D_
* @Description: De applicatie is gebouwd voor registratie van dagelijkse activiteiten voor de kookschool._x000D_
* Verschillende zaken worden bijgehouden nl.:_x000D_
* - Inschrijvingen_x000D_
* - Kook cursussen_x000D_
* - prestaties_x000D_
* - Klantenbestand_x000D_
* - Openstaande rekeningen_x000D_
* @Instructies: Om gebruik te kunnen maken van de applicatie moeten de volgende zaken eerst in orde gemaakt worden:_x000D_
* - Maak een database connectie met een database genoemd "kookschool"_x000D_
* - Navigeer naar de DatabaseConnection class en geef de credentials mee_x000D_
* - Navigeer naar de SQL folder in de root directory en draai de sql script in Heidi of ander database management system_x000D_
* - De mysql Java Connector zit in de applicatie structuur en kan gebruikt worden voor configuratie in geval nodig_x000D_
* - Run de main app_x000D_
* <p>_x000D_
* #@ENJOY!_x000D_
*/ | block_comment | nl | package com.unasat;_x000D_
_x000D_
import com.unasat.service.*;_x000D_
import com.unasat.utility.Messages;_x000D_
_x000D_
import java.sql.SQLException;_x000D_
import java.util.Scanner;_x000D_
_x000D_
import static com.unasat.utility.UtilityMethods.isInputNotCorrect;_x000D_
import static com.unasat.utility.UtilityMethods.isOptionCorrect;_x000D_
_x000D_
public class Main {_x000D_
_x000D_
/**_x000D_
* @Developer: Akhsaykumar Bhoendie_x000D_<SUF>*/_x000D_
_x000D_
public static void main(String[] args) throws SQLException {_x000D_
_x000D_
Messages.startApplication();_x000D_
boolean cannotProceed = true;_x000D_
Scanner scanner = new Scanner(System.in);_x000D_
String input;_x000D_
_x000D_
while (cannotProceed) {_x000D_
Messages.hoofdMenu();_x000D_
input = scanner.nextLine();_x000D_
_x000D_
if (isInputNotCorrect(input) || !isOptionCorrect(input)) {_x000D_
Messages.error1();_x000D_
} else {_x000D_
if (input.trim().equalsIgnoreCase("1")) {_x000D_
cannotProceed = false;_x000D_
Messages.goodbye();_x000D_
break;_x000D_
} else if (input.trim().equalsIgnoreCase("2")) {_x000D_
//kookcursus_x000D_
KookCursusService kookCursusService = new KookCursusService();_x000D_
kookCursusService.perform(scanner);_x000D_
} else if (input.trim().equalsIgnoreCase("3")) {_x000D_
//inschrijven_x000D_
DeelnemersService deelnemersService = new DeelnemersService();_x000D_
deelnemersService.perform(scanner);_x000D_
} else if (input.trim().equalsIgnoreCase("4")) {_x000D_
//klanten bestand_x000D_
KlantenBestandService klantenBestandService = new KlantenBestandService();_x000D_
klantenBestandService.perform(scanner);_x000D_
} else if (input.trim().equalsIgnoreCase("5")) {_x000D_
//prestaties_x000D_
PrestatieService prestatieService = new PrestatieService();_x000D_
prestatieService.perform(scanner);_x000D_
} else if (input.trim().equalsIgnoreCase("6")) {_x000D_
//schulden_x000D_
SchuldenService schuldenService = new SchuldenService();_x000D_
schuldenService.perform(scanner);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
scanner.reset();_x000D_
scanner.close();_x000D_
Messages.finished();_x000D_
_x000D_
}_x000D_
}_x000D_
| True | 1,193 | 360 | 1,296 | 388 | 1,285 | 361 | 1,296 | 388 | 1,429 | 404 | true | true | true | true | true | false |
1,635 | 39937_4 | import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class CateringImpl extends UnicastRemoteObject implements Catering {
Registrar registrar;
int businessNumber;
String name, address;
Scanner sc;
byte[] secretKey;
byte[] pseudonym;
String CF;
JFrame frame = new JFrame("Caterer");
JPanel p = new JPanel();
JTextField NameTextField = new JTextField();
JTextField BuisinessNumberTextField = new JTextField();
JTextField AddressTextField = new JTextField();
JTextField OutputTextField = new JTextField();
JButton logInButton = new JButton("Log in");
JButton getSecretkey = new JButton("Secret key");
JButton getPseudonym = new JButton("Pseudonym");
JButton getQRCode = new JButton("QR code");
JLabel NameLabel = new JLabel("Name");
JLabel BuisinessNumberLabel = new JLabel("Buisiness Number");
JLabel AddressLabel = new JLabel("Address");
JLabel OutputLabel = new JLabel("Output");
//hashing functie om hash in qrcode te genereren
MessageDigest md = MessageDigest.getInstance("SHA-256");
public CateringImpl() throws RemoteException, NoSuchAlgorithmException {
setFrame();
try {
// fire to localhost port 1099
Registry myRegistry = LocateRegistry.getRegistry("localhost", 1099);
registrar = (Registrar) myRegistry.lookup("Registrar");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws RemoteException, NoSuchAlgorithmException {
CateringImpl catering = new CateringImpl();
//catering.register();
}
public void setFrame(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(400,500));
NameLabel.setBounds(0,20,10,10);
BuisinessNumberLabel.setBounds(0,0,10,10);
AddressLabel.setBounds(0,0,10,10);
NameTextField.setVisible(true);
BuisinessNumberTextField.setVisible(true);
AddressTextField.setVisible(true);
OutputLabel.setVisible(false);
OutputTextField.setVisible(false);
p.setLayout(new GridLayout(5,2));
p.add(NameLabel);
p.add(NameTextField);
p.add(BuisinessNumberLabel);
p.add(BuisinessNumberTextField);
p.add(AddressLabel);
p.add(AddressTextField);
p.add(OutputLabel);
p.add(OutputTextField);
p.add(logInButton);
frame.add(p, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.add(getQRCode);
panel.add(getPseudonym);
panel.add(getSecretkey);
frame.add(panel, BorderLayout.PAGE_END);
frame.setSize(400,500);
getPseudonym.setVisible(false);
getSecretkey.setVisible(false);
getQRCode.setVisible(false);
NameTextField.setEditable(true);
BuisinessNumberTextField.setEditable(true);
AddressTextField.setEditable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.pack();
getQRCode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
genQRCode();
}catch (Exception ex){
ex.printStackTrace();
}
}
});
getSecretkey.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
OutputTextField.setText(Arrays.toString(secretKey));
}catch (Exception ex){
ex.printStackTrace();
}
}
});
getPseudonym.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
OutputTextField.setText(Arrays.toString(pseudonym));
}catch (Exception ex){
ex.printStackTrace();
}
}
});
logInButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
tryLogIn();
}catch (Exception ex){
ex.printStackTrace();
}
}
});
}
public void tryLogIn()throws Exception{
if(!Objects.equals(NameTextField,"") && !Objects.equals(BuisinessNumberTextField,"") && !Objects.equals(AddressTextField,"")){
this.name = NameTextField.getText();
this.businessNumber = Integer.parseInt(BuisinessNumberTextField.getText());
this.address = AddressTextField.getText();
this.CF = businessNumber + name + address;
p.remove(NameTextField);
p.remove(BuisinessNumberTextField);
p.remove(AddressTextField);
p.remove(NameLabel);
p.remove(BuisinessNumberLabel);
p.remove(AddressLabel);
p.remove(logInButton);
OutputLabel.setVisible(true);
OutputTextField.setVisible(true);
getQRCode.setVisible(true);
getSecretkey.setVisible(true);
getPseudonym.setVisible(true);
register();
String response = registrar.helloTo(name);
OutputTextField.setText(response);
}
}
//stuur een referentie naar onze eigen interface door naar de server zodat deze ons ook kan contacteren
public void register() throws IOException, WriterException {
registrar.register(this);
}
private static void printMenu() throws RemoteException, NoSuchAlgorithmException {
Scanner s = new Scanner(System.in);
int choice = 0;
System.out.println("-----Enroll BarOwner-----");
//CateringImpl catering = new CateringImpl();
//catering.register();
while (choice != -1) {
System.out.println();
System.out.println("1.Exit");
System.out.println("2. Print secret key");
System.out.println("3. Print pseudonym");
System.out.println("Enter your choice");
choice = s.nextInt();
switch (choice) {
case 1:
choice = -1;
break;
case 2:
//System.out.println(Arrays.toString(catering.secretKey));
break;
case 3:
//System.out.println(Arrays.toString(catering.pseudonym));
}
}
s.close();
}
//qr code generaten van random nummer, identifier en hash van pseudonym met randon nummer
public void genQRCode() throws IOException, WriterException {
Random rand = new Random();
int random = rand.nextInt(1000);
String tbhash = String.valueOf(random) + Arrays.toString(pseudonym);
md.update(tbhash.getBytes(StandardCharsets.UTF_8));
byte[] digest = md.digest();
String data = String.valueOf(random) + "|" + CF + "|" + Base64.getEncoder().encodeToString(digest);
BitMatrix matrix = new MultiFormatWriter().encode(
new String(data.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8),
BarcodeFormat.QR_CODE, 200, 200);
String path = "code" + businessNumber; //TODO tonen in gui
path += ".png";
MatrixToImageWriter.writeToFile(
matrix,
path.substring(path.lastIndexOf('.') + 1),
new File(path));
OutputTextField.setText(data);
System.out.println("qr: " + data);
System.out.println("random: " + random);
System.out.println("nym: " + pseudonym);
System.out.println("CF: " + CF);
}
@Override
public int getBusinessNumber() throws RemoteException {
return businessNumber;
}
@Override
public String getName() throws RemoteException {
return name;
}
@Override
public void setSecretKey(byte[] secretKey) throws RemoteException {
this.secretKey = secretKey;
}
@Override
public String getCF() throws RemoteException {
return CF;
}
@Override
public String getLocation() throws RemoteException {
return address;
}
@Override
public void setPseudonym(byte[] pseudonym) throws IOException, WriterException {
System.out.println("nym bij ontvangst: " + pseudonym);
this.pseudonym = pseudonym;
this.genQRCode();
}
}
| SprietMarthe/CoronaOpdracht_Robin_Lukas_Marthe | CF/src/CateringImpl.java | 2,606 | //qr code generaten van random nummer, identifier en hash van pseudonym met randon nummer | line_comment | nl | import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class CateringImpl extends UnicastRemoteObject implements Catering {
Registrar registrar;
int businessNumber;
String name, address;
Scanner sc;
byte[] secretKey;
byte[] pseudonym;
String CF;
JFrame frame = new JFrame("Caterer");
JPanel p = new JPanel();
JTextField NameTextField = new JTextField();
JTextField BuisinessNumberTextField = new JTextField();
JTextField AddressTextField = new JTextField();
JTextField OutputTextField = new JTextField();
JButton logInButton = new JButton("Log in");
JButton getSecretkey = new JButton("Secret key");
JButton getPseudonym = new JButton("Pseudonym");
JButton getQRCode = new JButton("QR code");
JLabel NameLabel = new JLabel("Name");
JLabel BuisinessNumberLabel = new JLabel("Buisiness Number");
JLabel AddressLabel = new JLabel("Address");
JLabel OutputLabel = new JLabel("Output");
//hashing functie om hash in qrcode te genereren
MessageDigest md = MessageDigest.getInstance("SHA-256");
public CateringImpl() throws RemoteException, NoSuchAlgorithmException {
setFrame();
try {
// fire to localhost port 1099
Registry myRegistry = LocateRegistry.getRegistry("localhost", 1099);
registrar = (Registrar) myRegistry.lookup("Registrar");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws RemoteException, NoSuchAlgorithmException {
CateringImpl catering = new CateringImpl();
//catering.register();
}
public void setFrame(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(400,500));
NameLabel.setBounds(0,20,10,10);
BuisinessNumberLabel.setBounds(0,0,10,10);
AddressLabel.setBounds(0,0,10,10);
NameTextField.setVisible(true);
BuisinessNumberTextField.setVisible(true);
AddressTextField.setVisible(true);
OutputLabel.setVisible(false);
OutputTextField.setVisible(false);
p.setLayout(new GridLayout(5,2));
p.add(NameLabel);
p.add(NameTextField);
p.add(BuisinessNumberLabel);
p.add(BuisinessNumberTextField);
p.add(AddressLabel);
p.add(AddressTextField);
p.add(OutputLabel);
p.add(OutputTextField);
p.add(logInButton);
frame.add(p, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.add(getQRCode);
panel.add(getPseudonym);
panel.add(getSecretkey);
frame.add(panel, BorderLayout.PAGE_END);
frame.setSize(400,500);
getPseudonym.setVisible(false);
getSecretkey.setVisible(false);
getQRCode.setVisible(false);
NameTextField.setEditable(true);
BuisinessNumberTextField.setEditable(true);
AddressTextField.setEditable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.pack();
getQRCode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
genQRCode();
}catch (Exception ex){
ex.printStackTrace();
}
}
});
getSecretkey.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
OutputTextField.setText(Arrays.toString(secretKey));
}catch (Exception ex){
ex.printStackTrace();
}
}
});
getPseudonym.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
OutputTextField.setText(Arrays.toString(pseudonym));
}catch (Exception ex){
ex.printStackTrace();
}
}
});
logInButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try{
tryLogIn();
}catch (Exception ex){
ex.printStackTrace();
}
}
});
}
public void tryLogIn()throws Exception{
if(!Objects.equals(NameTextField,"") && !Objects.equals(BuisinessNumberTextField,"") && !Objects.equals(AddressTextField,"")){
this.name = NameTextField.getText();
this.businessNumber = Integer.parseInt(BuisinessNumberTextField.getText());
this.address = AddressTextField.getText();
this.CF = businessNumber + name + address;
p.remove(NameTextField);
p.remove(BuisinessNumberTextField);
p.remove(AddressTextField);
p.remove(NameLabel);
p.remove(BuisinessNumberLabel);
p.remove(AddressLabel);
p.remove(logInButton);
OutputLabel.setVisible(true);
OutputTextField.setVisible(true);
getQRCode.setVisible(true);
getSecretkey.setVisible(true);
getPseudonym.setVisible(true);
register();
String response = registrar.helloTo(name);
OutputTextField.setText(response);
}
}
//stuur een referentie naar onze eigen interface door naar de server zodat deze ons ook kan contacteren
public void register() throws IOException, WriterException {
registrar.register(this);
}
private static void printMenu() throws RemoteException, NoSuchAlgorithmException {
Scanner s = new Scanner(System.in);
int choice = 0;
System.out.println("-----Enroll BarOwner-----");
//CateringImpl catering = new CateringImpl();
//catering.register();
while (choice != -1) {
System.out.println();
System.out.println("1.Exit");
System.out.println("2. Print secret key");
System.out.println("3. Print pseudonym");
System.out.println("Enter your choice");
choice = s.nextInt();
switch (choice) {
case 1:
choice = -1;
break;
case 2:
//System.out.println(Arrays.toString(catering.secretKey));
break;
case 3:
//System.out.println(Arrays.toString(catering.pseudonym));
}
}
s.close();
}
//qr code<SUF>
public void genQRCode() throws IOException, WriterException {
Random rand = new Random();
int random = rand.nextInt(1000);
String tbhash = String.valueOf(random) + Arrays.toString(pseudonym);
md.update(tbhash.getBytes(StandardCharsets.UTF_8));
byte[] digest = md.digest();
String data = String.valueOf(random) + "|" + CF + "|" + Base64.getEncoder().encodeToString(digest);
BitMatrix matrix = new MultiFormatWriter().encode(
new String(data.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8),
BarcodeFormat.QR_CODE, 200, 200);
String path = "code" + businessNumber; //TODO tonen in gui
path += ".png";
MatrixToImageWriter.writeToFile(
matrix,
path.substring(path.lastIndexOf('.') + 1),
new File(path));
OutputTextField.setText(data);
System.out.println("qr: " + data);
System.out.println("random: " + random);
System.out.println("nym: " + pseudonym);
System.out.println("CF: " + CF);
}
@Override
public int getBusinessNumber() throws RemoteException {
return businessNumber;
}
@Override
public String getName() throws RemoteException {
return name;
}
@Override
public void setSecretKey(byte[] secretKey) throws RemoteException {
this.secretKey = secretKey;
}
@Override
public String getCF() throws RemoteException {
return CF;
}
@Override
public String getLocation() throws RemoteException {
return address;
}
@Override
public void setPseudonym(byte[] pseudonym) throws IOException, WriterException {
System.out.println("nym bij ontvangst: " + pseudonym);
this.pseudonym = pseudonym;
this.genQRCode();
}
}
| True | 1,809 | 21 | 2,125 | 22 | 2,239 | 17 | 2,125 | 22 | 2,575 | 22 | false | false | false | false | false | true |
598 | 49834_4 | /*
* Geotoolkit.org - An Open Source Java GIS Toolkit
* http://www.geotoolkit.org
*
* (C) 2014, Geomatys
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotoolkit.processing.coverage.shadedrelief;
import org.apache.sis.coverage.grid.GridCoverage;
import org.apache.sis.parameter.ParameterBuilder;
import org.geotoolkit.processing.AbstractProcessDescriptor;
import org.geotoolkit.process.Process;
import org.geotoolkit.process.ProcessDescriptor;
import org.geotoolkit.processing.GeotkProcessingRegistry;
import org.geotoolkit.processing.ProcessBundle;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.operation.MathTransform1D;
import org.opengis.util.InternationalString;
/**
*
* @author Johann Sorel (Geomatys)
*/
public class ShadedReliefDescriptor extends AbstractProcessDescriptor {
public static final String NAME = "coverage:shadedrelief";
public static final InternationalString abs = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_abstract);
/*
* Coverage base image
*/
public static final String IN_COVERAGE_PARAM_NAME = "inCoverage";
public static final InternationalString IN_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inCoverage);
public static final ParameterDescriptor<GridCoverage> COVERAGE = new ParameterBuilder()
.addName(IN_COVERAGE_PARAM_NAME)
.setRemarks(IN_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/*
* Coverage elevation
*/
public static final String IN_ELEVATION_PARAM_NAME = "inElevation";
public static final InternationalString IN_ELEVATION_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<GridCoverage> ELEVATION = new ParameterBuilder()
.addName(IN_ELEVATION_PARAM_NAME)
.setRemarks(IN_ELEVATION_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/*
* Coverage elevation value to meters
*/
public static final String IN_ELECONV_PARAM_NAME = "inEleEnv";
public static final InternationalString IN_ELECONV_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<MathTransform1D> ELECONV = new ParameterBuilder()
.addName(IN_ELECONV_PARAM_NAME)
.setRemarks(IN_ELECONV_PARAM_REMARKS)
.setRequired(true)
.create(MathTransform1D.class, null);
/**Input parameters */
public static final ParameterDescriptorGroup INPUT_DESC =
new ParameterBuilder().addName("InputParameters").createGroup(COVERAGE, ELEVATION, ELECONV);
/*
* Coverage result
*/
public static final String OUT_COVERAGE_PARAM_NAME = "outCoverage";
public static final InternationalString OUT_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_outCoverage);
public static final ParameterDescriptor<GridCoverage> OUTCOVERAGE = new ParameterBuilder()
.addName(OUT_COVERAGE_PARAM_NAME)
.setRemarks(OUT_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/**Output parameters */
public static final ParameterDescriptorGroup OUTPUT_DESC = new ParameterBuilder().addName("OutputParameters").createGroup(OUTCOVERAGE);
public static final ProcessDescriptor INSTANCE = new ShadedReliefDescriptor();
private ShadedReliefDescriptor() {
super(NAME, GeotkProcessingRegistry.IDENTIFICATION, abs, INPUT_DESC, OUTPUT_DESC);
}
@Override
public Process createProcess(final ParameterValueGroup input) {
return new ShadedRelief(INSTANCE, input);
}
}
| Geomatys/geotoolkit | geotk-processing/src/main/java/org/geotoolkit/processing/coverage/shadedrelief/ShadedReliefDescriptor.java | 1,309 | /*
* Coverage elevation value to meters
*/ | block_comment | nl | /*
* Geotoolkit.org - An Open Source Java GIS Toolkit
* http://www.geotoolkit.org
*
* (C) 2014, Geomatys
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotoolkit.processing.coverage.shadedrelief;
import org.apache.sis.coverage.grid.GridCoverage;
import org.apache.sis.parameter.ParameterBuilder;
import org.geotoolkit.processing.AbstractProcessDescriptor;
import org.geotoolkit.process.Process;
import org.geotoolkit.process.ProcessDescriptor;
import org.geotoolkit.processing.GeotkProcessingRegistry;
import org.geotoolkit.processing.ProcessBundle;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.operation.MathTransform1D;
import org.opengis.util.InternationalString;
/**
*
* @author Johann Sorel (Geomatys)
*/
public class ShadedReliefDescriptor extends AbstractProcessDescriptor {
public static final String NAME = "coverage:shadedrelief";
public static final InternationalString abs = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_abstract);
/*
* Coverage base image
*/
public static final String IN_COVERAGE_PARAM_NAME = "inCoverage";
public static final InternationalString IN_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inCoverage);
public static final ParameterDescriptor<GridCoverage> COVERAGE = new ParameterBuilder()
.addName(IN_COVERAGE_PARAM_NAME)
.setRemarks(IN_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/*
* Coverage elevation
*/
public static final String IN_ELEVATION_PARAM_NAME = "inElevation";
public static final InternationalString IN_ELEVATION_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<GridCoverage> ELEVATION = new ParameterBuilder()
.addName(IN_ELEVATION_PARAM_NAME)
.setRemarks(IN_ELEVATION_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/*
* Coverage elevation value<SUF>*/
public static final String IN_ELECONV_PARAM_NAME = "inEleEnv";
public static final InternationalString IN_ELECONV_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<MathTransform1D> ELECONV = new ParameterBuilder()
.addName(IN_ELECONV_PARAM_NAME)
.setRemarks(IN_ELECONV_PARAM_REMARKS)
.setRequired(true)
.create(MathTransform1D.class, null);
/**Input parameters */
public static final ParameterDescriptorGroup INPUT_DESC =
new ParameterBuilder().addName("InputParameters").createGroup(COVERAGE, ELEVATION, ELECONV);
/*
* Coverage result
*/
public static final String OUT_COVERAGE_PARAM_NAME = "outCoverage";
public static final InternationalString OUT_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_outCoverage);
public static final ParameterDescriptor<GridCoverage> OUTCOVERAGE = new ParameterBuilder()
.addName(OUT_COVERAGE_PARAM_NAME)
.setRemarks(OUT_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage.class, null);
/**Output parameters */
public static final ParameterDescriptorGroup OUTPUT_DESC = new ParameterBuilder().addName("OutputParameters").createGroup(OUTCOVERAGE);
public static final ProcessDescriptor INSTANCE = new ShadedReliefDescriptor();
private ShadedReliefDescriptor() {
super(NAME, GeotkProcessingRegistry.IDENTIFICATION, abs, INPUT_DESC, OUTPUT_DESC);
}
@Override
public Process createProcess(final ParameterValueGroup input) {
return new ShadedRelief(INSTANCE, input);
}
}
| False | 968 | 11 | 1,125 | 10 | 1,109 | 12 | 1,125 | 10 | 1,344 | 14 | false | false | false | false | false | true |
386 | 7822_0 | package controllers;
import dal.repositories.DatabaseExecutionContext;
import dal.repositories.JPARecipeRepository;
import dal.repositories.JPAUserRepository;
import models.*;
import play.db.jpa.JPAApi;
import play.db.jpa.Transactional;
import play.mvc.*;
import views.html.*;
import views.html.shared.getResults;
import views.html.shared.index;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;
public class Application extends Controller {
private JPAUserRepository userRepo;
private JPARecipeRepository recipeRepo;
@Inject
public Application(JPAUserRepository userRepo, JPARecipeRepository recipeRepo) {
this.userRepo = userRepo;
this.recipeRepo = recipeRepo;
}
@Transactional
public Result index() {
User user = new User("harry", "[email protected]", "hallo123");
Recipe recipe = new Recipe("Rijst", "De perfecte rijst voor bodybuilders!", false);
Ingredient ingredient = new Ingredient("Water", 20, "water.pjg", Measurement.ml);
Kitchenware kitchenware = new Kitchenware("Vork");
userRepo.add(user);
recipeRepo.add(recipe);
// TODO:
// De recipe klasse persisten lukt niet, zou je hier naar kunnen kijken,
// waarom hij een error geeft?
return ok(index.render());
}
public Result getResults() {
List<User> users = userRepo.list();
List<Recipe> recipes = recipeRepo.list();
return ok(getResults.render(users, recipes));
}
/*public List<User> findAll() {
return entityManager.createNamedQuery("User.getAll", User.class)
.getResultList();
} */
}
| Daniel-Lin1/BoodschappenlijstApp | BoodschappenLijst/app/controllers/Application.java | 528 | // De recipe klasse persisten lukt niet, zou je hier naar kunnen kijken, | line_comment | nl | package controllers;
import dal.repositories.DatabaseExecutionContext;
import dal.repositories.JPARecipeRepository;
import dal.repositories.JPAUserRepository;
import models.*;
import play.db.jpa.JPAApi;
import play.db.jpa.Transactional;
import play.mvc.*;
import views.html.*;
import views.html.shared.getResults;
import views.html.shared.index;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;
public class Application extends Controller {
private JPAUserRepository userRepo;
private JPARecipeRepository recipeRepo;
@Inject
public Application(JPAUserRepository userRepo, JPARecipeRepository recipeRepo) {
this.userRepo = userRepo;
this.recipeRepo = recipeRepo;
}
@Transactional
public Result index() {
User user = new User("harry", "[email protected]", "hallo123");
Recipe recipe = new Recipe("Rijst", "De perfecte rijst voor bodybuilders!", false);
Ingredient ingredient = new Ingredient("Water", 20, "water.pjg", Measurement.ml);
Kitchenware kitchenware = new Kitchenware("Vork");
userRepo.add(user);
recipeRepo.add(recipe);
// TODO:
// De recipe<SUF>
// waarom hij een error geeft?
return ok(index.render());
}
public Result getResults() {
List<User> users = userRepo.list();
List<Recipe> recipes = recipeRepo.list();
return ok(getResults.render(users, recipes));
}
/*public List<User> findAll() {
return entityManager.createNamedQuery("User.getAll", User.class)
.getResultList();
} */
}
| True | 369 | 18 | 450 | 23 | 452 | 17 | 450 | 23 | 540 | 21 | false | false | false | false | false | true |
1,990 | 204396_11 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Graph;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.Arc2D;
import java.awt.geom.Line2D;
import javafx.collections.ObservableList;
/**
*
* @author fahri
*/
public class FahriCanvas extends java.awt.Canvas{
private Cizim cizim;
private Graphics2D lay1;
private int CX, CY, centerX, centerY;
private double Scale = 1;
private double ShiftX = 0, ShiftY = 0;
private double OldShiftX = 0, OldShiftY = 0;
private int MX, MY, mxb = 0, myb = 0, MicroBoxSize = 250, StartStopBoxSize = 250;
private int MouseShiftStX = 0, MouseShiftStY = 0, ZWindowStX = 0, ZWindowStY = 0;
public FahriCanvas() {
}
public FahriCanvas(Cizim ciz){
// lay1 = (Graphics2D) this.getGraphics();
setBackground(Color.LIGHT_GRAY);
this.cizim=ciz;
this.addComponentListener(new ComponentListener(){
@Override
public void componentResized(ComponentEvent ce) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
centerY = getHeight() / 2;
centerX = getWidth() / 2;
CX = (int) (centerX + ShiftX);
CY = (int) (centerY + ShiftY);
}
@Override
public void componentMoved(ComponentEvent ce) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void componentShown(ComponentEvent ce) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void componentHidden(ComponentEvent ce) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
this.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent me) {
Point pxy;
if (me.getClickCount() == 1)//&&!GrFunc.BevelEnable) SOL TIKLAMA
{
pxy = me.getPoint();
if(cizim.sekilSec(pxy,CX,CY,Scale))repaint();
}
}
@Override
public void mousePressed(MouseEvent me) {
MouseShiftStX = me.getX();
MouseShiftStY = me.getY();
if(cizim.getMoveEnable()){ OldShiftY=OldShiftX=0;}
}
@Override
public void mouseReleased(MouseEvent me) {
MouseShiftStX = 0;
MouseShiftStY = 0;
repaint();
cizim.setMoveEnable(false);
}
@Override
public void mouseEntered(MouseEvent me) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void mouseExited(MouseEvent me) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
this.addMouseMotionListener(new MouseMotionListener(){
@Override
public void mouseDragged(MouseEvent me) {
MouseShiftStX -= me.getX();
MouseShiftStY -= me.getY();
ShiftX -= MouseShiftStX;
ShiftY -= MouseShiftStY;
MouseShiftStX = me.getX();
MouseShiftStY = me.getY();
if(cizim.getMoveEnable()&&OldShiftX!=0){
cizim.MoveSelectedObject(OldShiftX-ShiftX,OldShiftY-ShiftY);
}
else{
CX = (int) (centerX + ShiftX);
CY = (int) (centerY + ShiftY);
}
OldShiftX=ShiftX;OldShiftY=ShiftY;
repaint();
}
@Override
public void mouseMoved(MouseEvent me) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
this.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent mwe) {
//int rotdir = mwe.getWheelRotation();
Scale += .01 * mwe.getWheelRotation() * mwe.getScrollAmount();
if (Scale <= 0) {
Scale = 0.001;
}
repaint();
}
});
}
public void setCizim(Cizim ciz){
this.cizim = ciz;
}
public void paint(Graphics g) {
this.ciz();
}
public void ciz() {
lay1 = (Graphics2D) this.getGraphics();
drawPlane();
Line ln;
Circle ar;
Rectangle rect;
ObservableList<Object> Shapes = cizim.getShapes();
for(int i=0;i<Shapes.size();i++){
if(Shapes.get(i) instanceof Line)
{
ln = (Line) Shapes.get(i);
lineciz(ln);
}
else if(Shapes.get(i) instanceof Circle)
{
ar = (Circle) Shapes.get(i);
arcciz(ar);
}
else if(Shapes.get(i) instanceof Rectangle)
{
rect = (Rectangle) Shapes.get(i);
for(int j=0;j<rect.Lines.size();j++)
lineciz( (Line) rect.Lines.get(j));
}
}
}
private void lineciz(Line ln) {
if(ln.isSelected())lay1.setColor(Color.yellow);else lay1.setColor(Color.black);
lay1.draw(new Line2D.Double(CX+(ln.xn1 * Scale), CY - (ln.yn1 * Scale),CX + (ln.xn2 * Scale), CY - (ln.yn2 * Scale)));
}
private void arcciz(Circle ar) {
if(ar.isSelected())lay1.setColor(Color.yellow);else lay1.setColor(Color.black);
lay1.drawArc(CX + (int)((ar.xc - ar.radius) * Scale) , CY - (int)((ar.yc + ar.radius) * Scale) , (int)(ar.radius * Scale)*2, (int)(ar.radius * Scale)*2, 0,360);
//lay1.drawArc(CX - (int)(( ar.radius/2 ) * Scale) , CY - (int)((ar.radius/2) * Scale) , (int)(ar.radius * Scale), (int)(ar.radius * Scale), 0,360);
//lay1.drawArc(CX + 0 , CY - 0 , (int)(50 * Scale), (int)(50 * Scale), 0,90);
//lay1.draw(new Arc2D.Double(CX-25, CY-25, 50 , 50 , 45,135, Arc2D.OPEN));
}
private void drawPlane(){
lay1.draw(new Line2D.Double(CX+(-2000), CY ,CX + (2000), CY ));
lay1.draw(new Line2D.Double(CX, CY+(-2000) ,CX , CY + (2000) ));
}
}
| ajanfahri/javaApp | src/Graph/FahriCanvas.java | 2,401 | //int rotdir = mwe.getWheelRotation(); | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Graph;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.Arc2D;
import java.awt.geom.Line2D;
import javafx.collections.ObservableList;
/**
*
* @author fahri
*/
public class FahriCanvas extends java.awt.Canvas{
private Cizim cizim;
private Graphics2D lay1;
private int CX, CY, centerX, centerY;
private double Scale = 1;
private double ShiftX = 0, ShiftY = 0;
private double OldShiftX = 0, OldShiftY = 0;
private int MX, MY, mxb = 0, myb = 0, MicroBoxSize = 250, StartStopBoxSize = 250;
private int MouseShiftStX = 0, MouseShiftStY = 0, ZWindowStX = 0, ZWindowStY = 0;
public FahriCanvas() {
}
public FahriCanvas(Cizim ciz){
// lay1 = (Graphics2D) this.getGraphics();
setBackground(Color.LIGHT_GRAY);
this.cizim=ciz;
this.addComponentListener(new ComponentListener(){
@Override
public void componentResized(ComponentEvent ce) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
centerY = getHeight() / 2;
centerX = getWidth() / 2;
CX = (int) (centerX + ShiftX);
CY = (int) (centerY + ShiftY);
}
@Override
public void componentMoved(ComponentEvent ce) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void componentShown(ComponentEvent ce) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void componentHidden(ComponentEvent ce) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
this.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent me) {
Point pxy;
if (me.getClickCount() == 1)//&&!GrFunc.BevelEnable) SOL TIKLAMA
{
pxy = me.getPoint();
if(cizim.sekilSec(pxy,CX,CY,Scale))repaint();
}
}
@Override
public void mousePressed(MouseEvent me) {
MouseShiftStX = me.getX();
MouseShiftStY = me.getY();
if(cizim.getMoveEnable()){ OldShiftY=OldShiftX=0;}
}
@Override
public void mouseReleased(MouseEvent me) {
MouseShiftStX = 0;
MouseShiftStY = 0;
repaint();
cizim.setMoveEnable(false);
}
@Override
public void mouseEntered(MouseEvent me) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void mouseExited(MouseEvent me) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
this.addMouseMotionListener(new MouseMotionListener(){
@Override
public void mouseDragged(MouseEvent me) {
MouseShiftStX -= me.getX();
MouseShiftStY -= me.getY();
ShiftX -= MouseShiftStX;
ShiftY -= MouseShiftStY;
MouseShiftStX = me.getX();
MouseShiftStY = me.getY();
if(cizim.getMoveEnable()&&OldShiftX!=0){
cizim.MoveSelectedObject(OldShiftX-ShiftX,OldShiftY-ShiftY);
}
else{
CX = (int) (centerX + ShiftX);
CY = (int) (centerY + ShiftY);
}
OldShiftX=ShiftX;OldShiftY=ShiftY;
repaint();
}
@Override
public void mouseMoved(MouseEvent me) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
this.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent mwe) {
//int rotdir<SUF>
Scale += .01 * mwe.getWheelRotation() * mwe.getScrollAmount();
if (Scale <= 0) {
Scale = 0.001;
}
repaint();
}
});
}
public void setCizim(Cizim ciz){
this.cizim = ciz;
}
public void paint(Graphics g) {
this.ciz();
}
public void ciz() {
lay1 = (Graphics2D) this.getGraphics();
drawPlane();
Line ln;
Circle ar;
Rectangle rect;
ObservableList<Object> Shapes = cizim.getShapes();
for(int i=0;i<Shapes.size();i++){
if(Shapes.get(i) instanceof Line)
{
ln = (Line) Shapes.get(i);
lineciz(ln);
}
else if(Shapes.get(i) instanceof Circle)
{
ar = (Circle) Shapes.get(i);
arcciz(ar);
}
else if(Shapes.get(i) instanceof Rectangle)
{
rect = (Rectangle) Shapes.get(i);
for(int j=0;j<rect.Lines.size();j++)
lineciz( (Line) rect.Lines.get(j));
}
}
}
private void lineciz(Line ln) {
if(ln.isSelected())lay1.setColor(Color.yellow);else lay1.setColor(Color.black);
lay1.draw(new Line2D.Double(CX+(ln.xn1 * Scale), CY - (ln.yn1 * Scale),CX + (ln.xn2 * Scale), CY - (ln.yn2 * Scale)));
}
private void arcciz(Circle ar) {
if(ar.isSelected())lay1.setColor(Color.yellow);else lay1.setColor(Color.black);
lay1.drawArc(CX + (int)((ar.xc - ar.radius) * Scale) , CY - (int)((ar.yc + ar.radius) * Scale) , (int)(ar.radius * Scale)*2, (int)(ar.radius * Scale)*2, 0,360);
//lay1.drawArc(CX - (int)(( ar.radius/2 ) * Scale) , CY - (int)((ar.radius/2) * Scale) , (int)(ar.radius * Scale), (int)(ar.radius * Scale), 0,360);
//lay1.drawArc(CX + 0 , CY - 0 , (int)(50 * Scale), (int)(50 * Scale), 0,90);
//lay1.draw(new Arc2D.Double(CX-25, CY-25, 50 , 50 , 45,135, Arc2D.OPEN));
}
private void drawPlane(){
lay1.draw(new Line2D.Double(CX+(-2000), CY ,CX + (2000), CY ));
lay1.draw(new Line2D.Double(CX, CY+(-2000) ,CX , CY + (2000) ));
}
}
| False | 1,764 | 12 | 1,942 | 13 | 2,113 | 12 | 1,942 | 13 | 2,329 | 15 | false | false | false | false | false | true |
1,821 | 77304_55 | package ru.ifmo.diplom.kirilchuk.jawelet.core.dwt.transforms.legall.impl;
import ru.ifmo.diplom.kirilchuk.jawelet.core.dwt.filters.Filter;
import ru.ifmo.diplom.kirilchuk.jawelet.core.dwt.filters.legall.impl.LeGallFiltersFactory;
import ru.ifmo.diplom.kirilchuk.jawelet.core.dwt.transforms.DWTransform1D;
import ru.ifmo.diplom.kirilchuk.jawelet.util.Sampler;
import ru.ifmo.diplom.kirilchuk.jawelet.util.Windower;
import ru.ifmo.diplom.kirilchuk.jawelet.util.extensioner.Extensioner;
import ru.ifmo.diplom.kirilchuk.jawelet.util.extensioner.actions.AddLastToEnd;
import ru.ifmo.diplom.kirilchuk.jawelet.util.extensioner.actions.CopyElementToBegin;
import ru.ifmo.diplom.kirilchuk.jawelet.util.extensioner.actions.MirrorExtension;
import ru.ifmo.diplom.kirilchuk.util.Assert;
import ru.ifmo.diplom.kirilchuk.util.MathUtils;
/**
* Class that represents DiscreteWaveletTransform on Le Gall filter bank basis.
*
* @author Kirilchuk V.E.
* @deprecated use lifting transform cause it ALWAYS give perfect reconstruction!
*/
public class LeGallWaveletTransform extends DWTransform1D {
private final Sampler sampler = new Sampler();
private final Windower windower = new Windower();
public LeGallWaveletTransform() {
super(new LeGallFiltersFactory());
}
@Override
public void decomposeInplace(double[] data, int toLevel) {
Assert.checkNotNull(data, "Data vector can`t be null.");
Assert.argCondition(toLevel>=1, "Level must be >= 1");
Assert.valueIs2Power(data.length, "Data must have at least 2^level elements."); //TODO can`t decompose to max level cause need at least 3 elements for extension
int n = data.length;
for (int step = 0; step < toLevel; ++step) {
decomposeInplace1Lvl(data, n);
n /= 2;
}
}
@Override
public void reconstructInplace(double[] data, int approxLength) {
Assert.checkNotNull(data, "Data vector can`t be null.");
Filter lowReconstructionFilter = filtersFactory.getLowReconstructionFilter();
Filter highReconstructionFilter = filtersFactory.getHighReconstructionFilter();
// while(approxLength <= data.length/2) {
double[] approximation = new double[approxLength];
System.arraycopy(data, 0, approximation, 0, approxLength);
double[] extendedApproximation = new Extensioner(approximation)
.schedule(new CopyElementToBegin(0))
.schedule(new AddLastToEnd())
.execute();
extendedApproximation = sampler.upsample(extendedApproximation);
extendedApproximation = MathUtils.convolve(extendedApproximation, lowReconstructionFilter.getCoeff());
extendedApproximation = windower.window(extendedApproximation, 2, approximation.length * 2 + 2);
double[] details = new double[approxLength]; //must have same length with approximation
System.arraycopy(data, approxLength, details, 0, approxLength);
double[] extendedDetails = new Extensioner(details)
.schedule(new CopyElementToBegin(1))
.schedule(new AddLastToEnd())
.execute();
extendedDetails = sampler.upsample(extendedDetails);
extendedDetails = MathUtils.convolve(extendedDetails, highReconstructionFilter.getCoeff());
extendedDetails = windower.window(extendedDetails, 4, details.length * 2 + 4);
for (int index = 0; index < approxLength * 2; index++) {
data[index] = extendedApproximation[index] + extendedDetails[index];
}
// approxLength *= 2; // upsampled Low(level) + upsampled High(level) = Low(level-1)
// }
}
/**
* +1 level of decomposition.
* <pre> For example:
* We have vector 1,1,1,1,2,2,2,2 where 1 are approximation and 2 are details.
* To decompose one more time we need call
* decomposeInplace1Lvl([1,1,1,1,2,2,2,2], 4);
* 4 - index where details start and approximations ended.
* </pre>
*
* @param data vector with approximation and details.
* @param endIndex index where details start and approximations ended.
*/
private void decomposeInplace1Lvl(double[] data, int endIndex) {
Filter lowDecompositionFilter = filtersFactory.getLowDecompositionFilter();
Filter highDecompositionFilter = filtersFactory.getHighDecompositionFilter();
double[] approximation = new double[endIndex]; //working only with approximation coefficients
System.arraycopy(data, 0, approximation, 0, endIndex);
double[] temp = new Extensioner(approximation)
.schedule(new MirrorExtension(1))
.execute();
//TODO ugly but need one more element...
double[] extended = new double[temp.length + 1];
System.arraycopy(temp, 0, extended, 0, temp.length);
extended[extended.length - 1] = approximation[approximation.length - 3];
/* Here in "extended" we have extended data to reduce boundary effect */
temp = MathUtils.convolve(extended, lowDecompositionFilter.getCoeff());
temp = sampler.downsample(temp);
temp = windower.window(temp, 2, endIndex / 2 + 2);
double[] temp2 = MathUtils.convolve(extended, highDecompositionFilter.getCoeff());
temp2 = sampler.downsample(temp2);
temp2 = windower.window(temp2, 1, endIndex / 2 + 1);
System.arraycopy(temp, 0, data, 0, temp.length);
System.arraycopy(temp2, 0, data, temp.length, temp2.length);
}
// @Override
// public DecompositionResult decompose(double[] data) {//same as in DWT instead of length restriction.
// Assert.argNotNull(data);//TODO after finding how to do this with lenght = 2.. remove this method.
// Assert.argCondition(data.length >= 4, "Data length must be >= 4.");
//
// //finding closest 2nd power value
// int value = MathUtils.getClosest2PowerValue(data.length);
// int level = MathUtils.getExact2Power(value);
//
// //extending if need
// if(data.length - value < 0) {
// data = new Extensioner(data)
// .schedule(new ZeroPaddingTo2Power(level))
// .execute();
// }
//
// return decompose(data, level);
// }
//
// @Override
// public DecompositionResult decompose(double[] data, int level) {//same as in DWT instead of length restriction.
// Assert.argNotNull(data);//TODO after finding how to do this with lenght = 2.. remove this method.
// Assert.argCondition(level >= 1, "Level argument must be >= 1.");
// Assert.argCondition(data.length >= 4, "Data length must be >= 4.");
//
// DecompositionResult result = new DecompositionResult();
// double[] approximation;
// double[] details;
// for (int i = 1; i <= level; ++i) {
// approximation = decomposeLow(data);
// details = decomposeHigh(data);
// result.setApproximation(approximation);
// result.addDetails(details);
// result.setLevel(i);
// if(approximation.length == 1) {
// break; //we can`t decompose more...
// }
// data = approximation; //approximation is data for next decomposition
// }
//
// return result;
// }
//
// @Override
// public double[] reconstruct(DecompositionResult decomposition) {
// return reconstruct(decomposition, 0);
// }
//
// @Override
// public double[] reconstruct(DecompositionResult decomposition, int level) {
// if (level >= decomposition.getLevel()) {
// throw new IllegalArgumentException("Level must be less than decomposition level.");
// }
//
// double[] reconstructed = decomposition.getApproximation();
// for (int i = decomposition.getLevel(); i > level; --i) {
// reconstructed = reconstruct(reconstructed, decomposition.getDetailsList().get(i - 1));
// }
//
// return reconstructed;
// }
//
// //TODO this implementation is to understand how to do it in common case...
// //asymmetric filters delays cause very much trouble.
// private double[] decomposeLow(final double[] data) {//TODO assumes that filter length is 5!!!
// double[] result;
//
// Action zeroPaddingToEven = new ZeroPaddingToEven();
//
// Filter lowDecompositionFilter = filtersFactory.getLowDecompositionFilter();
//
// int extra = zeroPaddingToEven.getExtensionLength(data.length);
// double[] temp = new Extensioner(data)
// .schedule(zeroPaddingToEven)
// .schedule(new MirrorExtension(1))
// .execute();
//
// //TODO ugly but need one more element...
// result = new double[temp.length + 1];
// System.arraycopy(temp, 0, result, 0, temp.length);
// result[result.length - 1] = data[data.length - 3];
//
// result = MathUtils.convolve(result, lowDecompositionFilter.getCoeff());
// result = sampler.downsample(result);
//
// return windower.window(result, 2, (data.length + extra) / 2 + 2);
// }
//
// //TODO this implementation is to understand how to do it in common case...
// //asymmetric filters delays cause very much trouble.
// private double[] decomposeHigh(final double[] data) {//TODO assumes that filter length is 3!!!
// double[] result;
//
// Action zeroPaddingToEven = new ZeroPaddingToEven();
//
// Filter highDecompositionFilter = filtersFactory.getHighDecompositionFilter();
//
// int extra = zeroPaddingToEven.getExtensionLength(data.length);
// double[] temp = new Extensioner(data)
// .schedule(zeroPaddingToEven)
// .schedule(new MirrorExtension(1))
// .execute();
//
// //TODO ugly but need one more element...
// result = new double[temp.length + 1];
// System.arraycopy(temp, 0, result, 0, temp.length);
// result[result.length - 1] = data[data.length - 3];
//
// result = MathUtils.convolve(result, highDecompositionFilter.getCoeff());
// result = sampler.downsample(result);
//
// return windower.window(result, 1, (data.length + extra) / 2 + 1);
// }
//
// private double[] reconstruct(double[] approximation, double[] details) {
// if (approximation.length != details.length) {
// throw new IllegalArgumentException("Data vectors must have equal size.");
// }
//
// Filter lowReconstructionFilter = filtersFactory.getLowReconstructionFilter();
// Filter highReconstructionFilter = filtersFactory.getHighReconstructionFilter();
//
// double[] extendedApproximation;
// extendedApproximation = new Extensioner(approximation)
// .schedule(new CopyElementToBegin(0))
// .schedule(new AddLastToEnd())
// .execute();
//
// extendedApproximation = sampler.upsample(extendedApproximation);
// extendedApproximation = MathUtils.convolve(extendedApproximation, lowReconstructionFilter.getCoeff());
// extendedApproximation = windower.window(extendedApproximation, 2, approximation.length * 2 + 2);
//
//
// double[] extendedDetails;
// extendedDetails = new Extensioner(details)
// .schedule(new CopyElementToBegin(1))
// .schedule(new AddLastToEnd())
// .execute();
//
// extendedDetails = sampler.upsample(extendedDetails);
// extendedDetails = MathUtils.convolve(extendedDetails, highReconstructionFilter.getCoeff());
// extendedDetails = windower.window(extendedDetails, 4, details.length * 2 + 4);
//
// double[] result = new double[extendedApproximation.length];
// for (int i = 0; i < result.length; i++) {
// result[i] = extendedApproximation[i] + extendedDetails[i];
// }
//
// return result;
// }
}
| VadimKirilchuk/jawelet | src/main/java/ru/ifmo/diplom/kirilchuk/jawelet/core/dwt/transforms/legall/impl/LeGallWaveletTransform.java | 3,539 | // Action zeroPaddingToEven = new ZeroPaddingToEven(); | line_comment | nl | package ru.ifmo.diplom.kirilchuk.jawelet.core.dwt.transforms.legall.impl;
import ru.ifmo.diplom.kirilchuk.jawelet.core.dwt.filters.Filter;
import ru.ifmo.diplom.kirilchuk.jawelet.core.dwt.filters.legall.impl.LeGallFiltersFactory;
import ru.ifmo.diplom.kirilchuk.jawelet.core.dwt.transforms.DWTransform1D;
import ru.ifmo.diplom.kirilchuk.jawelet.util.Sampler;
import ru.ifmo.diplom.kirilchuk.jawelet.util.Windower;
import ru.ifmo.diplom.kirilchuk.jawelet.util.extensioner.Extensioner;
import ru.ifmo.diplom.kirilchuk.jawelet.util.extensioner.actions.AddLastToEnd;
import ru.ifmo.diplom.kirilchuk.jawelet.util.extensioner.actions.CopyElementToBegin;
import ru.ifmo.diplom.kirilchuk.jawelet.util.extensioner.actions.MirrorExtension;
import ru.ifmo.diplom.kirilchuk.util.Assert;
import ru.ifmo.diplom.kirilchuk.util.MathUtils;
/**
* Class that represents DiscreteWaveletTransform on Le Gall filter bank basis.
*
* @author Kirilchuk V.E.
* @deprecated use lifting transform cause it ALWAYS give perfect reconstruction!
*/
public class LeGallWaveletTransform extends DWTransform1D {
private final Sampler sampler = new Sampler();
private final Windower windower = new Windower();
public LeGallWaveletTransform() {
super(new LeGallFiltersFactory());
}
@Override
public void decomposeInplace(double[] data, int toLevel) {
Assert.checkNotNull(data, "Data vector can`t be null.");
Assert.argCondition(toLevel>=1, "Level must be >= 1");
Assert.valueIs2Power(data.length, "Data must have at least 2^level elements."); //TODO can`t decompose to max level cause need at least 3 elements for extension
int n = data.length;
for (int step = 0; step < toLevel; ++step) {
decomposeInplace1Lvl(data, n);
n /= 2;
}
}
@Override
public void reconstructInplace(double[] data, int approxLength) {
Assert.checkNotNull(data, "Data vector can`t be null.");
Filter lowReconstructionFilter = filtersFactory.getLowReconstructionFilter();
Filter highReconstructionFilter = filtersFactory.getHighReconstructionFilter();
// while(approxLength <= data.length/2) {
double[] approximation = new double[approxLength];
System.arraycopy(data, 0, approximation, 0, approxLength);
double[] extendedApproximation = new Extensioner(approximation)
.schedule(new CopyElementToBegin(0))
.schedule(new AddLastToEnd())
.execute();
extendedApproximation = sampler.upsample(extendedApproximation);
extendedApproximation = MathUtils.convolve(extendedApproximation, lowReconstructionFilter.getCoeff());
extendedApproximation = windower.window(extendedApproximation, 2, approximation.length * 2 + 2);
double[] details = new double[approxLength]; //must have same length with approximation
System.arraycopy(data, approxLength, details, 0, approxLength);
double[] extendedDetails = new Extensioner(details)
.schedule(new CopyElementToBegin(1))
.schedule(new AddLastToEnd())
.execute();
extendedDetails = sampler.upsample(extendedDetails);
extendedDetails = MathUtils.convolve(extendedDetails, highReconstructionFilter.getCoeff());
extendedDetails = windower.window(extendedDetails, 4, details.length * 2 + 4);
for (int index = 0; index < approxLength * 2; index++) {
data[index] = extendedApproximation[index] + extendedDetails[index];
}
// approxLength *= 2; // upsampled Low(level) + upsampled High(level) = Low(level-1)
// }
}
/**
* +1 level of decomposition.
* <pre> For example:
* We have vector 1,1,1,1,2,2,2,2 where 1 are approximation and 2 are details.
* To decompose one more time we need call
* decomposeInplace1Lvl([1,1,1,1,2,2,2,2], 4);
* 4 - index where details start and approximations ended.
* </pre>
*
* @param data vector with approximation and details.
* @param endIndex index where details start and approximations ended.
*/
private void decomposeInplace1Lvl(double[] data, int endIndex) {
Filter lowDecompositionFilter = filtersFactory.getLowDecompositionFilter();
Filter highDecompositionFilter = filtersFactory.getHighDecompositionFilter();
double[] approximation = new double[endIndex]; //working only with approximation coefficients
System.arraycopy(data, 0, approximation, 0, endIndex);
double[] temp = new Extensioner(approximation)
.schedule(new MirrorExtension(1))
.execute();
//TODO ugly but need one more element...
double[] extended = new double[temp.length + 1];
System.arraycopy(temp, 0, extended, 0, temp.length);
extended[extended.length - 1] = approximation[approximation.length - 3];
/* Here in "extended" we have extended data to reduce boundary effect */
temp = MathUtils.convolve(extended, lowDecompositionFilter.getCoeff());
temp = sampler.downsample(temp);
temp = windower.window(temp, 2, endIndex / 2 + 2);
double[] temp2 = MathUtils.convolve(extended, highDecompositionFilter.getCoeff());
temp2 = sampler.downsample(temp2);
temp2 = windower.window(temp2, 1, endIndex / 2 + 1);
System.arraycopy(temp, 0, data, 0, temp.length);
System.arraycopy(temp2, 0, data, temp.length, temp2.length);
}
// @Override
// public DecompositionResult decompose(double[] data) {//same as in DWT instead of length restriction.
// Assert.argNotNull(data);//TODO after finding how to do this with lenght = 2.. remove this method.
// Assert.argCondition(data.length >= 4, "Data length must be >= 4.");
//
// //finding closest 2nd power value
// int value = MathUtils.getClosest2PowerValue(data.length);
// int level = MathUtils.getExact2Power(value);
//
// //extending if need
// if(data.length - value < 0) {
// data = new Extensioner(data)
// .schedule(new ZeroPaddingTo2Power(level))
// .execute();
// }
//
// return decompose(data, level);
// }
//
// @Override
// public DecompositionResult decompose(double[] data, int level) {//same as in DWT instead of length restriction.
// Assert.argNotNull(data);//TODO after finding how to do this with lenght = 2.. remove this method.
// Assert.argCondition(level >= 1, "Level argument must be >= 1.");
// Assert.argCondition(data.length >= 4, "Data length must be >= 4.");
//
// DecompositionResult result = new DecompositionResult();
// double[] approximation;
// double[] details;
// for (int i = 1; i <= level; ++i) {
// approximation = decomposeLow(data);
// details = decomposeHigh(data);
// result.setApproximation(approximation);
// result.addDetails(details);
// result.setLevel(i);
// if(approximation.length == 1) {
// break; //we can`t decompose more...
// }
// data = approximation; //approximation is data for next decomposition
// }
//
// return result;
// }
//
// @Override
// public double[] reconstruct(DecompositionResult decomposition) {
// return reconstruct(decomposition, 0);
// }
//
// @Override
// public double[] reconstruct(DecompositionResult decomposition, int level) {
// if (level >= decomposition.getLevel()) {
// throw new IllegalArgumentException("Level must be less than decomposition level.");
// }
//
// double[] reconstructed = decomposition.getApproximation();
// for (int i = decomposition.getLevel(); i > level; --i) {
// reconstructed = reconstruct(reconstructed, decomposition.getDetailsList().get(i - 1));
// }
//
// return reconstructed;
// }
//
// //TODO this implementation is to understand how to do it in common case...
// //asymmetric filters delays cause very much trouble.
// private double[] decomposeLow(final double[] data) {//TODO assumes that filter length is 5!!!
// double[] result;
//
// Action zeroPaddingToEven = new ZeroPaddingToEven();
//
// Filter lowDecompositionFilter = filtersFactory.getLowDecompositionFilter();
//
// int extra = zeroPaddingToEven.getExtensionLength(data.length);
// double[] temp = new Extensioner(data)
// .schedule(zeroPaddingToEven)
// .schedule(new MirrorExtension(1))
// .execute();
//
// //TODO ugly but need one more element...
// result = new double[temp.length + 1];
// System.arraycopy(temp, 0, result, 0, temp.length);
// result[result.length - 1] = data[data.length - 3];
//
// result = MathUtils.convolve(result, lowDecompositionFilter.getCoeff());
// result = sampler.downsample(result);
//
// return windower.window(result, 2, (data.length + extra) / 2 + 2);
// }
//
// //TODO this implementation is to understand how to do it in common case...
// //asymmetric filters delays cause very much trouble.
// private double[] decomposeHigh(final double[] data) {//TODO assumes that filter length is 3!!!
// double[] result;
//
// Action zeroPaddingToEven<SUF>
//
// Filter highDecompositionFilter = filtersFactory.getHighDecompositionFilter();
//
// int extra = zeroPaddingToEven.getExtensionLength(data.length);
// double[] temp = new Extensioner(data)
// .schedule(zeroPaddingToEven)
// .schedule(new MirrorExtension(1))
// .execute();
//
// //TODO ugly but need one more element...
// result = new double[temp.length + 1];
// System.arraycopy(temp, 0, result, 0, temp.length);
// result[result.length - 1] = data[data.length - 3];
//
// result = MathUtils.convolve(result, highDecompositionFilter.getCoeff());
// result = sampler.downsample(result);
//
// return windower.window(result, 1, (data.length + extra) / 2 + 1);
// }
//
// private double[] reconstruct(double[] approximation, double[] details) {
// if (approximation.length != details.length) {
// throw new IllegalArgumentException("Data vectors must have equal size.");
// }
//
// Filter lowReconstructionFilter = filtersFactory.getLowReconstructionFilter();
// Filter highReconstructionFilter = filtersFactory.getHighReconstructionFilter();
//
// double[] extendedApproximation;
// extendedApproximation = new Extensioner(approximation)
// .schedule(new CopyElementToBegin(0))
// .schedule(new AddLastToEnd())
// .execute();
//
// extendedApproximation = sampler.upsample(extendedApproximation);
// extendedApproximation = MathUtils.convolve(extendedApproximation, lowReconstructionFilter.getCoeff());
// extendedApproximation = windower.window(extendedApproximation, 2, approximation.length * 2 + 2);
//
//
// double[] extendedDetails;
// extendedDetails = new Extensioner(details)
// .schedule(new CopyElementToBegin(1))
// .schedule(new AddLastToEnd())
// .execute();
//
// extendedDetails = sampler.upsample(extendedDetails);
// extendedDetails = MathUtils.convolve(extendedDetails, highReconstructionFilter.getCoeff());
// extendedDetails = windower.window(extendedDetails, 4, details.length * 2 + 4);
//
// double[] result = new double[extendedApproximation.length];
// for (int i = 0; i < result.length; i++) {
// result[i] = extendedApproximation[i] + extendedDetails[i];
// }
//
// return result;
// }
}
| False | 2,777 | 14 | 3,197 | 14 | 3,169 | 14 | 3,197 | 14 | 3,552 | 18 | false | false | false | false | false | true |
228 | 28778_4 | import java.io.File;_x000D_
import java.io.FileNotFoundException;_x000D_
import java.util.ArrayList;_x000D_
import java.util.Scanner;_x000D_
import java.util.HashSet;_x000D_
_x000D_
/**_x000D_
* Een klasse om klanteninformatie te lezen uit een csv bestand_x000D_
* DE klantenfile bevat naaminfromatie, adresinformatie en contactinformatie_x000D_
* van 88 klanten verspreid over de wereld._x000D_
* <p>_x000D_
* Het bestand bevat volgende informatie_x000D_
* CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax_x000D_
* Informatie van 1 klant bevindt zich op 1 lijn en wordt gescheiden door ;_x000D_
*_x000D_
* @author Marc De Caluwé_x000D_
* @version 2019-12-01_x000D_
*/_x000D_
public class ContactReader {_x000D_
private String format;_x000D_
private ArrayList<ContactEntry> entries;_x000D_
_x000D_
public ContactReader() {_x000D_
this("contacts.csv");_x000D_
}_x000D_
_x000D_
public ContactReader(String filename) {_x000D_
// The format for the data._x000D_
format = "CustomerID;Namelient;NameContact;TitleContact;Addresd;City;Region;ZIP;Country;Phone;Fax";_x000D_
// Where to store the data._x000D_
entries = new ArrayList<>();_x000D_
_x000D_
// Attempt to read the complete set of data from file._x000D_
try {_x000D_
File pFile = new File("");_x000D_
File klantFile = new File(pFile.getAbsolutePath() + "/data/" + filename);_x000D_
Scanner klantfile = new Scanner(klantFile);_x000D_
// Lees het klantenbestand tot de laatste lijn_x000D_
while (klantfile.hasNextLine()) {_x000D_
String klantlijn = klantfile.nextLine();_x000D_
// Splits de klant en maak er een nieuw Klant-object van_x000D_
ContactEntry entry = new ContactEntry(klantlijn);_x000D_
entries.add(entry);_x000D_
}_x000D_
klantfile.close();_x000D_
} catch (FileNotFoundException e) {_x000D_
System.out.println("Er dook een probleem op: " + e.getMessage());_x000D_
}_x000D_
}_x000D_
_x000D_
public ArrayList<ContactEntry> getEntries() {_x000D_
return entries;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Print de data._x000D_
*/_x000D_
public void printData() {_x000D_
for (ContactEntry entry : entries) {_x000D_
System.out.println(entry);_x000D_
}_x000D_
}_x000D_
_x000D_
public HashSet<Contact> loadContacts() {_x000D_
HashSet<Contact> klanten = new HashSet<>();_x000D_
for(ContactEntry ke : getEntries()) {_x000D_
String[] data = ke.getData();_x000D_
Contact k = new Contact(data[ContactEntry.ID]);_x000D_
k.setName(data[ContactEntry.NAMECONTACT]);_x000D_
k.setTitle(data[ContactEntry.TITLECONTACT]);_x000D_
k.setCity(data[ContactEntry.CITY]);_x000D_
k.setRegion(data[ContactEntry.REGION]);_x000D_
k.setCountry(data[ContactEntry.COUNTRY]);_x000D_
klanten.add(k);_x000D_
}_x000D_
return klanten;_x000D_
}_x000D_
_x000D_
public static void main(String[] args) {_x000D_
try {_x000D_
ContactReader kr = new ContactReader();_x000D_
kr.printData();_x000D_
System.out.println("---------------------------------------------------------------");_x000D_
for (ContactEntry ke : kr.getEntries()) {_x000D_
String[] data = ke.getData();_x000D_
// we drukken het ID en bijhorende naam van elke klant_x000D_
System.out.println("ID=" + data[ContactEntry.ID] + ", name=" + data[ContactEntry.NAMECLIENT]);_x000D_
}_x000D_
} catch (Exception e) {_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
}_x000D_
| Boutoku/OOP-test-repository | oefeningen/src/ContactReader.java | 956 | // Lees het klantenbestand tot de laatste lijn_x000D_ | line_comment | nl | import java.io.File;_x000D_
import java.io.FileNotFoundException;_x000D_
import java.util.ArrayList;_x000D_
import java.util.Scanner;_x000D_
import java.util.HashSet;_x000D_
_x000D_
/**_x000D_
* Een klasse om klanteninformatie te lezen uit een csv bestand_x000D_
* DE klantenfile bevat naaminfromatie, adresinformatie en contactinformatie_x000D_
* van 88 klanten verspreid over de wereld._x000D_
* <p>_x000D_
* Het bestand bevat volgende informatie_x000D_
* CustomerID CompanyName ContactName ContactTitle Address City Region PostalCode Country Phone Fax_x000D_
* Informatie van 1 klant bevindt zich op 1 lijn en wordt gescheiden door ;_x000D_
*_x000D_
* @author Marc De Caluwé_x000D_
* @version 2019-12-01_x000D_
*/_x000D_
public class ContactReader {_x000D_
private String format;_x000D_
private ArrayList<ContactEntry> entries;_x000D_
_x000D_
public ContactReader() {_x000D_
this("contacts.csv");_x000D_
}_x000D_
_x000D_
public ContactReader(String filename) {_x000D_
// The format for the data._x000D_
format = "CustomerID;Namelient;NameContact;TitleContact;Addresd;City;Region;ZIP;Country;Phone;Fax";_x000D_
// Where to store the data._x000D_
entries = new ArrayList<>();_x000D_
_x000D_
// Attempt to read the complete set of data from file._x000D_
try {_x000D_
File pFile = new File("");_x000D_
File klantFile = new File(pFile.getAbsolutePath() + "/data/" + filename);_x000D_
Scanner klantfile = new Scanner(klantFile);_x000D_
// Lees het<SUF>
while (klantfile.hasNextLine()) {_x000D_
String klantlijn = klantfile.nextLine();_x000D_
// Splits de klant en maak er een nieuw Klant-object van_x000D_
ContactEntry entry = new ContactEntry(klantlijn);_x000D_
entries.add(entry);_x000D_
}_x000D_
klantfile.close();_x000D_
} catch (FileNotFoundException e) {_x000D_
System.out.println("Er dook een probleem op: " + e.getMessage());_x000D_
}_x000D_
}_x000D_
_x000D_
public ArrayList<ContactEntry> getEntries() {_x000D_
return entries;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Print de data._x000D_
*/_x000D_
public void printData() {_x000D_
for (ContactEntry entry : entries) {_x000D_
System.out.println(entry);_x000D_
}_x000D_
}_x000D_
_x000D_
public HashSet<Contact> loadContacts() {_x000D_
HashSet<Contact> klanten = new HashSet<>();_x000D_
for(ContactEntry ke : getEntries()) {_x000D_
String[] data = ke.getData();_x000D_
Contact k = new Contact(data[ContactEntry.ID]);_x000D_
k.setName(data[ContactEntry.NAMECONTACT]);_x000D_
k.setTitle(data[ContactEntry.TITLECONTACT]);_x000D_
k.setCity(data[ContactEntry.CITY]);_x000D_
k.setRegion(data[ContactEntry.REGION]);_x000D_
k.setCountry(data[ContactEntry.COUNTRY]);_x000D_
klanten.add(k);_x000D_
}_x000D_
return klanten;_x000D_
}_x000D_
_x000D_
public static void main(String[] args) {_x000D_
try {_x000D_
ContactReader kr = new ContactReader();_x000D_
kr.printData();_x000D_
System.out.println("---------------------------------------------------------------");_x000D_
for (ContactEntry ke : kr.getEntries()) {_x000D_
String[] data = ke.getData();_x000D_
// we drukken het ID en bijhorende naam van elke klant_x000D_
System.out.println("ID=" + data[ContactEntry.ID] + ", name=" + data[ContactEntry.NAMECLIENT]);_x000D_
}_x000D_
} catch (Exception e) {_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
}_x000D_
| True | 1,324 | 20 | 1,427 | 22 | 1,444 | 16 | 1,427 | 22 | 1,555 | 21 | false | false | false | false | false | true |
1,028 | 22062_0 | public class PartTimeWerknemer extends Werknemer {
public int urenGewerkt;
public PartTimeWerknemer( String voornaam, String achternaam, int nr, float sal, int urengw)
{
super(voornaam, achternaam, nr, sal);
this.urenGewerkt=urengw;
}
public float getWeekLoon() {
return this.salaris * (float)urenGewerkt;
}
public void salarisVerhogen(int percentage) {
if (percentage>5) { System.out.println("Fout: parttimewerknemer kunnen niet meer dan 5% opslag krijgen"); }
else
super.salarisVerhogen(percentage); // roep methode van Werknemer aan
}
} | MTA-Digital-Broadcast-2/I-Willems-Andy-Hendrickx-Matthias-Project-MHP | Willems-Andy/blz31/Oef7/PartTimeWerknemer.java | 209 | // roep methode van Werknemer aan | line_comment | nl | public class PartTimeWerknemer extends Werknemer {
public int urenGewerkt;
public PartTimeWerknemer( String voornaam, String achternaam, int nr, float sal, int urengw)
{
super(voornaam, achternaam, nr, sal);
this.urenGewerkt=urengw;
}
public float getWeekLoon() {
return this.salaris * (float)urenGewerkt;
}
public void salarisVerhogen(int percentage) {
if (percentage>5) { System.out.println("Fout: parttimewerknemer kunnen niet meer dan 5% opslag krijgen"); }
else
super.salarisVerhogen(percentage); // roep methode<SUF>
}
} | True | 185 | 10 | 216 | 12 | 188 | 8 | 216 | 12 | 224 | 11 | false | false | false | false | false | true |
3,473 | 130037_15 | /**
* SPDX-FileCopyrightText: (c) 2000 Liferay, Inc. https://liferay.com
* SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06
*/
/**
* Copyright (c) 2000, Columbia University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.liferay.portal.kernel.cal;
import com.liferay.petra.string.StringBundler;
import java.io.Serializable;
/**
* @author Jonathan Lennox
*/
public class Duration implements Cloneable, Serializable {
/**
* Constructor Duration
*/
public Duration() {
// Zero-initialization of all fields happens by default
}
/**
* Constructor Duration
*/
public Duration(int weeks) {
_weeks = weeks;
}
/**
* Constructor Duration
*/
public Duration(int hours, int minutes, int seconds) {
this(0, hours, minutes, seconds);
}
/**
* Constructor Duration
*/
public Duration(int days, int hours, int minutes, int seconds) {
_days = days;
_hours = hours;
_minutes = minutes;
_seconds = seconds;
}
/**
* Method clear
*/
public void clear() {
_weeks = 0;
_days = 0;
_hours = 0;
_minutes = 0;
_seconds = 0;
}
/**
* Method clone
*
* @return Object
*/
@Override
public Object clone() {
try {
Duration other = (Duration)super.clone();
other._weeks = _weeks;
other._days = _days;
other._hours = _hours;
other._minutes = _minutes;
other._seconds = _seconds;
return other;
}
catch (CloneNotSupportedException cloneNotSupportedException) {
throw new InternalError();
}
}
/**
* Method getDays
*
* @return int
*/
public int getDays() {
return _days;
}
/**
* Method getHours
*
* @return int
*/
public int getHours() {
return _hours;
}
/**
* Method getInterval
*
* @return long
*/
public long getInterval() {
return (_seconds * _MILLIS_PER_SECOND) +
(_minutes * _MILLIS_PER_MINUTE) + (_hours * _MILLIS_PER_HOUR) +
(_days * _MILLIS_PER_DAY) + (_weeks * _MILLIS_PER_WEEK);
}
/**
* Method getMinutes
*
* @return int
*/
public int getMinutes() {
return _minutes;
}
/**
* Method getSeconds
*
* @return int
*/
public int getSeconds() {
return _seconds;
}
/**
* Method getWeeks
*
* @return int
*/
public int getWeeks() {
return _weeks;
}
/**
* Method setDays
*/
public void setDays(int d) {
if (d < 0) {
throw new IllegalArgumentException("Day value out of range");
}
checkNonWeeksOkay(d);
_days = d;
normalize();
}
/**
* Method setHours
*/
public void setHours(int h) {
if (h < 0) {
throw new IllegalArgumentException("Hour value out of range");
}
checkNonWeeksOkay(h);
_hours = h;
normalize();
}
/**
* Method setInterval
*/
public void setInterval(long millis) {
if (millis < 0) {
throw new IllegalArgumentException("Negative-length interval");
}
clear();
_days = (int)(millis / _MILLIS_PER_DAY);
_seconds = (int)((millis % _MILLIS_PER_DAY) / _MILLIS_PER_SECOND);
normalize();
}
/**
* Method setMinutes
*/
public void setMinutes(int m) {
if (m < 0) {
throw new IllegalArgumentException("Minute value out of range");
}
checkNonWeeksOkay(m);
_minutes = m;
normalize();
}
/**
* Method setSeconds
*/
public void setSeconds(int s) {
if (s < 0) {
throw new IllegalArgumentException("Second value out of range");
}
checkNonWeeksOkay(s);
_seconds = s;
normalize();
}
/**
* Method setWeeks
*/
public void setWeeks(int w) {
if (w < 0) {
throw new IllegalArgumentException("Week value out of range");
}
checkWeeksOkay(w);
_weeks = w;
}
/**
* Method toString
*
* @return String
*/
@Override
public String toString() {
StringBundler sb = new StringBundler(12);
Class<?> clazz = getClass();
sb.append(clazz.getName());
sb.append("[weeks=");
sb.append(_weeks);
sb.append(",days=");
sb.append(_days);
sb.append(",hours=");
sb.append(_hours);
sb.append(",minutes=");
sb.append(_minutes);
sb.append(",seconds=");
sb.append(_seconds);
sb.append("]");
return sb.toString();
}
/**
* Method checkNonWeeksOkay
*/
protected void checkNonWeeksOkay(int f) {
if ((f != 0) && (_weeks != 0)) {
throw new IllegalStateException(
"Weeks and non-weeks are incompatible");
}
}
/**
* Method checkWeeksOkay
*/
protected void checkWeeksOkay(int f) {
if ((f != 0) &&
((_days != 0) || (_hours != 0) || (_minutes != 0) ||
(_seconds != 0))) {
throw new IllegalStateException(
"Weeks and non-weeks are incompatible");
}
}
/**
* Method normalize
*/
protected void normalize() {
_minutes += _seconds / _SECONDS_PER_MINUTE;
_seconds %= _SECONDS_PER_MINUTE;
_hours += _minutes / _MINUTES_PER_HOUR;
_minutes %= _MINUTES_PER_HOUR;
_days += _hours / _HOURS_PER_DAY;
_hours %= _HOURS_PER_DAY;
}
/**
* Field DAYS_PER_WEEK
*/
private static final int _DAYS_PER_WEEK = 7;
/**
* Field HOURS_PER_DAY
*/
private static final int _HOURS_PER_DAY = 24;
/**
* Field MILLIS_PER_DAY
*/
private static final long _MILLIS_PER_DAY =
_HOURS_PER_DAY * Duration._MILLIS_PER_HOUR;
/**
* Field MILLIS_PER_HOUR
*/
private static final long _MILLIS_PER_HOUR =
Duration._MINUTES_PER_HOUR * Duration._MILLIS_PER_MINUTE;
/**
* Field MILLIS_PER_MINUTE
*/
private static final long _MILLIS_PER_MINUTE =
Duration._SECONDS_PER_MINUTE * Duration._MILLIS_PER_SECOND;
/**
* Field MILLIS_PER_SECOND
*/
private static final long _MILLIS_PER_SECOND = 1000;
/**
* Field MILLIS_PER_WEEK
*/
private static final long _MILLIS_PER_WEEK =
_DAYS_PER_WEEK * _MILLIS_PER_DAY;
/**
* Field MINUTES_PER_HOUR
*/
private static final int _MINUTES_PER_HOUR = 60;
/**
* Field SECONDS_PER_MINUTE
*/
private static final int _SECONDS_PER_MINUTE = 60;
/**
* Field days
*/
private int _days;
/**
* Field hours
*/
private int _hours;
/**
* Field minutes
*/
private int _minutes;
/**
* Field seconds
*/
private int _seconds;
/**
* Field weeks
*/
private int _weeks;
} | liferay/liferay-portal | portal-kernel/src/com/liferay/portal/kernel/cal/Duration.java | 2,845 | /**
* Method getWeeks
*
* @return int
*/ | block_comment | nl | /**
* SPDX-FileCopyrightText: (c) 2000 Liferay, Inc. https://liferay.com
* SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06
*/
/**
* Copyright (c) 2000, Columbia University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.liferay.portal.kernel.cal;
import com.liferay.petra.string.StringBundler;
import java.io.Serializable;
/**
* @author Jonathan Lennox
*/
public class Duration implements Cloneable, Serializable {
/**
* Constructor Duration
*/
public Duration() {
// Zero-initialization of all fields happens by default
}
/**
* Constructor Duration
*/
public Duration(int weeks) {
_weeks = weeks;
}
/**
* Constructor Duration
*/
public Duration(int hours, int minutes, int seconds) {
this(0, hours, minutes, seconds);
}
/**
* Constructor Duration
*/
public Duration(int days, int hours, int minutes, int seconds) {
_days = days;
_hours = hours;
_minutes = minutes;
_seconds = seconds;
}
/**
* Method clear
*/
public void clear() {
_weeks = 0;
_days = 0;
_hours = 0;
_minutes = 0;
_seconds = 0;
}
/**
* Method clone
*
* @return Object
*/
@Override
public Object clone() {
try {
Duration other = (Duration)super.clone();
other._weeks = _weeks;
other._days = _days;
other._hours = _hours;
other._minutes = _minutes;
other._seconds = _seconds;
return other;
}
catch (CloneNotSupportedException cloneNotSupportedException) {
throw new InternalError();
}
}
/**
* Method getDays
*
* @return int
*/
public int getDays() {
return _days;
}
/**
* Method getHours
*
* @return int
*/
public int getHours() {
return _hours;
}
/**
* Method getInterval
*
* @return long
*/
public long getInterval() {
return (_seconds * _MILLIS_PER_SECOND) +
(_minutes * _MILLIS_PER_MINUTE) + (_hours * _MILLIS_PER_HOUR) +
(_days * _MILLIS_PER_DAY) + (_weeks * _MILLIS_PER_WEEK);
}
/**
* Method getMinutes
*
* @return int
*/
public int getMinutes() {
return _minutes;
}
/**
* Method getSeconds
*
* @return int
*/
public int getSeconds() {
return _seconds;
}
/**
* Method getWeeks
<SUF>*/
public int getWeeks() {
return _weeks;
}
/**
* Method setDays
*/
public void setDays(int d) {
if (d < 0) {
throw new IllegalArgumentException("Day value out of range");
}
checkNonWeeksOkay(d);
_days = d;
normalize();
}
/**
* Method setHours
*/
public void setHours(int h) {
if (h < 0) {
throw new IllegalArgumentException("Hour value out of range");
}
checkNonWeeksOkay(h);
_hours = h;
normalize();
}
/**
* Method setInterval
*/
public void setInterval(long millis) {
if (millis < 0) {
throw new IllegalArgumentException("Negative-length interval");
}
clear();
_days = (int)(millis / _MILLIS_PER_DAY);
_seconds = (int)((millis % _MILLIS_PER_DAY) / _MILLIS_PER_SECOND);
normalize();
}
/**
* Method setMinutes
*/
public void setMinutes(int m) {
if (m < 0) {
throw new IllegalArgumentException("Minute value out of range");
}
checkNonWeeksOkay(m);
_minutes = m;
normalize();
}
/**
* Method setSeconds
*/
public void setSeconds(int s) {
if (s < 0) {
throw new IllegalArgumentException("Second value out of range");
}
checkNonWeeksOkay(s);
_seconds = s;
normalize();
}
/**
* Method setWeeks
*/
public void setWeeks(int w) {
if (w < 0) {
throw new IllegalArgumentException("Week value out of range");
}
checkWeeksOkay(w);
_weeks = w;
}
/**
* Method toString
*
* @return String
*/
@Override
public String toString() {
StringBundler sb = new StringBundler(12);
Class<?> clazz = getClass();
sb.append(clazz.getName());
sb.append("[weeks=");
sb.append(_weeks);
sb.append(",days=");
sb.append(_days);
sb.append(",hours=");
sb.append(_hours);
sb.append(",minutes=");
sb.append(_minutes);
sb.append(",seconds=");
sb.append(_seconds);
sb.append("]");
return sb.toString();
}
/**
* Method checkNonWeeksOkay
*/
protected void checkNonWeeksOkay(int f) {
if ((f != 0) && (_weeks != 0)) {
throw new IllegalStateException(
"Weeks and non-weeks are incompatible");
}
}
/**
* Method checkWeeksOkay
*/
protected void checkWeeksOkay(int f) {
if ((f != 0) &&
((_days != 0) || (_hours != 0) || (_minutes != 0) ||
(_seconds != 0))) {
throw new IllegalStateException(
"Weeks and non-weeks are incompatible");
}
}
/**
* Method normalize
*/
protected void normalize() {
_minutes += _seconds / _SECONDS_PER_MINUTE;
_seconds %= _SECONDS_PER_MINUTE;
_hours += _minutes / _MINUTES_PER_HOUR;
_minutes %= _MINUTES_PER_HOUR;
_days += _hours / _HOURS_PER_DAY;
_hours %= _HOURS_PER_DAY;
}
/**
* Field DAYS_PER_WEEK
*/
private static final int _DAYS_PER_WEEK = 7;
/**
* Field HOURS_PER_DAY
*/
private static final int _HOURS_PER_DAY = 24;
/**
* Field MILLIS_PER_DAY
*/
private static final long _MILLIS_PER_DAY =
_HOURS_PER_DAY * Duration._MILLIS_PER_HOUR;
/**
* Field MILLIS_PER_HOUR
*/
private static final long _MILLIS_PER_HOUR =
Duration._MINUTES_PER_HOUR * Duration._MILLIS_PER_MINUTE;
/**
* Field MILLIS_PER_MINUTE
*/
private static final long _MILLIS_PER_MINUTE =
Duration._SECONDS_PER_MINUTE * Duration._MILLIS_PER_SECOND;
/**
* Field MILLIS_PER_SECOND
*/
private static final long _MILLIS_PER_SECOND = 1000;
/**
* Field MILLIS_PER_WEEK
*/
private static final long _MILLIS_PER_WEEK =
_DAYS_PER_WEEK * _MILLIS_PER_DAY;
/**
* Field MINUTES_PER_HOUR
*/
private static final int _MINUTES_PER_HOUR = 60;
/**
* Field SECONDS_PER_MINUTE
*/
private static final int _SECONDS_PER_MINUTE = 60;
/**
* Field days
*/
private int _days;
/**
* Field hours
*/
private int _hours;
/**
* Field minutes
*/
private int _minutes;
/**
* Field seconds
*/
private int _seconds;
/**
* Field weeks
*/
private int _weeks;
} | False | 2,077 | 18 | 2,426 | 16 | 2,441 | 19 | 2,426 | 16 | 3,098 | 20 | false | false | false | false | false | true |
498 | 84274_6 | package flame.effects;
import arc.*;
import arc.func.*;
import arc.graphics.*;
import arc.graphics.g2d.*;
import arc.math.*;
import arc.math.geom.*;
import arc.struct.*;
import arc.util.*;
import arc.util.pooling.*;
import arc.util.pooling.Pool.*;
import flame.Utils.*;
import flame.entities.*;
import mindustry.entities.*;
import mindustry.gen.*;
import mindustry.graphics.*;
/**
* @author EyeOfDarkness
*/
public class Disintegration implements Poolable{
float[] xs, ys;
int width, height;
float drawWidth, drawHeight;
TextureRegion region = new TextureRegion();
int uses = 0;
public float z = Layer.flyingUnit;
public Color drawnColor = Color.white.cpy(), scorchColor = Pal.rubble.cpy();
static Pool<Disintegration> pool = new BasicPool<>(Disintegration::new);
static int maxDimension = 64;
static Point2 tmpPoint = new Point2();
static FloatSeq fseq = new FloatSeq();
static int[] arr = {
0, 0,
1, 0,
1, 1,
0, 1
};
public Disintegration(){}
public static Disintegration generate(TextureRegion region, float x, float y, float rotation, float width, float height, Cons<DisintegrationEntity> cons){
int modW = (int)((5f / 320f) * Math.abs(width / Draw.scl));
int modH = (int)((5f / 320f) * Math.abs(height / Draw.scl));
return generate(region, x, y, rotation, width, height, modW, modH, cons);
}
public static Disintegration generate(TextureRegion region, float x, float y, float rotation, float width, float height, int iwidth, int iheight, Cons<DisintegrationEntity> cons){
//int modW = (int)((20f / 320f) * Math.abs(width / Draw.scl));
//int modH = (int)((20f / 320f) * Math.abs(height / Draw.scl));
float cos = Mathf.cosDeg(rotation);
float sin = Mathf.sinDeg(rotation);
Disintegration dis = pool.obtain();
dis.set(iwidth, iheight);
//dis.region = region;
dis.region.set(region);
dis.drawWidth = width;
dis.drawHeight = height;
dis.uses = 0;
int w = dis.width, h = dis.height;
for(int ix = 0; ix < w - 1; ix++){
for(int iy = 0; iy < h - 1; iy++){
float ox = 0f, oy = 0f;
for(int i = 0; i < 8; i += 2){
int bx = ix + arr[i];
int by = iy + arr[i + 1];
int pos = dis.toPos(bx, by);
ox += dis.xs[pos];
oy += dis.ys[pos];
}
ox /= 4f;
oy /= 4f;
float rx = (ox - 0.5f) * width;
float ry = (oy - 0.5f) * height;
float wx = (rx * cos - ry * sin) + x;
float wy = (rx * sin + ry * cos) + y;
DisintegrationEntity de = DisintegrationEntity.create();
de.source = dis;
de.x = wx;
de.y = wy;
de.rotation = rotation;
de.idx = dis.toPos(ix, iy);
de.offsetX = ox;
de.offsetY = oy;
de.lifetime = 6f * 60f;
cons.get(de);
de.add();
dis.uses++;
}
}
return dis;
}
public void set(int width, int height){
width = Mathf.clamp(width, 3, maxDimension);
height = Mathf.clamp(height, 3, maxDimension);
int size = width * height;
this.width = width;
this.height = height;
if(xs == null || xs.length != size) xs = new float[size];
if(ys == null || ys.length != size) ys = new float[size];
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
float fx = x / (width - 1f);
float fy = y / (height - 1f);
int idx = x + y * width;
if(x > 0 && x < (width - 1)){
fx += Mathf.range(0.1f, 0.4f) / (width - 1f);
}
if(y > 0 && y < (height - 1)){
fy += Mathf.range(0.1f, 0.4f) / (height - 1f);
}
xs[idx] = fx;
ys[idx] = fy;
}
}
}
Point2 getPos(int pos){
tmpPoint.x = pos % width;
tmpPoint.y = pos / width;
return tmpPoint;
}
int toPos(int x, int y){
return x + y * width;
}
@Override
public void reset(){
//xs = ys = null;
width = height = 0;
drawWidth = drawHeight = 0f;
drawnColor.set(Color.white);
scorchColor.set(Pal.rubble);
//region = Core.atlas.white();
region.set(Core.atlas.white());
uses = 0;
z = Layer.flyingUnit;
}
public static class DisintegrationEntity extends DrawEntity implements Poolable, Sized{
public Disintegration source;
int idx = 0;
float rotation = 0f;
float offsetX, offsetY;
public float vx, vy, vr, drag = 0.05f;
public float time, lifetime;
public float zOverride = -1f;
public boolean disintegrating = false;
static DisintegrationEntity create(){
return Pools.obtain(DisintegrationEntity.class, DisintegrationEntity::new);
}
public float getSize(){
return Math.max(source.drawWidth / (source.width - 1), source.drawHeight / (source.height - 1)) / 2f;
}
@Override
public void update(){
x += vx * Time.delta;
y += vy * Time.delta;
rotation += vr * Time.delta;
float dt = 1f - drag * Time.delta;
vx *= dt;
vy *= dt;
//vr *= dt;
if((time += Time.delta) >= lifetime){
remove();
}
}
@Override
public float hitSize(){
return Math.min(Math.abs(source.drawWidth) / source.width, Math.abs(source.drawHeight) / source.height);
}
@Override
public void draw(){
float cos = Mathf.cosDeg(rotation);
float sin = Mathf.sinDeg(rotation);
TextureRegion region = source.region;
float[] xs = source.xs, ys = source.ys;
float scl = 1f;
Point2 pos = source.getPos(idx);
if(disintegrating){
Tmp.c1.set(source.drawnColor).lerp(source.scorchColor, Mathf.curve(time / lifetime, 0f, 0.75f));
scl = Interp.pow5Out.apply(1f - Mathf.clamp(time / lifetime));
}else{
Tmp.c1.set(source.drawnColor).a(1f - Mathf.curve(time / lifetime, 0.7f, 1f));
}
float color = Tmp.c1.toFloatBits();
float mcolr = Color.clearFloatBits;
fseq.clear();
for(int i = 0; i < 8; i += 2){
int sx = pos.x + arr[i];
int sy = pos.y + arr[i + 1];
int ps = source.toPos(sx, sy);
float fx = xs[ps];
float fy = ys[ps];
float ox = (fx - offsetX) * source.drawWidth * scl;
float oy = (fy - offsetY) * source.drawHeight * scl;
float tx = (ox * cos - oy * sin) + x;
float ty = (ox * sin + oy * cos) + y;
float u = Mathf.lerp(region.u, region.u2, xs[ps]);
float v = Mathf.lerp(region.v2, region.v, ys[ps]);
fseq.addAll(tx, ty, color, u, v, mcolr);
}
Draw.z(zOverride != -1f ? zOverride : source.z);
Draw.vert(region.texture, fseq.items, 0, fseq.size);
}
@Override
public void reset(){
idx = 0;
time = 0f;
lifetime = 0f;
vx = vy = vr = 0f;
zOverride = -1f;
drag = 0.05f;
source = null;
disintegrating = false;
}
@Override
protected void removeGroup(){
super.removeGroup();
Groups.queueFree(this);
source.uses--;
if(source.uses <= 0){
idx = -1;
pool.free(source);
}
}
}
}
| EyeOfDarkness/FlameOut | src/flame/effects/Disintegration.java | 2,643 | //vr *= dt; | line_comment | nl | package flame.effects;
import arc.*;
import arc.func.*;
import arc.graphics.*;
import arc.graphics.g2d.*;
import arc.math.*;
import arc.math.geom.*;
import arc.struct.*;
import arc.util.*;
import arc.util.pooling.*;
import arc.util.pooling.Pool.*;
import flame.Utils.*;
import flame.entities.*;
import mindustry.entities.*;
import mindustry.gen.*;
import mindustry.graphics.*;
/**
* @author EyeOfDarkness
*/
public class Disintegration implements Poolable{
float[] xs, ys;
int width, height;
float drawWidth, drawHeight;
TextureRegion region = new TextureRegion();
int uses = 0;
public float z = Layer.flyingUnit;
public Color drawnColor = Color.white.cpy(), scorchColor = Pal.rubble.cpy();
static Pool<Disintegration> pool = new BasicPool<>(Disintegration::new);
static int maxDimension = 64;
static Point2 tmpPoint = new Point2();
static FloatSeq fseq = new FloatSeq();
static int[] arr = {
0, 0,
1, 0,
1, 1,
0, 1
};
public Disintegration(){}
public static Disintegration generate(TextureRegion region, float x, float y, float rotation, float width, float height, Cons<DisintegrationEntity> cons){
int modW = (int)((5f / 320f) * Math.abs(width / Draw.scl));
int modH = (int)((5f / 320f) * Math.abs(height / Draw.scl));
return generate(region, x, y, rotation, width, height, modW, modH, cons);
}
public static Disintegration generate(TextureRegion region, float x, float y, float rotation, float width, float height, int iwidth, int iheight, Cons<DisintegrationEntity> cons){
//int modW = (int)((20f / 320f) * Math.abs(width / Draw.scl));
//int modH = (int)((20f / 320f) * Math.abs(height / Draw.scl));
float cos = Mathf.cosDeg(rotation);
float sin = Mathf.sinDeg(rotation);
Disintegration dis = pool.obtain();
dis.set(iwidth, iheight);
//dis.region = region;
dis.region.set(region);
dis.drawWidth = width;
dis.drawHeight = height;
dis.uses = 0;
int w = dis.width, h = dis.height;
for(int ix = 0; ix < w - 1; ix++){
for(int iy = 0; iy < h - 1; iy++){
float ox = 0f, oy = 0f;
for(int i = 0; i < 8; i += 2){
int bx = ix + arr[i];
int by = iy + arr[i + 1];
int pos = dis.toPos(bx, by);
ox += dis.xs[pos];
oy += dis.ys[pos];
}
ox /= 4f;
oy /= 4f;
float rx = (ox - 0.5f) * width;
float ry = (oy - 0.5f) * height;
float wx = (rx * cos - ry * sin) + x;
float wy = (rx * sin + ry * cos) + y;
DisintegrationEntity de = DisintegrationEntity.create();
de.source = dis;
de.x = wx;
de.y = wy;
de.rotation = rotation;
de.idx = dis.toPos(ix, iy);
de.offsetX = ox;
de.offsetY = oy;
de.lifetime = 6f * 60f;
cons.get(de);
de.add();
dis.uses++;
}
}
return dis;
}
public void set(int width, int height){
width = Mathf.clamp(width, 3, maxDimension);
height = Mathf.clamp(height, 3, maxDimension);
int size = width * height;
this.width = width;
this.height = height;
if(xs == null || xs.length != size) xs = new float[size];
if(ys == null || ys.length != size) ys = new float[size];
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
float fx = x / (width - 1f);
float fy = y / (height - 1f);
int idx = x + y * width;
if(x > 0 && x < (width - 1)){
fx += Mathf.range(0.1f, 0.4f) / (width - 1f);
}
if(y > 0 && y < (height - 1)){
fy += Mathf.range(0.1f, 0.4f) / (height - 1f);
}
xs[idx] = fx;
ys[idx] = fy;
}
}
}
Point2 getPos(int pos){
tmpPoint.x = pos % width;
tmpPoint.y = pos / width;
return tmpPoint;
}
int toPos(int x, int y){
return x + y * width;
}
@Override
public void reset(){
//xs = ys = null;
width = height = 0;
drawWidth = drawHeight = 0f;
drawnColor.set(Color.white);
scorchColor.set(Pal.rubble);
//region = Core.atlas.white();
region.set(Core.atlas.white());
uses = 0;
z = Layer.flyingUnit;
}
public static class DisintegrationEntity extends DrawEntity implements Poolable, Sized{
public Disintegration source;
int idx = 0;
float rotation = 0f;
float offsetX, offsetY;
public float vx, vy, vr, drag = 0.05f;
public float time, lifetime;
public float zOverride = -1f;
public boolean disintegrating = false;
static DisintegrationEntity create(){
return Pools.obtain(DisintegrationEntity.class, DisintegrationEntity::new);
}
public float getSize(){
return Math.max(source.drawWidth / (source.width - 1), source.drawHeight / (source.height - 1)) / 2f;
}
@Override
public void update(){
x += vx * Time.delta;
y += vy * Time.delta;
rotation += vr * Time.delta;
float dt = 1f - drag * Time.delta;
vx *= dt;
vy *= dt;
//vr *=<SUF>
if((time += Time.delta) >= lifetime){
remove();
}
}
@Override
public float hitSize(){
return Math.min(Math.abs(source.drawWidth) / source.width, Math.abs(source.drawHeight) / source.height);
}
@Override
public void draw(){
float cos = Mathf.cosDeg(rotation);
float sin = Mathf.sinDeg(rotation);
TextureRegion region = source.region;
float[] xs = source.xs, ys = source.ys;
float scl = 1f;
Point2 pos = source.getPos(idx);
if(disintegrating){
Tmp.c1.set(source.drawnColor).lerp(source.scorchColor, Mathf.curve(time / lifetime, 0f, 0.75f));
scl = Interp.pow5Out.apply(1f - Mathf.clamp(time / lifetime));
}else{
Tmp.c1.set(source.drawnColor).a(1f - Mathf.curve(time / lifetime, 0.7f, 1f));
}
float color = Tmp.c1.toFloatBits();
float mcolr = Color.clearFloatBits;
fseq.clear();
for(int i = 0; i < 8; i += 2){
int sx = pos.x + arr[i];
int sy = pos.y + arr[i + 1];
int ps = source.toPos(sx, sy);
float fx = xs[ps];
float fy = ys[ps];
float ox = (fx - offsetX) * source.drawWidth * scl;
float oy = (fy - offsetY) * source.drawHeight * scl;
float tx = (ox * cos - oy * sin) + x;
float ty = (ox * sin + oy * cos) + y;
float u = Mathf.lerp(region.u, region.u2, xs[ps]);
float v = Mathf.lerp(region.v2, region.v, ys[ps]);
fseq.addAll(tx, ty, color, u, v, mcolr);
}
Draw.z(zOverride != -1f ? zOverride : source.z);
Draw.vert(region.texture, fseq.items, 0, fseq.size);
}
@Override
public void reset(){
idx = 0;
time = 0f;
lifetime = 0f;
vx = vy = vr = 0f;
zOverride = -1f;
drag = 0.05f;
source = null;
disintegrating = false;
}
@Override
protected void removeGroup(){
super.removeGroup();
Groups.queueFree(this);
source.uses--;
if(source.uses <= 0){
idx = -1;
pool.free(source);
}
}
}
}
| False | 2,046 | 5 | 2,259 | 5 | 2,429 | 5 | 2,259 | 5 | 2,621 | 6 | false | false | false | false | false | true |
4,265 | 23541_4 | package org.firstinspires.ftc.teamcode;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.classes.Drivetrain;
import org.firstinspires.ftc.teamcode.classes.Hardware;
import org.firstinspires.ftc.teamcode.classes.Lift;
import org.firstinspires.ftc.teamcode.classes.Camera;
import org.firstinspires.ftc.teamcode.classes.extra.GethPath;
import org.firstinspires.ftc.teamcode.classes.extra.Position;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.TouchSensor;
import static org.firstinspires.ftc.teamcode.classes.Hardware.*;
import static org.firstinspires.ftc.teamcode.classes.extra.StartingPositions.*;
@Autonomous(name = "Autonomous :)", group = "Centerstage")
public class AutonomousCenterstage extends LinearOpMode {
//Robot parts
Hardware RobotHardware = new Hardware();
TouchSensor None;
public Drivetrain CenterstageDriveTrain;
public Lift Slides;
public Lift Arm;
public Lift Slider;
public Camera Cam1;
//Auton data
StartPos sPos = StartPos.UNKNOWN;
public String StartPosString;
public void runOpMode()
{
RobotHardware.StartHardware(hardwareMap);
CenterstageDriveTrain = new Drivetrain(imu, lfront, lback, rfront, rback, lfront, lback, rfront, 1,1,1,1,1); // TODO add odometry pod stuf
Arm = new Lift(armMotor, Lift.LiftType.SinlejointedArm, 100, 32, 0, 0.00755190904, false, 1, ArmLimit);
Slider = new Lift(SliderMotor, Lift.LiftType.LinearSlides, 100, 32, 1, 0, true, 1, ArmLimit);
Cam1 = new Camera(cam, vsPortal, AprilProcessor, TfodProcessor);
telemetry.addData("Status: ", "Calibrating...");
CenterstageDriveTrain.Init();
Arm.Init();
Cam1.initVSProcesor();
telemetry.update();
try {
File startPosFile = new File("org\\firstinspires\\ftc\\teamcode\\classes\\extra\\datafiles\\StartingPosition.txt");
BufferedReader fileReader = new BufferedReader(new FileReader(startPosFile));
StartPosString = fileReader.readLine();
}
catch (IOException e)
{
telemetry.addData("Error: ", e);
}
telemetry.addData("Status: ", "Selecting start pos...");
telemetry.addData("StartPos: ", StartPosString);
telemetry.update();
//Autonomous selecting pos
while(!gamepad1.back && !isStopRequested())
{
if (gamepad1.a)
sPos = StartPos.BLUE1;
if (gamepad1.b)
sPos = StartPos.BLUE2;
if (gamepad1.x)
sPos = StartPos.RED1;
if (gamepad1.y)
sPos = StartPos.RED2;
telemetry.addData("Status: ", "Selecting start pos...");
telemetry.addData("StartPos: ", sPos);
telemetry.update();
}
telemetry.addData("Status: ", "Waiting for start...");
telemetry.update();
// hier blijven herkennen tot start
waitForStart();
// Code after start is pressed------------------------------------------------------------------------------------
while(!isStopRequested()) {
Position TeamEllementPos = Cam1.GetTfodLocation(Cam1.HighestRecon());
telemetry.addData("pos X: ", TeamEllementPos.x);
telemetry.addData("pos Y: ", TeamEllementPos.y);
telemetry.update();
//if( positie, 1, 2 of 3; rijd naar de juiste plek
}
}
}
| screwlooosescientists/FtcRobotController-master_ScrewLoooseScientists | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/AutonomousCenterstage.java | 1,201 | //if( positie, 1, 2 of 3; rijd naar de juiste plek | line_comment | nl | package org.firstinspires.ftc.teamcode;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.teamcode.classes.Drivetrain;
import org.firstinspires.ftc.teamcode.classes.Hardware;
import org.firstinspires.ftc.teamcode.classes.Lift;
import org.firstinspires.ftc.teamcode.classes.Camera;
import org.firstinspires.ftc.teamcode.classes.extra.GethPath;
import org.firstinspires.ftc.teamcode.classes.extra.Position;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.TouchSensor;
import static org.firstinspires.ftc.teamcode.classes.Hardware.*;
import static org.firstinspires.ftc.teamcode.classes.extra.StartingPositions.*;
@Autonomous(name = "Autonomous :)", group = "Centerstage")
public class AutonomousCenterstage extends LinearOpMode {
//Robot parts
Hardware RobotHardware = new Hardware();
TouchSensor None;
public Drivetrain CenterstageDriveTrain;
public Lift Slides;
public Lift Arm;
public Lift Slider;
public Camera Cam1;
//Auton data
StartPos sPos = StartPos.UNKNOWN;
public String StartPosString;
public void runOpMode()
{
RobotHardware.StartHardware(hardwareMap);
CenterstageDriveTrain = new Drivetrain(imu, lfront, lback, rfront, rback, lfront, lback, rfront, 1,1,1,1,1); // TODO add odometry pod stuf
Arm = new Lift(armMotor, Lift.LiftType.SinlejointedArm, 100, 32, 0, 0.00755190904, false, 1, ArmLimit);
Slider = new Lift(SliderMotor, Lift.LiftType.LinearSlides, 100, 32, 1, 0, true, 1, ArmLimit);
Cam1 = new Camera(cam, vsPortal, AprilProcessor, TfodProcessor);
telemetry.addData("Status: ", "Calibrating...");
CenterstageDriveTrain.Init();
Arm.Init();
Cam1.initVSProcesor();
telemetry.update();
try {
File startPosFile = new File("org\\firstinspires\\ftc\\teamcode\\classes\\extra\\datafiles\\StartingPosition.txt");
BufferedReader fileReader = new BufferedReader(new FileReader(startPosFile));
StartPosString = fileReader.readLine();
}
catch (IOException e)
{
telemetry.addData("Error: ", e);
}
telemetry.addData("Status: ", "Selecting start pos...");
telemetry.addData("StartPos: ", StartPosString);
telemetry.update();
//Autonomous selecting pos
while(!gamepad1.back && !isStopRequested())
{
if (gamepad1.a)
sPos = StartPos.BLUE1;
if (gamepad1.b)
sPos = StartPos.BLUE2;
if (gamepad1.x)
sPos = StartPos.RED1;
if (gamepad1.y)
sPos = StartPos.RED2;
telemetry.addData("Status: ", "Selecting start pos...");
telemetry.addData("StartPos: ", sPos);
telemetry.update();
}
telemetry.addData("Status: ", "Waiting for start...");
telemetry.update();
// hier blijven herkennen tot start
waitForStart();
// Code after start is pressed------------------------------------------------------------------------------------
while(!isStopRequested()) {
Position TeamEllementPos = Cam1.GetTfodLocation(Cam1.HighestRecon());
telemetry.addData("pos X: ", TeamEllementPos.x);
telemetry.addData("pos Y: ", TeamEllementPos.y);
telemetry.update();
//if( positie,<SUF>
}
}
}
| True | 871 | 23 | 988 | 23 | 1,021 | 21 | 988 | 23 | 1,227 | 23 | false | false | false | false | false | true |
902 | 43984_4 | package nl.han.ica.oopd.bubbletrouble;
import java.util.List;
import java.util.Random;
import nl.han.ica.oopg.collision.CollidedTile;
import nl.han.ica.oopg.collision.CollisionSide;
import nl.han.ica.oopg.collision.ICollidableWithGameObjects;
import nl.han.ica.oopg.collision.ICollidableWithTiles;
import nl.han.ica.oopg.exceptions.TileNotFoundException;
import nl.han.ica.oopg.objects.GameObject;
import nl.han.ica.oopg.objects.Sprite;
import nl.han.ica.oopg.objects.SpriteObject;
import processing.core.PGraphics;
import processing.core.PVector;
public class Bubble extends SpriteObject implements ICollidableWithTiles, ICollidableWithGameObjects {
private BubbleTrouble bubbleTrouble;
private Powerup powerupMovespeed;
private Powerup powerupProjectilespeed;
private Projectile projectile;
private Player player;
private Random random;
private int bubbleSize;
public Bubble(int bubbleSize, BubbleTrouble bubbleTrouble, Sprite sprite, Player player, Projectile projectile) {
super(sprite);
this.bubbleTrouble = bubbleTrouble;
this.player = player;
this.projectile = projectile;
powerupMovespeed = new PowerupMoveSpeed(new Sprite("src/main/resources/bubble-trouble/movespeedpowerup.png"),
bubbleTrouble, player);
powerupProjectilespeed = new PowerupProjectileSpeed(
new Sprite("src/main/resources/bubble-trouble/projectilespeedpowerup.png"), bubbleTrouble, player, projectile);
this.bubbleSize = bubbleSize;
random = new Random();
setGravity(0.20f);
setySpeed(-bubbleSize / 10f);
setxSpeed(-bubbleSize / 8f);
setHeight(bubbleSize);
setWidth(bubbleSize);
}
@Override
public void update() {
}
@Override
public void tileCollisionOccurred(List<CollidedTile> collidedTiles) {
PVector vector;
for (CollidedTile ct : collidedTiles) {
if (ct.getTile() instanceof FloorTile) {
try {
if (CollisionSide.BOTTOM.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setY(vector.y - getHeight());
setySpeed(-getySpeed());
setDirection(225);
}
if (CollisionSide.LEFT.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setX(vector.x - getWidth());
setxSpeed(-getxSpeed());
setDirection(345);
}
if (CollisionSide.TOP.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setY(vector.y - getHeight());
setySpeed(-getySpeed());
if (getDirection() <= 180) {
setDirection(15);
} else {
setDirection(345);
}
}
if (CollisionSide.RIGHT.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
System.out.println(bubbleSize);
if (bubbleSize == 64) {
setX(vector.x + getWidth());
} else if (bubbleSize == 32) {
setX(vector.x + getWidth()+32);
} else if (bubbleSize == 16) {
setX(vector.x + getWidth()+64);
}
setxSpeed(-getxSpeed());
setDirection(15);
}
} catch (TileNotFoundException e) {
e.printStackTrace();
}
}
}
}
@Override
public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) {
for (GameObject g : collidedGameObjects) {
if (g instanceof Projectile || g instanceof ProjectileTrail) {
// Projectile projectile = (Projectile) g;
// bubbleTrouble.deleteGameObject(this);
if (bubbleSize > 16) {
System.out.println("Bubble groter dan 16: splitsen");
int smallerBubbleSize = bubbleSize / 2;
Bubble newBubble1 = new Bubble(smallerBubbleSize, bubbleTrouble,
new Sprite("src/main/resources/bubble-trouble/bubbleblue.png"), player, player.getProjectile());
newBubble1.setxSpeed(-getxSpeed());
// De twee nieuwe bubbles moeten verplaatst om te voorkomen dat ze direct weer
// botsen.
// En wellicht daardoor direct verdwijnen, omdat projectiel niet direct
// verdwijnt bij botsing.
// TODO: Mooier om in plaats hiervan nieuwe bubbels na aanmaken even tijdje
// 'onbotsbaar te maken'
// Dit via ander stukje bubble logica, dan verschieten ze niet opeens.
final int VERPLAATSEN_BIJ_BOTSING = 40;
newBubble1.setX(getX() + VERPLAATSEN_BIJ_BOTSING);
newBubble1.setY(getY());
newBubble1.setySpeed(getySpeed());
bubbleTrouble.addGameObject(newBubble1);
// Maak ook de huidige bubbel kleiner.
this.bubbleSize = smallerBubbleSize;
setWidth(bubbleSize);
setX(getX() - VERPLAATSEN_BIJ_BOTSING);
setHeight(bubbleSize);
} else {
bubbleTrouble.deleteGameObject(this);
}
int powerupRoll = random.nextInt(4);
System.out.println(powerupRoll);
if (powerupRoll == 0) {
if (bubbleTrouble.isProjectilePowerupSpawned() == false) {
bubbleTrouble.addGameObject(powerupProjectilespeed, getX(), getY() + 10);
bubbleTrouble.setProjectilePowerupSpawned(true);
}
} else if (powerupRoll == 1) {
if (bubbleTrouble.isMovespeedPowerupSpawned() == false) {
bubbleTrouble.addGameObject(powerupMovespeed, getX(), getY() + 10);
bubbleTrouble.setMovespeedPowerupSpawned(true);
}
}
} else if (g instanceof Bubble) {
// bubble
}
}
}
@Override
public void draw(PGraphics g) {
// g.fill(120, 120, 230);
// g.ellipse(x, y, bubbleSize, bubbleSize);
g.image(getImage(), x, y, getWidth(), getHeight());
}
}
| Kafune/oopd-bp-bubble-trouble | src/main/java/nl/han/ica/oopd/bubbletrouble/Bubble.java | 2,025 | // TODO: Mooier om in plaats hiervan nieuwe bubbels na aanmaken even tijdje | line_comment | nl | package nl.han.ica.oopd.bubbletrouble;
import java.util.List;
import java.util.Random;
import nl.han.ica.oopg.collision.CollidedTile;
import nl.han.ica.oopg.collision.CollisionSide;
import nl.han.ica.oopg.collision.ICollidableWithGameObjects;
import nl.han.ica.oopg.collision.ICollidableWithTiles;
import nl.han.ica.oopg.exceptions.TileNotFoundException;
import nl.han.ica.oopg.objects.GameObject;
import nl.han.ica.oopg.objects.Sprite;
import nl.han.ica.oopg.objects.SpriteObject;
import processing.core.PGraphics;
import processing.core.PVector;
public class Bubble extends SpriteObject implements ICollidableWithTiles, ICollidableWithGameObjects {
private BubbleTrouble bubbleTrouble;
private Powerup powerupMovespeed;
private Powerup powerupProjectilespeed;
private Projectile projectile;
private Player player;
private Random random;
private int bubbleSize;
public Bubble(int bubbleSize, BubbleTrouble bubbleTrouble, Sprite sprite, Player player, Projectile projectile) {
super(sprite);
this.bubbleTrouble = bubbleTrouble;
this.player = player;
this.projectile = projectile;
powerupMovespeed = new PowerupMoveSpeed(new Sprite("src/main/resources/bubble-trouble/movespeedpowerup.png"),
bubbleTrouble, player);
powerupProjectilespeed = new PowerupProjectileSpeed(
new Sprite("src/main/resources/bubble-trouble/projectilespeedpowerup.png"), bubbleTrouble, player, projectile);
this.bubbleSize = bubbleSize;
random = new Random();
setGravity(0.20f);
setySpeed(-bubbleSize / 10f);
setxSpeed(-bubbleSize / 8f);
setHeight(bubbleSize);
setWidth(bubbleSize);
}
@Override
public void update() {
}
@Override
public void tileCollisionOccurred(List<CollidedTile> collidedTiles) {
PVector vector;
for (CollidedTile ct : collidedTiles) {
if (ct.getTile() instanceof FloorTile) {
try {
if (CollisionSide.BOTTOM.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setY(vector.y - getHeight());
setySpeed(-getySpeed());
setDirection(225);
}
if (CollisionSide.LEFT.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setX(vector.x - getWidth());
setxSpeed(-getxSpeed());
setDirection(345);
}
if (CollisionSide.TOP.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
setY(vector.y - getHeight());
setySpeed(-getySpeed());
if (getDirection() <= 180) {
setDirection(15);
} else {
setDirection(345);
}
}
if (CollisionSide.RIGHT.equals(ct.getCollisionSide())) {
vector = bubbleTrouble.getTileMap().getTilePixelLocation(ct.getTile());
System.out.println(bubbleSize);
if (bubbleSize == 64) {
setX(vector.x + getWidth());
} else if (bubbleSize == 32) {
setX(vector.x + getWidth()+32);
} else if (bubbleSize == 16) {
setX(vector.x + getWidth()+64);
}
setxSpeed(-getxSpeed());
setDirection(15);
}
} catch (TileNotFoundException e) {
e.printStackTrace();
}
}
}
}
@Override
public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) {
for (GameObject g : collidedGameObjects) {
if (g instanceof Projectile || g instanceof ProjectileTrail) {
// Projectile projectile = (Projectile) g;
// bubbleTrouble.deleteGameObject(this);
if (bubbleSize > 16) {
System.out.println("Bubble groter dan 16: splitsen");
int smallerBubbleSize = bubbleSize / 2;
Bubble newBubble1 = new Bubble(smallerBubbleSize, bubbleTrouble,
new Sprite("src/main/resources/bubble-trouble/bubbleblue.png"), player, player.getProjectile());
newBubble1.setxSpeed(-getxSpeed());
// De twee nieuwe bubbles moeten verplaatst om te voorkomen dat ze direct weer
// botsen.
// En wellicht daardoor direct verdwijnen, omdat projectiel niet direct
// verdwijnt bij botsing.
// TODO: Mooier<SUF>
// 'onbotsbaar te maken'
// Dit via ander stukje bubble logica, dan verschieten ze niet opeens.
final int VERPLAATSEN_BIJ_BOTSING = 40;
newBubble1.setX(getX() + VERPLAATSEN_BIJ_BOTSING);
newBubble1.setY(getY());
newBubble1.setySpeed(getySpeed());
bubbleTrouble.addGameObject(newBubble1);
// Maak ook de huidige bubbel kleiner.
this.bubbleSize = smallerBubbleSize;
setWidth(bubbleSize);
setX(getX() - VERPLAATSEN_BIJ_BOTSING);
setHeight(bubbleSize);
} else {
bubbleTrouble.deleteGameObject(this);
}
int powerupRoll = random.nextInt(4);
System.out.println(powerupRoll);
if (powerupRoll == 0) {
if (bubbleTrouble.isProjectilePowerupSpawned() == false) {
bubbleTrouble.addGameObject(powerupProjectilespeed, getX(), getY() + 10);
bubbleTrouble.setProjectilePowerupSpawned(true);
}
} else if (powerupRoll == 1) {
if (bubbleTrouble.isMovespeedPowerupSpawned() == false) {
bubbleTrouble.addGameObject(powerupMovespeed, getX(), getY() + 10);
bubbleTrouble.setMovespeedPowerupSpawned(true);
}
}
} else if (g instanceof Bubble) {
// bubble
}
}
}
@Override
public void draw(PGraphics g) {
// g.fill(120, 120, 230);
// g.ellipse(x, y, bubbleSize, bubbleSize);
g.image(getImage(), x, y, getWidth(), getHeight());
}
}
| True | 1,483 | 21 | 1,783 | 29 | 1,662 | 19 | 1,783 | 29 | 2,366 | 23 | false | false | false | false | false | true |
3,512 | 137639_1 | package com.lovejjfg.blogdemo.ui;
import android.content.Context;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
/**
* Created by lovejjfg on 2015/11/8.
*/
public class SlideToFinishLayout extends FrameLayout {
private ViewDragHelper mViewDragHelper;
private View mContentView;
private int mContentWidth;
private AppCompatActivity activity;
private int mMoveLeft;
private boolean isClose;
private CallBack mCallBack;
private float MINVEL;
public SlideToFinishLayout(Context context) {
this(context, null);
}
public SlideToFinishLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlideToFinishLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
MINVEL = getResources().getDisplayMetrics().density * 1000;
if (context instanceof AppCompatActivity) {
activity = (AppCompatActivity) context;
}
mViewDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(View child, int pointerId) {
return false;//child == mContentView;//只有mContentView可以移动
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
mMoveLeft = left;
if (isClose && (left == mContentWidth)) {
finishActivity();
}
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
if (xvel > MINVEL) {
Log.e("xvel.." + xvel, "TRUE:" + MINVEL);
isClose = true;
mViewDragHelper.smoothSlideViewTo(releasedChild, mContentWidth, releasedChild.getTop());
} else {
Log.e("xvel:" + xvel, "FALSE:" + MINVEL);
if (mMoveLeft >= (mContentWidth / 2)) {
//滑动超过屏幕的一半,那么就可以判断为true了!
isClose = true;
mViewDragHelper.smoothSlideViewTo(releasedChild, mContentWidth, releasedChild.getTop());
} else {
mViewDragHelper.settleCapturedViewAt(0, releasedChild.getTop());
}
}
invalidate();
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
//这样的话,页面就只能向右滑动了!
return Math.min(mContentWidth, Math.max(left, 0));
}
@Override
public int getViewHorizontalDragRange(View child) {
//一定要重写这个方法,返回>0的值,不然当子View可以消耗触摸事件时就会无法移动。
return mContentWidth;
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
super.onEdgeDragStarted(edgeFlags, pointerId);
//在里面处理我们需要实现边界滑动有效的view
mViewDragHelper.captureChildView(mContentView, pointerId);
}
});
mViewDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
}
private void finishActivity() {
if (mCallBack != null) {
mCallBack.onFinish();
}
if (null != activity) {
activity.finish();
activity.overridePendingTransition(0, 0);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mViewDragHelper.shouldInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mViewDragHelper.processTouchEvent(event);
return true;
//这里一定要记得返回true;
}
@Override
public void computeScroll() {
super.computeScroll();
if (mViewDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
// invalidate();
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
mContentWidth = mContentView.getWidth();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
//该布局中应该只有一个子布局,所有的其他布局填充到这个子布局中。
mContentView = getChildAt(0);
}
public void SetCallBack(CallBack callBack) {
mCallBack = callBack;
}
public interface CallBack {
void onFinish();
}
}
| lovejjfg/MyBlogDemo | app/src/main/java/com/lovejjfg/blogdemo/ui/SlideToFinishLayout.java | 1,396 | //child == mContentView;//只有mContentView可以移动 | line_comment | nl | package com.lovejjfg.blogdemo.ui;
import android.content.Context;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
/**
* Created by lovejjfg on 2015/11/8.
*/
public class SlideToFinishLayout extends FrameLayout {
private ViewDragHelper mViewDragHelper;
private View mContentView;
private int mContentWidth;
private AppCompatActivity activity;
private int mMoveLeft;
private boolean isClose;
private CallBack mCallBack;
private float MINVEL;
public SlideToFinishLayout(Context context) {
this(context, null);
}
public SlideToFinishLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlideToFinishLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
MINVEL = getResources().getDisplayMetrics().density * 1000;
if (context instanceof AppCompatActivity) {
activity = (AppCompatActivity) context;
}
mViewDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() {
@Override
public boolean tryCaptureView(View child, int pointerId) {
return false;//child ==<SUF>
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
mMoveLeft = left;
if (isClose && (left == mContentWidth)) {
finishActivity();
}
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
if (xvel > MINVEL) {
Log.e("xvel.." + xvel, "TRUE:" + MINVEL);
isClose = true;
mViewDragHelper.smoothSlideViewTo(releasedChild, mContentWidth, releasedChild.getTop());
} else {
Log.e("xvel:" + xvel, "FALSE:" + MINVEL);
if (mMoveLeft >= (mContentWidth / 2)) {
//滑动超过屏幕的一半,那么就可以判断为true了!
isClose = true;
mViewDragHelper.smoothSlideViewTo(releasedChild, mContentWidth, releasedChild.getTop());
} else {
mViewDragHelper.settleCapturedViewAt(0, releasedChild.getTop());
}
}
invalidate();
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
//这样的话,页面就只能向右滑动了!
return Math.min(mContentWidth, Math.max(left, 0));
}
@Override
public int getViewHorizontalDragRange(View child) {
//一定要重写这个方法,返回>0的值,不然当子View可以消耗触摸事件时就会无法移动。
return mContentWidth;
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
super.onEdgeDragStarted(edgeFlags, pointerId);
//在里面处理我们需要实现边界滑动有效的view
mViewDragHelper.captureChildView(mContentView, pointerId);
}
});
mViewDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
}
private void finishActivity() {
if (mCallBack != null) {
mCallBack.onFinish();
}
if (null != activity) {
activity.finish();
activity.overridePendingTransition(0, 0);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mViewDragHelper.shouldInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mViewDragHelper.processTouchEvent(event);
return true;
//这里一定要记得返回true;
}
@Override
public void computeScroll() {
super.computeScroll();
if (mViewDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
// invalidate();
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
mContentWidth = mContentView.getWidth();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
//该布局中应该只有一个子布局,所有的其他布局填充到这个子布局中。
mContentView = getChildAt(0);
}
public void SetCallBack(CallBack callBack) {
mCallBack = callBack;
}
public interface CallBack {
void onFinish();
}
}
| False | 1,051 | 11 | 1,169 | 11 | 1,234 | 11 | 1,169 | 11 | 1,463 | 15 | false | false | false | false | false | true |
701 | 8349_7 | package nl.hsleiden.game;
import java.util.ArrayList;
/**
* Dit is een level. Hier kun je een aantal methoden aanroepen om informatie over het level te krijgen,
* of om tiles en/of elementen toe te voegen aan het spel.
* */
public class Level {
private Tile[][] tiles;
private ArrayList<Element> elements;
private Element focusedElement;
private ArrayList<Element> bufferedElements;
public Level() {
bufferedElements = new ArrayList<>();
}
/**
* @return het element dat door de camera gefocussed wordt.
* */
public Element getFocusedElement() {
return focusedElement;
}
/**
* Set het element dat door de camera gefocussed moet worden.
* @param focusedElement het element waarop gefocussed moet worden.
* */
public void setFocusedElement(Element focusedElement) {
this.focusedElement = focusedElement;
}
/**
* Met deze methode kun je de tiles van dit level opvragen.
* @return de tiles van dit level.
* */
public Tile[][] getTiles() {
return tiles;
}
/**
* Met deze methode kun je de elementen van dit level opvragen.
* @return de elementen van dit level.
* */
public ArrayList<Element> getElements() {
return elements;
}
/**
* @return de breedte van het level.
* */
public int getWidth() {
return tiles[0].length * 80;
}
/**
* @return de hoogte van het level.
* */
public int getHeigt() {
return tiles.length * 80;
}
/**
* Plaats de tiles in dit level.
* @param tiles de tiles die in dit level moeten.
* */
public void setTiles(Tile[][] tiles) {
this.tiles = tiles;
}
/**
* Plaats de elements in dit level.
* @param elements de tiles die in dit level moeten.
* */
public void setElements(ArrayList<Element> elements) {
this.elements = elements;
}
public void refreshElements(){
this.bufferedElements.clear();
this.bufferedElements.addAll(elements);
}
public ArrayList<Element> getBufferedElements() {
return bufferedElements;
}
}
| Hogeschool-Leiden/GameEngine | src/main/java/nl/hsleiden/game/Level.java | 622 | /**
* Plaats de tiles in dit level.
* @param tiles de tiles die in dit level moeten.
* */ | block_comment | nl | package nl.hsleiden.game;
import java.util.ArrayList;
/**
* Dit is een level. Hier kun je een aantal methoden aanroepen om informatie over het level te krijgen,
* of om tiles en/of elementen toe te voegen aan het spel.
* */
public class Level {
private Tile[][] tiles;
private ArrayList<Element> elements;
private Element focusedElement;
private ArrayList<Element> bufferedElements;
public Level() {
bufferedElements = new ArrayList<>();
}
/**
* @return het element dat door de camera gefocussed wordt.
* */
public Element getFocusedElement() {
return focusedElement;
}
/**
* Set het element dat door de camera gefocussed moet worden.
* @param focusedElement het element waarop gefocussed moet worden.
* */
public void setFocusedElement(Element focusedElement) {
this.focusedElement = focusedElement;
}
/**
* Met deze methode kun je de tiles van dit level opvragen.
* @return de tiles van dit level.
* */
public Tile[][] getTiles() {
return tiles;
}
/**
* Met deze methode kun je de elementen van dit level opvragen.
* @return de elementen van dit level.
* */
public ArrayList<Element> getElements() {
return elements;
}
/**
* @return de breedte van het level.
* */
public int getWidth() {
return tiles[0].length * 80;
}
/**
* @return de hoogte van het level.
* */
public int getHeigt() {
return tiles.length * 80;
}
/**
* Plaats de tiles<SUF>*/
public void setTiles(Tile[][] tiles) {
this.tiles = tiles;
}
/**
* Plaats de elements in dit level.
* @param elements de tiles die in dit level moeten.
* */
public void setElements(ArrayList<Element> elements) {
this.elements = elements;
}
public void refreshElements(){
this.bufferedElements.clear();
this.bufferedElements.addAll(elements);
}
public ArrayList<Element> getBufferedElements() {
return bufferedElements;
}
}
| True | 498 | 28 | 539 | 29 | 582 | 30 | 539 | 29 | 651 | 34 | false | false | false | false | false | true |
3,685 | 100994_2 | package pipeline;
public abstract class BasePipeline implements IPipeline{
private Boolean running = false;
private Boolean success = false;
protected BasePipeline(boolean autostart) {
if(autostart){
this.startPipeline();
}
}
protected BasePipeline() {
}
@Override
public void startPipeline(){
System.out.println("Started pipeline");
this.running = true;
this.onPipelineStarts();
Boolean sourcesPhaseSuccess;
try {
sourcesPhaseSuccess = this.runSources();
}catch(Exception e){
sourcesPhaseSuccess = false;
}
if(Boolean.FALSE.equals(sourcesPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean packagePhaseSuccess;
try {
packagePhaseSuccess = this.runPackage();
}catch(Exception e){
packagePhaseSuccess = false;
}
if(Boolean.FALSE.equals(packagePhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean buildPhaseSuccess;
try {
buildPhaseSuccess = this.runBuild();
}catch(Exception e){
buildPhaseSuccess = false;
}
if(Boolean.FALSE.equals(buildPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean testPhaseSuccess;
try {
testPhaseSuccess = this.runTest();
}catch(Exception e){
testPhaseSuccess = false;
}
if(Boolean.FALSE.equals(testPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean analysisPhaseSuccess;
try {
analysisPhaseSuccess = this.runAnalysis();
}catch(Exception e){
analysisPhaseSuccess = false;
}
if(Boolean.FALSE.equals(analysisPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean deployPhaseSuccess;
try {
deployPhaseSuccess = this.runDeploy();
}catch(Exception e){
deployPhaseSuccess = false;
}
if(Boolean.FALSE.equals(deployPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean utilityPhaseSuccess;
try {
utilityPhaseSuccess = this.runUtility();
}catch(Exception e){
utilityPhaseSuccess = false;
}
if(Boolean.FALSE.equals(utilityPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
this.running = false;
this.success = true;
this.onPipelineEnds();
}
@Override
public void onPipelineStarts() {
System.out.println("Callback not overriden");
}
@Override
public Boolean runSources() {
System.out.println("1. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runPackage() {
System.out.println("2. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runBuild() {
System.out.println("3. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runTest() {
System.out.println("4. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runAnalysis() {
System.out.println("5. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runDeploy() {
System.out.println("6. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runUtility() {
System.out.println("7. Running this phases default activity. For different functionality, please override method on initialization.");
return true;
}
@Override
public void endPipeline(){
System.out.println("Ended pipeline");
this.running = false;
this.onPipelineEnds();
}
@Override
public void onPipelineEnds() {
// this.running = false;
System.out.println("Callback not overriden");
if(this.getSuccess()){
this.onPipelineSuccess();
}
else{
this.onPipelineFail();
}
}
@Override
public void onPipelineSuccess(){
System.out.println("Pipepeline succeeded");
}
@Override
public void onPipelineFail(){
System.out.println("Pipeline failed");
}
@Override
public Boolean getRunning() {
return running;
}
@Override
public void setRunning(Boolean running) {
this.running = running;
}
@Override
public Boolean getSuccess() {
return success;
}
@Override
public void setSuccess(Boolean success) {
this.success = success;
}
// TODO: Read this better and also keep this logic into account or somehting idk
// Een deployment sprint is gekoppeld aan een development pipeline die eindigt met deployment.
//Andere sprints kunnen ook worden gekoppeld aan een development pipeline die
//automatisch/handmatig wordt uitgevoerd. Daarvan kan het einde ook deployment zijn (naar bv een
//testomgeving), maar het kan ook eindigen na het uitvoeren van de tests en publicatie van
//testresultaten.
}
| mjlpjacoavans/avans-devops-project | src/main/java/pipeline/BasePipeline.java | 1,621 | // Een deployment sprint is gekoppeld aan een development pipeline die eindigt met deployment. | line_comment | nl | package pipeline;
public abstract class BasePipeline implements IPipeline{
private Boolean running = false;
private Boolean success = false;
protected BasePipeline(boolean autostart) {
if(autostart){
this.startPipeline();
}
}
protected BasePipeline() {
}
@Override
public void startPipeline(){
System.out.println("Started pipeline");
this.running = true;
this.onPipelineStarts();
Boolean sourcesPhaseSuccess;
try {
sourcesPhaseSuccess = this.runSources();
}catch(Exception e){
sourcesPhaseSuccess = false;
}
if(Boolean.FALSE.equals(sourcesPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean packagePhaseSuccess;
try {
packagePhaseSuccess = this.runPackage();
}catch(Exception e){
packagePhaseSuccess = false;
}
if(Boolean.FALSE.equals(packagePhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean buildPhaseSuccess;
try {
buildPhaseSuccess = this.runBuild();
}catch(Exception e){
buildPhaseSuccess = false;
}
if(Boolean.FALSE.equals(buildPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean testPhaseSuccess;
try {
testPhaseSuccess = this.runTest();
}catch(Exception e){
testPhaseSuccess = false;
}
if(Boolean.FALSE.equals(testPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean analysisPhaseSuccess;
try {
analysisPhaseSuccess = this.runAnalysis();
}catch(Exception e){
analysisPhaseSuccess = false;
}
if(Boolean.FALSE.equals(analysisPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean deployPhaseSuccess;
try {
deployPhaseSuccess = this.runDeploy();
}catch(Exception e){
deployPhaseSuccess = false;
}
if(Boolean.FALSE.equals(deployPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
Boolean utilityPhaseSuccess;
try {
utilityPhaseSuccess = this.runUtility();
}catch(Exception e){
utilityPhaseSuccess = false;
}
if(Boolean.FALSE.equals(utilityPhaseSuccess)){
this.running = false;
this.success = false;
this.onPipelineEnds();
return;
}
this.running = false;
this.success = true;
this.onPipelineEnds();
}
@Override
public void onPipelineStarts() {
System.out.println("Callback not overriden");
}
@Override
public Boolean runSources() {
System.out.println("1. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runPackage() {
System.out.println("2. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runBuild() {
System.out.println("3. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runTest() {
System.out.println("4. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runAnalysis() {
System.out.println("5. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runDeploy() {
System.out.println("6. Running this phases default activity. For defferent fcuntionality, please override methon on initialization.");
return true;
}
@Override
public Boolean runUtility() {
System.out.println("7. Running this phases default activity. For different functionality, please override method on initialization.");
return true;
}
@Override
public void endPipeline(){
System.out.println("Ended pipeline");
this.running = false;
this.onPipelineEnds();
}
@Override
public void onPipelineEnds() {
// this.running = false;
System.out.println("Callback not overriden");
if(this.getSuccess()){
this.onPipelineSuccess();
}
else{
this.onPipelineFail();
}
}
@Override
public void onPipelineSuccess(){
System.out.println("Pipepeline succeeded");
}
@Override
public void onPipelineFail(){
System.out.println("Pipeline failed");
}
@Override
public Boolean getRunning() {
return running;
}
@Override
public void setRunning(Boolean running) {
this.running = running;
}
@Override
public Boolean getSuccess() {
return success;
}
@Override
public void setSuccess(Boolean success) {
this.success = success;
}
// TODO: Read this better and also keep this logic into account or somehting idk
// Een deployment<SUF>
//Andere sprints kunnen ook worden gekoppeld aan een development pipeline die
//automatisch/handmatig wordt uitgevoerd. Daarvan kan het einde ook deployment zijn (naar bv een
//testomgeving), maar het kan ook eindigen na het uitvoeren van de tests en publicatie van
//testresultaten.
}
| True | 1,254 | 19 | 1,348 | 22 | 1,499 | 18 | 1,348 | 22 | 1,635 | 19 | false | false | false | false | false | true |
2,274 | 159741_13 | package jmri.jmrix.mqtt;
import jmri.Light;
import jmri.implementation.AbstractVariableLight;
import javax.annotation.Nonnull;
/**
* MQTT implementation of the Light interface.
*
* @author Bob Jacobsen Copyright (C) 2001, 2008, 2020, 2023
* @author Paul Bender Copyright (C) 2010
* @author Fredrik Elestedt Copyright (C) 2020
*/
public class MqttLight extends AbstractVariableLight implements MqttEventListener {
private final MqttAdapter mqttAdapter;
private final String sendTopic;
private final String rcvTopic;
static public String intensityText = "INTENSITY "; // public for script access
public MqttLight(MqttAdapter ma, String systemName, String userName, String sendTopic, String rcvTopic) {
super(systemName, userName);
this.sendTopic = sendTopic;
this.rcvTopic = rcvTopic;
this.mqttAdapter = ma;
this.mqttAdapter.subscribe(rcvTopic, this);
}
public void setParser(MqttContentParser<Light> parser) {
this.parser = parser;
}
MqttContentParser<Light> parser = new MqttContentParser<Light>() {
private static final String onText = "ON";
private static final String offText = "OFF";
int stateFromString(String payload) {
if (payload.startsWith(intensityText)) return -1; // means don't change state
switch (payload) {
case onText: return ON;
case offText: return OFF;
default: return UNKNOWN;
}
}
@Override
public void beanFromPayload(@Nonnull Light bean, @Nonnull String payload, @Nonnull String topic) {
log.debug("beanFromPayload {} {} {}", bean, payload, topic);
int state = stateFromString(payload);
if (state == -1) {
// don't change anything
log.trace(" no changes");
return;
}
boolean couldBeSendMessage = topic.endsWith(sendTopic);
boolean couldBeRcvMessage = topic.endsWith(rcvTopic);
if (couldBeSendMessage) {
log.trace(" setCommandedState {}", state);
setCommandedState(state);
} else if (couldBeRcvMessage) {
setState(state);
log.trace(" setState {}", state);
} else {
log.warn("{} failure to decode topic {} {}", getDisplayName(), topic, payload);
}
}
@Override
public @Nonnull String payloadFromBean(@Nonnull Light bean, int newState){
String toReturn = "UNKNOWN";
switch (getState()) {
case Light.ON:
toReturn = onText;
break;
case Light.OFF:
toReturn = offText;
break;
default:
log.error("Light {} has a state which is not supported {}", getDisplayName(), newState);
break;
}
return toReturn;
}
};
// For AbstractVariableLight
@Override
protected int getNumberOfSteps() {
return 20;
}
// For AbstractVariableLight
@Override
protected void sendIntensity(double intensity) {
sendMessage(intensityText+intensity);
}
// For AbstractVariableLight
@Override
protected void sendOnOffCommand(int newState) {
switch (newState) {
case ON:
sendMessage(true);
break;
case OFF:
sendMessage(false);
break;
default:
log.error("Unexpected state to sendOnOff: {}", newState);
}
}
// Handle a request to change state by sending a formatted packet
// to the server.
@Override
protected void doNewState(int oldState, int newState) {
log.debug("doNewState with old state {} new state {}", oldState, newState);
if (oldState == newState) {
return; //no change, just quit.
} // sort out states
if ((newState & Light.ON) != 0) {
// first look for the double case, which we can't handle
if ((newState & Light.OFF) != 0) {
// this is the disaster case!
log.error("Cannot command {} to both ON and OFF {}", getDisplayName(), newState);
return;
} else {
// send a ON command
sendMessage(true);
}
} else {
// send a OFF command
sendMessage(false);
}
}
private void sendMessage(boolean on) {
this.sendMessage(on ? "ON" : "OFF");
}
private void sendMessage(String c) {
jmri.util.ThreadingUtil.runOnLayoutEventually(() -> {
mqttAdapter.publish(this.sendTopic, c.getBytes());
});
log.debug("sent {}", c);
}
@Override
public void setState(int newState) {
log.debug("setState {} was {}", newState, mState);
if (newState != ON && newState != OFF && newState != UNKNOWN) {
throw new IllegalArgumentException("cannot set state value " + newState);
}
// do the state change in the hardware
doNewState(mState, newState);
// change value and tell listeners
notifyStateChange(mState, newState);
}
//request a status update from the layout
@Override
public void requestUpdateFromLayout() {
}
@Override
public void notifyMqttMessage(String receivedTopic, String message) {
if (! ( receivedTopic.endsWith(rcvTopic) || receivedTopic.endsWith(sendTopic) ) ) {
log.error("{} got a message whose topic ({}) wasn't for me ({})", getDisplayName(), receivedTopic, rcvTopic);
return;
}
log.debug("notifyMqttMessage with {}", message);
// parser doesn't support intensity, so first handle that here
if (message.startsWith(intensityText)) {
var stringValue = message.substring(intensityText.length());
try {
double intensity = Double.parseDouble(stringValue);
log.debug("setting received intensity with {}", intensity);
setObservedAnalogValue(intensity);
} catch (NumberFormatException e) {
log.warn("could not parse input {}", receivedTopic, e);
}
}
// handle on/off
parser.beanFromPayload(this, message, receivedTopic);
}
@Override
public void dispose() {
mqttAdapter.unsubscribe(rcvTopic,this);
super.dispose();
}
private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MqttLight.class);
}
| bobjacobsen/JMRI | java/src/jmri/jmrix/mqtt/MqttLight.java | 1,820 | // change value and tell listeners | line_comment | nl | package jmri.jmrix.mqtt;
import jmri.Light;
import jmri.implementation.AbstractVariableLight;
import javax.annotation.Nonnull;
/**
* MQTT implementation of the Light interface.
*
* @author Bob Jacobsen Copyright (C) 2001, 2008, 2020, 2023
* @author Paul Bender Copyright (C) 2010
* @author Fredrik Elestedt Copyright (C) 2020
*/
public class MqttLight extends AbstractVariableLight implements MqttEventListener {
private final MqttAdapter mqttAdapter;
private final String sendTopic;
private final String rcvTopic;
static public String intensityText = "INTENSITY "; // public for script access
public MqttLight(MqttAdapter ma, String systemName, String userName, String sendTopic, String rcvTopic) {
super(systemName, userName);
this.sendTopic = sendTopic;
this.rcvTopic = rcvTopic;
this.mqttAdapter = ma;
this.mqttAdapter.subscribe(rcvTopic, this);
}
public void setParser(MqttContentParser<Light> parser) {
this.parser = parser;
}
MqttContentParser<Light> parser = new MqttContentParser<Light>() {
private static final String onText = "ON";
private static final String offText = "OFF";
int stateFromString(String payload) {
if (payload.startsWith(intensityText)) return -1; // means don't change state
switch (payload) {
case onText: return ON;
case offText: return OFF;
default: return UNKNOWN;
}
}
@Override
public void beanFromPayload(@Nonnull Light bean, @Nonnull String payload, @Nonnull String topic) {
log.debug("beanFromPayload {} {} {}", bean, payload, topic);
int state = stateFromString(payload);
if (state == -1) {
// don't change anything
log.trace(" no changes");
return;
}
boolean couldBeSendMessage = topic.endsWith(sendTopic);
boolean couldBeRcvMessage = topic.endsWith(rcvTopic);
if (couldBeSendMessage) {
log.trace(" setCommandedState {}", state);
setCommandedState(state);
} else if (couldBeRcvMessage) {
setState(state);
log.trace(" setState {}", state);
} else {
log.warn("{} failure to decode topic {} {}", getDisplayName(), topic, payload);
}
}
@Override
public @Nonnull String payloadFromBean(@Nonnull Light bean, int newState){
String toReturn = "UNKNOWN";
switch (getState()) {
case Light.ON:
toReturn = onText;
break;
case Light.OFF:
toReturn = offText;
break;
default:
log.error("Light {} has a state which is not supported {}", getDisplayName(), newState);
break;
}
return toReturn;
}
};
// For AbstractVariableLight
@Override
protected int getNumberOfSteps() {
return 20;
}
// For AbstractVariableLight
@Override
protected void sendIntensity(double intensity) {
sendMessage(intensityText+intensity);
}
// For AbstractVariableLight
@Override
protected void sendOnOffCommand(int newState) {
switch (newState) {
case ON:
sendMessage(true);
break;
case OFF:
sendMessage(false);
break;
default:
log.error("Unexpected state to sendOnOff: {}", newState);
}
}
// Handle a request to change state by sending a formatted packet
// to the server.
@Override
protected void doNewState(int oldState, int newState) {
log.debug("doNewState with old state {} new state {}", oldState, newState);
if (oldState == newState) {
return; //no change, just quit.
} // sort out states
if ((newState & Light.ON) != 0) {
// first look for the double case, which we can't handle
if ((newState & Light.OFF) != 0) {
// this is the disaster case!
log.error("Cannot command {} to both ON and OFF {}", getDisplayName(), newState);
return;
} else {
// send a ON command
sendMessage(true);
}
} else {
// send a OFF command
sendMessage(false);
}
}
private void sendMessage(boolean on) {
this.sendMessage(on ? "ON" : "OFF");
}
private void sendMessage(String c) {
jmri.util.ThreadingUtil.runOnLayoutEventually(() -> {
mqttAdapter.publish(this.sendTopic, c.getBytes());
});
log.debug("sent {}", c);
}
@Override
public void setState(int newState) {
log.debug("setState {} was {}", newState, mState);
if (newState != ON && newState != OFF && newState != UNKNOWN) {
throw new IllegalArgumentException("cannot set state value " + newState);
}
// do the state change in the hardware
doNewState(mState, newState);
// change value<SUF>
notifyStateChange(mState, newState);
}
//request a status update from the layout
@Override
public void requestUpdateFromLayout() {
}
@Override
public void notifyMqttMessage(String receivedTopic, String message) {
if (! ( receivedTopic.endsWith(rcvTopic) || receivedTopic.endsWith(sendTopic) ) ) {
log.error("{} got a message whose topic ({}) wasn't for me ({})", getDisplayName(), receivedTopic, rcvTopic);
return;
}
log.debug("notifyMqttMessage with {}", message);
// parser doesn't support intensity, so first handle that here
if (message.startsWith(intensityText)) {
var stringValue = message.substring(intensityText.length());
try {
double intensity = Double.parseDouble(stringValue);
log.debug("setting received intensity with {}", intensity);
setObservedAnalogValue(intensity);
} catch (NumberFormatException e) {
log.warn("could not parse input {}", receivedTopic, e);
}
}
// handle on/off
parser.beanFromPayload(this, message, receivedTopic);
}
@Override
public void dispose() {
mqttAdapter.unsubscribe(rcvTopic,this);
super.dispose();
}
private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MqttLight.class);
}
| False | 1,395 | 6 | 1,466 | 6 | 1,609 | 6 | 1,466 | 6 | 1,843 | 7 | false | false | false | false | false | true |
2,997 | 23390_5 | package novi.basics;
import java.util.Scanner;
public class Main {
public static Scanner PLAYERINPUT = new Scanner(System.in);
public static void main(String[] args) {
// -- vanaf hier gaan we het spel opnieuw spelen met andere spelers (nadat op het eind keuze 2 gekozen is)
// de 1e speler om zijn naam vragen
System.out.println("Player 1, what is your name?");
// de naam van de 1e speler opslaan
String player1Name = PLAYERINPUT.next();
Player player1 = new Player(player1Name,'x');
// de 2e speler om zijn naam vragen
System.out.println("Player 2, what is your name?");
// de naam van de 2e speler opslaan
String player2Name = PLAYERINPUT.next();
Player player2 = new Player(player2Name,'o');
TicTacToe game = new TicTacToe(player1, player2);
int spelkeuze;
spelkeuze = ChooseGame();
if (spelkeuze == 1) {
TicTactoe.play();
} else {
TripleDigits.play;
}
// speler spel laten kiezen --> TicTacToe of TripleDigits
}
// vragen of de spelers nog een keer willen spelen
//1: nog een keer spelen
//2: van spelers wisselen
//3: afsluiten
// speler keuze opslaan
// bij keuze 1: terug naar het maken van het bord
// bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen
// bij keuze 3: het spel en de applicatie helemaal afsluiten
}
private static int ChooseGame() {
System.out.println("Which game do you wish to play?");
System.out.println("Press 1 for Tictactoe or press 2 for TripleDigits");
Scanner welkspel = new Scanner(System.in);
int inputInt;
inputInt = welkspel.nextInt();
return inputInt;
}
} | hogeschoolnovi/tic-tac-toe-SunshineSummerville | src/novi/basics/Main.java | 578 | // speler spel laten kiezen --> TicTacToe of TripleDigits | line_comment | nl | package novi.basics;
import java.util.Scanner;
public class Main {
public static Scanner PLAYERINPUT = new Scanner(System.in);
public static void main(String[] args) {
// -- vanaf hier gaan we het spel opnieuw spelen met andere spelers (nadat op het eind keuze 2 gekozen is)
// de 1e speler om zijn naam vragen
System.out.println("Player 1, what is your name?");
// de naam van de 1e speler opslaan
String player1Name = PLAYERINPUT.next();
Player player1 = new Player(player1Name,'x');
// de 2e speler om zijn naam vragen
System.out.println("Player 2, what is your name?");
// de naam van de 2e speler opslaan
String player2Name = PLAYERINPUT.next();
Player player2 = new Player(player2Name,'o');
TicTacToe game = new TicTacToe(player1, player2);
int spelkeuze;
spelkeuze = ChooseGame();
if (spelkeuze == 1) {
TicTactoe.play();
} else {
TripleDigits.play;
}
// speler spel<SUF>
}
// vragen of de spelers nog een keer willen spelen
//1: nog een keer spelen
//2: van spelers wisselen
//3: afsluiten
// speler keuze opslaan
// bij keuze 1: terug naar het maken van het bord
// bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen
// bij keuze 3: het spel en de applicatie helemaal afsluiten
}
private static int ChooseGame() {
System.out.println("Which game do you wish to play?");
System.out.println("Press 1 for Tictactoe or press 2 for TripleDigits");
Scanner welkspel = new Scanner(System.in);
int inputInt;
inputInt = welkspel.nextInt();
return inputInt;
}
} | True | 478 | 15 | 544 | 21 | 495 | 12 | 544 | 21 | 589 | 20 | false | false | false | false | false | true |
2,809 | 197234_2 | package Strukturer;
import java.util.*;
public class TabellStakk <T> implements Stakk<T> {
private T[] a; // en T-tabell
private int antall; // antall verdier på stakken
public TabellStakk() // konstruktør - tabellengde 8
{
this(8);
}
@SuppressWarnings("unchecked") // pga. konverteringen: Object[] -> T[]
public TabellStakk(int lengde) // valgfri tabellengde
{
if (lengde < 0)
throw new IllegalArgumentException("Negativ tabellengde!");
a = (T[]) new Object[lengde]; // oppretter tabellen
antall = 0; // stakken er tom
}
@Override
public void leggInn(T verdi) {
if (antall == a.length)
a = Arrays.copyOf(a, antall == 0 ? 1 : 2 * antall); // dobler
a[antall++] = verdi;
}
@Override
public T kikk() {
if (antall == 0) // sjekker om stakken er tom
throw new NoSuchElementException("Stakken er tom!");
return a[antall - 1]; // returnerer den øverste verdien
}
@Override
public T taUt() {
if (antall == 0) // sjekker om stakken er tom
throw new NoSuchElementException("Stakken er tom!");
antall--; // reduserer antallet
T temp = a[antall]; // tar var på det øverste objektet
a[antall] = null; // tilrettelegger for resirkulering
return temp; // returnerer den øverste verdien
}
@Override
public int antall() {
return antall;
}
@Override
public boolean tom() {
return antall == 0;
}
@Override
public void nullstill() {
for (T i : a) {
i = null;
}
antall = 0;
}
public String toString() {
StringJoiner sj = new StringJoiner(", ", "[", "]");
for(int i = antall-1; i >= 0; i--){
if(a[i] != null) sj.add(a[i].toString());
}
return sj.toString();
}
public static <T> void kopier(Stakk<T> A, Stakk<T> B) {
T temp;
Stakk<T> hjelp = new TabellStakk<T>(A.antall());
while (A.antall() > 0) {
hjelp.leggInn(A.taUt());
}
while (hjelp.antall() > 0) {
temp = hjelp.kikk();
A.leggInn(temp);
B.leggInn(hjelp.taUt());
}
}
public static <T> void snu(Stakk<T> a) {
Stakk<T> hjelp = new TabellStakk<T>(a.antall());
Stakk<T> hjelp2 = new TabellStakk<T>(a.antall());
while (a.antall() != 0) {
hjelp.leggInn(a.taUt());
}
while (hjelp.antall() != 0) {
hjelp2.leggInn(hjelp.taUt());
}
while (hjelp2.antall() != 0) {
a.leggInn(hjelp2.taUt());
}
}
public static <T> void snu2(Stakk<T> a) {
T temp;
Stakk<T> hjelp = new TabellStakk<>(a.antall());
for (int i = 0; i < a.antall(); i++) {
temp = a.taUt();
while (a.antall() > i) {
hjelp.leggInn(a.taUt());
}
a.leggInn(temp);
while (hjelp.antall() > 0) a.leggInn(hjelp.taUt());
}
}
public static <T> void Kopier2(Stakk<T> a, Stakk<T> b) {
int n = a.antall();
while (n > 0) {
for (int j = 0; j < n; j++) b.leggInn(a.taUt());
T temp = b.kikk();
for (int j = 0; j < n; j++) a.leggInn(b.taUt());
b.leggInn(temp);
n--;
}
}
public static <T> void sorter(Stakk<T> A, Comparator<? super T> c){
Stakk<T> B = new TabellStakk<T>();
T temp; int n = 0;
while (!A.tom())
{
temp = A.taUt();
n = 0;
while (!B.tom() && c.compare(temp,B.kikk()) < 0)
{
n++; A.leggInn(B.taUt());
}
B.leggInn(temp);
for (int i = 0; i < n; i++) B.leggInn(A.taUt());
}
while (!B.tom()) A.leggInn(B.taUt());
}
}
| githansen/DATS2300 | src/Strukturer/TabellStakk.java | 1,505 | // pga. konverteringen: Object[] -> T[] | line_comment | nl | package Strukturer;
import java.util.*;
public class TabellStakk <T> implements Stakk<T> {
private T[] a; // en T-tabell
private int antall; // antall verdier på stakken
public TabellStakk() // konstruktør - tabellengde 8
{
this(8);
}
@SuppressWarnings("unchecked") // pga. konverteringen:<SUF>
public TabellStakk(int lengde) // valgfri tabellengde
{
if (lengde < 0)
throw new IllegalArgumentException("Negativ tabellengde!");
a = (T[]) new Object[lengde]; // oppretter tabellen
antall = 0; // stakken er tom
}
@Override
public void leggInn(T verdi) {
if (antall == a.length)
a = Arrays.copyOf(a, antall == 0 ? 1 : 2 * antall); // dobler
a[antall++] = verdi;
}
@Override
public T kikk() {
if (antall == 0) // sjekker om stakken er tom
throw new NoSuchElementException("Stakken er tom!");
return a[antall - 1]; // returnerer den øverste verdien
}
@Override
public T taUt() {
if (antall == 0) // sjekker om stakken er tom
throw new NoSuchElementException("Stakken er tom!");
antall--; // reduserer antallet
T temp = a[antall]; // tar var på det øverste objektet
a[antall] = null; // tilrettelegger for resirkulering
return temp; // returnerer den øverste verdien
}
@Override
public int antall() {
return antall;
}
@Override
public boolean tom() {
return antall == 0;
}
@Override
public void nullstill() {
for (T i : a) {
i = null;
}
antall = 0;
}
public String toString() {
StringJoiner sj = new StringJoiner(", ", "[", "]");
for(int i = antall-1; i >= 0; i--){
if(a[i] != null) sj.add(a[i].toString());
}
return sj.toString();
}
public static <T> void kopier(Stakk<T> A, Stakk<T> B) {
T temp;
Stakk<T> hjelp = new TabellStakk<T>(A.antall());
while (A.antall() > 0) {
hjelp.leggInn(A.taUt());
}
while (hjelp.antall() > 0) {
temp = hjelp.kikk();
A.leggInn(temp);
B.leggInn(hjelp.taUt());
}
}
public static <T> void snu(Stakk<T> a) {
Stakk<T> hjelp = new TabellStakk<T>(a.antall());
Stakk<T> hjelp2 = new TabellStakk<T>(a.antall());
while (a.antall() != 0) {
hjelp.leggInn(a.taUt());
}
while (hjelp.antall() != 0) {
hjelp2.leggInn(hjelp.taUt());
}
while (hjelp2.antall() != 0) {
a.leggInn(hjelp2.taUt());
}
}
public static <T> void snu2(Stakk<T> a) {
T temp;
Stakk<T> hjelp = new TabellStakk<>(a.antall());
for (int i = 0; i < a.antall(); i++) {
temp = a.taUt();
while (a.antall() > i) {
hjelp.leggInn(a.taUt());
}
a.leggInn(temp);
while (hjelp.antall() > 0) a.leggInn(hjelp.taUt());
}
}
public static <T> void Kopier2(Stakk<T> a, Stakk<T> b) {
int n = a.antall();
while (n > 0) {
for (int j = 0; j < n; j++) b.leggInn(a.taUt());
T temp = b.kikk();
for (int j = 0; j < n; j++) a.leggInn(b.taUt());
b.leggInn(temp);
n--;
}
}
public static <T> void sorter(Stakk<T> A, Comparator<? super T> c){
Stakk<T> B = new TabellStakk<T>();
T temp; int n = 0;
while (!A.tom())
{
temp = A.taUt();
n = 0;
while (!B.tom() && c.compare(temp,B.kikk()) < 0)
{
n++; A.leggInn(B.taUt());
}
B.leggInn(temp);
for (int i = 0; i < n; i++) B.leggInn(A.taUt());
}
while (!B.tom()) A.leggInn(B.taUt());
}
}
| False | 1,216 | 13 | 1,328 | 13 | 1,372 | 13 | 1,328 | 13 | 1,527 | 13 | false | false | false | false | false | true |
1,237 | 74014_3 | package HZ2_TimeOfDay;
import static org.junit.jupiter.api.Assertions.*;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
class MyMathTest {
/**
* Returns the square root (rounded down) of the given nonnegative number.
*
* @pre The given number must be nonnegative.
* | 0 <= x
* @post The result is the greatest nonnegative integer whose square is not greater than the given number.
* | 0 <= result &&
* | result * result <= x &&
* | x < (result + 1) * (result + 1)
*/
int sqrt(int x) {
int result = 0;
while ((result + 1) * (result + 1) <= x)
result++;
return result;
}
/**
* Geeft het grootste van de drie gegeven getallen terug.
*
* @post Het resultaat is groeter dan of gelijk aan de gegeven getallen.
* | result >= x && result >= y && result >= z
* @post Het resultaat is gelijk aan één van de gegeven getallen.
* | result == x || result == y || result == z
*/
int max3(int x, int y, int z) {
return x > y ? x > z ? x : z : y > z ? y : z;
}
/**
* Geeft de mediaan van de drie verschillende gegeven getallen terug.
* TODO: Schrijf volledige formele documentatie.
*/
int mediaan(int x, int y, int z) {
return 0; // TODO: Implementeer.
}
/**
* Geeft het aantal voorkomens van 'waarde' in 'getallen' terug.
* @pre Het argument `getallen` wijst naar een array; het is geen null-verwijzing.
* | getallen != null
* @post Het resultaat is gelijk aan het aantal indices in `getallen` waarop `waarde` voorkomt.
* | result == IntStream.range(0, getallen.length).filter(i -> getallen[i] == waarde).count()
*/
int tel(int[] getallen, int waarde) {
int result = 0;
for (int i = 0; i < getallen.length; i++)
if (getallen[i] == waarde)
result++;
return result;
}
/**
* Verhoogt het element op index `index` in array `array` met `bedrag`.
*
* @pre Het argument `array` wijst naar een array.
* | array != null
* @pre De gegeven index is een geldige index voor `array`.
* | 0 <= index && index < array.length
* @post De waarde in `array` op de gegeven index is gelijk aan de oude waarde plus het gegeven bedrag.
* | array[index] == old(array[index]) + bedrag
*/
void verhoogElement(int[] array, int index, int bedrag) {
array[index] += bedrag;
}
/**
* Verwisselt de elementen op de gegeven indices in de gegeven array met elkaar.
* TODO: Schrijf volledige informele en formele documentatie.
*/
void verwissel(int[] getallen, int index1, int index2) {
// TODO: Implementeer
}
/**
* Vervangt elk getal in de gegeven array door zijn negatie.
* @pre Het argument `getallen` wijst naar een array.
* | getallen != null
* @post Voor elke positie in `getallen` geldt dat de nieuwe waarde op die positie gelijk is aan de negatie van de oude waarde op die positie.
* | IntStream.range(0, getallen.length).allMatch(i -> getallen[i] == -old(getallen.clone())[i])
*/
// voeg bovenaan (tussen de package-regel en de class-regel) 'import java.util.stream.IntStream;' toe als Eclipse dit niet zelf doet.
void negatie(int[] getallen) {
for (int i = 0; i < getallen.length; i++)
getallen[i] = -getallen[i];
}
/**
* Geeft de index terug van het eerste voorkomen van `needle` in `haystack`, of -1 als `needle` niet voorkomt in `haystack`.
*
* @pre | haystack != null
* @post Als de needle zich op index 0 bevindt, dan is het resultaat gelijk aan 0 (Deze postconditie is een speciaal geval van de laatste, ter illustratie.)
* | !(haystack.length > 0 && haystack[0] == needle) || result == 0
* @post Als het resultaat -1 is, dan ...
* | result != -1 || IntStream.range(0, haystack.length).allMatch(i -> haystack[i] != needle)
* @post Als het resultaat niet -1 is, dan ...
* | result == -1 || true // VERVANG 'true' DOOR DE VOORWAARDE
*/
int find(int[] haystack, int needle) {
return 0; // TODO: Implementeer
}
/**
* Sorteert de getallen in de gegeven array van klein naar groot.
* @post VUL AAN
* | true // VUL AAN
*/
void sort(int[] values) {
// TODO: Implementeer
}
@Test
void testSqrt() {
assertEquals(3, sqrt(9));
assertEquals(0, sqrt(0));
assertEquals(3, sqrt(15));
assertEquals(4, sqrt(16));
}
@Test
void testMax3() {
assertEquals(30, max3(10, 20, 30));
assertEquals(30, max3(20, 10, 30));
assertEquals(30, max3(10, 30, 20));
assertEquals(30, max3(20, 30, 10));
assertEquals(30, max3(30, 10, 20));
assertEquals(30, max3(30, 20, 10));
}
// TODO: Schrijf grondige tests voor mediaan, verwissel, find, en sort.
@Test
void testTel() {
assertEquals(0, tel(new int[] {10, 20, 30}, 15));
assertEquals(1, tel(new int[] {10, 20, 30}, 20));
assertEquals(2, tel(new int[] {10, 20, 30, 20}, 20));
assertEquals(3, tel(new int[] {10, 20, 10, 30, 10}, 10));
}
@Test
void testVerhoogElement() {
int[] mijnArray = {10, 20, 30};
verhoogElement(mijnArray, 1, 5);
assertArrayEquals(new int[] {10, 25, 30}, mijnArray);
}
@Test
void testNegatie() {
int[] mijnArray = {10, -20, 30};
negatie(mijnArray);
assertArrayEquals(new int[] {-10, 20, -30}, mijnArray);
}
}
| OndaLH/OGP | OGP/src/HZ2_TimeOfDay/MyMathTest.java | 1,958 | /**
* Geeft het aantal voorkomens van 'waarde' in 'getallen' terug.
* @pre Het argument `getallen` wijst naar een array; het is geen null-verwijzing.
* | getallen != null
* @post Het resultaat is gelijk aan het aantal indices in `getallen` waarop `waarde` voorkomt.
* | result == IntStream.range(0, getallen.length).filter(i -> getallen[i] == waarde).count()
*/ | block_comment | nl | package HZ2_TimeOfDay;
import static org.junit.jupiter.api.Assertions.*;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
class MyMathTest {
/**
* Returns the square root (rounded down) of the given nonnegative number.
*
* @pre The given number must be nonnegative.
* | 0 <= x
* @post The result is the greatest nonnegative integer whose square is not greater than the given number.
* | 0 <= result &&
* | result * result <= x &&
* | x < (result + 1) * (result + 1)
*/
int sqrt(int x) {
int result = 0;
while ((result + 1) * (result + 1) <= x)
result++;
return result;
}
/**
* Geeft het grootste van de drie gegeven getallen terug.
*
* @post Het resultaat is groeter dan of gelijk aan de gegeven getallen.
* | result >= x && result >= y && result >= z
* @post Het resultaat is gelijk aan één van de gegeven getallen.
* | result == x || result == y || result == z
*/
int max3(int x, int y, int z) {
return x > y ? x > z ? x : z : y > z ? y : z;
}
/**
* Geeft de mediaan van de drie verschillende gegeven getallen terug.
* TODO: Schrijf volledige formele documentatie.
*/
int mediaan(int x, int y, int z) {
return 0; // TODO: Implementeer.
}
/**
* Geeft het aantal<SUF>*/
int tel(int[] getallen, int waarde) {
int result = 0;
for (int i = 0; i < getallen.length; i++)
if (getallen[i] == waarde)
result++;
return result;
}
/**
* Verhoogt het element op index `index` in array `array` met `bedrag`.
*
* @pre Het argument `array` wijst naar een array.
* | array != null
* @pre De gegeven index is een geldige index voor `array`.
* | 0 <= index && index < array.length
* @post De waarde in `array` op de gegeven index is gelijk aan de oude waarde plus het gegeven bedrag.
* | array[index] == old(array[index]) + bedrag
*/
void verhoogElement(int[] array, int index, int bedrag) {
array[index] += bedrag;
}
/**
* Verwisselt de elementen op de gegeven indices in de gegeven array met elkaar.
* TODO: Schrijf volledige informele en formele documentatie.
*/
void verwissel(int[] getallen, int index1, int index2) {
// TODO: Implementeer
}
/**
* Vervangt elk getal in de gegeven array door zijn negatie.
* @pre Het argument `getallen` wijst naar een array.
* | getallen != null
* @post Voor elke positie in `getallen` geldt dat de nieuwe waarde op die positie gelijk is aan de negatie van de oude waarde op die positie.
* | IntStream.range(0, getallen.length).allMatch(i -> getallen[i] == -old(getallen.clone())[i])
*/
// voeg bovenaan (tussen de package-regel en de class-regel) 'import java.util.stream.IntStream;' toe als Eclipse dit niet zelf doet.
void negatie(int[] getallen) {
for (int i = 0; i < getallen.length; i++)
getallen[i] = -getallen[i];
}
/**
* Geeft de index terug van het eerste voorkomen van `needle` in `haystack`, of -1 als `needle` niet voorkomt in `haystack`.
*
* @pre | haystack != null
* @post Als de needle zich op index 0 bevindt, dan is het resultaat gelijk aan 0 (Deze postconditie is een speciaal geval van de laatste, ter illustratie.)
* | !(haystack.length > 0 && haystack[0] == needle) || result == 0
* @post Als het resultaat -1 is, dan ...
* | result != -1 || IntStream.range(0, haystack.length).allMatch(i -> haystack[i] != needle)
* @post Als het resultaat niet -1 is, dan ...
* | result == -1 || true // VERVANG 'true' DOOR DE VOORWAARDE
*/
int find(int[] haystack, int needle) {
return 0; // TODO: Implementeer
}
/**
* Sorteert de getallen in de gegeven array van klein naar groot.
* @post VUL AAN
* | true // VUL AAN
*/
void sort(int[] values) {
// TODO: Implementeer
}
@Test
void testSqrt() {
assertEquals(3, sqrt(9));
assertEquals(0, sqrt(0));
assertEquals(3, sqrt(15));
assertEquals(4, sqrt(16));
}
@Test
void testMax3() {
assertEquals(30, max3(10, 20, 30));
assertEquals(30, max3(20, 10, 30));
assertEquals(30, max3(10, 30, 20));
assertEquals(30, max3(20, 30, 10));
assertEquals(30, max3(30, 10, 20));
assertEquals(30, max3(30, 20, 10));
}
// TODO: Schrijf grondige tests voor mediaan, verwissel, find, en sort.
@Test
void testTel() {
assertEquals(0, tel(new int[] {10, 20, 30}, 15));
assertEquals(1, tel(new int[] {10, 20, 30}, 20));
assertEquals(2, tel(new int[] {10, 20, 30, 20}, 20));
assertEquals(3, tel(new int[] {10, 20, 10, 30, 10}, 10));
}
@Test
void testVerhoogElement() {
int[] mijnArray = {10, 20, 30};
verhoogElement(mijnArray, 1, 5);
assertArrayEquals(new int[] {10, 25, 30}, mijnArray);
}
@Test
void testNegatie() {
int[] mijnArray = {10, -20, 30};
negatie(mijnArray);
assertArrayEquals(new int[] {-10, 20, -30}, mijnArray);
}
}
| True | 1,759 | 116 | 1,925 | 132 | 1,884 | 117 | 1,925 | 132 | 2,080 | 128 | false | false | false | false | false | true |
1,414 | 70576_15 |
import greenfoot.*;
import java.util.List;
/**
*
* @author R. Springer
*/
public class TileEngine {
public static int TILE_WIDTH;
public static int TILE_HEIGHT;
public static int SCREEN_HEIGHT;
public static int SCREEN_WIDTH;
public static int MAP_WIDTH;
public static int MAP_HEIGHT;
public static boolean isSolid = true;
private World world;
private int[][] map;
private Tile[][] generateMap;
private TileFactory tileFactory;
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
*/
public TileEngine(World world, int tileWidth, int tileHeight) {
this.world = world;
TILE_WIDTH = tileWidth;
TILE_HEIGHT = tileHeight;
SCREEN_WIDTH = world.getWidth();
SCREEN_HEIGHT = world.getHeight();
this.tileFactory = new TileFactory();
}
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
* @param map A tilemap with numbers
*/
public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) {
this(world, tileWidth, tileHeight);
this.setMap(map);
}
/**
* The setMap method used to set a map. This method also clears the previous
* map and generates a new one.
*
* @param map
*/
public void setMap(int[][] map) {
this.clearTilesWorld();
this.map = map;
MAP_HEIGHT = this.map.length;
MAP_WIDTH = this.map[0].length;
this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH];
this.generateWorld();
}
/**
* The setTileFactory sets a tilefactory. You can use this if you want to
* create you own tilefacory and use it in the class.
*
* @param tf A Tilefactory or extend of it.
*/
public void setTileFactory(TileFactory tf) {
this.tileFactory = tf;
}
/**
* Removes al the tiles from the world.
*/
public void clearTilesWorld() {
List<Tile> removeObjects = this.world.getObjects(Tile.class);
this.world.removeObjects(removeObjects);
this.map = null;
this.generateMap = null;
MAP_HEIGHT = 0;
MAP_WIDTH = 0;
}
/**
* Creates the tile world based on the TileFactory and the map icons.
*/
public void generateWorld() {
int mapID = 0;
for (int y = 0; y < MAP_HEIGHT; y++) {
for (int x = 0; x < MAP_WIDTH; x++) {
// Nummer ophalen in de int array
mapID++;
int mapIcon = this.map[y][x];
if (mapIcon == -1) {
continue;
}
// Als de mapIcon -1 is dan wordt de code hieronder overgeslagen
// Dus er wordt geen tile aangemaakt. -1 is dus geen tile;
Tile createdTile = this.tileFactory.createTile(mapIcon);
createdTile.setMapID(mapID);
createdTile.setMapIcon(mapIcon);
addTileAt(createdTile, x, y);
}
}
}
/**
* Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and
* TILE_HEIGHT
*
* @param tile The Tile
* @param colom The colom where the tile exist in the map
* @param row The row where the tile exist in the map
*/
public void addTileAt(Tile tile, int colom, int row) {
// De X en Y positie zitten het midden van de Actor.
// De tilemap genereerd een wereld gebaseerd op dat de X en Y
// positie links boven in zitten. Vandaar de we de helft van de
// breedte en hoogte optellen zodat de X en Y links boven zit voor
// het toevoegen van het object.
this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2);
// Toevoegen aan onze lokale array. Makkelijk om de tile op te halen
// op basis van een x en y positie van de map
this.generateMap[row][colom] = tile;
tile.setColom(colom);
tile.setRow(row);
}
/**
* Retrieves a tile at the location based on colom and row in the map
*
* @param colom
* @param row
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return null;
}
return this.generateMap[row][colom];
}
/**
* Retrieves a tile based on a x and y position in the world
*
* @param x X-position in the world
* @param y Y-position in the world
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
Tile tile = getTileAt(col, row);
return tile;
}
/**
* Removes tile at the given colom and row
*
* @param colom
* @param row
* @return true if the tile has successfully been removed
*/
public boolean removeTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return false;
}
Tile tile = this.generateMap[row][colom];
if (tile != null) {
this.world.removeObject(tile);
this.generateMap[row][colom] = null;
return true;
}
return false;
}
/**
* Removes tile at the given x and y position
*
* @param x X-position in the world
* @param y Y-position in the world
* @return true if the tile has successfully been removed
*/
public boolean removeTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
return removeTileAt(col, row);
}
/**
* Removes the tile based on a tile
*
* @param tile Tile from the tilemap
* @return true if the tile has successfully been removed
*/
public boolean removeTile(Tile tile) {
int colom = tile.getColom();
int row = tile.getRow();
if (colom != -1 && row != -1) {
return this.removeTileAt(colom, row);
}
return false;
}
/**
* This methode checks if a tile on a x and y position in the world is solid
* or not.
*
* @param x X-position in the world
* @param y Y-position in the world
* @return Tile at location is solid
*/
public boolean checkTileSolid(int x, int y) {
Tile tile = getTileAtXY(x, y);
if (tile != null && tile.isSolid) {
return true;
}
return false;
}
/**
* This methode returns a colom based on a x position.
*
* @param x
* @return the colom
*/
public int getColumn(int x) {
return (int) Math.floor(x / TILE_WIDTH);
}
/**
* This methode returns a row based on a y position.
*
* @param y
* @return the row
*/
public int getRow(int y) {
return (int) Math.floor(y / TILE_HEIGHT);
}
/**
* This methode returns a x position based on the colom
*
* @param col
* @return The x position
*/
public int getX(int col) {
return col * TILE_WIDTH;
}
/**
* This methode returns a y position based on the row
*
* @param row
* @return The y position
*/
public int getY(int row) {
return row * TILE_HEIGHT;
}
}
| ROCMondriaanTIN/project-greenfoot-game-ilyassahr | TileEngine.java | 2,436 | // het toevoegen van het object. | line_comment | nl |
import greenfoot.*;
import java.util.List;
/**
*
* @author R. Springer
*/
public class TileEngine {
public static int TILE_WIDTH;
public static int TILE_HEIGHT;
public static int SCREEN_HEIGHT;
public static int SCREEN_WIDTH;
public static int MAP_WIDTH;
public static int MAP_HEIGHT;
public static boolean isSolid = true;
private World world;
private int[][] map;
private Tile[][] generateMap;
private TileFactory tileFactory;
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
*/
public TileEngine(World world, int tileWidth, int tileHeight) {
this.world = world;
TILE_WIDTH = tileWidth;
TILE_HEIGHT = tileHeight;
SCREEN_WIDTH = world.getWidth();
SCREEN_HEIGHT = world.getHeight();
this.tileFactory = new TileFactory();
}
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
* @param map A tilemap with numbers
*/
public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) {
this(world, tileWidth, tileHeight);
this.setMap(map);
}
/**
* The setMap method used to set a map. This method also clears the previous
* map and generates a new one.
*
* @param map
*/
public void setMap(int[][] map) {
this.clearTilesWorld();
this.map = map;
MAP_HEIGHT = this.map.length;
MAP_WIDTH = this.map[0].length;
this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH];
this.generateWorld();
}
/**
* The setTileFactory sets a tilefactory. You can use this if you want to
* create you own tilefacory and use it in the class.
*
* @param tf A Tilefactory or extend of it.
*/
public void setTileFactory(TileFactory tf) {
this.tileFactory = tf;
}
/**
* Removes al the tiles from the world.
*/
public void clearTilesWorld() {
List<Tile> removeObjects = this.world.getObjects(Tile.class);
this.world.removeObjects(removeObjects);
this.map = null;
this.generateMap = null;
MAP_HEIGHT = 0;
MAP_WIDTH = 0;
}
/**
* Creates the tile world based on the TileFactory and the map icons.
*/
public void generateWorld() {
int mapID = 0;
for (int y = 0; y < MAP_HEIGHT; y++) {
for (int x = 0; x < MAP_WIDTH; x++) {
// Nummer ophalen in de int array
mapID++;
int mapIcon = this.map[y][x];
if (mapIcon == -1) {
continue;
}
// Als de mapIcon -1 is dan wordt de code hieronder overgeslagen
// Dus er wordt geen tile aangemaakt. -1 is dus geen tile;
Tile createdTile = this.tileFactory.createTile(mapIcon);
createdTile.setMapID(mapID);
createdTile.setMapIcon(mapIcon);
addTileAt(createdTile, x, y);
}
}
}
/**
* Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and
* TILE_HEIGHT
*
* @param tile The Tile
* @param colom The colom where the tile exist in the map
* @param row The row where the tile exist in the map
*/
public void addTileAt(Tile tile, int colom, int row) {
// De X en Y positie zitten het midden van de Actor.
// De tilemap genereerd een wereld gebaseerd op dat de X en Y
// positie links boven in zitten. Vandaar de we de helft van de
// breedte en hoogte optellen zodat de X en Y links boven zit voor
// het toevoegen<SUF>
this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2);
// Toevoegen aan onze lokale array. Makkelijk om de tile op te halen
// op basis van een x en y positie van de map
this.generateMap[row][colom] = tile;
tile.setColom(colom);
tile.setRow(row);
}
/**
* Retrieves a tile at the location based on colom and row in the map
*
* @param colom
* @param row
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return null;
}
return this.generateMap[row][colom];
}
/**
* Retrieves a tile based on a x and y position in the world
*
* @param x X-position in the world
* @param y Y-position in the world
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
Tile tile = getTileAt(col, row);
return tile;
}
/**
* Removes tile at the given colom and row
*
* @param colom
* @param row
* @return true if the tile has successfully been removed
*/
public boolean removeTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return false;
}
Tile tile = this.generateMap[row][colom];
if (tile != null) {
this.world.removeObject(tile);
this.generateMap[row][colom] = null;
return true;
}
return false;
}
/**
* Removes tile at the given x and y position
*
* @param x X-position in the world
* @param y Y-position in the world
* @return true if the tile has successfully been removed
*/
public boolean removeTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
return removeTileAt(col, row);
}
/**
* Removes the tile based on a tile
*
* @param tile Tile from the tilemap
* @return true if the tile has successfully been removed
*/
public boolean removeTile(Tile tile) {
int colom = tile.getColom();
int row = tile.getRow();
if (colom != -1 && row != -1) {
return this.removeTileAt(colom, row);
}
return false;
}
/**
* This methode checks if a tile on a x and y position in the world is solid
* or not.
*
* @param x X-position in the world
* @param y Y-position in the world
* @return Tile at location is solid
*/
public boolean checkTileSolid(int x, int y) {
Tile tile = getTileAtXY(x, y);
if (tile != null && tile.isSolid) {
return true;
}
return false;
}
/**
* This methode returns a colom based on a x position.
*
* @param x
* @return the colom
*/
public int getColumn(int x) {
return (int) Math.floor(x / TILE_WIDTH);
}
/**
* This methode returns a row based on a y position.
*
* @param y
* @return the row
*/
public int getRow(int y) {
return (int) Math.floor(y / TILE_HEIGHT);
}
/**
* This methode returns a x position based on the colom
*
* @param col
* @return The x position
*/
public int getX(int col) {
return col * TILE_WIDTH;
}
/**
* This methode returns a y position based on the row
*
* @param row
* @return The y position
*/
public int getY(int row) {
return row * TILE_HEIGHT;
}
}
| True | 1,986 | 9 | 2,087 | 10 | 2,278 | 8 | 2,101 | 10 | 2,498 | 9 | false | false | false | false | false | true |
3,761 | 17287_9 | package views;
import controllers.ScreensController;
import interfaces.ControlledScreen;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
/**
* <p>This screen is a AnchorPane and uses ControlledScreen as navigation manager
* Shows the content that is needed for the user to print the orderlists.
* uses {@link orderListPrintController} as controller<p>
*
* @author Sander
*/
public class OrderListPrintView extends AnchorPane implements ControlledScreen {
@FXML Label introLabel, exampleLabel, listLabel, amountLabel;
@FXML Button printButton;
@FXML ComboBox listItems;
@FXML TextArea listArea;
@FXML TextField txtFileName;
/**
* <p> Used for registering itself in the hashMap of the ScreensController
* to enable navigation </p>
*
* @param screensController screencontroller that it registers itself in
*/
public void setScreenController(ScreensController screensController) {
}
/**
* Constructor
*/
public OrderListPrintView() {
createView();
setUpContentPane();
}
/**
* <p> adds the style class and sets the fixed height to the screen </p>
*/
private void createView() {
getStyleClass().add("background");
setMinSize(1200, 800);
}
/**
* <p> sets up the main screen, this will be seen by the user </p>
*/
public void setUpContentPane() {
// creating the gridpane, this is where all the displayed content goes
GridPane contentPane = new GridPane();
contentPane.setLayoutX(100);
contentPane.setLayoutY(200);
/* Creating all vboxes that are used to organize the sectors used in the
* contentPane
*/
HBox introBox = new HBox();
VBox vertBox1 = new VBox();
vertBox1.setSpacing(20);
VBox vertBox2 = new VBox(10);
vertBox2.setPadding(new Insets(0, 0, 0, 40));
VBox buttonBox = new VBox();
/*
* this label is used to work around setting a placeholder for a
* tableView
*/
introLabel =
new Label("Hier kunt u de gepersonaliseerde bestellijsten uitprinten voor de klanten.");
//exampleLabel = new Label("Print voorbeeld:");
//amountLabel = new Label("Aantal bestellijsten die geprint\nzullen worden: 10");
//listLabel = new Label("Selecteer welke bestellijst u wilt uitprinten:");
// creating the buttons and setting their properties
printButton = new Button("Printen");
printButton.getStyleClass().add("form_buttons");
Label lblFileName = new Label("Bestandsnaam");
txtFileName = new TextField();
//listItems = new ComboBox();
//listArea = new TextArea();
//Add all items to their corresponding containers
buttonBox.getChildren().addAll(lblFileName, txtFileName, printButton);
buttonBox.setAlignment(Pos.BASELINE_LEFT);
vertBox2.setAlignment(Pos.CENTER);
introBox.getChildren().add(introLabel);
contentPane.add(introBox, 0, 0);
contentPane.add(buttonBox, 0, 1);
contentPane.add(vertBox2, 1, 1);
//contentPane.add(buttonBox, 1, 2);
getChildren().addAll(contentPane);
}
/**
* @return the printButton
*/
public Button getPrintButton() {
return this.printButton;
}
/**
* @return the txtFileName
*/
public TextField getTxtFileName() {
return this.txtFileName;
}
}
| mvankampen/Wijnfestijn | src/views/OrderListPrintView.java | 1,073 | //amountLabel = new Label("Aantal bestellijsten die geprint\nzullen worden: 10"); | line_comment | nl | package views;
import controllers.ScreensController;
import interfaces.ControlledScreen;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
/**
* <p>This screen is a AnchorPane and uses ControlledScreen as navigation manager
* Shows the content that is needed for the user to print the orderlists.
* uses {@link orderListPrintController} as controller<p>
*
* @author Sander
*/
public class OrderListPrintView extends AnchorPane implements ControlledScreen {
@FXML Label introLabel, exampleLabel, listLabel, amountLabel;
@FXML Button printButton;
@FXML ComboBox listItems;
@FXML TextArea listArea;
@FXML TextField txtFileName;
/**
* <p> Used for registering itself in the hashMap of the ScreensController
* to enable navigation </p>
*
* @param screensController screencontroller that it registers itself in
*/
public void setScreenController(ScreensController screensController) {
}
/**
* Constructor
*/
public OrderListPrintView() {
createView();
setUpContentPane();
}
/**
* <p> adds the style class and sets the fixed height to the screen </p>
*/
private void createView() {
getStyleClass().add("background");
setMinSize(1200, 800);
}
/**
* <p> sets up the main screen, this will be seen by the user </p>
*/
public void setUpContentPane() {
// creating the gridpane, this is where all the displayed content goes
GridPane contentPane = new GridPane();
contentPane.setLayoutX(100);
contentPane.setLayoutY(200);
/* Creating all vboxes that are used to organize the sectors used in the
* contentPane
*/
HBox introBox = new HBox();
VBox vertBox1 = new VBox();
vertBox1.setSpacing(20);
VBox vertBox2 = new VBox(10);
vertBox2.setPadding(new Insets(0, 0, 0, 40));
VBox buttonBox = new VBox();
/*
* this label is used to work around setting a placeholder for a
* tableView
*/
introLabel =
new Label("Hier kunt u de gepersonaliseerde bestellijsten uitprinten voor de klanten.");
//exampleLabel = new Label("Print voorbeeld:");
//amountLabel =<SUF>
//listLabel = new Label("Selecteer welke bestellijst u wilt uitprinten:");
// creating the buttons and setting their properties
printButton = new Button("Printen");
printButton.getStyleClass().add("form_buttons");
Label lblFileName = new Label("Bestandsnaam");
txtFileName = new TextField();
//listItems = new ComboBox();
//listArea = new TextArea();
//Add all items to their corresponding containers
buttonBox.getChildren().addAll(lblFileName, txtFileName, printButton);
buttonBox.setAlignment(Pos.BASELINE_LEFT);
vertBox2.setAlignment(Pos.CENTER);
introBox.getChildren().add(introLabel);
contentPane.add(introBox, 0, 0);
contentPane.add(buttonBox, 0, 1);
contentPane.add(vertBox2, 1, 1);
//contentPane.add(buttonBox, 1, 2);
getChildren().addAll(contentPane);
}
/**
* @return the printButton
*/
public Button getPrintButton() {
return this.printButton;
}
/**
* @return the txtFileName
*/
public TextField getTxtFileName() {
return this.txtFileName;
}
}
| False | 843 | 24 | 928 | 25 | 962 | 24 | 928 | 25 | 1,066 | 26 | false | false | false | false | false | true |
1,986 | 96975_1 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package sources.formatreaders;
import java.util.List;
import model.EmbeddedMediaObject;
import model.EmbeddedMediaObject.MediaVersion;
import model.EmbeddedMediaObject.WithMediaRights;
import model.EmbeddedMediaObject.WithMediaType;
import model.basicDataTypes.Language;
import model.basicDataTypes.LiteralOrResource;
import model.basicDataTypes.MultiLiteralOrResource;
import model.basicDataTypes.ProvenanceInfo;
import model.basicDataTypes.Resource;
import model.resources.CulturalObject;
import model.resources.CulturalObject.CulturalObjectData;
import search.FiltersFields;
import search.Sources;
import sources.FilterValuesMap;
import sources.core.Utils;
import sources.utils.JsonContextRecord;
import sources.utils.StringUtils;
public class RijksmuseumItemRecordFormatter extends CulturalRecordFormatter {
public RijksmuseumItemRecordFormatter() {
super(FilterValuesMap.getMap(Sources.Rijksmuseum));
object = new CulturalObject();
}
@Override
public CulturalObject fillObjectFrom(JsonContextRecord rec) {
CulturalObjectData model = (CulturalObjectData) object.getDescriptiveData();
rec.enterContext("artObject");
String id = rec.getStringValue("objectNumber");
Language[] language = null;
List<String> langs = rec.getStringArrayValue("language");
if (Utils.hasInfo(langs)){
language = new Language[langs.size()];
for (int i = 0; i < langs.size(); i++) {
language[i] = Language.getLanguage(langs.get(i));
}
}
if (!Utils.hasInfo(language)){
language = getLanguagesFromText(rec.getStringValue("title"),
rec.getStringValue("titles"),
rec.getStringValue("longTitle"),
rec.getStringValue("description"));
}
rec.setLanguages(language);
model.setDclanguage(StringUtils.getLiteralLanguages(language));
// List<Object> vals =
// getValuesMap().translateToCommon(CommonFilters.TYPE.getId(),
// rec.getStringValue("ProvidedCHO.type"));
// WithMediaType type = WithMediaType.getType(vals.get(0).toString());
// model.setDcidentifier(rec.getMultiLiteralOrResourceValue("dcIdentifier"));
// model.setDccoverage(rec.getMultiLiteralOrResourceValue("dcCoverage"));
// model.setDcrights(rec.getMultiLiteralOrResourceValue("dcRights"));
// model.setDctermsspatial(rec.getMultiLiteralOrResourceValue("location","classification.places"));
model.setCountry(new MultiLiteralOrResource(Language.EN,"Netherlands"));
model.setCity(new MultiLiteralOrResource(Language.EN,"Amsterdam"));
model.setCoordinates(StringUtils.getPoint("52.36", "4.885278"));
// model.setDccreated(rec.getWithDateArrayValue("dctermsCreated"));
// model.setDcformat(rec.getMultiLiteralOrResourceValue("dcFormat"));
// model.setDctermsmedium(rec.getMultiLiteralOrResourceValue("dctermsMedium"));
// model.setIsRelatedTo(rec.getMultiLiteralOrResourceValue("edmIsRelatedTo"));
model.setDccreator(rec.getMultiLiteralOrResourceValue("principalMaker"));
model.setDccontributor(rec.getMultiLiteralOrResourceValue("makers[.*].name"));
model.setKeywords(rec.getMultiLiteralOrResourceValue("classification.iconClassDescription","materials","techniques","objectTypes"));
model.setLabel(rec.getMultiLiteralValue("title", "titles","longTitle"));
model.setDescription(rec.getMultiLiteralValue("description","subTitle","scLabelLine"));
model.setDates(StringUtils.getDates(rec.getStringArrayValue("dating.year")));
List<String> types = rec.getStringArrayValue("objectTypes");
WithMediaType type = null;
for (String string : types) {
type = WithMediaType.getType(getValuesMap().translateToCommon(FiltersFields.TYPE.getFilterId(), string).get(0).toString());
if (type.isKnown()){
break;
}
}
// model.setDctype(rec.getMultiLiteralOrResourceValue("WebResource.type"));
// model.setDccontributor(rec.getMultiLiteralOrResourceValue("dcContributor"));
// LiteralOrResource rights = rec.getLiteralOrResourceValue("WebResource.rights");
// WithMediaRights withMediaRights = rights == null ? null
// : (WithMediaRights) getValuesMap().translateToCommon(CommonFilters.RIGHTS.getId(), rights.getURI())
// .get(0);
// model.getDates().addAll(rec.getWithDateArrayValue("dcDate"));
// model.setIsShownAt(rec.getLiteralOrResourceValue("Aggregation.isShownAt"));
// model.setIsShownBy(rec.getLiteralOrResourceValue("Aggregation.isShownBy"));
object.addToProvenance(new ProvenanceInfo(Sources.Rijksmuseum.toString(),
"https://www.rijksmuseum.nl/en/collection/" + id, id));
// List<String> theViews = rec.getStringArrayValue("hasView");
// model.getDates().addAll(rec.getWithDateArrayValue("year"));
Resource isShownBy = model.getIsShownBy();
String uri2 = isShownBy == null ? null : isShownBy.toString();
String uri3 = rec.getStringValue("webImage.url");
if (Utils.hasInfo(uri3)) {
EmbeddedMediaObject medThumb = new EmbeddedMediaObject();
medThumb.setUrl(uri3);
medThumb.setWidth(rec.getIntValue("webImage.width"));
medThumb.setHeight(rec.getIntValue("webImage.height"));
medThumb.setType(type);
medThumb.setOriginalRights(new LiteralOrResource("http://creativecommons.org/publicdomain/zero/1.0/deed.en"));
medThumb.setWithRights(WithMediaRights.Public);
object.addMedia(MediaVersion.Original, medThumb);
}
return object;
}
}
| ails-lab/with | app/sources/formatreaders/RijksmuseumItemRecordFormatter.java | 1,836 | // List<Object> vals = | line_comment | nl | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package sources.formatreaders;
import java.util.List;
import model.EmbeddedMediaObject;
import model.EmbeddedMediaObject.MediaVersion;
import model.EmbeddedMediaObject.WithMediaRights;
import model.EmbeddedMediaObject.WithMediaType;
import model.basicDataTypes.Language;
import model.basicDataTypes.LiteralOrResource;
import model.basicDataTypes.MultiLiteralOrResource;
import model.basicDataTypes.ProvenanceInfo;
import model.basicDataTypes.Resource;
import model.resources.CulturalObject;
import model.resources.CulturalObject.CulturalObjectData;
import search.FiltersFields;
import search.Sources;
import sources.FilterValuesMap;
import sources.core.Utils;
import sources.utils.JsonContextRecord;
import sources.utils.StringUtils;
public class RijksmuseumItemRecordFormatter extends CulturalRecordFormatter {
public RijksmuseumItemRecordFormatter() {
super(FilterValuesMap.getMap(Sources.Rijksmuseum));
object = new CulturalObject();
}
@Override
public CulturalObject fillObjectFrom(JsonContextRecord rec) {
CulturalObjectData model = (CulturalObjectData) object.getDescriptiveData();
rec.enterContext("artObject");
String id = rec.getStringValue("objectNumber");
Language[] language = null;
List<String> langs = rec.getStringArrayValue("language");
if (Utils.hasInfo(langs)){
language = new Language[langs.size()];
for (int i = 0; i < langs.size(); i++) {
language[i] = Language.getLanguage(langs.get(i));
}
}
if (!Utils.hasInfo(language)){
language = getLanguagesFromText(rec.getStringValue("title"),
rec.getStringValue("titles"),
rec.getStringValue("longTitle"),
rec.getStringValue("description"));
}
rec.setLanguages(language);
model.setDclanguage(StringUtils.getLiteralLanguages(language));
// List<Object> vals<SUF>
// getValuesMap().translateToCommon(CommonFilters.TYPE.getId(),
// rec.getStringValue("ProvidedCHO.type"));
// WithMediaType type = WithMediaType.getType(vals.get(0).toString());
// model.setDcidentifier(rec.getMultiLiteralOrResourceValue("dcIdentifier"));
// model.setDccoverage(rec.getMultiLiteralOrResourceValue("dcCoverage"));
// model.setDcrights(rec.getMultiLiteralOrResourceValue("dcRights"));
// model.setDctermsspatial(rec.getMultiLiteralOrResourceValue("location","classification.places"));
model.setCountry(new MultiLiteralOrResource(Language.EN,"Netherlands"));
model.setCity(new MultiLiteralOrResource(Language.EN,"Amsterdam"));
model.setCoordinates(StringUtils.getPoint("52.36", "4.885278"));
// model.setDccreated(rec.getWithDateArrayValue("dctermsCreated"));
// model.setDcformat(rec.getMultiLiteralOrResourceValue("dcFormat"));
// model.setDctermsmedium(rec.getMultiLiteralOrResourceValue("dctermsMedium"));
// model.setIsRelatedTo(rec.getMultiLiteralOrResourceValue("edmIsRelatedTo"));
model.setDccreator(rec.getMultiLiteralOrResourceValue("principalMaker"));
model.setDccontributor(rec.getMultiLiteralOrResourceValue("makers[.*].name"));
model.setKeywords(rec.getMultiLiteralOrResourceValue("classification.iconClassDescription","materials","techniques","objectTypes"));
model.setLabel(rec.getMultiLiteralValue("title", "titles","longTitle"));
model.setDescription(rec.getMultiLiteralValue("description","subTitle","scLabelLine"));
model.setDates(StringUtils.getDates(rec.getStringArrayValue("dating.year")));
List<String> types = rec.getStringArrayValue("objectTypes");
WithMediaType type = null;
for (String string : types) {
type = WithMediaType.getType(getValuesMap().translateToCommon(FiltersFields.TYPE.getFilterId(), string).get(0).toString());
if (type.isKnown()){
break;
}
}
// model.setDctype(rec.getMultiLiteralOrResourceValue("WebResource.type"));
// model.setDccontributor(rec.getMultiLiteralOrResourceValue("dcContributor"));
// LiteralOrResource rights = rec.getLiteralOrResourceValue("WebResource.rights");
// WithMediaRights withMediaRights = rights == null ? null
// : (WithMediaRights) getValuesMap().translateToCommon(CommonFilters.RIGHTS.getId(), rights.getURI())
// .get(0);
// model.getDates().addAll(rec.getWithDateArrayValue("dcDate"));
// model.setIsShownAt(rec.getLiteralOrResourceValue("Aggregation.isShownAt"));
// model.setIsShownBy(rec.getLiteralOrResourceValue("Aggregation.isShownBy"));
object.addToProvenance(new ProvenanceInfo(Sources.Rijksmuseum.toString(),
"https://www.rijksmuseum.nl/en/collection/" + id, id));
// List<String> theViews = rec.getStringArrayValue("hasView");
// model.getDates().addAll(rec.getWithDateArrayValue("year"));
Resource isShownBy = model.getIsShownBy();
String uri2 = isShownBy == null ? null : isShownBy.toString();
String uri3 = rec.getStringValue("webImage.url");
if (Utils.hasInfo(uri3)) {
EmbeddedMediaObject medThumb = new EmbeddedMediaObject();
medThumb.setUrl(uri3);
medThumb.setWidth(rec.getIntValue("webImage.width"));
medThumb.setHeight(rec.getIntValue("webImage.height"));
medThumb.setType(type);
medThumb.setOriginalRights(new LiteralOrResource("http://creativecommons.org/publicdomain/zero/1.0/deed.en"));
medThumb.setWithRights(WithMediaRights.Public);
object.addMedia(MediaVersion.Original, medThumb);
}
return object;
}
}
| False | 1,384 | 6 | 1,657 | 7 | 1,606 | 7 | 1,657 | 7 | 1,986 | 8 | false | false | false | false | false | true |
138 | 45760_41 | package l2f.gameserver.model.entity.achievements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.World;
/**
*
* @author Nik
*
*/
public class PlayerCounters
{
private static final Logger _log = LoggerFactory.getLogger(PlayerCounters.class);
public static PlayerCounters DUMMY_COUNTER = new PlayerCounters(null);
// Player
public int pvpKills = 0;
public int pkInARowKills = 0;
public int highestKarma = 0;
public int timesDied = 0;
public int playersRessurected = 0;
public int duelsWon = 0;
public int fameAcquired = 0;
public long expAcquired = 0;
public int recipesSucceeded = 0;
public int recipesFailed = 0;
public int manorSeedsSow = 0;
public int critsDone = 0;
public int mcritsDone = 0;
public int maxSoulCrystalLevel = 0;
public int fishCaught = 0;
public int treasureBoxesOpened = 0;
public int unrepeatableQuestsCompleted = 0;
public int repeatableQuestsCompleted = 0;
public long adenaDestroyed = 0;
public int recommendsMade = 0;
public int foundationItemsMade = 0;
public long distanceWalked = 0;
// Enchants
public int enchantNormalSucceeded = 0;
public int enchantBlessedSucceeded = 0;
public int highestEnchant = 0;
// Clan & Olympiad
public int olyHiScore = 0;
public int olyGamesWon = 0;
public int olyGamesLost = 0;
public int timesHero = 0;
public int timesMarried = 0;
public int castleSiegesWon = 0;
public int fortSiegesWon = 0;
public int dominionSiegesWon = 0;
// Epic Bosses.
public int antharasKilled = 0;
public int baiumKilled = 0;
public int valakasKilled = 0;
public int orfenKilled = 0;
public int antQueenKilled = 0;
public int coreKilled = 0;
public int belethKilled = 0;
public int sailrenKilled = 0;
public int baylorKilled = 0;
public int zakenKilled = 0;
public int tiatKilled = 0;
public int freyaKilled = 0;
public int frintezzaKilled = 0;
// Other kills
public int mobsKilled = 0;
public int raidsKilled = 0;
public int championsKilled = 0;
public int townGuardsKilled = 0;
public int siegeGuardsKilled = 0;
public int playersKilledInSiege = 0;
public int playersKilledInDominion = 0;
public int timesVoted = 0;
public int krateisCubePoints = 0;
public int krateisCubeTotalPoints = 0;
// Here comes the code...
private Player _activeChar = null;
private int _playerObjId = 0;
public PlayerCounters(Player activeChar)
{
_activeChar = activeChar;
_playerObjId = activeChar == null ? 0 : activeChar.getObjectId();
}
public PlayerCounters(int playerObjId)
{
_activeChar = World.getPlayer(playerObjId);
_playerObjId = playerObjId;
}
protected Player getChar()
{
return _activeChar;
}
public long getPoints(String fieldName)
{
if (_activeChar == null)
return 0;
try {return getClass().getField(fieldName).getLong(this);}
catch (Exception e) {e.printStackTrace();}
return 0;
}
// public void save()
// {
// if (_activeChar == null)
// return;
//
//
// // Because im SQL noob
// Connection con = null;
// Connection con2 = null;
// PreparedStatement statement2 = null;
// PreparedStatement statement3 = null;
// ResultSet rs = null;
// try
// {
// con2 = DatabaseFactory.getInstance().getConnection();
// statement2 = con2.prepareStatement("SELECT char_id FROM character_counters WHERE char_id = " + _playerObjId + ";");
// rs = statement2.executeQuery();
// if (!rs.next())
// {
// statement3 = con2.prepareStatement("INSERT INTO character_counters (char_id) values (?);");
// statement3.setInt(1, _playerObjId);
// statement3.execute();
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con2, statement2, rs);
// }
//
// PreparedStatement statement = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// StringBuilder sb = new StringBuilder();
// sb.append("UPDATE character_counters SET ");
// boolean firstPassed = false;
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we wont save.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// if (firstPassed)
// sb.append(",");
// sb.append(field.getName());
// sb.append("=");
//
// try
// {
// sb.append(field.getInt(this));
// }
// catch (IllegalArgumentException | IllegalAccessException | SecurityException e)
// {
// sb.append(field.getLong(this));
// }
//
// firstPassed = true;
// }
// sb.append(" WHERE char_id=" + _playerObjId + ";");
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement);
// }
// }
//
// public void load()
// {
// if (_activeChar == null)
// return;
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("SELECT * FROM character_counters WHERE char_id = ?");
// statement.setInt(1, getChar().getObjectId());
// rs = statement.executeQuery();
// while(rs.next())
// {
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// try
// {
// field.setInt(this, rs.getInt(field.getName()));
// }
// catch (SQLException sqle)
// {
// field.setLong(this, rs.getLong(field.getName()));
// }
// }
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// public static String generateTopHtml(String fieldName, int maxTop, boolean asc)
// {
// Map<Integer, Long> tops = loadCounter(fieldName, maxTop, asc);
// int order = 1;
//
// StringBuilder sb = new StringBuilder(tops.size() * 100);
// sb.append("<table width=300 border=0>");
// for (Entry<Integer, Long> top : tops.entrySet())
// {
// sb.append("<tr><td><table border=0 width=294 bgcolor=" + (order % 2 == 0 ? "1E1E1E" : "090909") + ">")
// .append("<tr><td fixwidth=10%><font color=LEVEL>").append(order++).append(".<font></td>")
// .append("<td fixwidth=45%>").append(CharacterDAO.getInstance().getNameByObjectId(top.getKey()))
// .append("</td><td fixwidth=45%><font color=777777>").append(top.getValue())
// .append("</font></td></tr>")
// .append("</table></td></tr>");
// }
// sb.append("</table>");
//
// return sb.toString();
// }
// public static Map<Integer, Long> loadCounter(String fieldName, int maxRetrieved, boolean asc)
// {
// Map<Integer, Long> ret = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try(Connection con = DatabaseFactory.getInstance().getConnection())
// {
// statement = con.prepareStatement("SELECT char_id, " + fieldName + " FROM character_counters ORDER BY " + fieldName + " " + (asc ? "ASC" : "DESC") + " LIMIT 0, " + maxRetrieved + ";");
// rs = statement.executeQuery();
// ret = new LinkedHashMap<Integer, Long>(rs.getFetchSize());
// while (rs.next())
// {
// int charObjId = rs.getInt(1);
// long value = rs.getLong(2);
// ret.put(charObjId, value);
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(null, statement, rs);
// }
//
// return ret == null ? Collections.emptyMap() : ret;
// }
//
// public static void checkTable()
// {
// // Generate used fields list.
// List<String> fieldNames = new ArrayList<String>();
// for (Field field : PlayerCounters.class.getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// default:
// fieldNames.add(field.getName());
// }
// }
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("DESC character_counters");
// rs = statement.executeQuery();
// while(rs.next())
// {
// //_log.info("Checking column: " + rs.getString(1));
// fieldNames.remove(rs.getString(1));
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
//
// if (!fieldNames.isEmpty())
// {
// StringBuilder sb = new StringBuilder(fieldNames.size() * 30);
//
// try
// {
// sb.append("ALTER TABLE character_counters");
// for (String str : fieldNames)
// {
// _log.info("PlayerCounters Update: Adding missing column name: " + str);
//
// Class<?> fieldType = PlayerCounters.class.getField(str).getType();
// if (fieldType == int.class || fieldType == Integer.class)
// sb.append(" ADD COLUMN " + str + " int(11) NOT NULL DEFAULT 0,");
// else if (fieldType == long.class || fieldType == Long.class)
// sb.append(" ADD COLUMN " + str + " bigint(20) NOT NULL DEFAULT 0,");
// else
// _log.warn("Unsupported data type: " + fieldType);
//
// }
// sb.setCharAt(sb.length() - 1, ';');
//
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// _log.info("PlayerCounters Update: Changes executed!");
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// }
}
| Arodev76/L2Advanced | src/main/java/l2f/gameserver/model/entity/achievements/PlayerCounters.java | 3,636 | // int order = 1; | line_comment | nl | package l2f.gameserver.model.entity.achievements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.World;
/**
*
* @author Nik
*
*/
public class PlayerCounters
{
private static final Logger _log = LoggerFactory.getLogger(PlayerCounters.class);
public static PlayerCounters DUMMY_COUNTER = new PlayerCounters(null);
// Player
public int pvpKills = 0;
public int pkInARowKills = 0;
public int highestKarma = 0;
public int timesDied = 0;
public int playersRessurected = 0;
public int duelsWon = 0;
public int fameAcquired = 0;
public long expAcquired = 0;
public int recipesSucceeded = 0;
public int recipesFailed = 0;
public int manorSeedsSow = 0;
public int critsDone = 0;
public int mcritsDone = 0;
public int maxSoulCrystalLevel = 0;
public int fishCaught = 0;
public int treasureBoxesOpened = 0;
public int unrepeatableQuestsCompleted = 0;
public int repeatableQuestsCompleted = 0;
public long adenaDestroyed = 0;
public int recommendsMade = 0;
public int foundationItemsMade = 0;
public long distanceWalked = 0;
// Enchants
public int enchantNormalSucceeded = 0;
public int enchantBlessedSucceeded = 0;
public int highestEnchant = 0;
// Clan & Olympiad
public int olyHiScore = 0;
public int olyGamesWon = 0;
public int olyGamesLost = 0;
public int timesHero = 0;
public int timesMarried = 0;
public int castleSiegesWon = 0;
public int fortSiegesWon = 0;
public int dominionSiegesWon = 0;
// Epic Bosses.
public int antharasKilled = 0;
public int baiumKilled = 0;
public int valakasKilled = 0;
public int orfenKilled = 0;
public int antQueenKilled = 0;
public int coreKilled = 0;
public int belethKilled = 0;
public int sailrenKilled = 0;
public int baylorKilled = 0;
public int zakenKilled = 0;
public int tiatKilled = 0;
public int freyaKilled = 0;
public int frintezzaKilled = 0;
// Other kills
public int mobsKilled = 0;
public int raidsKilled = 0;
public int championsKilled = 0;
public int townGuardsKilled = 0;
public int siegeGuardsKilled = 0;
public int playersKilledInSiege = 0;
public int playersKilledInDominion = 0;
public int timesVoted = 0;
public int krateisCubePoints = 0;
public int krateisCubeTotalPoints = 0;
// Here comes the code...
private Player _activeChar = null;
private int _playerObjId = 0;
public PlayerCounters(Player activeChar)
{
_activeChar = activeChar;
_playerObjId = activeChar == null ? 0 : activeChar.getObjectId();
}
public PlayerCounters(int playerObjId)
{
_activeChar = World.getPlayer(playerObjId);
_playerObjId = playerObjId;
}
protected Player getChar()
{
return _activeChar;
}
public long getPoints(String fieldName)
{
if (_activeChar == null)
return 0;
try {return getClass().getField(fieldName).getLong(this);}
catch (Exception e) {e.printStackTrace();}
return 0;
}
// public void save()
// {
// if (_activeChar == null)
// return;
//
//
// // Because im SQL noob
// Connection con = null;
// Connection con2 = null;
// PreparedStatement statement2 = null;
// PreparedStatement statement3 = null;
// ResultSet rs = null;
// try
// {
// con2 = DatabaseFactory.getInstance().getConnection();
// statement2 = con2.prepareStatement("SELECT char_id FROM character_counters WHERE char_id = " + _playerObjId + ";");
// rs = statement2.executeQuery();
// if (!rs.next())
// {
// statement3 = con2.prepareStatement("INSERT INTO character_counters (char_id) values (?);");
// statement3.setInt(1, _playerObjId);
// statement3.execute();
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con2, statement2, rs);
// }
//
// PreparedStatement statement = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// StringBuilder sb = new StringBuilder();
// sb.append("UPDATE character_counters SET ");
// boolean firstPassed = false;
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we wont save.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// if (firstPassed)
// sb.append(",");
// sb.append(field.getName());
// sb.append("=");
//
// try
// {
// sb.append(field.getInt(this));
// }
// catch (IllegalArgumentException | IllegalAccessException | SecurityException e)
// {
// sb.append(field.getLong(this));
// }
//
// firstPassed = true;
// }
// sb.append(" WHERE char_id=" + _playerObjId + ";");
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement);
// }
// }
//
// public void load()
// {
// if (_activeChar == null)
// return;
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("SELECT * FROM character_counters WHERE char_id = ?");
// statement.setInt(1, getChar().getObjectId());
// rs = statement.executeQuery();
// while(rs.next())
// {
// for (Field field : getClass().getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// }
//
// try
// {
// field.setInt(this, rs.getInt(field.getName()));
// }
// catch (SQLException sqle)
// {
// field.setLong(this, rs.getLong(field.getName()));
// }
// }
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// public static String generateTopHtml(String fieldName, int maxTop, boolean asc)
// {
// Map<Integer, Long> tops = loadCounter(fieldName, maxTop, asc);
// int order<SUF>
//
// StringBuilder sb = new StringBuilder(tops.size() * 100);
// sb.append("<table width=300 border=0>");
// for (Entry<Integer, Long> top : tops.entrySet())
// {
// sb.append("<tr><td><table border=0 width=294 bgcolor=" + (order % 2 == 0 ? "1E1E1E" : "090909") + ">")
// .append("<tr><td fixwidth=10%><font color=LEVEL>").append(order++).append(".<font></td>")
// .append("<td fixwidth=45%>").append(CharacterDAO.getInstance().getNameByObjectId(top.getKey()))
// .append("</td><td fixwidth=45%><font color=777777>").append(top.getValue())
// .append("</font></td></tr>")
// .append("</table></td></tr>");
// }
// sb.append("</table>");
//
// return sb.toString();
// }
// public static Map<Integer, Long> loadCounter(String fieldName, int maxRetrieved, boolean asc)
// {
// Map<Integer, Long> ret = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try(Connection con = DatabaseFactory.getInstance().getConnection())
// {
// statement = con.prepareStatement("SELECT char_id, " + fieldName + " FROM character_counters ORDER BY " + fieldName + " " + (asc ? "ASC" : "DESC") + " LIMIT 0, " + maxRetrieved + ";");
// rs = statement.executeQuery();
// ret = new LinkedHashMap<Integer, Long>(rs.getFetchSize());
// while (rs.next())
// {
// int charObjId = rs.getInt(1);
// long value = rs.getLong(2);
// ret.put(charObjId, value);
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(null, statement, rs);
// }
//
// return ret == null ? Collections.emptyMap() : ret;
// }
//
// public static void checkTable()
// {
// // Generate used fields list.
// List<String> fieldNames = new ArrayList<String>();
// for (Field field : PlayerCounters.class.getFields())
// {
// switch (field.getName()) // Fields that we dont use here.
// {
// case "_activeChar":
// case "_playerObjId":
// case "DUMMY_COUNTER":
// continue;
// default:
// fieldNames.add(field.getName());
// }
// }
//
// Connection con = null;
// PreparedStatement statement = null;
// ResultSet rs = null;
// try
// {
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement("DESC character_counters");
// rs = statement.executeQuery();
// while(rs.next())
// {
// //_log.info("Checking column: " + rs.getString(1));
// fieldNames.remove(rs.getString(1));
// }
// }
// catch(Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
//
// if (!fieldNames.isEmpty())
// {
// StringBuilder sb = new StringBuilder(fieldNames.size() * 30);
//
// try
// {
// sb.append("ALTER TABLE character_counters");
// for (String str : fieldNames)
// {
// _log.info("PlayerCounters Update: Adding missing column name: " + str);
//
// Class<?> fieldType = PlayerCounters.class.getField(str).getType();
// if (fieldType == int.class || fieldType == Integer.class)
// sb.append(" ADD COLUMN " + str + " int(11) NOT NULL DEFAULT 0,");
// else if (fieldType == long.class || fieldType == Long.class)
// sb.append(" ADD COLUMN " + str + " bigint(20) NOT NULL DEFAULT 0,");
// else
// _log.warn("Unsupported data type: " + fieldType);
//
// }
// sb.setCharAt(sb.length() - 1, ';');
//
// con = DatabaseFactory.getInstance().getConnection();
// statement = con.prepareStatement(sb.toString());
// statement.execute();
// _log.info("PlayerCounters Update: Changes executed!");
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// DbUtils.closeQuietly(con, statement, rs);
// }
// }
// }
}
| False | 2,776 | 8 | 3,514 | 9 | 3,234 | 8 | 3,514 | 9 | 4,068 | 9 | false | false | false | false | false | true |
3,884 | 68057_2 | package edu.nps.moves.dis7;
import java.io.*;
/**
* Not specified in the standard. This is used by the ESPDU
*
* Copyright (c) 2008-2016, MOVES Institute, Naval Postgraduate School. All
* rights reserved. This work is licensed under the BSD open source license,
* available at https://www.movesinstitute.org/licenses/bsd.html
*
* @author DMcG
*/
public class DeadReckoningParameters extends Object implements Serializable {
/**
* Algorithm to use in computing dead reckoning. See EBV doc.
*/
protected short deadReckoningAlgorithm;
/**
* Dead reckoning parameters. Contents depends on algorithm.
*/
protected short[] parameters = new short[15];
/**
* Linear acceleration of the entity
*/
protected Vector3Float entityLinearAcceleration = new Vector3Float();
/**
* Angular velocity of the entity
*/
protected Vector3Float entityAngularVelocity = new Vector3Float();
/**
* Constructor
*/
public DeadReckoningParameters() {
}
public int getMarshalledSize() {
int marshalSize = 0;
marshalSize = marshalSize + 1; // deadReckoningAlgorithm
marshalSize = marshalSize + 15 * 1; // parameters
marshalSize = marshalSize + entityLinearAcceleration.getMarshalledSize(); // entityLinearAcceleration
marshalSize = marshalSize + entityAngularVelocity.getMarshalledSize(); // entityAngularVelocity
return marshalSize;
}
public void setDeadReckoningAlgorithm(short pDeadReckoningAlgorithm) {
deadReckoningAlgorithm = pDeadReckoningAlgorithm;
}
public short getDeadReckoningAlgorithm() {
return deadReckoningAlgorithm;
}
public void setParameters(short[] pParameters) {
parameters = pParameters;
}
public short[] getParameters() {
return parameters;
}
public void setEntityLinearAcceleration(Vector3Float pEntityLinearAcceleration) {
entityLinearAcceleration = pEntityLinearAcceleration;
}
public Vector3Float getEntityLinearAcceleration() {
return entityLinearAcceleration;
}
public void setEntityAngularVelocity(Vector3Float pEntityAngularVelocity) {
entityAngularVelocity = pEntityAngularVelocity;
}
public Vector3Float getEntityAngularVelocity() {
return entityAngularVelocity;
}
public void marshal(DataOutputStream dos) {
try {
dos.writeByte((byte) deadReckoningAlgorithm);
for (int idx = 0; idx < parameters.length; idx++) {
dos.writeByte(parameters[idx]);
} // end of array marshaling
entityLinearAcceleration.marshal(dos);
entityAngularVelocity.marshal(dos);
} // end try
catch (Exception e) {
System.out.println(e);
}
} // end of marshal method
public void unmarshal(DataInputStream dis) {
try {
deadReckoningAlgorithm = (short) dis.readUnsignedByte();
for (int idx = 0; idx < parameters.length; idx++) {
parameters[idx] = dis.readByte();
} // end of array unmarshaling
entityLinearAcceleration.unmarshal(dis);
entityAngularVelocity.unmarshal(dis);
} // end try
catch (Exception e) {
System.out.println(e);
}
} // end of unmarshal method
/**
* Packs a Pdu into the ByteBuffer.
*
* @throws java.nio.BufferOverflowException if buff is too small
* @throws java.nio.ReadOnlyBufferException if buff is read only
* @see java.nio.ByteBuffer
* @param buff The ByteBuffer at the position to begin writing
* @since ??
*/
public void marshal(java.nio.ByteBuffer buff) {
buff.put((byte) deadReckoningAlgorithm);
for (int idx = 0; idx < parameters.length; idx++) {
buff.put((byte) parameters[idx]);
} // end of array marshaling
entityLinearAcceleration.marshal(buff);
entityAngularVelocity.marshal(buff);
} // end of marshal method
/**
* Unpacks a Pdu from the underlying data.
*
* @throws java.nio.BufferUnderflowException if buff is too small
* @see java.nio.ByteBuffer
* @param buff The ByteBuffer at the position to begin reading
* @since ??
*/
public void unmarshal(java.nio.ByteBuffer buff) {
deadReckoningAlgorithm = (short) (buff.get() & 0xFF);
for (int idx = 0; idx < parameters.length; idx++) {
parameters[idx] = buff.get();
} // end of array unmarshaling
entityLinearAcceleration.unmarshal(buff);
entityAngularVelocity.unmarshal(buff);
} // end of unmarshal method
/*
* The equals method doesn't always work--mostly it works only on classes that consist only of primitives. Be careful.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return equalsImpl(obj);
}
/**
* Compare all fields that contribute to the state, ignoring transient and
* static fields, for <code>this</code> and the supplied object
*
* @param obj the object to compare to
* @return true if the objects are equal, false otherwise.
*/
public boolean equalsImpl(Object obj) {
boolean ivarsEqual = true;
if (!(obj instanceof DeadReckoningParameters)) {
return false;
}
final DeadReckoningParameters rhs = (DeadReckoningParameters) obj;
if (!(deadReckoningAlgorithm == rhs.deadReckoningAlgorithm)) {
ivarsEqual = false;
}
for (int idx = 0; idx < 15; idx++) {
if (!(parameters[idx] == rhs.parameters[idx])) {
ivarsEqual = false;
}
}
if (!(entityLinearAcceleration.equals(rhs.entityLinearAcceleration))) {
ivarsEqual = false;
}
if (!(entityAngularVelocity.equals(rhs.entityAngularVelocity))) {
ivarsEqual = false;
}
return ivarsEqual;
}
} // end of class
| open-dis/open-dis-java | src/main/java/edu/nps/moves/dis7/DeadReckoningParameters.java | 1,775 | /**
* Dead reckoning parameters. Contents depends on algorithm.
*/ | block_comment | nl | package edu.nps.moves.dis7;
import java.io.*;
/**
* Not specified in the standard. This is used by the ESPDU
*
* Copyright (c) 2008-2016, MOVES Institute, Naval Postgraduate School. All
* rights reserved. This work is licensed under the BSD open source license,
* available at https://www.movesinstitute.org/licenses/bsd.html
*
* @author DMcG
*/
public class DeadReckoningParameters extends Object implements Serializable {
/**
* Algorithm to use in computing dead reckoning. See EBV doc.
*/
protected short deadReckoningAlgorithm;
/**
* Dead reckoning parameters.<SUF>*/
protected short[] parameters = new short[15];
/**
* Linear acceleration of the entity
*/
protected Vector3Float entityLinearAcceleration = new Vector3Float();
/**
* Angular velocity of the entity
*/
protected Vector3Float entityAngularVelocity = new Vector3Float();
/**
* Constructor
*/
public DeadReckoningParameters() {
}
public int getMarshalledSize() {
int marshalSize = 0;
marshalSize = marshalSize + 1; // deadReckoningAlgorithm
marshalSize = marshalSize + 15 * 1; // parameters
marshalSize = marshalSize + entityLinearAcceleration.getMarshalledSize(); // entityLinearAcceleration
marshalSize = marshalSize + entityAngularVelocity.getMarshalledSize(); // entityAngularVelocity
return marshalSize;
}
public void setDeadReckoningAlgorithm(short pDeadReckoningAlgorithm) {
deadReckoningAlgorithm = pDeadReckoningAlgorithm;
}
public short getDeadReckoningAlgorithm() {
return deadReckoningAlgorithm;
}
public void setParameters(short[] pParameters) {
parameters = pParameters;
}
public short[] getParameters() {
return parameters;
}
public void setEntityLinearAcceleration(Vector3Float pEntityLinearAcceleration) {
entityLinearAcceleration = pEntityLinearAcceleration;
}
public Vector3Float getEntityLinearAcceleration() {
return entityLinearAcceleration;
}
public void setEntityAngularVelocity(Vector3Float pEntityAngularVelocity) {
entityAngularVelocity = pEntityAngularVelocity;
}
public Vector3Float getEntityAngularVelocity() {
return entityAngularVelocity;
}
public void marshal(DataOutputStream dos) {
try {
dos.writeByte((byte) deadReckoningAlgorithm);
for (int idx = 0; idx < parameters.length; idx++) {
dos.writeByte(parameters[idx]);
} // end of array marshaling
entityLinearAcceleration.marshal(dos);
entityAngularVelocity.marshal(dos);
} // end try
catch (Exception e) {
System.out.println(e);
}
} // end of marshal method
public void unmarshal(DataInputStream dis) {
try {
deadReckoningAlgorithm = (short) dis.readUnsignedByte();
for (int idx = 0; idx < parameters.length; idx++) {
parameters[idx] = dis.readByte();
} // end of array unmarshaling
entityLinearAcceleration.unmarshal(dis);
entityAngularVelocity.unmarshal(dis);
} // end try
catch (Exception e) {
System.out.println(e);
}
} // end of unmarshal method
/**
* Packs a Pdu into the ByteBuffer.
*
* @throws java.nio.BufferOverflowException if buff is too small
* @throws java.nio.ReadOnlyBufferException if buff is read only
* @see java.nio.ByteBuffer
* @param buff The ByteBuffer at the position to begin writing
* @since ??
*/
public void marshal(java.nio.ByteBuffer buff) {
buff.put((byte) deadReckoningAlgorithm);
for (int idx = 0; idx < parameters.length; idx++) {
buff.put((byte) parameters[idx]);
} // end of array marshaling
entityLinearAcceleration.marshal(buff);
entityAngularVelocity.marshal(buff);
} // end of marshal method
/**
* Unpacks a Pdu from the underlying data.
*
* @throws java.nio.BufferUnderflowException if buff is too small
* @see java.nio.ByteBuffer
* @param buff The ByteBuffer at the position to begin reading
* @since ??
*/
public void unmarshal(java.nio.ByteBuffer buff) {
deadReckoningAlgorithm = (short) (buff.get() & 0xFF);
for (int idx = 0; idx < parameters.length; idx++) {
parameters[idx] = buff.get();
} // end of array unmarshaling
entityLinearAcceleration.unmarshal(buff);
entityAngularVelocity.unmarshal(buff);
} // end of unmarshal method
/*
* The equals method doesn't always work--mostly it works only on classes that consist only of primitives. Be careful.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return equalsImpl(obj);
}
/**
* Compare all fields that contribute to the state, ignoring transient and
* static fields, for <code>this</code> and the supplied object
*
* @param obj the object to compare to
* @return true if the objects are equal, false otherwise.
*/
public boolean equalsImpl(Object obj) {
boolean ivarsEqual = true;
if (!(obj instanceof DeadReckoningParameters)) {
return false;
}
final DeadReckoningParameters rhs = (DeadReckoningParameters) obj;
if (!(deadReckoningAlgorithm == rhs.deadReckoningAlgorithm)) {
ivarsEqual = false;
}
for (int idx = 0; idx < 15; idx++) {
if (!(parameters[idx] == rhs.parameters[idx])) {
ivarsEqual = false;
}
}
if (!(entityLinearAcceleration.equals(rhs.entityLinearAcceleration))) {
ivarsEqual = false;
}
if (!(entityAngularVelocity.equals(rhs.entityAngularVelocity))) {
ivarsEqual = false;
}
return ivarsEqual;
}
} // end of class
| False | 1,380 | 15 | 1,434 | 16 | 1,562 | 16 | 1,434 | 16 | 1,808 | 18 | false | false | false | false | false | true |
3,728 | 39965_6 | _x000D_
package domeinLaag;_x000D_
_x000D_
// Imports_x000D_
import java.util.HashSet;_x000D_
import java.util.Iterator;_x000D_
import java.util.TreeMap;_x000D_
_x000D_
/**_x000D_
* Een object van deze klasse representeert één luchthaven._x000D_
* Een Luchthaven heeft een naam en een code (afkorting)._x000D_
* Eventueel heeft de luchthaven ook een werkplaats._x000D_
* Tot slot ligt de luchthaven in een land._x000D_
*/_x000D_
public class Luchthaven_x000D_
{_x000D_
// Attributes_x000D_
private String naam = ""; // De naam van de luchthaven._x000D_
private String code = ""; // De code (afkorting) van de luchthaven._x000D_
private boolean werkPlaats = false; // Of de luchthaven een werkplaats heeft of niet._x000D_
_x000D_
// Relaties_x000D_
private Land land; // In welk land de luchthaven ligt._x000D_
private static HashSet<Luchthaven> alleLuchthavens = new HashSet<Luchthaven>(); // Een statische HashSet van alle luchthavens._x000D_
_x000D_
// Constructors_x000D_
/**_x000D_
* Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt door Main om de boel even te vullen._x000D_
* Dit zodat er ook wat te testen valt._x000D_
* @param nm de naam van de luchthaven_x000D_
* @param cd de code (afkorting) van de luchthaven_x000D_
* @param wp true als de luchthaven een werkplaats heeft, anders false_x000D_
* @param ln het land waar de luchthaven in ligt_x000D_
*/_x000D_
public Luchthaven (String nm, String cd, boolean wp, Land ln)_x000D_
{_x000D_
this.naam = nm;_x000D_
this.code = cd;_x000D_
this.werkPlaats = wp;_x000D_
this.land = ln;_x000D_
alleLuchthavens.add(this);_x000D_
land.addLuchthaven(this);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt om in_x000D_
* de RegLuchthavenController. De diverse attributen worden met zet-methoden naderhand gevuld._x000D_
*/_x000D_
public Luchthaven ()_x000D_
{_x000D_
} _x000D_
_x000D_
// Setters_x000D_
/**_x000D_
* Deze methode zet de naam van het Luchthaven._x000D_
* @param nm de naam van de Luchthaven_x000D_
* @throws java.lang.IllegalArgumentException als de naam al bestaat in dat land_x000D_
* of als de naam geen geldige waarde heeft_x000D_
*/_x000D_
public void setNaam (String nm) throws IllegalArgumentException_x000D_
{_x000D_
if (land.getLuchthavens().get(nm.trim()) != null)_x000D_
{_x000D_
throw new IllegalArgumentException("Naam bestaat al!");_x000D_
}_x000D_
else if (nm.trim().length() == 0)_x000D_
{_x000D_
throw new IllegalArgumentException("Naam heeft geen geldige waarde!");_x000D_
}_x000D_
else_x000D_
{_x000D_
this.naam = nm.trim();_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze methode zet de code (afkorting) van de Luchthaven._x000D_
* @param code de code (afkorting) van de Luchthaven_x000D_
*/_x000D_
public void setCode (String code)_x000D_
{_x000D_
this.code = code;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze methode zet het land waar de Luchthaven in ligt._x000D_
* Hiertoe moet ook een aanpassing gedaan worden in het land._x000D_
* Eerst moet de luchthaven namelijk uit het oude land verwijderd worden._x000D_
* Het toevoegen aan het nieuwe land (en het verwijderen uit het oude) hoeft_x000D_
* alleen te gebeuren als de luchthaven al aan alleLuchthavens toegevoegd._x000D_
* Zo niet, dan deze luchthaven namelijk nog nooit bewaard._x000D_
* @param land het land waar de Luchthaven in ligt_x000D_
*/_x000D_
public void setLand (Land land)_x000D_
{_x000D_
if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard._x000D_
{_x000D_
this.land.removeLuchthaven(this); // Eerst de luchthaven verwijderen uit het oude land._x000D_
}_x000D_
this.land = land; // Vervolgens het land veranderen._x000D_
if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard._x000D_
{_x000D_
this.land.addLuchthaven(this); // Tot slot de luchthaven toevoegen aan het nieuwe land._x000D_
}_x000D_
} _x000D_
_x000D_
/**_x000D_
* Deze methode zet of de Luchthaven een werkplaats heeft of niet._x000D_
* @param wp true als de Luchthaven een werkplaats heeft en anders false_x000D_
*/_x000D_
public void setWerkPlaats (boolean wp)_x000D_
{_x000D_
werkPlaats = wp;_x000D_
} _x000D_
_x000D_
// Getters_x000D_
/**_x000D_
* Deze methode geeft de naam van de Luchthaven._x000D_
* @return de naam van de Luchthaven_x000D_
*/_x000D_
public String getNaam ()_x000D_
{_x000D_
return naam;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze methode geeft de code van de Luchthaven._x000D_
* @return de code (afkorting) van de Luchthaven_x000D_
*/_x000D_
public String getCode ()_x000D_
{_x000D_
return this.code;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze methode geeft true als er een werkplaats is en anders false._x000D_
* @return true als er een werkplaats is op de Luchthaven_x000D_
*/_x000D_
public boolean getWerkPlaats ()_x000D_
{_x000D_
return werkPlaats;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze methode geeft het Land waar de Luchthaven ligt._x000D_
* @return het Land waar de Luchthaven ligt_x000D_
*/_x000D_
public Land getLand ()_x000D_
{_x000D_
return land;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze statische methode geeft alle luchthavennamen en Luchthavens terug._x000D_
* @return een TreeMap van luchthavennamen en Luchthavens_x000D_
*/_x000D_
public static TreeMap<String, Luchthaven> getAlleLuchthavens ()_x000D_
{_x000D_
TreeMap<String, Luchthaven> alleLh = new TreeMap<String, Luchthaven>();_x000D_
for (Iterator<Luchthaven> i = alleLuchthavens.iterator(); i.hasNext();)_x000D_
{_x000D_
Luchthaven lh = i.next();_x000D_
alleLh.put(lh.naam, lh);_x000D_
}_x000D_
return alleLh;_x000D_
} _x000D_
_x000D_
// Overige Methodes_x000D_
/**_x000D_
* Deze methode bewaart deze Luchthaven door hem toe te voegen aan de Luchthavens van het land en alleLuchthavens._x000D_
* @throws domeinLaag.LuchthavenException als nog niet alle attributen een waarde hebben_x000D_
*/_x000D_
public void bewaar () throws LuchthavenException_x000D_
{_x000D_
if (land == null)_x000D_
{_x000D_
throw new LuchthavenException("Land niet ingevuld!");_x000D_
}_x000D_
else if (naam.isEmpty())_x000D_
{_x000D_
throw new LuchthavenException("Naam niet ingevuld!");_x000D_
}_x000D_
else if (code.isEmpty())_x000D_
{_x000D_
throw new LuchthavenException("Code niet ingevuld!");_x000D_
}_x000D_
else_x000D_
{_x000D_
alleLuchthavens.add(this);_x000D_
land.addLuchthaven(this);_x000D_
}_x000D_
}_x000D_
}_x000D_
| mpkossen/1ooto1project | src/domeinLaag/Luchthaven.java | 2,024 | /**_x000D_
* Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt door Main om de boel even te vullen._x000D_
* Dit zodat er ook wat te testen valt._x000D_
* @param nm de naam van de luchthaven_x000D_
* @param cd de code (afkorting) van de luchthaven_x000D_
* @param wp true als de luchthaven een werkplaats heeft, anders false_x000D_
* @param ln het land waar de luchthaven in ligt_x000D_
*/ | block_comment | nl | _x000D_
package domeinLaag;_x000D_
_x000D_
// Imports_x000D_
import java.util.HashSet;_x000D_
import java.util.Iterator;_x000D_
import java.util.TreeMap;_x000D_
_x000D_
/**_x000D_
* Een object van deze klasse representeert één luchthaven._x000D_
* Een Luchthaven heeft een naam en een code (afkorting)._x000D_
* Eventueel heeft de luchthaven ook een werkplaats._x000D_
* Tot slot ligt de luchthaven in een land._x000D_
*/_x000D_
public class Luchthaven_x000D_
{_x000D_
// Attributes_x000D_
private String naam = ""; // De naam van de luchthaven._x000D_
private String code = ""; // De code (afkorting) van de luchthaven._x000D_
private boolean werkPlaats = false; // Of de luchthaven een werkplaats heeft of niet._x000D_
_x000D_
// Relaties_x000D_
private Land land; // In welk land de luchthaven ligt._x000D_
private static HashSet<Luchthaven> alleLuchthavens = new HashSet<Luchthaven>(); // Een statische HashSet van alle luchthavens._x000D_
_x000D_
// Constructors_x000D_
/**_x000D_
* Constructor voor het<SUF>*/_x000D_
public Luchthaven (String nm, String cd, boolean wp, Land ln)_x000D_
{_x000D_
this.naam = nm;_x000D_
this.code = cd;_x000D_
this.werkPlaats = wp;_x000D_
this.land = ln;_x000D_
alleLuchthavens.add(this);_x000D_
land.addLuchthaven(this);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Constructor voor het aanmaken van een Luchthaven. Wordt gebruikt om in_x000D_
* de RegLuchthavenController. De diverse attributen worden met zet-methoden naderhand gevuld._x000D_
*/_x000D_
public Luchthaven ()_x000D_
{_x000D_
} _x000D_
_x000D_
// Setters_x000D_
/**_x000D_
* Deze methode zet de naam van het Luchthaven._x000D_
* @param nm de naam van de Luchthaven_x000D_
* @throws java.lang.IllegalArgumentException als de naam al bestaat in dat land_x000D_
* of als de naam geen geldige waarde heeft_x000D_
*/_x000D_
public void setNaam (String nm) throws IllegalArgumentException_x000D_
{_x000D_
if (land.getLuchthavens().get(nm.trim()) != null)_x000D_
{_x000D_
throw new IllegalArgumentException("Naam bestaat al!");_x000D_
}_x000D_
else if (nm.trim().length() == 0)_x000D_
{_x000D_
throw new IllegalArgumentException("Naam heeft geen geldige waarde!");_x000D_
}_x000D_
else_x000D_
{_x000D_
this.naam = nm.trim();_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze methode zet de code (afkorting) van de Luchthaven._x000D_
* @param code de code (afkorting) van de Luchthaven_x000D_
*/_x000D_
public void setCode (String code)_x000D_
{_x000D_
this.code = code;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze methode zet het land waar de Luchthaven in ligt._x000D_
* Hiertoe moet ook een aanpassing gedaan worden in het land._x000D_
* Eerst moet de luchthaven namelijk uit het oude land verwijderd worden._x000D_
* Het toevoegen aan het nieuwe land (en het verwijderen uit het oude) hoeft_x000D_
* alleen te gebeuren als de luchthaven al aan alleLuchthavens toegevoegd._x000D_
* Zo niet, dan deze luchthaven namelijk nog nooit bewaard._x000D_
* @param land het land waar de Luchthaven in ligt_x000D_
*/_x000D_
public void setLand (Land land)_x000D_
{_x000D_
if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard._x000D_
{_x000D_
this.land.removeLuchthaven(this); // Eerst de luchthaven verwijderen uit het oude land._x000D_
}_x000D_
this.land = land; // Vervolgens het land veranderen._x000D_
if (alleLuchthavens.contains(this)) // Indien true het land al eens bewaard._x000D_
{_x000D_
this.land.addLuchthaven(this); // Tot slot de luchthaven toevoegen aan het nieuwe land._x000D_
}_x000D_
} _x000D_
_x000D_
/**_x000D_
* Deze methode zet of de Luchthaven een werkplaats heeft of niet._x000D_
* @param wp true als de Luchthaven een werkplaats heeft en anders false_x000D_
*/_x000D_
public void setWerkPlaats (boolean wp)_x000D_
{_x000D_
werkPlaats = wp;_x000D_
} _x000D_
_x000D_
// Getters_x000D_
/**_x000D_
* Deze methode geeft de naam van de Luchthaven._x000D_
* @return de naam van de Luchthaven_x000D_
*/_x000D_
public String getNaam ()_x000D_
{_x000D_
return naam;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze methode geeft de code van de Luchthaven._x000D_
* @return de code (afkorting) van de Luchthaven_x000D_
*/_x000D_
public String getCode ()_x000D_
{_x000D_
return this.code;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze methode geeft true als er een werkplaats is en anders false._x000D_
* @return true als er een werkplaats is op de Luchthaven_x000D_
*/_x000D_
public boolean getWerkPlaats ()_x000D_
{_x000D_
return werkPlaats;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze methode geeft het Land waar de Luchthaven ligt._x000D_
* @return het Land waar de Luchthaven ligt_x000D_
*/_x000D_
public Land getLand ()_x000D_
{_x000D_
return land;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Deze statische methode geeft alle luchthavennamen en Luchthavens terug._x000D_
* @return een TreeMap van luchthavennamen en Luchthavens_x000D_
*/_x000D_
public static TreeMap<String, Luchthaven> getAlleLuchthavens ()_x000D_
{_x000D_
TreeMap<String, Luchthaven> alleLh = new TreeMap<String, Luchthaven>();_x000D_
for (Iterator<Luchthaven> i = alleLuchthavens.iterator(); i.hasNext();)_x000D_
{_x000D_
Luchthaven lh = i.next();_x000D_
alleLh.put(lh.naam, lh);_x000D_
}_x000D_
return alleLh;_x000D_
} _x000D_
_x000D_
// Overige Methodes_x000D_
/**_x000D_
* Deze methode bewaart deze Luchthaven door hem toe te voegen aan de Luchthavens van het land en alleLuchthavens._x000D_
* @throws domeinLaag.LuchthavenException als nog niet alle attributen een waarde hebben_x000D_
*/_x000D_
public void bewaar () throws LuchthavenException_x000D_
{_x000D_
if (land == null)_x000D_
{_x000D_
throw new LuchthavenException("Land niet ingevuld!");_x000D_
}_x000D_
else if (naam.isEmpty())_x000D_
{_x000D_
throw new LuchthavenException("Naam niet ingevuld!");_x000D_
}_x000D_
else if (code.isEmpty())_x000D_
{_x000D_
throw new LuchthavenException("Code niet ingevuld!");_x000D_
}_x000D_
else_x000D_
{_x000D_
alleLuchthavens.add(this);_x000D_
land.addLuchthaven(this);_x000D_
}_x000D_
}_x000D_
}_x000D_
| True | 2,882 | 159 | 3,230 | 175 | 3,007 | 160 | 3,230 | 175 | 3,341 | 179 | false | false | false | false | false | true |
3,631 | 69955_2 | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package de.qreator.vertx.VertxDatabase;_x000D_
_x000D_
import io.vertx.core.AbstractVerticle;_x000D_
import io.vertx.core.Future;_x000D_
import io.vertx.core.eventbus.DeliveryOptions;_x000D_
import io.vertx.core.http.HttpServer;_x000D_
import io.vertx.core.http.HttpServerResponse;_x000D_
import io.vertx.core.json.Json;_x000D_
import io.vertx.core.json.JsonObject;_x000D_
import io.vertx.ext.web.Router;_x000D_
import io.vertx.ext.web.RoutingContext;_x000D_
import io.vertx.ext.web.Session;_x000D_
import io.vertx.ext.web.handler.BodyHandler;_x000D_
import io.vertx.ext.web.handler.CookieHandler;_x000D_
import io.vertx.ext.web.handler.SessionHandler;_x000D_
import io.vertx.ext.web.handler.StaticHandler;_x000D_
import io.vertx.ext.web.sstore.LocalSessionStore;_x000D_
import org.slf4j.Logger;_x000D_
import org.slf4j.LoggerFactory;_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author menze_x000D_
*/_x000D_
public class HttpVerticle extends AbstractVerticle {_x000D_
_x000D_
private int port = 8080;_x000D_
private static final Logger LOGGER = LoggerFactory.getLogger("de.qreator.vertx.VertxDatabase.HttpServer");_x000D_
private static final String EB_ADRESSE = "vertxdatabase.eventbus";_x000D_
_x000D_
public void start(Future<Void> startFuture) throws Exception {_x000D_
_x000D_
HttpServer server = vertx.createHttpServer();_x000D_
_x000D_
LocalSessionStore store = LocalSessionStore.create(vertx);_x000D_
SessionHandler sessionHandler = SessionHandler.create(store);_x000D_
_x000D_
Router router = Router.router(vertx);_x000D_
_x000D_
router.route().handler(CookieHandler.create());_x000D_
router.route().handler(sessionHandler);_x000D_
router.post().handler(BodyHandler.create());_x000D_
router.post("/anfrage").handler(this::anfragenHandler);_x000D_
router.route("/static/geheim/*").handler(this::geheimeSeiten);_x000D_
router.route("/static/*").handler(StaticHandler.create().setDefaultContentEncoding("UTF-8").setCachingEnabled(false));_x000D_
_x000D_
server.requestHandler(router::accept).listen(port, "0.0.0.0", listener -> {_x000D_
if (listener.succeeded()) {_x000D_
LOGGER.info("Http-Server auf Port " + port + " gestartet");_x000D_
startFuture.complete();_x000D_
} else {_x000D_
startFuture.fail(listener.cause());_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
private void geheimeSeiten(RoutingContext routingContext) {_x000D_
LOGGER.info("Router für geheime Seiten");_x000D_
Session session = routingContext.session();_x000D_
if (session.get("angemeldet") == null) { // wenn nicht angemeldet, dann Passwort verlangen_x000D_
routingContext.response().setStatusCode(303);_x000D_
routingContext.response().putHeader("Location", "/static/passwort.html");_x000D_
routingContext.response().end();_x000D_
} else {_x000D_
LOGGER.info("Weiterleitung zum nächsten Router");_x000D_
routingContext.next(); // sonst weiter zum nächsten Router_x000D_
}_x000D_
}_x000D_
_x000D_
private void anfragenHandler(RoutingContext routingContext) {_x000D_
LOGGER.info("Router für Anfragen");_x000D_
String typ = routingContext.request().getParam("typ");_x000D_
HttpServerResponse response = routingContext.response();_x000D_
response.putHeader("content-type", "application/json");_x000D_
JsonObject jo = new JsonObject();_x000D_
Session session = routingContext.session();_x000D_
_x000D_
if (typ.equals("angemeldet")) {_x000D_
LOGGER.info("Anfrage, ob User angemeldet ist.");_x000D_
String angemeldet = session.get("angemeldet");_x000D_
jo.put("typ", "angemeldet");_x000D_
if (angemeldet != null && angemeldet.equals("ja")) {_x000D_
LOGGER.info("User ist angemeldet.");_x000D_
jo.put("text", "ja");_x000D_
} else {_x000D_
LOGGER.info("User ist NICHT angemeldet. Somit Passworteingabe erforderlich");_x000D_
jo.put("text", "nein");_x000D_
}_x000D_
response.end(Json.encodePrettily(jo));_x000D_
} else if (typ.equals("anmeldedaten")) {_x000D_
String name = routingContext.request().getParam("anmeldename");_x000D_
String passwort = routingContext.request().getParam("passwort");_x000D_
LOGGER.info("Anmeldeanfrage von User " + name + " mit dem Passwort " + passwort);_x000D_
_x000D_
JsonObject request = new JsonObject().put("name", name).put("passwort", passwort);_x000D_
_x000D_
DeliveryOptions options = new DeliveryOptions().addHeader("action", "ueberpruefe-passwort");_x000D_
vertx.eventBus().send(EB_ADRESSE, request, options, reply -> {_x000D_
if (reply.succeeded()) {_x000D_
JsonObject body = (JsonObject) reply.result().body();_x000D_
if (body.getBoolean("passwortStimmt") == true) {_x000D_
session.put("angemeldet", "ja");_x000D_
jo.put("typ", "überprüfung").put("text", "ok");_x000D_
} else {_x000D_
jo.put("typ", "überprüfung").put("text", "nein");_x000D_
}_x000D_
response.end(Json.encodePrettily(jo));_x000D_
} else {_x000D_
jo.put("typ", "überprüfung").put("text", "nein");_x000D_
response.end(Json.encodePrettily(jo));_x000D_
}_x000D_
});_x000D_
_x000D_
} else if (typ.equals("logout")) {_x000D_
LOGGER.info("Logout-Anfrage");_x000D_
session.put("angemeldet", null);_x000D_
jo.put("typ", "logout");_x000D_
response.end(Json.encodePrettily(jo));_x000D_
}_x000D_
}_x000D_
}_x000D_
| menzelths/VertxWeb | src/main/java/de/qreator/vertx/VertxDatabase/HttpVerticle.java | 1,563 | // wenn nicht angemeldet, dann Passwort verlangen_x000D_ | line_comment | nl | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package de.qreator.vertx.VertxDatabase;_x000D_
_x000D_
import io.vertx.core.AbstractVerticle;_x000D_
import io.vertx.core.Future;_x000D_
import io.vertx.core.eventbus.DeliveryOptions;_x000D_
import io.vertx.core.http.HttpServer;_x000D_
import io.vertx.core.http.HttpServerResponse;_x000D_
import io.vertx.core.json.Json;_x000D_
import io.vertx.core.json.JsonObject;_x000D_
import io.vertx.ext.web.Router;_x000D_
import io.vertx.ext.web.RoutingContext;_x000D_
import io.vertx.ext.web.Session;_x000D_
import io.vertx.ext.web.handler.BodyHandler;_x000D_
import io.vertx.ext.web.handler.CookieHandler;_x000D_
import io.vertx.ext.web.handler.SessionHandler;_x000D_
import io.vertx.ext.web.handler.StaticHandler;_x000D_
import io.vertx.ext.web.sstore.LocalSessionStore;_x000D_
import org.slf4j.Logger;_x000D_
import org.slf4j.LoggerFactory;_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author menze_x000D_
*/_x000D_
public class HttpVerticle extends AbstractVerticle {_x000D_
_x000D_
private int port = 8080;_x000D_
private static final Logger LOGGER = LoggerFactory.getLogger("de.qreator.vertx.VertxDatabase.HttpServer");_x000D_
private static final String EB_ADRESSE = "vertxdatabase.eventbus";_x000D_
_x000D_
public void start(Future<Void> startFuture) throws Exception {_x000D_
_x000D_
HttpServer server = vertx.createHttpServer();_x000D_
_x000D_
LocalSessionStore store = LocalSessionStore.create(vertx);_x000D_
SessionHandler sessionHandler = SessionHandler.create(store);_x000D_
_x000D_
Router router = Router.router(vertx);_x000D_
_x000D_
router.route().handler(CookieHandler.create());_x000D_
router.route().handler(sessionHandler);_x000D_
router.post().handler(BodyHandler.create());_x000D_
router.post("/anfrage").handler(this::anfragenHandler);_x000D_
router.route("/static/geheim/*").handler(this::geheimeSeiten);_x000D_
router.route("/static/*").handler(StaticHandler.create().setDefaultContentEncoding("UTF-8").setCachingEnabled(false));_x000D_
_x000D_
server.requestHandler(router::accept).listen(port, "0.0.0.0", listener -> {_x000D_
if (listener.succeeded()) {_x000D_
LOGGER.info("Http-Server auf Port " + port + " gestartet");_x000D_
startFuture.complete();_x000D_
} else {_x000D_
startFuture.fail(listener.cause());_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
private void geheimeSeiten(RoutingContext routingContext) {_x000D_
LOGGER.info("Router für geheime Seiten");_x000D_
Session session = routingContext.session();_x000D_
if (session.get("angemeldet") == null) { // wenn nicht<SUF>
routingContext.response().setStatusCode(303);_x000D_
routingContext.response().putHeader("Location", "/static/passwort.html");_x000D_
routingContext.response().end();_x000D_
} else {_x000D_
LOGGER.info("Weiterleitung zum nächsten Router");_x000D_
routingContext.next(); // sonst weiter zum nächsten Router_x000D_
}_x000D_
}_x000D_
_x000D_
private void anfragenHandler(RoutingContext routingContext) {_x000D_
LOGGER.info("Router für Anfragen");_x000D_
String typ = routingContext.request().getParam("typ");_x000D_
HttpServerResponse response = routingContext.response();_x000D_
response.putHeader("content-type", "application/json");_x000D_
JsonObject jo = new JsonObject();_x000D_
Session session = routingContext.session();_x000D_
_x000D_
if (typ.equals("angemeldet")) {_x000D_
LOGGER.info("Anfrage, ob User angemeldet ist.");_x000D_
String angemeldet = session.get("angemeldet");_x000D_
jo.put("typ", "angemeldet");_x000D_
if (angemeldet != null && angemeldet.equals("ja")) {_x000D_
LOGGER.info("User ist angemeldet.");_x000D_
jo.put("text", "ja");_x000D_
} else {_x000D_
LOGGER.info("User ist NICHT angemeldet. Somit Passworteingabe erforderlich");_x000D_
jo.put("text", "nein");_x000D_
}_x000D_
response.end(Json.encodePrettily(jo));_x000D_
} else if (typ.equals("anmeldedaten")) {_x000D_
String name = routingContext.request().getParam("anmeldename");_x000D_
String passwort = routingContext.request().getParam("passwort");_x000D_
LOGGER.info("Anmeldeanfrage von User " + name + " mit dem Passwort " + passwort);_x000D_
_x000D_
JsonObject request = new JsonObject().put("name", name).put("passwort", passwort);_x000D_
_x000D_
DeliveryOptions options = new DeliveryOptions().addHeader("action", "ueberpruefe-passwort");_x000D_
vertx.eventBus().send(EB_ADRESSE, request, options, reply -> {_x000D_
if (reply.succeeded()) {_x000D_
JsonObject body = (JsonObject) reply.result().body();_x000D_
if (body.getBoolean("passwortStimmt") == true) {_x000D_
session.put("angemeldet", "ja");_x000D_
jo.put("typ", "überprüfung").put("text", "ok");_x000D_
} else {_x000D_
jo.put("typ", "überprüfung").put("text", "nein");_x000D_
}_x000D_
response.end(Json.encodePrettily(jo));_x000D_
} else {_x000D_
jo.put("typ", "überprüfung").put("text", "nein");_x000D_
response.end(Json.encodePrettily(jo));_x000D_
}_x000D_
});_x000D_
_x000D_
} else if (typ.equals("logout")) {_x000D_
LOGGER.info("Logout-Anfrage");_x000D_
session.put("angemeldet", null);_x000D_
jo.put("typ", "logout");_x000D_
response.end(Json.encodePrettily(jo));_x000D_
}_x000D_
}_x000D_
}_x000D_
| False | 1,983 | 20 | 2,186 | 20 | 2,212 | 16 | 2,186 | 20 | 2,401 | 21 | false | false | false | false | false | true |
4,553 | 26864_4 | /*
* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.runtime.tree.xpath;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.LexerNoViableAltException;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.Vocabulary;
import org.antlr.v4.runtime.VocabularyImpl;
import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.misc.Interval;
/** Mimic the old XPathLexer from .g4 file */
public class XPathLexer extends Lexer {
public static final int
TOKEN_REF=1, RULE_REF=2, ANYWHERE=3, ROOT=4, WILDCARD=5, BANG=6, ID=7,
STRING=8;
public final static String[] modeNames = {
"DEFAULT_MODE"
};
public static final String[] ruleNames = {
"ANYWHERE", "ROOT", "WILDCARD", "BANG", "ID", "NameChar", "NameStartChar",
"STRING"
};
private static final String[] _LITERAL_NAMES = {
null, null, null, "'//'", "'/'", "'*'", "'!'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, "TOKEN_REF", "RULE_REF", "ANYWHERE", "ROOT", "WILDCARD", "BANG",
"ID", "STRING"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
public String getGrammarFileName() { return "XPathLexer.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public ATN getATN() {
return null;
}
protected int line = 1;
protected int charPositionInLine = 0;
public XPathLexer(CharStream input) {
super(input);
}
@Override
public Token nextToken() {
_tokenStartCharIndex = _input.index();
CommonToken t = null;
while ( t==null ) {
switch ( _input.LA(1) ) {
case '/':
consume();
if ( _input.LA(1)=='/' ) {
consume();
t = new CommonToken(ANYWHERE, "//");
}
else {
t = new CommonToken(ROOT, "/");
}
break;
case '*':
consume();
t = new CommonToken(WILDCARD, "*");
break;
case '!':
consume();
t = new CommonToken(BANG, "!");
break;
case '\'':
String s = matchString();
t = new CommonToken(STRING, s);
break;
case CharStream.EOF :
return new CommonToken(EOF, "<EOF>");
default:
if ( isNameStartChar(_input.LA(1)) ) {
String id = matchID();
if ( Character.isUpperCase(id.charAt(0)) ) t = new CommonToken(TOKEN_REF, id);
else t = new CommonToken(RULE_REF, id);
}
else {
throw new LexerNoViableAltException(this, _input, _tokenStartCharIndex, null);
}
break;
}
}
t.setStartIndex(_tokenStartCharIndex);
t.setCharPositionInLine(_tokenStartCharIndex);
t.setLine(line);
return t;
}
public void consume() {
int curChar = _input.LA(1);
if ( curChar=='\n' ) {
line++;
charPositionInLine=0;
}
else {
charPositionInLine++;
}
_input.consume();
}
@Override
public int getCharPositionInLine() {
return charPositionInLine;
}
public String matchID() {
int start = _input.index();
consume(); // drop start char
while ( isNameChar(_input.LA(1)) ) {
consume();
}
return _input.getText(Interval.of(start,_input.index()-1));
}
public String matchString() {
int start = _input.index();
consume(); // drop first quote
while ( _input.LA(1)!='\'' ) {
consume();
}
consume(); // drop last quote
return _input.getText(Interval.of(start,_input.index()-1));
}
public boolean isNameChar(int c) { return Character.isUnicodeIdentifierPart(c); }
public boolean isNameStartChar(int c) { return Character.isUnicodeIdentifierStart(c); }
}
| tonyarnold/antlr4 | runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathLexer.java | 1,647 | // drop start char | line_comment | nl | /*
* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.runtime.tree.xpath;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.LexerNoViableAltException;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.Vocabulary;
import org.antlr.v4.runtime.VocabularyImpl;
import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.misc.Interval;
/** Mimic the old XPathLexer from .g4 file */
public class XPathLexer extends Lexer {
public static final int
TOKEN_REF=1, RULE_REF=2, ANYWHERE=3, ROOT=4, WILDCARD=5, BANG=6, ID=7,
STRING=8;
public final static String[] modeNames = {
"DEFAULT_MODE"
};
public static final String[] ruleNames = {
"ANYWHERE", "ROOT", "WILDCARD", "BANG", "ID", "NameChar", "NameStartChar",
"STRING"
};
private static final String[] _LITERAL_NAMES = {
null, null, null, "'//'", "'/'", "'*'", "'!'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, "TOKEN_REF", "RULE_REF", "ANYWHERE", "ROOT", "WILDCARD", "BANG",
"ID", "STRING"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
public String getGrammarFileName() { return "XPathLexer.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public ATN getATN() {
return null;
}
protected int line = 1;
protected int charPositionInLine = 0;
public XPathLexer(CharStream input) {
super(input);
}
@Override
public Token nextToken() {
_tokenStartCharIndex = _input.index();
CommonToken t = null;
while ( t==null ) {
switch ( _input.LA(1) ) {
case '/':
consume();
if ( _input.LA(1)=='/' ) {
consume();
t = new CommonToken(ANYWHERE, "//");
}
else {
t = new CommonToken(ROOT, "/");
}
break;
case '*':
consume();
t = new CommonToken(WILDCARD, "*");
break;
case '!':
consume();
t = new CommonToken(BANG, "!");
break;
case '\'':
String s = matchString();
t = new CommonToken(STRING, s);
break;
case CharStream.EOF :
return new CommonToken(EOF, "<EOF>");
default:
if ( isNameStartChar(_input.LA(1)) ) {
String id = matchID();
if ( Character.isUpperCase(id.charAt(0)) ) t = new CommonToken(TOKEN_REF, id);
else t = new CommonToken(RULE_REF, id);
}
else {
throw new LexerNoViableAltException(this, _input, _tokenStartCharIndex, null);
}
break;
}
}
t.setStartIndex(_tokenStartCharIndex);
t.setCharPositionInLine(_tokenStartCharIndex);
t.setLine(line);
return t;
}
public void consume() {
int curChar = _input.LA(1);
if ( curChar=='\n' ) {
line++;
charPositionInLine=0;
}
else {
charPositionInLine++;
}
_input.consume();
}
@Override
public int getCharPositionInLine() {
return charPositionInLine;
}
public String matchID() {
int start = _input.index();
consume(); // drop start<SUF>
while ( isNameChar(_input.LA(1)) ) {
consume();
}
return _input.getText(Interval.of(start,_input.index()-1));
}
public String matchString() {
int start = _input.index();
consume(); // drop first quote
while ( _input.LA(1)!='\'' ) {
consume();
}
consume(); // drop last quote
return _input.getText(Interval.of(start,_input.index()-1));
}
public boolean isNameChar(int c) { return Character.isUnicodeIdentifierPart(c); }
public boolean isNameStartChar(int c) { return Character.isUnicodeIdentifierStart(c); }
}
| False | 1,259 | 4 | 1,503 | 4 | 1,461 | 4 | 1,503 | 4 | 1,859 | 4 | false | false | false | false | false | true |
2,959 | 74879_0 | package nl.novi.javaprogrammeren;
import nl.novi.javaprogrammeren.overerving.Rocket;
import nl.novi.javaprogrammeren.overerving.SpaceXRocket;
public class Main {
/*
Bekijk onderstaande code. Er zijn twee klasse, twee objecten.
SpaceXRocket extends Rocket.
Op dit moment vliegen beide raketten 100 meter per 1 fuel-eenheid.
Pas de code zo aan dat de SpaceXRocket 150 meter per 1 fuel-eendheid omhoog gaat.
Gebruik hiervoor super() of Override.
Je hoeft alleen code aan te passen in SpaceXRocket
*/
public static void main(String[] args) {
Rocket genericRocket = new Rocket(100);
genericRocket.fly(10);
System.out.println(genericRocket.toString());
SpaceXRocket spaceXRocket = new SpaceXRocket(100);
spaceXRocket.fly(10);
System.out.println(spaceXRocket.toString());
}
}
| hogeschoolnovi/SD-BE-JP-Overerving-01a | src/nl/novi/javaprogrammeren/Main.java | 285 | /*
Bekijk onderstaande code. Er zijn twee klasse, twee objecten.
SpaceXRocket extends Rocket.
Op dit moment vliegen beide raketten 100 meter per 1 fuel-eenheid.
Pas de code zo aan dat de SpaceXRocket 150 meter per 1 fuel-eendheid omhoog gaat.
Gebruik hiervoor super() of Override.
Je hoeft alleen code aan te passen in SpaceXRocket
*/ | block_comment | nl | package nl.novi.javaprogrammeren;
import nl.novi.javaprogrammeren.overerving.Rocket;
import nl.novi.javaprogrammeren.overerving.SpaceXRocket;
public class Main {
/*
Bekijk onderstaande code.<SUF>*/
public static void main(String[] args) {
Rocket genericRocket = new Rocket(100);
genericRocket.fly(10);
System.out.println(genericRocket.toString());
SpaceXRocket spaceXRocket = new SpaceXRocket(100);
spaceXRocket.fly(10);
System.out.println(spaceXRocket.toString());
}
}
| True | 230 | 107 | 262 | 113 | 247 | 100 | 262 | 113 | 299 | 122 | false | false | false | false | false | true |
4,011 | 137137_0 | package nl.tjonahen.asyncdemo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableAsync
public class DinerdemoApplication {
public static void main(String[] args) {
SpringApplication.run(DinerdemoApplication.class, args);
}
}
@Slf4j
@RestController
@RequiredArgsConstructor
class DinerController {
private final BarMicroService bms;
private final KitchenMicroService kms;
@GetMapping("/menu")
public MenuKaart getMenuKaart() throws InterruptedException, ExecutionException {
log.info("Getting menu...");
CompletableFuture<List<Drankje>> drankjesCompleteFuture = bms.getMenu();
CompletableFuture<List<Snack>> snaksCompletableFuture = kms.getMenu();
CompletableFuture.allOf(drankjesCompleteFuture, snaksCompletableFuture).join();
log.info("Menu items received...");
return new MenuKaart(drankjesCompleteFuture.get(), snaksCompletableFuture.get());
}
}
/*
{
drankjes : [{omschrijving:"cola"}],
snaks :[{}]
*/
@AllArgsConstructor
@Getter
@Setter
class MenuKaart {
private List<Drankje> drankjes;
private List<Snack> snaks;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
class Drankje {
private String omschrijving;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
class Snack {
private String omschrijving;
}
@Slf4j
@Service
class BarMicroService {
@Async
CompletableFuture<List<Drankje>> getMenu() throws InterruptedException {
log.info("Get Drankjes");
// Artificial delay of 1s for demonstration purposes
Thread.sleep(2000L);
log.info("Return Drankjes menu");
return CompletableFuture.completedFuture(new ArrayList<Drankje>() {
{
add(new Drankje("cola"));
}
});
}
}
@Slf4j
@Service
class KitchenMicroService {
@Async
CompletableFuture<List<Snack>> getMenu() throws InterruptedException {
log.info("Get Snack");
// Artificial delay of 2s for demonstration purposes
Thread.sleep(1000L);
log.info("Return Snack menu");
return CompletableFuture.completedFuture(new ArrayList<Snack>() {
{
add(new Snack("shanghai nootjes"));
}
});
}
}
| pnmtjonahen/stunning-tribble | async/src/main/java/nl/tjonahen/asyncdemo/DinerdemoApplication.java | 894 | /*
{
drankjes : [{omschrijving:"cola"}],
snaks :[{}]
*/ | block_comment | nl | package nl.tjonahen.asyncdemo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableAsync
public class DinerdemoApplication {
public static void main(String[] args) {
SpringApplication.run(DinerdemoApplication.class, args);
}
}
@Slf4j
@RestController
@RequiredArgsConstructor
class DinerController {
private final BarMicroService bms;
private final KitchenMicroService kms;
@GetMapping("/menu")
public MenuKaart getMenuKaart() throws InterruptedException, ExecutionException {
log.info("Getting menu...");
CompletableFuture<List<Drankje>> drankjesCompleteFuture = bms.getMenu();
CompletableFuture<List<Snack>> snaksCompletableFuture = kms.getMenu();
CompletableFuture.allOf(drankjesCompleteFuture, snaksCompletableFuture).join();
log.info("Menu items received...");
return new MenuKaart(drankjesCompleteFuture.get(), snaksCompletableFuture.get());
}
}
/*
{
drankjes<SUF>*/
@AllArgsConstructor
@Getter
@Setter
class MenuKaart {
private List<Drankje> drankjes;
private List<Snack> snaks;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
class Drankje {
private String omschrijving;
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
class Snack {
private String omschrijving;
}
@Slf4j
@Service
class BarMicroService {
@Async
CompletableFuture<List<Drankje>> getMenu() throws InterruptedException {
log.info("Get Drankjes");
// Artificial delay of 1s for demonstration purposes
Thread.sleep(2000L);
log.info("Return Drankjes menu");
return CompletableFuture.completedFuture(new ArrayList<Drankje>() {
{
add(new Drankje("cola"));
}
});
}
}
@Slf4j
@Service
class KitchenMicroService {
@Async
CompletableFuture<List<Snack>> getMenu() throws InterruptedException {
log.info("Get Snack");
// Artificial delay of 2s for demonstration purposes
Thread.sleep(1000L);
log.info("Return Snack menu");
return CompletableFuture.completedFuture(new ArrayList<Snack>() {
{
add(new Snack("shanghai nootjes"));
}
});
}
}
| False | 594 | 23 | 747 | 26 | 769 | 26 | 747 | 26 | 896 | 27 | false | false | false | false | false | true |
4,084 | 52511_0 | package ui.view;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class ValidHtmlTest {
private WebDriver driver;
@Before
public void setUp() {
// vul hier JOUW pad naar chromedriver in
// Voor Windows (vergeet "\" niet te escapen met een tweede "\")
// System.setProperty("webdriver.chrome.driver", "C:\\Users\\...\\chromedriver.exe");
// Voor mac:
System.setProperty("webdriver.chrome.driver", "C:\\Applications\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
}
@After
public void clean() {
driver.quit();
}
@Test // Voer deze test uit als je je project opgeladen hebt
public void isValidHtml() {
driver.get("https://validator.w3.org/#validate_by_uri+with_options");
WebElement invulveld = driver.findElement(By.id("uri"));
// verander naar de url die je wil valideren
invulveld.sendKeys("https://webontwerp.ucll.be/web1/reeksen/");
Select dropdown = new Select(driver.findElement(By.id("uri-doctype")));
dropdown.selectByValue("HTML5");
WebElement button = driver.findElement(By.cssSelector(".submit_button"));
button.click();
WebElement pass = driver.findElement(By.cssSelector("p.success"));
assertEquals("Document checking completed. No errors or warnings to show.", pass.getText());
}
}
| quinten-bosch/Web-2-Labo | Labo 3 GET en Selenium/src/test/java/ui/view/ValidHtmlTest.java | 526 | // vul hier JOUW pad naar chromedriver in | line_comment | nl | package ui.view;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class ValidHtmlTest {
private WebDriver driver;
@Before
public void setUp() {
// vul hier<SUF>
// Voor Windows (vergeet "\" niet te escapen met een tweede "\")
// System.setProperty("webdriver.chrome.driver", "C:\\Users\\...\\chromedriver.exe");
// Voor mac:
System.setProperty("webdriver.chrome.driver", "C:\\Applications\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
}
@After
public void clean() {
driver.quit();
}
@Test // Voer deze test uit als je je project opgeladen hebt
public void isValidHtml() {
driver.get("https://validator.w3.org/#validate_by_uri+with_options");
WebElement invulveld = driver.findElement(By.id("uri"));
// verander naar de url die je wil valideren
invulveld.sendKeys("https://webontwerp.ucll.be/web1/reeksen/");
Select dropdown = new Select(driver.findElement(By.id("uri-doctype")));
dropdown.selectByValue("HTML5");
WebElement button = driver.findElement(By.cssSelector(".submit_button"));
button.click();
WebElement pass = driver.findElement(By.cssSelector("p.success"));
assertEquals("Document checking completed. No errors or warnings to show.", pass.getText());
}
}
| True | 359 | 11 | 465 | 13 | 453 | 12 | 465 | 13 | 529 | 12 | false | false | false | false | false | true |
367 | 41440_24 | import java.util.*; //importeren van java.util_x000D_
import java.io.*; //importeren van java.io_x000D_
_x000D_
public class Phonebook {_x000D_
Vector <Person> people;_x000D_
int n; //class variable omdat het niet in de methode zelf mocht voor recursie_x000D_
_x000D_
public Phonebook(String file) {_x000D_
people = new Vector <Person> ();_x000D_
read(file);_x000D_
}_x000D_
_x000D_
public void read (String file) {//begin functie inlezen bestand_x000D_
try {//try catch voor fouten_x000D_
File bestandnaam = new File(file); //bestandsnaam doorgeven_x000D_
Scanner lezer = new Scanner(bestandnaam); //scanner voor het inlezen van het bestand_x000D_
while (lezer.hasNextLine()) {//while loop om door alle regels in het bestand te gaan_x000D_
String data = lezer.nextLine(); //volgende line in het bestand _x000D_
StringTokenizer st = new StringTokenizer(data, ",");//naam los van de nummers maken in tokenizer_x000D_
Person L = new Person(st.nextToken(), st.nextToken());//object L aanmaken en de naam en het nummer erin invoegen _x000D_
people.add(L); //naam toevoegen aan vector_x000D_
}_x000D_
lezer.close();_x000D_
} catch (Exception error) {// als er een fout gevonden is_x000D_
System.out.println("Fout gevonden.");_x000D_
error.printStackTrace();_x000D_
}_x000D_
}_x000D_
_x000D_
public String toString() {_x000D_
String allesin1 = ""; //lege string die gevuld wordt met de namen en nummers_x000D_
for (Person L: people) {//loop om door alle people te gaan_x000D_
//printen van name en number in de vector die onderdeel zijn van class Person_x000D_
allesin1 = allesin1 + L.name + " " + L.number + "\n";_x000D_
}_x000D_
return allesin1; //returnen van de string met alles erin _x000D_
}_x000D_
_x000D_
public String number(String name) {_x000D_
for (Person L: people) {//loop om door alle people te gaan_x000D_
if (name.equals(L.name)) {_x000D_
return L.name + " " + L.number;_x000D_
}_x000D_
}_x000D_
return "Geen overeenkomsten gevonden."; //als er geen overeenkomsten zijn_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
public void sort(){_x000D_
n = people.size();_x000D_
people = sort(people);//eerste aanroep recursie_x000D_
_x000D_
_x000D_
}_x000D_
private Vector <Person> sort (Vector <Person> tosort) {_x000D_
_x000D_
//Bubblesort base case_x000D_
if (n == 1) {_x000D_
return tosort;_x000D_
}//body_x000D_
int count = 0; //zodat de recursie niet onnodig in wordt gegaan_x000D_
for (int i = 0; i < n-1; i++) {_x000D_
Person P = tosort.get(i); //haalt huidige in de vector op_x000D_
Person L = tosort.get(i+1); // haalt de volgende in de vector op_x000D_
String s2 = P.name; //zet type person om in string name_x000D_
String s1 = L.name; //zet type person om in string name_x000D_
if (isSmaller(s1, s2)) { //isSmaller om te vergelijken of s1 kleiner is dan s2 _x000D_
tosort.set(i, L); // draait de namen om_x000D_
tosort.set(i + 1, P);_x000D_
count = count +1;_x000D_
}_x000D_
}_x000D_
if (count == 0) {_x000D_
return tosort;_x000D_
}_x000D_
n = n-1;_x000D_
return sort(tosort);// recursie_x000D_
}_x000D_
private boolean isSmaller (String s1, String s2) {_x000D_
// returns true if s1 <s2 alphabetically_x000D_
_x000D_
boolean builtdifferent = false; //boolean voor de while loop_x000D_
boolean iskleiner = false; //boolean voor als s1 kleiner is dan s2 dus s2 bovenaan moet zijn_x000D_
int i = 0;//teller om de letters te vergelijken op pos i in de string_x000D_
while (!builtdifferent) {//while loop die doorgaat tot er een verschil is tussen de 2 strings_x000D_
if (s1.toLowerCase().charAt(i) != s2.toLowerCase().charAt(i)) {_x000D_
if ((int)s1.toLowerCase().charAt(i) < (int)s2.toLowerCase().charAt(i)) {// hoe lager getal hoe eerder alfabet_x000D_
iskleiner = true; //als s1 kleiner is dan s2_x000D_
}_x000D_
builtdifferent = true; //voor het eindigen van de while loop_x000D_
_x000D_
}else {_x000D_
i++; //om door te gaan naar het volgende character van de string_x000D_
}_x000D_
}_x000D_
return iskleiner;_x000D_
_x000D_
}_x000D_
}_x000D_
| DMR-max/symbolic-AI-0 | Phonebook.java | 1,271 | //zet type person om in string name_x000D_ | line_comment | nl | import java.util.*; //importeren van java.util_x000D_
import java.io.*; //importeren van java.io_x000D_
_x000D_
public class Phonebook {_x000D_
Vector <Person> people;_x000D_
int n; //class variable omdat het niet in de methode zelf mocht voor recursie_x000D_
_x000D_
public Phonebook(String file) {_x000D_
people = new Vector <Person> ();_x000D_
read(file);_x000D_
}_x000D_
_x000D_
public void read (String file) {//begin functie inlezen bestand_x000D_
try {//try catch voor fouten_x000D_
File bestandnaam = new File(file); //bestandsnaam doorgeven_x000D_
Scanner lezer = new Scanner(bestandnaam); //scanner voor het inlezen van het bestand_x000D_
while (lezer.hasNextLine()) {//while loop om door alle regels in het bestand te gaan_x000D_
String data = lezer.nextLine(); //volgende line in het bestand _x000D_
StringTokenizer st = new StringTokenizer(data, ",");//naam los van de nummers maken in tokenizer_x000D_
Person L = new Person(st.nextToken(), st.nextToken());//object L aanmaken en de naam en het nummer erin invoegen _x000D_
people.add(L); //naam toevoegen aan vector_x000D_
}_x000D_
lezer.close();_x000D_
} catch (Exception error) {// als er een fout gevonden is_x000D_
System.out.println("Fout gevonden.");_x000D_
error.printStackTrace();_x000D_
}_x000D_
}_x000D_
_x000D_
public String toString() {_x000D_
String allesin1 = ""; //lege string die gevuld wordt met de namen en nummers_x000D_
for (Person L: people) {//loop om door alle people te gaan_x000D_
//printen van name en number in de vector die onderdeel zijn van class Person_x000D_
allesin1 = allesin1 + L.name + " " + L.number + "\n";_x000D_
}_x000D_
return allesin1; //returnen van de string met alles erin _x000D_
}_x000D_
_x000D_
public String number(String name) {_x000D_
for (Person L: people) {//loop om door alle people te gaan_x000D_
if (name.equals(L.name)) {_x000D_
return L.name + " " + L.number;_x000D_
}_x000D_
}_x000D_
return "Geen overeenkomsten gevonden."; //als er geen overeenkomsten zijn_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
public void sort(){_x000D_
n = people.size();_x000D_
people = sort(people);//eerste aanroep recursie_x000D_
_x000D_
_x000D_
}_x000D_
private Vector <Person> sort (Vector <Person> tosort) {_x000D_
_x000D_
//Bubblesort base case_x000D_
if (n == 1) {_x000D_
return tosort;_x000D_
}//body_x000D_
int count = 0; //zodat de recursie niet onnodig in wordt gegaan_x000D_
for (int i = 0; i < n-1; i++) {_x000D_
Person P = tosort.get(i); //haalt huidige in de vector op_x000D_
Person L = tosort.get(i+1); // haalt de volgende in de vector op_x000D_
String s2 = P.name; //zet type person om in string name_x000D_
String s1 = L.name; //zet type<SUF>
if (isSmaller(s1, s2)) { //isSmaller om te vergelijken of s1 kleiner is dan s2 _x000D_
tosort.set(i, L); // draait de namen om_x000D_
tosort.set(i + 1, P);_x000D_
count = count +1;_x000D_
}_x000D_
}_x000D_
if (count == 0) {_x000D_
return tosort;_x000D_
}_x000D_
n = n-1;_x000D_
return sort(tosort);// recursie_x000D_
}_x000D_
private boolean isSmaller (String s1, String s2) {_x000D_
// returns true if s1 <s2 alphabetically_x000D_
_x000D_
boolean builtdifferent = false; //boolean voor de while loop_x000D_
boolean iskleiner = false; //boolean voor als s1 kleiner is dan s2 dus s2 bovenaan moet zijn_x000D_
int i = 0;//teller om de letters te vergelijken op pos i in de string_x000D_
while (!builtdifferent) {//while loop die doorgaat tot er een verschil is tussen de 2 strings_x000D_
if (s1.toLowerCase().charAt(i) != s2.toLowerCase().charAt(i)) {_x000D_
if ((int)s1.toLowerCase().charAt(i) < (int)s2.toLowerCase().charAt(i)) {// hoe lager getal hoe eerder alfabet_x000D_
iskleiner = true; //als s1 kleiner is dan s2_x000D_
}_x000D_
builtdifferent = true; //voor het eindigen van de while loop_x000D_
_x000D_
}else {_x000D_
i++; //om door te gaan naar het volgende character van de string_x000D_
}_x000D_
}_x000D_
return iskleiner;_x000D_
_x000D_
}_x000D_
}_x000D_
| True | 1,627 | 14 | 1,830 | 15 | 1,761 | 15 | 1,830 | 15 | 1,989 | 15 | false | false | false | false | false | true |
1,537 | 161617_1 | // =========================================================================== //
// //
// Copyright 2008-2011 Andrew Casey, Jun Li, Jesse Doherty, //
// Maxime Chevalier-Boisvert, Toheed Aslam, Anton Dubrau, Nurudeen Lameed, //
// Amina Aslam, Rahul Garg, Soroush Radpour, Olivier Savary Belanger, //
// Laurie Hendren, Clark Verbrugge and McGill University. //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// //
// =========================================================================== //
package natlab.toolkits.rewrite;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import ast.ASTNode;
/**
* A representation of the result of a node transformation. A
* transformed node can be either empty, a single node or a list of
* nodes. These two are mutually exclusive.
*/
public class TransformedNode extends ArrayList<ASTNode>
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Creates an empty transformed node e.g. the result of deleting a
* node.
*/
public TransformedNode(){
super();
}
/**
* Creates a single node.
*/
public TransformedNode( ast.ASTNode node ){
super();
add(node);
}
/**
* Creates a multiple transformed node.
* If there is only one or zero element in the list, creates either a singleNode or emptyNode
*/
public TransformedNode( ast.ASTNode[] nodes ){
this( Arrays.asList( nodes ) );
}
public TransformedNode( Collection<? extends ASTNode> nodes ){
super(nodes);
}
public boolean isEmptyNode()
{
return isEmpty();
}
public boolean isSingleNode()
{
return size() == 1;
}
public boolean isMultipleNodes()
{
return size() > 1;
}
public ast.ASTNode getSingleNode()
{
if( isSingleNode() )
return get(0);
else{
String msg = "Attempted to getSingleNode from non single transformed node.";
UnsupportedOperationException e;
e = new UnsupportedOperationException(msg);
throw e;
}
}
/**
* returns
* @return
*/
public List<ast.ASTNode> getMultipleNodes()
{
if( isMultipleNodes() )
return (List<ast.ASTNode>)super.clone();
else{
String msg = "Attempted to getMultipleNodes from a non multiple transformed node.";
UnsupportedOperationException e;
e = new UnsupportedOperationException(msg);
throw e;
}
}
@Override
public String toString() {
String msg = "transformedNode with ";
if (isSingleNode()){
msg += "single node: \n"+getSingleNode().getPrettyPrinted();
} else if (isMultipleNodes()){
msg += "multiple nodes: \n";
for (ast.ASTNode node : this){
msg += "["+node.getPrettyPrinted()+"]\n";
}
} else {
msg += "no node (empty)";
}
return msg;
}
}
| Sable/mclab-core | languages/Natlab/src/natlab/toolkits/rewrite/TransformedNode.java | 1,088 | // Maxime Chevalier-Boisvert, Toheed Aslam, Anton Dubrau, Nurudeen Lameed, // | line_comment | nl | // =========================================================================== //
// //
// Copyright 2008-2011 Andrew Casey, Jun Li, Jesse Doherty, //
// Maxime Chevalier-Boisvert,<SUF>
// Amina Aslam, Rahul Garg, Soroush Radpour, Olivier Savary Belanger, //
// Laurie Hendren, Clark Verbrugge and McGill University. //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// //
// =========================================================================== //
package natlab.toolkits.rewrite;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import ast.ASTNode;
/**
* A representation of the result of a node transformation. A
* transformed node can be either empty, a single node or a list of
* nodes. These two are mutually exclusive.
*/
public class TransformedNode extends ArrayList<ASTNode>
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Creates an empty transformed node e.g. the result of deleting a
* node.
*/
public TransformedNode(){
super();
}
/**
* Creates a single node.
*/
public TransformedNode( ast.ASTNode node ){
super();
add(node);
}
/**
* Creates a multiple transformed node.
* If there is only one or zero element in the list, creates either a singleNode or emptyNode
*/
public TransformedNode( ast.ASTNode[] nodes ){
this( Arrays.asList( nodes ) );
}
public TransformedNode( Collection<? extends ASTNode> nodes ){
super(nodes);
}
public boolean isEmptyNode()
{
return isEmpty();
}
public boolean isSingleNode()
{
return size() == 1;
}
public boolean isMultipleNodes()
{
return size() > 1;
}
public ast.ASTNode getSingleNode()
{
if( isSingleNode() )
return get(0);
else{
String msg = "Attempted to getSingleNode from non single transformed node.";
UnsupportedOperationException e;
e = new UnsupportedOperationException(msg);
throw e;
}
}
/**
* returns
* @return
*/
public List<ast.ASTNode> getMultipleNodes()
{
if( isMultipleNodes() )
return (List<ast.ASTNode>)super.clone();
else{
String msg = "Attempted to getMultipleNodes from a non multiple transformed node.";
UnsupportedOperationException e;
e = new UnsupportedOperationException(msg);
throw e;
}
}
@Override
public String toString() {
String msg = "transformedNode with ";
if (isSingleNode()){
msg += "single node: \n"+getSingleNode().getPrettyPrinted();
} else if (isMultipleNodes()){
msg += "multiple nodes: \n";
for (ast.ASTNode node : this){
msg += "["+node.getPrettyPrinted()+"]\n";
}
} else {
msg += "no node (empty)";
}
return msg;
}
}
| False | 831 | 31 | 905 | 36 | 980 | 26 | 905 | 36 | 1,093 | 32 | false | false | false | false | false | true |
3,157 | 7813_2 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class ElectricGuitar here.
*
* @author Jan Kroon
* @version 1
*/
public abstract class ElectricGuitar extends Actor
{
public static int electricGuitarCount = 0;
public static void anotherElectricGuitarManufactured() {
//this.electricGuitarCount++; // Gaat niet goed, waarom?
ElectricGuitar.electricGuitarCount++;
System.out.println("CHECK Number of electric guitars BackStage: " + String.valueOf(ElectricGuitar.electricGuitarCount));
}
/**
* Act - do whatever the ElectricGuitar wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
}
| jankroon/Guitars | ElectricGuitar.java | 255 | //this.electricGuitarCount++; // Gaat niet goed, waarom? | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class ElectricGuitar here.
*
* @author Jan Kroon
* @version 1
*/
public abstract class ElectricGuitar extends Actor
{
public static int electricGuitarCount = 0;
public static void anotherElectricGuitarManufactured() {
//this.electricGuitarCount++; //<SUF>
ElectricGuitar.electricGuitarCount++;
System.out.println("CHECK Number of electric guitars BackStage: " + String.valueOf(ElectricGuitar.electricGuitarCount));
}
/**
* Act - do whatever the ElectricGuitar wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
}
| False | 205 | 18 | 228 | 20 | 218 | 16 | 228 | 20 | 256 | 21 | false | false | false | false | false | true |
3,402 | 45216_8 | package repairshop;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class TestRepairshop {
public static void main(String[] args) throws IOException {
Repairshop r1 = new Repairshop();
Klant k1 = new Klant("Jos","De Wolf", "04/52455313" ,"[email protected]");
Klant k2 = new Klant("Jes","De vis", "04/52455313" ,"[email protected]");
Bedrijf b1 = new Bedrijf("Jef","De Kat","04/2369745","bedr@opn&co.com","opn&co");
Item i1 = new Item("horloge", "geeft tijd niet goed aan",50, "bezig met reparatie");
Item i2 = new Item("Jas","mouw gescheurd",100,"bezig met reparatie");
Item i3 = new Item("autozetels","versleten(gescheurd, krakken,...)",500,"in werking");
// corrigeert statussen naar statussen dat ik in andere methods gebruik
i1.corigeerstatus();
i2.corigeerstatus();
i3.corigeerstatus();
// klant brengt item binnen
k1.addItem(i1);
k1.addItem(i2);
b1.addItem(i3);
// alle items van een klant die binnen zijn
k1.showItems();
System.out.println("------------");
// zorgt ervoor dat een item klaar is met reparatie
i1.statusComplete();
k1.showItems();
System.out.println("------------");
// klant kan met een status opzoeken en zien welke items mezig zijn met reparatie of klaar om op te halen
System.out.println(k1.searchItem("bezig met reparatie"));
System.out.println("------------");
// korting op prijs
System.out.println(k1.kortingscoupon(i1));
System.out.println(b1.kortingscoupon(i3));
System.out.println("--------------");
// onders functie staat in commentaar omdat hij een nieuwe map op uw computer maakt met daarin een txt bestand
//
// de file komt op uw c schijf terecht dan user/username/ dan zal er een mapje bijgekomen zijn repairshop met een txt bestand met daarin klant
// r1.WriteObjectToFile(k1);
//
//
// btw op prijs zodat klant weet wat hij/zij uiteintelijk betaalt
k1.betaling(i3);
b1.betaling(i3);
System.out.println("--------------");
// voeg item toe aan hashmap
r1.wachtrij(i1);
r1.wachtrij(i2);
// laat alle items zien in hashmap
System.out.println(r1.getItems());
// verwijder items die klaar zijn
r1.deleteKlaar();
System.out.println(r1.getItems());
System.out.println("---------------");
// zet klant in hasmap
r1.voegKlantToe(k1);
r1.voegKlantToe(k2);
r1.voegKlantToe(b1);
// System.out.println(r1.getContacten());
System.out.println("-------------------");
// print klant uit met al zijn items die in de winkel is
r1.klantEnHunItems();
r1.ExportToCSV();
}
}
| kristofmoons/repairshop | src/repairshop/TestRepairshop.java | 948 | // btw op prijs zodat klant weet wat hij/zij uiteintelijk betaalt | line_comment | nl | package repairshop;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class TestRepairshop {
public static void main(String[] args) throws IOException {
Repairshop r1 = new Repairshop();
Klant k1 = new Klant("Jos","De Wolf", "04/52455313" ,"[email protected]");
Klant k2 = new Klant("Jes","De vis", "04/52455313" ,"[email protected]");
Bedrijf b1 = new Bedrijf("Jef","De Kat","04/2369745","bedr@opn&co.com","opn&co");
Item i1 = new Item("horloge", "geeft tijd niet goed aan",50, "bezig met reparatie");
Item i2 = new Item("Jas","mouw gescheurd",100,"bezig met reparatie");
Item i3 = new Item("autozetels","versleten(gescheurd, krakken,...)",500,"in werking");
// corrigeert statussen naar statussen dat ik in andere methods gebruik
i1.corigeerstatus();
i2.corigeerstatus();
i3.corigeerstatus();
// klant brengt item binnen
k1.addItem(i1);
k1.addItem(i2);
b1.addItem(i3);
// alle items van een klant die binnen zijn
k1.showItems();
System.out.println("------------");
// zorgt ervoor dat een item klaar is met reparatie
i1.statusComplete();
k1.showItems();
System.out.println("------------");
// klant kan met een status opzoeken en zien welke items mezig zijn met reparatie of klaar om op te halen
System.out.println(k1.searchItem("bezig met reparatie"));
System.out.println("------------");
// korting op prijs
System.out.println(k1.kortingscoupon(i1));
System.out.println(b1.kortingscoupon(i3));
System.out.println("--------------");
// onders functie staat in commentaar omdat hij een nieuwe map op uw computer maakt met daarin een txt bestand
//
// de file komt op uw c schijf terecht dan user/username/ dan zal er een mapje bijgekomen zijn repairshop met een txt bestand met daarin klant
// r1.WriteObjectToFile(k1);
//
//
// btw op<SUF>
k1.betaling(i3);
b1.betaling(i3);
System.out.println("--------------");
// voeg item toe aan hashmap
r1.wachtrij(i1);
r1.wachtrij(i2);
// laat alle items zien in hashmap
System.out.println(r1.getItems());
// verwijder items die klaar zijn
r1.deleteKlaar();
System.out.println(r1.getItems());
System.out.println("---------------");
// zet klant in hasmap
r1.voegKlantToe(k1);
r1.voegKlantToe(k2);
r1.voegKlantToe(b1);
// System.out.println(r1.getContacten());
System.out.println("-------------------");
// print klant uit met al zijn items die in de winkel is
r1.klantEnHunItems();
r1.ExportToCSV();
}
}
| True | 802 | 23 | 939 | 27 | 891 | 17 | 941 | 27 | 982 | 25 | false | false | false | false | false | true |
4,570 | 96410_9 | /**
* Copyright 2011, Tobias Senger
*
* This file is part of animamea.
*
* Animamea is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Animamea is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with animamea. If not, see <http://www.gnu.org/licenses/>.
*/
package de.tsenger.animamea.tools;
import java.math.BigInteger;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;
/**
* Helfer-Klasse zum Konventieren verschiedener Datentypen und Strukturen
*
* @author Tobias Senger ([email protected])
*
*/
public class Converter {
public static Date BCDtoDate(byte[] yymmdd) {
if( yymmdd==null || yymmdd.length!=6 ){
throw new IllegalArgumentException("Argument must have length 6, was " + (yymmdd==null?0:yymmdd.length));
}
int year = 2000 + yymmdd[0]*10 + yymmdd[1];
int month = yymmdd[2]*10 + yymmdd[3] - 1; // Java month index starts with 0...
int day = yymmdd[4]*10 + yymmdd[5];
GregorianCalendar gregCal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
gregCal.set(year, month, day,0,0,0);
return gregCal.getTime();
}
/**
* Converts a byte into a unsigned integer value.
*
* @param value
* @return
*/
public static int toUnsignedInt(byte value) {
return (value & 0x7F) + (value < 0 ? 128 : 0);
}
public static long ByteArrayToLong(byte[] bytes) {
long lo = 0;
for (int i = 0; i < 8; i++) {
lo <<= 8;
lo += (bytes[i] & 0x000000FF);
}
return lo;
}
/**
* Writes a <code>long</code> to byte array as sixteen bytes, high byte
* first.
*
* @param v
* a <code>long</code> to be converted.
*/
public static byte[] longToByteArray(long v) {
byte[] ivByes = new byte[8];
ivByes[0] = (byte) (v >>> 56);
ivByes[1] = (byte) (v >>> 48);
ivByes[2] = (byte) (v >>> 40);
ivByes[3] = (byte) (v >>> 32);
ivByes[4] = (byte) (v >>> 24);
ivByes[5] = (byte) (v >>> 16);
ivByes[6] = (byte) (v >>> 8);
ivByes[7] = (byte) (v >>> 0);
return ivByes;
}
/**
* Konvertiert ein BigInteger in ein ByteArray. Ein führendes Byte mit dem
* Wert 0 wird dabei angeschnitten. (Kennzeichen für einen positiven Wert,
* bei BigIntger)
*
* @param bi
* Das zu konvertierende BigInteger-Objekt.
* @return Byte-Array ohne führendes 0-Byte
*/
public static byte[] bigIntToByteArray(BigInteger bi) {
byte[] temp = bi.toByteArray();
byte[] returnbytes = null;
if (temp[0] == 0) {
returnbytes = new byte[temp.length - 1];
System.arraycopy(temp, 1, returnbytes, 0, returnbytes.length);
return returnbytes;
} else
return temp;
}
/**
* Dekodiert aus dem übergebenen Byte-Array einen ECPoint. Das benötigte
* prime field p wird aus der übergebenen Kurve übernommen Das erste Byte
* muss den Wert 0x04 enthalten (uncompressed point).
*
* @param value
* Byte Array der Form {0x04 || x-Bytes[] || y-Bytes[]}
* @param curve
* Die Kurve auf der der Punkt liegen soll.
* @return Point generiert aus den Input-Daten
* @throws IllegalArgumentException
* Falls das erste Byte nicht den Wert 0x04 enthält, enthält das
* übergebene Byte-Array offensichtlich keinen unkomprimierten Punkt
*/
public static ECPoint byteArrayToECPoint(byte[] value, ECCurve.Fp curve)
throws IllegalArgumentException {
byte[] x = new byte[(value.length - 1) / 2];
byte[] y = new byte[(value.length - 1) / 2];
if (value[0] != (byte) 0x04)
throw new IllegalArgumentException("No uncompressed Point found!");
else {
System.arraycopy(value, 1, x, 0, (value.length - 1) / 2);
System.arraycopy(value, 1 + ((value.length - 1) / 2), y, 0,
(value.length - 1) / 2);
// ECFieldElement.Fp xE = new ECFieldElement.Fp(curve.getQ(),
// new BigInteger(1, x));
// ECFieldElement.Fp yE = new ECFieldElement.Fp(curve.getQ(),
// new BigInteger(1, y));
// ECPoint point = new ECPoint.Fp(curve, xE, yE);
ECPoint point = curve.createPoint(new BigInteger(1, x), new BigInteger(1, y));
return point;
}
}
}
| tsenger/animamea | animamea/src/de/tsenger/animamea/tools/Converter.java | 1,712 | // ECFieldElement.Fp yE = new ECFieldElement.Fp(curve.getQ(), | line_comment | nl | /**
* Copyright 2011, Tobias Senger
*
* This file is part of animamea.
*
* Animamea is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Animamea is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with animamea. If not, see <http://www.gnu.org/licenses/>.
*/
package de.tsenger.animamea.tools;
import java.math.BigInteger;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;
/**
* Helfer-Klasse zum Konventieren verschiedener Datentypen und Strukturen
*
* @author Tobias Senger ([email protected])
*
*/
public class Converter {
public static Date BCDtoDate(byte[] yymmdd) {
if( yymmdd==null || yymmdd.length!=6 ){
throw new IllegalArgumentException("Argument must have length 6, was " + (yymmdd==null?0:yymmdd.length));
}
int year = 2000 + yymmdd[0]*10 + yymmdd[1];
int month = yymmdd[2]*10 + yymmdd[3] - 1; // Java month index starts with 0...
int day = yymmdd[4]*10 + yymmdd[5];
GregorianCalendar gregCal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
gregCal.set(year, month, day,0,0,0);
return gregCal.getTime();
}
/**
* Converts a byte into a unsigned integer value.
*
* @param value
* @return
*/
public static int toUnsignedInt(byte value) {
return (value & 0x7F) + (value < 0 ? 128 : 0);
}
public static long ByteArrayToLong(byte[] bytes) {
long lo = 0;
for (int i = 0; i < 8; i++) {
lo <<= 8;
lo += (bytes[i] & 0x000000FF);
}
return lo;
}
/**
* Writes a <code>long</code> to byte array as sixteen bytes, high byte
* first.
*
* @param v
* a <code>long</code> to be converted.
*/
public static byte[] longToByteArray(long v) {
byte[] ivByes = new byte[8];
ivByes[0] = (byte) (v >>> 56);
ivByes[1] = (byte) (v >>> 48);
ivByes[2] = (byte) (v >>> 40);
ivByes[3] = (byte) (v >>> 32);
ivByes[4] = (byte) (v >>> 24);
ivByes[5] = (byte) (v >>> 16);
ivByes[6] = (byte) (v >>> 8);
ivByes[7] = (byte) (v >>> 0);
return ivByes;
}
/**
* Konvertiert ein BigInteger in ein ByteArray. Ein führendes Byte mit dem
* Wert 0 wird dabei angeschnitten. (Kennzeichen für einen positiven Wert,
* bei BigIntger)
*
* @param bi
* Das zu konvertierende BigInteger-Objekt.
* @return Byte-Array ohne führendes 0-Byte
*/
public static byte[] bigIntToByteArray(BigInteger bi) {
byte[] temp = bi.toByteArray();
byte[] returnbytes = null;
if (temp[0] == 0) {
returnbytes = new byte[temp.length - 1];
System.arraycopy(temp, 1, returnbytes, 0, returnbytes.length);
return returnbytes;
} else
return temp;
}
/**
* Dekodiert aus dem übergebenen Byte-Array einen ECPoint. Das benötigte
* prime field p wird aus der übergebenen Kurve übernommen Das erste Byte
* muss den Wert 0x04 enthalten (uncompressed point).
*
* @param value
* Byte Array der Form {0x04 || x-Bytes[] || y-Bytes[]}
* @param curve
* Die Kurve auf der der Punkt liegen soll.
* @return Point generiert aus den Input-Daten
* @throws IllegalArgumentException
* Falls das erste Byte nicht den Wert 0x04 enthält, enthält das
* übergebene Byte-Array offensichtlich keinen unkomprimierten Punkt
*/
public static ECPoint byteArrayToECPoint(byte[] value, ECCurve.Fp curve)
throws IllegalArgumentException {
byte[] x = new byte[(value.length - 1) / 2];
byte[] y = new byte[(value.length - 1) / 2];
if (value[0] != (byte) 0x04)
throw new IllegalArgumentException("No uncompressed Point found!");
else {
System.arraycopy(value, 1, x, 0, (value.length - 1) / 2);
System.arraycopy(value, 1 + ((value.length - 1) / 2), y, 0,
(value.length - 1) / 2);
// ECFieldElement.Fp xE = new ECFieldElement.Fp(curve.getQ(),
// new BigInteger(1, x));
// ECFieldElement.Fp yE<SUF>
// new BigInteger(1, y));
// ECPoint point = new ECPoint.Fp(curve, xE, yE);
ECPoint point = curve.createPoint(new BigInteger(1, x), new BigInteger(1, y));
return point;
}
}
}
| False | 1,455 | 22 | 1,596 | 23 | 1,573 | 22 | 1,596 | 23 | 1,817 | 27 | false | false | false | false | false | true |
1,766 | 29606_1 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.teamin.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Henrik
*/
@Entity
@Table(name = "MORGENBROED")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Morgenbroed.findAll", query = "SELECT m FROM Morgenbroed m"),
@NamedQuery(name = "Morgenbroed.findByUserId", query = "SELECT m FROM Morgenbroed m WHERE m.userId = :userId"),
@NamedQuery(name = "Morgenbroed.findByBestilt", query = "SELECT m FROM Morgenbroed m WHERE m.bestilt = :bestilt"),
@NamedQuery(name = "Morgenbroed.findByBetalt", query = "SELECT m FROM Morgenbroed m WHERE m.betalt = :betalt")})
public class Morgenbroed implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 3)
@Column(name = "USER_ID")
private String userId;
@Basic(optional = false)
@NotNull
@Column(name = "BESTILT")
private int bestilt;
@Basic(optional = false)
@NotNull
@Column(name = "BETALT")
private int betalt;
public Morgenbroed() {
}
public Morgenbroed(String userId) {
this.userId = userId;
}
public Morgenbroed(String userId, int bestilt, int betalt) {
this.userId = userId;
this.bestilt = bestilt;
this.betalt = betalt;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public int getBestilt() {
return bestilt;
}
public void setBestilt(int bestilt) {
this.bestilt = bestilt;
}
public int getBetalt() {
return betalt;
}
public void setBetalt(int betalt) {
this.betalt = betalt;
}
@Override
public int hashCode() {
int hash = 0;
hash += (userId != null ? userId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Morgenbroed)) {
return false;
}
Morgenbroed other = (Morgenbroed) object;
if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.teamin.entity.Morgenbroed[ userId=" + userId + " ]";
}
}
| TopEE/TeaminMorgenbroedBatch | src/java/com/teamin/entity/Morgenbroed.java | 940 | /**
*
* @author Henrik
*/ | block_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.teamin.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Henrik
<SUF>*/
@Entity
@Table(name = "MORGENBROED")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Morgenbroed.findAll", query = "SELECT m FROM Morgenbroed m"),
@NamedQuery(name = "Morgenbroed.findByUserId", query = "SELECT m FROM Morgenbroed m WHERE m.userId = :userId"),
@NamedQuery(name = "Morgenbroed.findByBestilt", query = "SELECT m FROM Morgenbroed m WHERE m.bestilt = :bestilt"),
@NamedQuery(name = "Morgenbroed.findByBetalt", query = "SELECT m FROM Morgenbroed m WHERE m.betalt = :betalt")})
public class Morgenbroed implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 3)
@Column(name = "USER_ID")
private String userId;
@Basic(optional = false)
@NotNull
@Column(name = "BESTILT")
private int bestilt;
@Basic(optional = false)
@NotNull
@Column(name = "BETALT")
private int betalt;
public Morgenbroed() {
}
public Morgenbroed(String userId) {
this.userId = userId;
}
public Morgenbroed(String userId, int bestilt, int betalt) {
this.userId = userId;
this.bestilt = bestilt;
this.betalt = betalt;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public int getBestilt() {
return bestilt;
}
public void setBestilt(int bestilt) {
this.bestilt = bestilt;
}
public int getBetalt() {
return betalt;
}
public void setBetalt(int betalt) {
this.betalt = betalt;
}
@Override
public int hashCode() {
int hash = 0;
hash += (userId != null ? userId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Morgenbroed)) {
return false;
}
Morgenbroed other = (Morgenbroed) object;
if ((this.userId == null && other.userId != null) || (this.userId != null && !this.userId.equals(other.userId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.teamin.entity.Morgenbroed[ userId=" + userId + " ]";
}
}
| False | 723 | 8 | 835 | 11 | 858 | 10 | 835 | 11 | 945 | 11 | false | false | false | false | false | true |
110 | 43508_11 | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.models.Television;
import nl.novi.techiteasy.repositories.TelevisionRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
@RestController
// @RequestMapping("/persons")
// Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen
public class TelevisionController {
// Vorige week maakten we nog gebruik van een List<String>, nu gebruiken we de repository met een echte database.
// We injecteren de repository hier via de constructor, maar je mag ook @Autowired gebruiken.
private final TelevisionRepository televisionRepository;
// Constructor injection
public TelevisionController(TelevisionRepository televisionRepository) {
this.televisionRepository = televisionRepository;
}
// Show all televisions
@GetMapping("/televisions")
public ResponseEntity<List<Television>> getAllTelevisions(@RequestParam(value = "brand", required = false) String brand) { // Of ResponseEntity<String>
List<Television> televisions;
// Als geen merk ingevuld, geen parameters, geef dan alle entries weer.
if (brand == null) {
// Vul de televisions lijst met alle televisions
televisions = televisionRepository.findAll();
// Als wel een merk ingevuld, geef dan alle televisies van dit merk weer
} else {
// Vul de televisions lijst met alle television die een bepaald merk hebben
televisions = televisionRepository.findAllTelevisionsByBrandEqualsIgnoreCase(brand);
}
// return ResponseEntity.ok().body(televisions);
return new ResponseEntity<>(televisions, HttpStatus.OK); // 200 OK
}
// Geef 1 television met een specifieke id weer
@GetMapping("televisions/{id}")
public ResponseEntity<Television> getTelevision(@PathVariable("id") Long id) { // Verschil met: @PathVariable int id?
// Haal de television met het gegeven id uit de database.
// Het Optional datatype betekend "wel of niet". Als er geen television gevonden wordt, dan is de Optional empty,
// maar als er wel een television gevonden wordt, dan staat de television in de Optional en kun je deze er uit
// halen met de get-methode. Op deze manier krijg je niet meteen een error als de tv niet in de database voorkomt.
// Je kunt dat probleem zelf oplossen. In dit geval doen we dat door een RecordNotFoundException op te gooien met een message.
Optional<Television> television = televisionRepository.findById(id);
// Check of de optional empty is. Het tegenovergestelde alternatief is "television.isPresent()"
if (television.isEmpty()) {
// Als er geen television in de optional staat, roepen we hier de RecordNotFoundException constructor aan met message.
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Als er wel een television in de optional staat, dan halen we die uit de optional met de get-methode.
Television television1 = television.get(); // Haal het uit de optional en stop het in television1
// Return de television en een 200 status
return ResponseEntity.ok().body(television1);
}
}
// We geven hier een television mee in de parameter. Zorg dat je JSON object exact overeenkomt met het Television object.
@PostMapping("/televisions")
public ResponseEntity<Television> addTelevision(@RequestBody Television television) {
// Er vanuit gaande dat televisies direct in de applicatie worden toegevoegd als ze gekocht zijn.
television.setOriginalStock(LocalDate.now()); // Wat doet dit in de database?
// Sla de nieuwe tv in de database op met de save-methode van de repository
Television returnTelevision = televisionRepository.save(television);
// Hier moet eigen nog een URI uri response.
// Return de gemaakte television en een 201 status
return ResponseEntity.created(null).body(returnTelevision);
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Object> deleteTelevision(@PathVariable("id") Long id) {
// Verwijder de television met het opgegeven id uit de database.
televisionRepository.deleteById(id);
// Return een 204 status
return ResponseEntity.noContent().build();
}
// Update a television
@PutMapping("/televisions/{id}")
public ResponseEntity<Television> updateTelevision(@PathVariable Long id, @RequestBody Television newTelevision) {
// Haal de aan te passen tv uit de database met het gegeven id
Optional<Television> television = televisionRepository.findById(id);
// Als eerste checken we of de aan te passen tv wel in de database bestaat.
if (television.isEmpty()) {
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Verander alle waardes van de television uit de database naar de waardes van de television uit de parameters.
// Behalve de id. Als je de id veranderd, dan wordt er een nieuw object gemaakt in de database.
Television television1 = television.get();
television1.setAvailableSize(newTelevision.getAvailableSize());
television1.setAmbiLight(newTelevision.getAmbiLight());
television1.setBluetooth(newTelevision.getBluetooth());
television1.setBrand(newTelevision.getBrand());
television1.setHdr(newTelevision.getHdr());
television1.setName(newTelevision.getName());
television1.setOriginalStock(newTelevision.getOriginalStock());
television1.setPrice(newTelevision.getPrice());
television1.setRefreshRate(newTelevision.getRefreshRate());
television1.setScreenQuality(newTelevision.getScreenQuality());
television1.setScreenType(newTelevision.getScreenType());
television1.setSmartTv(newTelevision.getSmartTv());
television1.setSold(newTelevision.getSold());
television1.setType(newTelevision.getType());
television1.setVoiceControl(newTelevision.getVoiceControl());
television1.setWifi(newTelevision.getWifi());
// Sla de gewijzigde waarden op in de database onder dezelfde id. Dit moet je niet vergeten.
Television returnTelevision = televisionRepository.save(television1);
// Return de nieuwe versie van deze tv en een 200 code
return ResponseEntity.ok().body(returnTelevision);
}
}
// Televisie gedeeltelijk bijwerken
@PatchMapping("/televisions/{id}")
public ResponseEntity<Television> updatePartialTelevision(@PathVariable Long id, @RequestBody Television newTelevision) {
Optional<Television> television = televisionRepository.findById(id);
if (television.isEmpty()) {
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Het verschil tussen een patch en een put methode is dat een put een compleet object update,
// waar een patch een gedeeltelijk object kan updaten.
// Zet alles in een null-check, om te voorkomen dat je perongelijk bestaande waardes overschrijft met null-waardes.
// Intellij heeft een handige postfix voor null-checks. Dit doe je door bijvoorbeeld "newTelevision.getBrand().notnull" te typen en dan op tab te drukken.
Television television1 = television.get();
if (newTelevision.getAmbiLight() != null) {
television1.setAmbiLight(newTelevision.getAmbiLight());
}
if (newTelevision.getAvailableSize() != null) {
television1.setAvailableSize(newTelevision.getAvailableSize());
}
if (newTelevision.getBluetooth()) {
television1.setBluetooth(newTelevision.getBluetooth());
}
if (newTelevision.getBrand() != null) {
television1.setBrand(newTelevision.getBrand());
}
if (newTelevision.getHdr() != null) {
television1.setHdr(newTelevision.getHdr());
}
if (newTelevision.getName() != null) {
television1.setName(newTelevision.getName());
}
if (newTelevision.getOriginalStock() != null) {
television1.setOriginalStock(newTelevision.getOriginalStock());
}
if (newTelevision.getPrice() != null) {
television1.setPrice(newTelevision.getPrice());
}
if (newTelevision.getRefreshRate() != null) {
television1.setRefreshRate(newTelevision.getRefreshRate());
}
if (newTelevision.getScreenQuality() != null) {
television1.setScreenQuality(newTelevision.getScreenQuality());
}
if (newTelevision.getScreenType() != null) {
television1.setScreenType(newTelevision.getScreenType());
}
if (newTelevision.getSmartTv() != null) {
television1.setSmartTv(newTelevision.getSmartTv());
}
if (newTelevision.getSold() != null) {
television1.setSold(newTelevision.getSold());
}
if (newTelevision.getType() != null) {
television1.setType(newTelevision.getType());
}
if (newTelevision.getVoiceControl() != null) {
television1.setVoiceControl(newTelevision.getVoiceControl());
}
if (newTelevision.getWifi() != null) {
television1.setWifi(newTelevision.getWifi());
}
Television returnTelevision = televisionRepository.save(television1);
return ResponseEntity.ok().body(returnTelevision);
}
}
} | Aphelion-im/Les-11-uitwerking-opdracht-backend-spring-boot-tech-it-easy-model | src/main/java/nl/novi/techiteasy/controllers/TelevisionController.java | 2,825 | // Het Optional datatype betekend "wel of niet". Als er geen television gevonden wordt, dan is de Optional empty, | line_comment | nl | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.models.Television;
import nl.novi.techiteasy.repositories.TelevisionRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
@RestController
// @RequestMapping("/persons")
// Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen
public class TelevisionController {
// Vorige week maakten we nog gebruik van een List<String>, nu gebruiken we de repository met een echte database.
// We injecteren de repository hier via de constructor, maar je mag ook @Autowired gebruiken.
private final TelevisionRepository televisionRepository;
// Constructor injection
public TelevisionController(TelevisionRepository televisionRepository) {
this.televisionRepository = televisionRepository;
}
// Show all televisions
@GetMapping("/televisions")
public ResponseEntity<List<Television>> getAllTelevisions(@RequestParam(value = "brand", required = false) String brand) { // Of ResponseEntity<String>
List<Television> televisions;
// Als geen merk ingevuld, geen parameters, geef dan alle entries weer.
if (brand == null) {
// Vul de televisions lijst met alle televisions
televisions = televisionRepository.findAll();
// Als wel een merk ingevuld, geef dan alle televisies van dit merk weer
} else {
// Vul de televisions lijst met alle television die een bepaald merk hebben
televisions = televisionRepository.findAllTelevisionsByBrandEqualsIgnoreCase(brand);
}
// return ResponseEntity.ok().body(televisions);
return new ResponseEntity<>(televisions, HttpStatus.OK); // 200 OK
}
// Geef 1 television met een specifieke id weer
@GetMapping("televisions/{id}")
public ResponseEntity<Television> getTelevision(@PathVariable("id") Long id) { // Verschil met: @PathVariable int id?
// Haal de television met het gegeven id uit de database.
// Het Optional<SUF>
// maar als er wel een television gevonden wordt, dan staat de television in de Optional en kun je deze er uit
// halen met de get-methode. Op deze manier krijg je niet meteen een error als de tv niet in de database voorkomt.
// Je kunt dat probleem zelf oplossen. In dit geval doen we dat door een RecordNotFoundException op te gooien met een message.
Optional<Television> television = televisionRepository.findById(id);
// Check of de optional empty is. Het tegenovergestelde alternatief is "television.isPresent()"
if (television.isEmpty()) {
// Als er geen television in de optional staat, roepen we hier de RecordNotFoundException constructor aan met message.
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Als er wel een television in de optional staat, dan halen we die uit de optional met de get-methode.
Television television1 = television.get(); // Haal het uit de optional en stop het in television1
// Return de television en een 200 status
return ResponseEntity.ok().body(television1);
}
}
// We geven hier een television mee in de parameter. Zorg dat je JSON object exact overeenkomt met het Television object.
@PostMapping("/televisions")
public ResponseEntity<Television> addTelevision(@RequestBody Television television) {
// Er vanuit gaande dat televisies direct in de applicatie worden toegevoegd als ze gekocht zijn.
television.setOriginalStock(LocalDate.now()); // Wat doet dit in de database?
// Sla de nieuwe tv in de database op met de save-methode van de repository
Television returnTelevision = televisionRepository.save(television);
// Hier moet eigen nog een URI uri response.
// Return de gemaakte television en een 201 status
return ResponseEntity.created(null).body(returnTelevision);
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Object> deleteTelevision(@PathVariable("id") Long id) {
// Verwijder de television met het opgegeven id uit de database.
televisionRepository.deleteById(id);
// Return een 204 status
return ResponseEntity.noContent().build();
}
// Update a television
@PutMapping("/televisions/{id}")
public ResponseEntity<Television> updateTelevision(@PathVariable Long id, @RequestBody Television newTelevision) {
// Haal de aan te passen tv uit de database met het gegeven id
Optional<Television> television = televisionRepository.findById(id);
// Als eerste checken we of de aan te passen tv wel in de database bestaat.
if (television.isEmpty()) {
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Verander alle waardes van de television uit de database naar de waardes van de television uit de parameters.
// Behalve de id. Als je de id veranderd, dan wordt er een nieuw object gemaakt in de database.
Television television1 = television.get();
television1.setAvailableSize(newTelevision.getAvailableSize());
television1.setAmbiLight(newTelevision.getAmbiLight());
television1.setBluetooth(newTelevision.getBluetooth());
television1.setBrand(newTelevision.getBrand());
television1.setHdr(newTelevision.getHdr());
television1.setName(newTelevision.getName());
television1.setOriginalStock(newTelevision.getOriginalStock());
television1.setPrice(newTelevision.getPrice());
television1.setRefreshRate(newTelevision.getRefreshRate());
television1.setScreenQuality(newTelevision.getScreenQuality());
television1.setScreenType(newTelevision.getScreenType());
television1.setSmartTv(newTelevision.getSmartTv());
television1.setSold(newTelevision.getSold());
television1.setType(newTelevision.getType());
television1.setVoiceControl(newTelevision.getVoiceControl());
television1.setWifi(newTelevision.getWifi());
// Sla de gewijzigde waarden op in de database onder dezelfde id. Dit moet je niet vergeten.
Television returnTelevision = televisionRepository.save(television1);
// Return de nieuwe versie van deze tv en een 200 code
return ResponseEntity.ok().body(returnTelevision);
}
}
// Televisie gedeeltelijk bijwerken
@PatchMapping("/televisions/{id}")
public ResponseEntity<Television> updatePartialTelevision(@PathVariable Long id, @RequestBody Television newTelevision) {
Optional<Television> television = televisionRepository.findById(id);
if (television.isEmpty()) {
throw new RecordNotFoundException("No television found with id: " + id);
} else {
// Het verschil tussen een patch en een put methode is dat een put een compleet object update,
// waar een patch een gedeeltelijk object kan updaten.
// Zet alles in een null-check, om te voorkomen dat je perongelijk bestaande waardes overschrijft met null-waardes.
// Intellij heeft een handige postfix voor null-checks. Dit doe je door bijvoorbeeld "newTelevision.getBrand().notnull" te typen en dan op tab te drukken.
Television television1 = television.get();
if (newTelevision.getAmbiLight() != null) {
television1.setAmbiLight(newTelevision.getAmbiLight());
}
if (newTelevision.getAvailableSize() != null) {
television1.setAvailableSize(newTelevision.getAvailableSize());
}
if (newTelevision.getBluetooth()) {
television1.setBluetooth(newTelevision.getBluetooth());
}
if (newTelevision.getBrand() != null) {
television1.setBrand(newTelevision.getBrand());
}
if (newTelevision.getHdr() != null) {
television1.setHdr(newTelevision.getHdr());
}
if (newTelevision.getName() != null) {
television1.setName(newTelevision.getName());
}
if (newTelevision.getOriginalStock() != null) {
television1.setOriginalStock(newTelevision.getOriginalStock());
}
if (newTelevision.getPrice() != null) {
television1.setPrice(newTelevision.getPrice());
}
if (newTelevision.getRefreshRate() != null) {
television1.setRefreshRate(newTelevision.getRefreshRate());
}
if (newTelevision.getScreenQuality() != null) {
television1.setScreenQuality(newTelevision.getScreenQuality());
}
if (newTelevision.getScreenType() != null) {
television1.setScreenType(newTelevision.getScreenType());
}
if (newTelevision.getSmartTv() != null) {
television1.setSmartTv(newTelevision.getSmartTv());
}
if (newTelevision.getSold() != null) {
television1.setSold(newTelevision.getSold());
}
if (newTelevision.getType() != null) {
television1.setType(newTelevision.getType());
}
if (newTelevision.getVoiceControl() != null) {
television1.setVoiceControl(newTelevision.getVoiceControl());
}
if (newTelevision.getWifi() != null) {
television1.setWifi(newTelevision.getWifi());
}
Television returnTelevision = televisionRepository.save(television1);
return ResponseEntity.ok().body(returnTelevision);
}
}
} | True | 2,131 | 26 | 2,479 | 32 | 2,293 | 24 | 2,479 | 32 | 2,750 | 27 | false | false | false | false | false | true |
3,869 | 107781_3 | import java.util.*;
public class JData { //JData stands for Julian Date, as used in astronomy.
private int dia, mes, ano;
private int julianData;
//--- CONSTRUTORES --------------------------------------------
public JData(int dia, int mes , int ano) {
this.dia = dia;
this.mes = mes;
this.ano = ano;
this.julianData = dataToJData(dia, mes, ano);
}
public JData() {
Calendar cal = Calendar.getInstance();
this.ano = cal.get(Calendar.YEAR);
this.mes = cal.get(Calendar.MONTH) + 1;
this.dia = cal.get(Calendar.DAY_OF_MONTH);
this.julianData = dataToJData(this.dia, this.mes, this.ano);
}
//--- METODOS ------------------------------------------------
//--- getters
public int getDia() {
return dia;
}
public int getMes() {
return mes;
}
public int getAno() {
return ano;
}
public int getJulianData() {
return julianData;
}
//--- print functions
public void printData() {
System.out.printf("%02d-%02d-%04d",dia, mes, ano);
}
public void printDataExtenso(int dia, int mes, int ano) {
System.out.print(getDia() + " de " + nomeDoMes() + " de " + getAno());
}
//--- conversion functions
public int dataToJData(int dia, int mes, int ano) { // only for dates after 01-01-2000
int diasTotal = 0;
int diasExtra = (ano - 2000) / 4;
diasTotal = (ano - 2000) * 365 + diasExtra;
for (int i = 0; i < mes; i++) {
diasTotal += diasNoMes(i, ano);
}
diasTotal += dia;
return diasTotal;
}
public String nomeDoMes() {
String[] meses = {"Janeiro", "Fevereiro", "Marco", "Abril", "Maio",
"Junho", "Julho", "Agosto", "Setembro", "Outubro",
"Novembro", "Dezembro"};
return meses[mes - 1];
}
public void vaiParaAmanha() {
if (dia < diasNoMes(mes, ano)) {
dia++;
} else {
dia = 1;
if (mes == 12) {
mes = 1;
ano++;
} else {
mes++;
}
}
//~ dataArray[0] += 1;
}
public void vaiParaOntem() {
if (dia > 1) {
dia--;
} else {
if (mes == 1) {
mes = 12;
ano--;
} else {
mes--;
}
dia = diasNoMes(mes, ano);
}
//~ dataArray[0] -= 1;
}
public boolean dataIgual(JData oldData) {
if (julianData == oldData.julianData) {
return true;
}
return false;
}
public boolean dataMaior(JData oldData) {
if (julianData > oldData.julianData) {
return true;
}
return false;
}
public boolean dataMenor(JData oldData) {
if (julianData < oldData.julianData) {
return true;
}
return false;
}
public int subtract(JData oldData) {
return julianData - oldData.julianData;
}
//--- METODODOS DA CLASSE ------------------------------------
public static boolean bissexto(int ano) {
return ((ano % 4 == 0) && (ano % 100 != 0) || (ano % 400 == 0));
}
public static int diasNoMes(int mes, int ano) {
int dias = 0;
switch (mes) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
default: //Fevereiro
return (bissexto(ano)) ? 28 : 29;
}
}
public static boolean validarData(int dia, int mes, int ano) {
return((dia <= diasNoMes(mes, ano)) && (mes > 0 && mes < 13));
}
}
| obiwit/100cerebros | Ano 1/P2/LuisMoura/aula03/JData.java | 1,317 | //--- getters | line_comment | nl | import java.util.*;
public class JData { //JData stands for Julian Date, as used in astronomy.
private int dia, mes, ano;
private int julianData;
//--- CONSTRUTORES --------------------------------------------
public JData(int dia, int mes , int ano) {
this.dia = dia;
this.mes = mes;
this.ano = ano;
this.julianData = dataToJData(dia, mes, ano);
}
public JData() {
Calendar cal = Calendar.getInstance();
this.ano = cal.get(Calendar.YEAR);
this.mes = cal.get(Calendar.MONTH) + 1;
this.dia = cal.get(Calendar.DAY_OF_MONTH);
this.julianData = dataToJData(this.dia, this.mes, this.ano);
}
//--- METODOS ------------------------------------------------
//--- getters<SUF>
public int getDia() {
return dia;
}
public int getMes() {
return mes;
}
public int getAno() {
return ano;
}
public int getJulianData() {
return julianData;
}
//--- print functions
public void printData() {
System.out.printf("%02d-%02d-%04d",dia, mes, ano);
}
public void printDataExtenso(int dia, int mes, int ano) {
System.out.print(getDia() + " de " + nomeDoMes() + " de " + getAno());
}
//--- conversion functions
public int dataToJData(int dia, int mes, int ano) { // only for dates after 01-01-2000
int diasTotal = 0;
int diasExtra = (ano - 2000) / 4;
diasTotal = (ano - 2000) * 365 + diasExtra;
for (int i = 0; i < mes; i++) {
diasTotal += diasNoMes(i, ano);
}
diasTotal += dia;
return diasTotal;
}
public String nomeDoMes() {
String[] meses = {"Janeiro", "Fevereiro", "Marco", "Abril", "Maio",
"Junho", "Julho", "Agosto", "Setembro", "Outubro",
"Novembro", "Dezembro"};
return meses[mes - 1];
}
public void vaiParaAmanha() {
if (dia < diasNoMes(mes, ano)) {
dia++;
} else {
dia = 1;
if (mes == 12) {
mes = 1;
ano++;
} else {
mes++;
}
}
//~ dataArray[0] += 1;
}
public void vaiParaOntem() {
if (dia > 1) {
dia--;
} else {
if (mes == 1) {
mes = 12;
ano--;
} else {
mes--;
}
dia = diasNoMes(mes, ano);
}
//~ dataArray[0] -= 1;
}
public boolean dataIgual(JData oldData) {
if (julianData == oldData.julianData) {
return true;
}
return false;
}
public boolean dataMaior(JData oldData) {
if (julianData > oldData.julianData) {
return true;
}
return false;
}
public boolean dataMenor(JData oldData) {
if (julianData < oldData.julianData) {
return true;
}
return false;
}
public int subtract(JData oldData) {
return julianData - oldData.julianData;
}
//--- METODODOS DA CLASSE ------------------------------------
public static boolean bissexto(int ano) {
return ((ano % 4 == 0) && (ano % 100 != 0) || (ano % 400 == 0));
}
public static int diasNoMes(int mes, int ano) {
int dias = 0;
switch (mes) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
default: //Fevereiro
return (bissexto(ano)) ? 28 : 29;
}
}
public static boolean validarData(int dia, int mes, int ano) {
return((dia <= diasNoMes(mes, ano)) && (mes > 0 && mes < 13));
}
}
| False | 1,097 | 4 | 1,284 | 4 | 1,242 | 3 | 1,284 | 4 | 1,469 | 5 | false | false | false | false | false | true |
1,089 | 165279_4 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ui.controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import ui.VIVESbike;
/**
* FXML Controller class
*
* @author Martijn
*/
public class StartschermController implements Initializable {
// referentie naar VIVESbike (main)
private VIVESbike parent;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
/**
* Referentie naar parent (start) instellen
*
* @param parent referentie naar de runnable class die alle oproepen naar de
* schermen bestuurt
*/
public void setParent(VIVESbike p) {
parent = p;
}
}
| MaximilianCoutuer/vivesbike | src/ui/controller/StartschermController.java | 280 | /**
* Referentie naar parent (start) instellen
*
* @param parent referentie naar de runnable class die alle oproepen naar de
* schermen bestuurt
*/ | block_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ui.controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import ui.VIVESbike;
/**
* FXML Controller class
*
* @author Martijn
*/
public class StartschermController implements Initializable {
// referentie naar VIVESbike (main)
private VIVESbike parent;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
/**
* Referentie naar parent<SUF>*/
public void setParent(VIVESbike p) {
parent = p;
}
}
| True | 218 | 47 | 256 | 45 | 254 | 45 | 256 | 45 | 285 | 51 | false | false | false | false | false | true |
2,739 | 75903_24 |
// PACKAGE GENTLY - GENTLE RUNTIME LIBRARY
// COPYRIGHT (C) 2000-2013 COMPILERTOOLS.NET
// ALL RIGHTS RESERVED. MAY BE DISTRIBUTED
// AS PART OF SOFTWARE GENERATED WITH GENTLE
package Gently;_x000D_
_x000D_
public class SemanticActions_x000D_
{_x000D_
public static void TraceAction()_x000D_
{_x000D_
}_x000D_
_x000D_
// === Parser Actions ===_x000D_
_x000D_
// ...................................................................._x000D_
// called in semantic actions of parser :_x000D_
// SourceRange //1_x000D_
// SourceRangeEmpty //2_x000D_
// ...................................................................._x000D_
_x000D_
// Source Range_x000D_
// ------------_x000D_
// called in semantic action of generated parser_x000D_
// m : m1 ... mn {_x000D_
// x = Node (...);_x000D_
// SourceRange($1, $n, x);_x000D_
// $$ = x;_x000D_
// }_x000D_
static LexerState Voriger = null;_x000D_
_x000D_
public static void SourceRange(JavaNode x1, JavaNode x2, JavaNode x,_x000D_
LexerState PEgon, int Folding)_x000D_
// 1_x000D_
{_x000D_
_x000D_
int line1 = x1.getCoordinate().getLine();_x000D_
int offset1 = x1.getCoordinate().getOffset();_x000D_
int length1 = x1.getCoordinate().getLength();_x000D_
int offset2 = x2.getCoordinate().getOffset();_x000D_
int length2 = x2.getCoordinate().getLength();_x000D_
_x000D_
int line = line1;_x000D_
int offset = offset1;_x000D_
int length = offset2 + length2 - offset1;_x000D_
_x000D_
if (Voriger == null)_x000D_
Voriger = PEgon;_x000D_
_x000D_
x.setCoordinate(new Coordinate(TokenStream.CurrentFile, line, offset,_x000D_
length));_x000D_
_x000D_
x.SetChildPositions();_x000D_
_x000D_
if (x.folding != 1)_x000D_
x.folding = Folding;_x000D_
_x000D_
Voriger = PEgon;_x000D_
}_x000D_
_x000D_
// SourceRangeEmpty_x000D_
// ----------------_x000D_
// called in semantic action of generated parser_x000D_
// see SourceRange_x000D_
// used for empty rhs_x000D_
public static void SourceRangeEmpty(JavaNode x, LexerState PEgon)_x000D_
{_x000D_
x.setCoordinate(new Coordinate(TokenStream.CurrentFile, PEgon.SourceLine,_x000D_
PEgon.SourceOffset, 0 // length_x000D_
));_x000D_
_x000D_
}_x000D_
_x000D_
// === Lexer Actions ===_x000D_
_x000D_
// Yywhitespace_x000D_
// ------------_x000D_
// called in semantic action of generated lexer rules for whitespace_x000D_
// e.g._x000D_
// " " {_x000D_
// Yywhitespace(yytext);_x000D_
// }_x000D_
public static void Yywhitespace(String str, LexerState LEgon)_x000D_
{_x000D_
final int len = str.length();_x000D_
_x000D_
CheckForEol(str, LEgon);_x000D_
_x000D_
JavaStringValue node = new JavaStringValue(str);_x000D_
_x000D_
// int offset = Egon.SourceOffset-len;_x000D_
int offset = LEgon.SourceOffset - len;_x000D_
TokenStream.STARTOFFSET = offset;_x000D_
_x000D_
node.setCoordinate(new Coordinate( // COORD 1 YyWhitespace (Lexer)_x000D_
TokenStream.CurrentFile, LEgon.SourceLine, offset, len));_x000D_
_x000D_
LEgon.yylval = node;_x000D_
LexerState.LEXERSTATE_yylval = node;_x000D_
_x000D_
}_x000D_
_x000D_
// Yyunmatched_x000D_
// -----------_x000D_
// called in semantic action of generated lexer rule_x000D_
// for unmatched input_x000D_
// e.g._x000D_
// . {_x000D_
// Yyunmatched(yytext);_x000D_
// }_x000D_
public static void Yyunmatched(String str, LexerState LEgon)_x000D_
{_x000D_
final int startoffset = LEgon.SourceOffset;// +1;_x000D_
final int len = str.length();_x000D_
_x000D_
TokenStream.STARTOFFSET = startoffset;_x000D_
_x000D_
CheckForEol(str, LEgon);_x000D_
_x000D_
JavaStringValue node = new JavaStringValue(str);_x000D_
_x000D_
int offset = LEgon.SourceOffset - len;_x000D_
node.setCoordinate(new Coordinate( // COORD 2 Yytext (Lexer)_x000D_
TokenStream.CurrentFile, LEgon.SourceLine, startoffset, // offset,_x000D_
len));_x000D_
_x000D_
LEgon.yylval = node;_x000D_
LexerState.LEXERSTATE_yylval = node;_x000D_
_x000D_
}_x000D_
_x000D_
// Yytext_x000D_
// ------_x000D_
// called in semactic actions of lex rules for matched tokens_x000D_
// e.g._x000D_
// "abc" {_x000D_
// yylval = Yytext(yytext);_x000D_
// return tokencode;_x000D_
// }_x000D_
public static JavaNode Yytext(String str, LexerState LEgon)_x000D_
{_x000D_
_x000D_
final int startoffset = LEgon.SourceOffset;// +1;_x000D_
final int len = str.length();_x000D_
_x000D_
TokenStream.STARTOFFSET = startoffset;_x000D_
_x000D_
CheckForEol(str, LEgon);_x000D_
_x000D_
JavaStringValue node = new JavaStringValue(str);_x000D_
_x000D_
node.setCoordinate(new Coordinate( // COORD 2 Yytext (Lexer)_x000D_
TokenStream.CurrentFile, LEgon.SourceLine, startoffset, // offset,_x000D_
len));_x000D_
_x000D_
LEgon.yylval = node;_x000D_
LexerState.LEXERSTATE_yylval = node;_x000D_
_x000D_
return node;_x000D_
}_x000D_
_x000D_
// see value converter_x000D_
public static void AssignYylval(JavaNode node, LexerState Egon)_x000D_
{_x000D_
Egon.yylval = node;_x000D_
LexerState.LEXERSTATE_yylval = node;_x000D_
}_x000D_
_x000D_
private static void CheckForEol(String str, LexerState LEgon)_x000D_
{_x000D_
final int len = str.length();_x000D_
_x000D_
for (int i = 0; i < len; i++) {_x000D_
char ch = str.charAt(i);_x000D_
_x000D_
LEgon.SourceOffset++; // NEXTCOL 1 YyWhitespace_x000D_
LexerState.LEXERSTATE_SourceOffset++;_x000D_
_x000D_
if (ch == '\n') {_x000D_
LEgon.SourceLine++; // NEXTLINE 1 YyWhitespace_x000D_
LexerState.LEXERSTATE_SourceLine++;_x000D_
}_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
| fraunhoferfokus/ot3 | OT3COMPILER/Gently/SemanticActions.java | 1,670 | // see value converter_x000D_ | line_comment | nl |
// PACKAGE GENTLY - GENTLE RUNTIME LIBRARY
// COPYRIGHT (C) 2000-2013 COMPILERTOOLS.NET
// ALL RIGHTS RESERVED. MAY BE DISTRIBUTED
// AS PART OF SOFTWARE GENERATED WITH GENTLE
package Gently;_x000D_
_x000D_
public class SemanticActions_x000D_
{_x000D_
public static void TraceAction()_x000D_
{_x000D_
}_x000D_
_x000D_
// === Parser Actions ===_x000D_
_x000D_
// ...................................................................._x000D_
// called in semantic actions of parser :_x000D_
// SourceRange //1_x000D_
// SourceRangeEmpty //2_x000D_
// ...................................................................._x000D_
_x000D_
// Source Range_x000D_
// ------------_x000D_
// called in semantic action of generated parser_x000D_
// m : m1 ... mn {_x000D_
// x = Node (...);_x000D_
// SourceRange($1, $n, x);_x000D_
// $$ = x;_x000D_
// }_x000D_
static LexerState Voriger = null;_x000D_
_x000D_
public static void SourceRange(JavaNode x1, JavaNode x2, JavaNode x,_x000D_
LexerState PEgon, int Folding)_x000D_
// 1_x000D_
{_x000D_
_x000D_
int line1 = x1.getCoordinate().getLine();_x000D_
int offset1 = x1.getCoordinate().getOffset();_x000D_
int length1 = x1.getCoordinate().getLength();_x000D_
int offset2 = x2.getCoordinate().getOffset();_x000D_
int length2 = x2.getCoordinate().getLength();_x000D_
_x000D_
int line = line1;_x000D_
int offset = offset1;_x000D_
int length = offset2 + length2 - offset1;_x000D_
_x000D_
if (Voriger == null)_x000D_
Voriger = PEgon;_x000D_
_x000D_
x.setCoordinate(new Coordinate(TokenStream.CurrentFile, line, offset,_x000D_
length));_x000D_
_x000D_
x.SetChildPositions();_x000D_
_x000D_
if (x.folding != 1)_x000D_
x.folding = Folding;_x000D_
_x000D_
Voriger = PEgon;_x000D_
}_x000D_
_x000D_
// SourceRangeEmpty_x000D_
// ----------------_x000D_
// called in semantic action of generated parser_x000D_
// see SourceRange_x000D_
// used for empty rhs_x000D_
public static void SourceRangeEmpty(JavaNode x, LexerState PEgon)_x000D_
{_x000D_
x.setCoordinate(new Coordinate(TokenStream.CurrentFile, PEgon.SourceLine,_x000D_
PEgon.SourceOffset, 0 // length_x000D_
));_x000D_
_x000D_
}_x000D_
_x000D_
// === Lexer Actions ===_x000D_
_x000D_
// Yywhitespace_x000D_
// ------------_x000D_
// called in semantic action of generated lexer rules for whitespace_x000D_
// e.g._x000D_
// " " {_x000D_
// Yywhitespace(yytext);_x000D_
// }_x000D_
public static void Yywhitespace(String str, LexerState LEgon)_x000D_
{_x000D_
final int len = str.length();_x000D_
_x000D_
CheckForEol(str, LEgon);_x000D_
_x000D_
JavaStringValue node = new JavaStringValue(str);_x000D_
_x000D_
// int offset = Egon.SourceOffset-len;_x000D_
int offset = LEgon.SourceOffset - len;_x000D_
TokenStream.STARTOFFSET = offset;_x000D_
_x000D_
node.setCoordinate(new Coordinate( // COORD 1 YyWhitespace (Lexer)_x000D_
TokenStream.CurrentFile, LEgon.SourceLine, offset, len));_x000D_
_x000D_
LEgon.yylval = node;_x000D_
LexerState.LEXERSTATE_yylval = node;_x000D_
_x000D_
}_x000D_
_x000D_
// Yyunmatched_x000D_
// -----------_x000D_
// called in semantic action of generated lexer rule_x000D_
// for unmatched input_x000D_
// e.g._x000D_
// . {_x000D_
// Yyunmatched(yytext);_x000D_
// }_x000D_
public static void Yyunmatched(String str, LexerState LEgon)_x000D_
{_x000D_
final int startoffset = LEgon.SourceOffset;// +1;_x000D_
final int len = str.length();_x000D_
_x000D_
TokenStream.STARTOFFSET = startoffset;_x000D_
_x000D_
CheckForEol(str, LEgon);_x000D_
_x000D_
JavaStringValue node = new JavaStringValue(str);_x000D_
_x000D_
int offset = LEgon.SourceOffset - len;_x000D_
node.setCoordinate(new Coordinate( // COORD 2 Yytext (Lexer)_x000D_
TokenStream.CurrentFile, LEgon.SourceLine, startoffset, // offset,_x000D_
len));_x000D_
_x000D_
LEgon.yylval = node;_x000D_
LexerState.LEXERSTATE_yylval = node;_x000D_
_x000D_
}_x000D_
_x000D_
// Yytext_x000D_
// ------_x000D_
// called in semactic actions of lex rules for matched tokens_x000D_
// e.g._x000D_
// "abc" {_x000D_
// yylval = Yytext(yytext);_x000D_
// return tokencode;_x000D_
// }_x000D_
public static JavaNode Yytext(String str, LexerState LEgon)_x000D_
{_x000D_
_x000D_
final int startoffset = LEgon.SourceOffset;// +1;_x000D_
final int len = str.length();_x000D_
_x000D_
TokenStream.STARTOFFSET = startoffset;_x000D_
_x000D_
CheckForEol(str, LEgon);_x000D_
_x000D_
JavaStringValue node = new JavaStringValue(str);_x000D_
_x000D_
node.setCoordinate(new Coordinate( // COORD 2 Yytext (Lexer)_x000D_
TokenStream.CurrentFile, LEgon.SourceLine, startoffset, // offset,_x000D_
len));_x000D_
_x000D_
LEgon.yylval = node;_x000D_
LexerState.LEXERSTATE_yylval = node;_x000D_
_x000D_
return node;_x000D_
}_x000D_
_x000D_
// see value<SUF>
public static void AssignYylval(JavaNode node, LexerState Egon)_x000D_
{_x000D_
Egon.yylval = node;_x000D_
LexerState.LEXERSTATE_yylval = node;_x000D_
}_x000D_
_x000D_
private static void CheckForEol(String str, LexerState LEgon)_x000D_
{_x000D_
final int len = str.length();_x000D_
_x000D_
for (int i = 0; i < len; i++) {_x000D_
char ch = str.charAt(i);_x000D_
_x000D_
LEgon.SourceOffset++; // NEXTCOL 1 YyWhitespace_x000D_
LexerState.LEXERSTATE_SourceOffset++;_x000D_
_x000D_
if (ch == '\n') {_x000D_
LEgon.SourceLine++; // NEXTLINE 1 YyWhitespace_x000D_
LexerState.LEXERSTATE_SourceLine++;_x000D_
}_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
| False | 2,343 | 10 | 2,535 | 11 | 2,652 | 11 | 2,535 | 11 | 2,827 | 11 | false | false | false | false | false | true |
4,082 | 26801_0 | package io.quarkus.cli.plugin;
import java.util.ArrayList;
import java.util.List;
import io.quarkus.cli.common.OutputOptionMixin;
import picocli.CommandLine.Command;
import picocli.CommandLine.ExitCode;
@Command
public class JBangCommand implements PluginCommand {
private String location; //alias, url, maven coords
private JBangSupport jbang;
private OutputOptionMixin output;
private final List<String> arguments = new ArrayList<>();
public JBangCommand() {
super();
}
public JBangCommand(String location, OutputOptionMixin output) {
this.location = location;
this.jbang = new JBangSupport(!output.isCliTest(), output);
this.output = output;
this.arguments.add(location);
}
@Override
public Integer call() throws Exception {
if (jbang.ensureJBangIsInstalled()) {
return PluginCommand.super.call();
} else {
output.error("Unable to find JBang! Command execution aborted!");
return ExitCode.SOFTWARE;
}
}
@Override
public List<String> getCommand() {
return jbang.getCommand();
}
@Override
public List<String> getArguments() {
return arguments;
}
public OutputOptionMixin getOutput() {
return output;
}
@Override
public void useArguments(List<String> arguments) {
this.arguments.clear();
this.arguments.add(location);
this.arguments.addAll(arguments);
}
}
| quarkusio/quarkus | devtools/cli/src/main/java/io/quarkus/cli/plugin/JBangCommand.java | 423 | //alias, url, maven coords | line_comment | nl | package io.quarkus.cli.plugin;
import java.util.ArrayList;
import java.util.List;
import io.quarkus.cli.common.OutputOptionMixin;
import picocli.CommandLine.Command;
import picocli.CommandLine.ExitCode;
@Command
public class JBangCommand implements PluginCommand {
private String location; //alias, url,<SUF>
private JBangSupport jbang;
private OutputOptionMixin output;
private final List<String> arguments = new ArrayList<>();
public JBangCommand() {
super();
}
public JBangCommand(String location, OutputOptionMixin output) {
this.location = location;
this.jbang = new JBangSupport(!output.isCliTest(), output);
this.output = output;
this.arguments.add(location);
}
@Override
public Integer call() throws Exception {
if (jbang.ensureJBangIsInstalled()) {
return PluginCommand.super.call();
} else {
output.error("Unable to find JBang! Command execution aborted!");
return ExitCode.SOFTWARE;
}
}
@Override
public List<String> getCommand() {
return jbang.getCommand();
}
@Override
public List<String> getArguments() {
return arguments;
}
public OutputOptionMixin getOutput() {
return output;
}
@Override
public void useArguments(List<String> arguments) {
this.arguments.clear();
this.arguments.add(location);
this.arguments.addAll(arguments);
}
}
| False | 311 | 8 | 351 | 7 | 389 | 7 | 351 | 7 | 432 | 8 | false | false | false | false | false | true |
3,206 | 14818_5 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.slaves;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.Util;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.TaskListener;
import jenkins.model.Jenkins;
import jenkins.model.identity.InstanceIdentityProvider;
import jenkins.slaves.RemotingWorkDirSettings;
import jenkins.util.SystemProperties;
import jenkins.websocket.WebSockets;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
/**
* {@link ComputerLauncher} via inbound connections.
*
* @author Stephen Connolly
* @author Kohsuke Kawaguchi
*/
@SuppressWarnings("deprecation") // see comments about CasC
public class JNLPLauncher extends ComputerLauncher {
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
@CheckForNull
public String tunnel;
/**
* @deprecated No longer used.
*/
@Deprecated
public final transient String vmargs = null;
@NonNull
private RemotingWorkDirSettings workDirSettings = RemotingWorkDirSettings.getEnabledDefaults();
private boolean webSocket;
/**
* @see #getInboundAgentUrl()
*/
@NonNull
@Restricted(NoExternalUse.class)
public static final String CUSTOM_INBOUND_URL_PROPERTY = "jenkins.agent.inboundUrl";
/**
* @deprecated no useful properties, use {@link #JNLPLauncher()}
*/
@Deprecated
public JNLPLauncher(@CheckForNull String tunnel, @CheckForNull String vmargs, @CheckForNull RemotingWorkDirSettings workDirSettings) {
this(tunnel, vmargs);
if (workDirSettings != null) {
setWorkDirSettings(workDirSettings);
}
}
/**
* @deprecated no useful properties, use {@link #JNLPLauncher()}
*/
@Deprecated
public JNLPLauncher(@CheckForNull String tunnel) {
this.tunnel = Util.fixEmptyAndTrim(tunnel);
}
/**
* @deprecated no useful properties, use {@link #JNLPLauncher()}
*/
@Deprecated
public JNLPLauncher(@CheckForNull String tunnel, @CheckForNull String vmargs) {
this.tunnel = Util.fixEmptyAndTrim(tunnel);
}
@DataBoundConstructor
public JNLPLauncher() {
}
/**
* @deprecated no useful properties, use {@link #JNLPLauncher()}
*/
@Deprecated
public JNLPLauncher(boolean enableWorkDir) {
this(null, null, enableWorkDir
? RemotingWorkDirSettings.getEnabledDefaults()
: RemotingWorkDirSettings.getDisabledDefaults());
}
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "workDirSettings in readResolve is needed for data migration.")
protected Object readResolve() {
if (workDirSettings == null) {
// For the migrated code agents are always disabled
workDirSettings = RemotingWorkDirSettings.getDisabledDefaults();
}
return this;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
public RemotingWorkDirSettings getWorkDirSettings() {
return workDirSettings;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
@DataBoundSetter
public final void setWorkDirSettings(@NonNull RemotingWorkDirSettings workDirSettings) {
this.workDirSettings = workDirSettings;
}
@Override
public boolean isLaunchSupported() {
return false;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
public boolean isWebSocket() {
return webSocket;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
@DataBoundSetter
public void setWebSocket(boolean webSocket) {
this.webSocket = webSocket;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
public String getTunnel() {
return tunnel;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
@DataBoundSetter
public void setTunnel(String tunnel) {
this.tunnel = Util.fixEmptyAndTrim(tunnel);
}
@Override
public void launch(SlaveComputer computer, TaskListener listener) {
// do nothing as we cannot self start
}
/**
* @deprecated as of 1.XXX
* Use {@link Jenkins#getDescriptor(Class)}
*/
@Deprecated
@Restricted(NoExternalUse.class)
public static /*almost final*/ Descriptor<ComputerLauncher> DESCRIPTOR;
@NonNull
@Restricted(NoExternalUse.class)
public String getRemotingOptionsUnix(@NonNull Computer computer) {
return getRemotingOptions(escapeUnix(computer.getName()));
}
@NonNull
@Restricted(NoExternalUse.class)
public String getRemotingOptionsWindows(@NonNull Computer computer) {
return getRemotingOptions(escapeWindows(computer.getName()));
}
@Restricted(DoNotUse.class)
public boolean isConfigured() {
return webSocket || tunnel != null || workDirSettings.isConfigured();
}
private String getRemotingOptions(String computerName) {
StringBuilder sb = new StringBuilder();
sb.append("-name ");
sb.append(computerName);
sb.append(' ');
if (isWebSocket()) {
sb.append("-webSocket ");
}
if (tunnel != null) {
sb.append(" -tunnel ");
sb.append(tunnel);
sb.append(' ');
}
return sb.toString();
}
/**
* {@link Jenkins#checkGoodName(String)} saves us from most troublesome characters, but we still have to deal with
* spaces and therefore with double quotes and backticks.
*/
private static String escapeUnix(@NonNull String input) {
if (!input.isEmpty() && input.chars().allMatch(Character::isLetterOrDigit)) {
return input;
}
Escaper escaper =
Escapers.builder().addEscape('"', "\\\"").addEscape('`', "\\`").build();
return "\"" + escaper.escape(input) + "\"";
}
/**
* {@link Jenkins#checkGoodName(String)} saves us from most troublesome characters, but we still have to deal with
* spaces and therefore with double quotes.
*/
private static String escapeWindows(@NonNull String input) {
if (!input.isEmpty() && input.chars().allMatch(Character::isLetterOrDigit)) {
return input;
}
Escaper escaper = Escapers.builder().addEscape('"', "\\\"").build();
return "\"" + escaper.escape(input) + "\"";
}
/**
* Gets work directory options as a String.
*
* In public API {@code getWorkDirSettings().toCommandLineArgs(computer)} should be used instead
* @param computer Computer
* @return Command line options for launching with the WorkDir
*/
@NonNull
@Restricted(NoExternalUse.class)
public String getWorkDirOptions(@NonNull Computer computer) {
if (!(computer instanceof SlaveComputer)) {
return "";
}
return workDirSettings.toCommandLineString((SlaveComputer) computer);
}
@Extension @Symbol({"inbound", "jnlp"})
public static class DescriptorImpl extends Descriptor<ComputerLauncher> {
@SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "for backward compatibility")
public DescriptorImpl() {
DESCRIPTOR = this;
}
@NonNull
@Override
public String getDisplayName() {
return Messages.JNLPLauncher_displayName();
}
/**
* Checks if Work Dir settings should be displayed.
*
* This flag is checked in {@code config.jelly} before displaying the
* {@link JNLPLauncher#workDirSettings} property.
* By default the configuration is displayed only for {@link JNLPLauncher},
* but the implementation can be overridden.
* @return {@code true} if work directories are supported by the launcher type.
* @since 2.73
*/
public boolean isWorkDirSupported() {
// This property is included only for JNLPLauncher by default.
// Causes JENKINS-45895 in the case of includes otherwise
return DescriptorImpl.class.equals(getClass());
}
@Restricted(DoNotUse.class)
public boolean isTcpSupported() {
return Jenkins.get().getTcpSlaveAgentListener() != null;
}
@Restricted(DoNotUse.class)
public boolean isInstanceIdentityInstalled() {
return InstanceIdentityProvider.RSA.getCertificate() != null && InstanceIdentityProvider.RSA.getPrivateKey() != null;
}
@Restricted(DoNotUse.class)
public boolean isWebSocketSupported() {
return WebSockets.isSupported();
}
}
/**
* Overrides the url that inbound TCP agents should connect to
* as advertised in the agent.jnlp file. If not set, the default
* behavior is unchanged and returns the root URL.
*
* This enables using a private address for inbound tcp agents,
* separate from Jenkins root URL.
*
* @see <a href="https://issues.jenkins.io/browse/JENKINS-63222">JENKINS-63222</a>
*/
@Restricted(NoExternalUse.class)
public static String getInboundAgentUrl() {
String url = SystemProperties.getString(CUSTOM_INBOUND_URL_PROPERTY);
if (url == null || url.isEmpty()) {
return Jenkins.get().getRootUrl();
}
return url;
}
}
| jenkinsci/jenkins | core/src/main/java/hudson/slaves/JNLPLauncher.java | 3,353 | /**
* @see #getInboundAgentUrl()
*/ | block_comment | nl | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.slaves;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.Util;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.TaskListener;
import jenkins.model.Jenkins;
import jenkins.model.identity.InstanceIdentityProvider;
import jenkins.slaves.RemotingWorkDirSettings;
import jenkins.util.SystemProperties;
import jenkins.websocket.WebSockets;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
/**
* {@link ComputerLauncher} via inbound connections.
*
* @author Stephen Connolly
* @author Kohsuke Kawaguchi
*/
@SuppressWarnings("deprecation") // see comments about CasC
public class JNLPLauncher extends ComputerLauncher {
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
@CheckForNull
public String tunnel;
/**
* @deprecated No longer used.
*/
@Deprecated
public final transient String vmargs = null;
@NonNull
private RemotingWorkDirSettings workDirSettings = RemotingWorkDirSettings.getEnabledDefaults();
private boolean webSocket;
/**
* @see #getInboundAgentUrl()
<SUF>*/
@NonNull
@Restricted(NoExternalUse.class)
public static final String CUSTOM_INBOUND_URL_PROPERTY = "jenkins.agent.inboundUrl";
/**
* @deprecated no useful properties, use {@link #JNLPLauncher()}
*/
@Deprecated
public JNLPLauncher(@CheckForNull String tunnel, @CheckForNull String vmargs, @CheckForNull RemotingWorkDirSettings workDirSettings) {
this(tunnel, vmargs);
if (workDirSettings != null) {
setWorkDirSettings(workDirSettings);
}
}
/**
* @deprecated no useful properties, use {@link #JNLPLauncher()}
*/
@Deprecated
public JNLPLauncher(@CheckForNull String tunnel) {
this.tunnel = Util.fixEmptyAndTrim(tunnel);
}
/**
* @deprecated no useful properties, use {@link #JNLPLauncher()}
*/
@Deprecated
public JNLPLauncher(@CheckForNull String tunnel, @CheckForNull String vmargs) {
this.tunnel = Util.fixEmptyAndTrim(tunnel);
}
@DataBoundConstructor
public JNLPLauncher() {
}
/**
* @deprecated no useful properties, use {@link #JNLPLauncher()}
*/
@Deprecated
public JNLPLauncher(boolean enableWorkDir) {
this(null, null, enableWorkDir
? RemotingWorkDirSettings.getEnabledDefaults()
: RemotingWorkDirSettings.getDisabledDefaults());
}
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "workDirSettings in readResolve is needed for data migration.")
protected Object readResolve() {
if (workDirSettings == null) {
// For the migrated code agents are always disabled
workDirSettings = RemotingWorkDirSettings.getDisabledDefaults();
}
return this;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
public RemotingWorkDirSettings getWorkDirSettings() {
return workDirSettings;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
@DataBoundSetter
public final void setWorkDirSettings(@NonNull RemotingWorkDirSettings workDirSettings) {
this.workDirSettings = workDirSettings;
}
@Override
public boolean isLaunchSupported() {
return false;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
public boolean isWebSocket() {
return webSocket;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
@DataBoundSetter
public void setWebSocket(boolean webSocket) {
this.webSocket = webSocket;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
public String getTunnel() {
return tunnel;
}
/**
* Deprecated (only used with deprecated {@code -jnlpUrl} mode), but cannot mark it as such without breaking CasC.
*/
@DataBoundSetter
public void setTunnel(String tunnel) {
this.tunnel = Util.fixEmptyAndTrim(tunnel);
}
@Override
public void launch(SlaveComputer computer, TaskListener listener) {
// do nothing as we cannot self start
}
/**
* @deprecated as of 1.XXX
* Use {@link Jenkins#getDescriptor(Class)}
*/
@Deprecated
@Restricted(NoExternalUse.class)
public static /*almost final*/ Descriptor<ComputerLauncher> DESCRIPTOR;
@NonNull
@Restricted(NoExternalUse.class)
public String getRemotingOptionsUnix(@NonNull Computer computer) {
return getRemotingOptions(escapeUnix(computer.getName()));
}
@NonNull
@Restricted(NoExternalUse.class)
public String getRemotingOptionsWindows(@NonNull Computer computer) {
return getRemotingOptions(escapeWindows(computer.getName()));
}
@Restricted(DoNotUse.class)
public boolean isConfigured() {
return webSocket || tunnel != null || workDirSettings.isConfigured();
}
private String getRemotingOptions(String computerName) {
StringBuilder sb = new StringBuilder();
sb.append("-name ");
sb.append(computerName);
sb.append(' ');
if (isWebSocket()) {
sb.append("-webSocket ");
}
if (tunnel != null) {
sb.append(" -tunnel ");
sb.append(tunnel);
sb.append(' ');
}
return sb.toString();
}
/**
* {@link Jenkins#checkGoodName(String)} saves us from most troublesome characters, but we still have to deal with
* spaces and therefore with double quotes and backticks.
*/
private static String escapeUnix(@NonNull String input) {
if (!input.isEmpty() && input.chars().allMatch(Character::isLetterOrDigit)) {
return input;
}
Escaper escaper =
Escapers.builder().addEscape('"', "\\\"").addEscape('`', "\\`").build();
return "\"" + escaper.escape(input) + "\"";
}
/**
* {@link Jenkins#checkGoodName(String)} saves us from most troublesome characters, but we still have to deal with
* spaces and therefore with double quotes.
*/
private static String escapeWindows(@NonNull String input) {
if (!input.isEmpty() && input.chars().allMatch(Character::isLetterOrDigit)) {
return input;
}
Escaper escaper = Escapers.builder().addEscape('"', "\\\"").build();
return "\"" + escaper.escape(input) + "\"";
}
/**
* Gets work directory options as a String.
*
* In public API {@code getWorkDirSettings().toCommandLineArgs(computer)} should be used instead
* @param computer Computer
* @return Command line options for launching with the WorkDir
*/
@NonNull
@Restricted(NoExternalUse.class)
public String getWorkDirOptions(@NonNull Computer computer) {
if (!(computer instanceof SlaveComputer)) {
return "";
}
return workDirSettings.toCommandLineString((SlaveComputer) computer);
}
@Extension @Symbol({"inbound", "jnlp"})
public static class DescriptorImpl extends Descriptor<ComputerLauncher> {
@SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "for backward compatibility")
public DescriptorImpl() {
DESCRIPTOR = this;
}
@NonNull
@Override
public String getDisplayName() {
return Messages.JNLPLauncher_displayName();
}
/**
* Checks if Work Dir settings should be displayed.
*
* This flag is checked in {@code config.jelly} before displaying the
* {@link JNLPLauncher#workDirSettings} property.
* By default the configuration is displayed only for {@link JNLPLauncher},
* but the implementation can be overridden.
* @return {@code true} if work directories are supported by the launcher type.
* @since 2.73
*/
public boolean isWorkDirSupported() {
// This property is included only for JNLPLauncher by default.
// Causes JENKINS-45895 in the case of includes otherwise
return DescriptorImpl.class.equals(getClass());
}
@Restricted(DoNotUse.class)
public boolean isTcpSupported() {
return Jenkins.get().getTcpSlaveAgentListener() != null;
}
@Restricted(DoNotUse.class)
public boolean isInstanceIdentityInstalled() {
return InstanceIdentityProvider.RSA.getCertificate() != null && InstanceIdentityProvider.RSA.getPrivateKey() != null;
}
@Restricted(DoNotUse.class)
public boolean isWebSocketSupported() {
return WebSockets.isSupported();
}
}
/**
* Overrides the url that inbound TCP agents should connect to
* as advertised in the agent.jnlp file. If not set, the default
* behavior is unchanged and returns the root URL.
*
* This enables using a private address for inbound tcp agents,
* separate from Jenkins root URL.
*
* @see <a href="https://issues.jenkins.io/browse/JENKINS-63222">JENKINS-63222</a>
*/
@Restricted(NoExternalUse.class)
public static String getInboundAgentUrl() {
String url = SystemProperties.getString(CUSTOM_INBOUND_URL_PROPERTY);
if (url == null || url.isEmpty()) {
return Jenkins.get().getRootUrl();
}
return url;
}
}
| False | 2,579 | 14 | 2,728 | 13 | 2,901 | 15 | 2,728 | 13 | 3,388 | 16 | false | false | false | false | false | true |
4,705 | 177532_14 | package nl.wildlands.wildlandseducation.Activities;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import nl.wildlands.wildlandseducation.GlobalSettings.DefaultApplication;
import nl.wildlands.wildlandseducation.R;
/**
* Activity waarbij de docent de gegevens van de quiz kan invoeren
* en deze vervolgens d.m.v. socekts wordt aangemaakt
*/
public class GenerateQuiz extends Activity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
ImageButton backBtn; // ImageButton om terug te gaan
Button generateQuiz; // Button om quiz te genereren
Socket mSocket; // Socket voor de quizverbinding
private SeekBar bar; // Seekbar om tijd dynamisch in te stellen
private TextView textProgress, genereerQuiz,tijd; // TextView voor weergave huidige tijdsinput
/**
* Actie die voltrokken wordt, als de socket een bepaald bericht krijgt
*/
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
GenerateQuiz.this.runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0]; // Zet de data om in een JSONObject
String success; // Succes van aanmaken
int quizID; // ID van de gegenereerde quiz
try {
success = data.getString("success"); // Success message
quizID = data.getInt("quizid"); // Quizid
} catch (JSONException e) {
return;
}
startNewActivity(success, quizID); // Roep startNewActivity aan met de waardes
}
});
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Zet layout
setContentView(R.layout.activity_generate_quiz);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // Fullscreen
WindowManager.LayoutParams.FLAG_FULLSCREEN);
generateQuiz = (Button)findViewById(R.id.generateQuiz); // Button voor genereren quiz
generateQuiz.setOnClickListener(this); // Activeer knopactie
backBtn = (ImageButton)findViewById(R.id.quitbutton); // ImageButton om terug te gaan
backBtn.setOnClickListener(this); // Activeer knopactie
bar =(SeekBar)findViewById(R.id.seekBar1); // Seekbar om tijd in te stellen
bar.setOnSeekBarChangeListener(this); // Actie bij het veranderen van de seekbar
textProgress = (TextView)findViewById(R.id.textView3); // Tekst voor de actuele tijdsinstelling
genereerQuiz = (TextView)findViewById(R.id.textView1);
tijd = (TextView)findViewById(R.id.textView2);
Typeface tf = DefaultApplication.tf2;
// Verander de lettertypes
genereerQuiz.setTypeface(tf);
tijd.setTypeface(tf);
Typeface tf2 = DefaultApplication.tf;
// Verander de lettertypes
generateQuiz.setTypeface(tf2);
textProgress.setTypeface(tf2);
mSocket = ((DefaultApplication)this.getApplicationContext()).getSocket(); // Vraag de centrale socket op
mSocket.connect(); // Maak verbinding met de server
}
@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.generateQuiz: // Genereer quiz ingedrukt
mSocket.emit("createQuiz",""); // Verzend het verzoek om een quiz te maken
startListening(); // Wacht op bevestiging
break;
case R.id.quitbutton:
Intent i = new Intent(this, ChooseQuizGroup.class); // Backbutton gaat naar choose quiz group activity
startActivity(i);
this.finish(); // Beeindig deze activity
break;
}
}
public void startListening()
{
mSocket.on("quizCreated", onNewMessage); // Start de actie als de socket bevestiging krijgt
}
/**
* Zet het quizid en de lengte van de quiz in de global variables
* en start een nieuwe activity
* @param success
* @param quizID
*/
public void startNewActivity(String success, int quizID)
{
((DefaultApplication)this.getApplication()).setSocketcode(quizID); // Zet de socketcode
((DefaultApplication)this.getApplication()).setDuration(bar.getProgress()); // Zet de quizduur in minuten
Intent codeScreen = new Intent(this, QuizStart.class); // Intent met het wachtscherm
startActivity(codeScreen); // Start het wachtscherm
this.finish();
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textProgress.setText(progress+ " MIN"); // Bij verandering van de balk, zet de actuele tijdinstelling
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
| wildlands/wildlands-android | app/src/main/java/nl/wildlands/wildlandseducation/Activities/GenerateQuiz.java | 1,678 | // Actie bij het veranderen van de seekbar | line_comment | nl | package nl.wildlands.wildlandseducation.Activities;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import nl.wildlands.wildlandseducation.GlobalSettings.DefaultApplication;
import nl.wildlands.wildlandseducation.R;
/**
* Activity waarbij de docent de gegevens van de quiz kan invoeren
* en deze vervolgens d.m.v. socekts wordt aangemaakt
*/
public class GenerateQuiz extends Activity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
ImageButton backBtn; // ImageButton om terug te gaan
Button generateQuiz; // Button om quiz te genereren
Socket mSocket; // Socket voor de quizverbinding
private SeekBar bar; // Seekbar om tijd dynamisch in te stellen
private TextView textProgress, genereerQuiz,tijd; // TextView voor weergave huidige tijdsinput
/**
* Actie die voltrokken wordt, als de socket een bepaald bericht krijgt
*/
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
GenerateQuiz.this.runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0]; // Zet de data om in een JSONObject
String success; // Succes van aanmaken
int quizID; // ID van de gegenereerde quiz
try {
success = data.getString("success"); // Success message
quizID = data.getInt("quizid"); // Quizid
} catch (JSONException e) {
return;
}
startNewActivity(success, quizID); // Roep startNewActivity aan met de waardes
}
});
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Zet layout
setContentView(R.layout.activity_generate_quiz);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // Fullscreen
WindowManager.LayoutParams.FLAG_FULLSCREEN);
generateQuiz = (Button)findViewById(R.id.generateQuiz); // Button voor genereren quiz
generateQuiz.setOnClickListener(this); // Activeer knopactie
backBtn = (ImageButton)findViewById(R.id.quitbutton); // ImageButton om terug te gaan
backBtn.setOnClickListener(this); // Activeer knopactie
bar =(SeekBar)findViewById(R.id.seekBar1); // Seekbar om tijd in te stellen
bar.setOnSeekBarChangeListener(this); // Actie bij<SUF>
textProgress = (TextView)findViewById(R.id.textView3); // Tekst voor de actuele tijdsinstelling
genereerQuiz = (TextView)findViewById(R.id.textView1);
tijd = (TextView)findViewById(R.id.textView2);
Typeface tf = DefaultApplication.tf2;
// Verander de lettertypes
genereerQuiz.setTypeface(tf);
tijd.setTypeface(tf);
Typeface tf2 = DefaultApplication.tf;
// Verander de lettertypes
generateQuiz.setTypeface(tf2);
textProgress.setTypeface(tf2);
mSocket = ((DefaultApplication)this.getApplicationContext()).getSocket(); // Vraag de centrale socket op
mSocket.connect(); // Maak verbinding met de server
}
@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.generateQuiz: // Genereer quiz ingedrukt
mSocket.emit("createQuiz",""); // Verzend het verzoek om een quiz te maken
startListening(); // Wacht op bevestiging
break;
case R.id.quitbutton:
Intent i = new Intent(this, ChooseQuizGroup.class); // Backbutton gaat naar choose quiz group activity
startActivity(i);
this.finish(); // Beeindig deze activity
break;
}
}
public void startListening()
{
mSocket.on("quizCreated", onNewMessage); // Start de actie als de socket bevestiging krijgt
}
/**
* Zet het quizid en de lengte van de quiz in de global variables
* en start een nieuwe activity
* @param success
* @param quizID
*/
public void startNewActivity(String success, int quizID)
{
((DefaultApplication)this.getApplication()).setSocketcode(quizID); // Zet de socketcode
((DefaultApplication)this.getApplication()).setDuration(bar.getProgress()); // Zet de quizduur in minuten
Intent codeScreen = new Intent(this, QuizStart.class); // Intent met het wachtscherm
startActivity(codeScreen); // Start het wachtscherm
this.finish();
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textProgress.setText(progress+ " MIN"); // Bij verandering van de balk, zet de actuele tijdinstelling
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
| True | 1,196 | 12 | 1,355 | 12 | 1,358 | 10 | 1,359 | 12 | 1,639 | 12 | false | false | false | false | false | true |
4,091 | 134899_9 | package tree;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import syms.Scope;
import java_cup.runtime.ComplexSymbolFactory.Location;
import syms.SymEntry;
/**
* class StatementNode - Abstract syntax tree representation of statements.
* @version $Revision: 22 $ $Date: 2014-05-20 15:14:36 +1000 (Tue, 20 May 2014) $
* Classes defined within StatementNode extend it.
*/
public abstract class StatementNode {
/** Location in the input source program (line and column number effectively).
* All statements have a location within the original source code.
*/
private Location loc;
/** Constructor */
protected StatementNode( Location loc ) {
this.loc = loc;
}
public Location getLocation() {
return loc;
}
/** All statement nodes provide an accept method to implement the visitor
* pattern to traverse the tree.
* @param visitor class implementing the details of the particular
* traversal.
*/
public abstract void accept( StatementVisitor visitor );
/** All statement nodes provide a genCode method to implement the visitor
* pattern to traverse the tree for code generation.
* @param visitor class implementing the code generation
*/
public abstract Code genCode( StatementTransform<Code> visitor );
/** Debugging output of a statement at an indent level */
public abstract String toString( int level );
/** Debugging output at level 0 */
@Override
public String toString() {
return this.toString(0);
}
/** Returns a string with a newline followed by spaces of length 2n. */
public static String newLine( int n ) {
String indent = "\n";
while( n > 0) {
indent += " ";
n--;
}
return indent;
}
/** Node representing a Block consisting of declarations and
* body of a procedure, function, or the main program. */
public static class BlockNode extends StatementNode {
protected DeclNode.DeclListNode procedures;
protected StatementNode body;
protected Scope blockLocals;
/** Constructor for a block within a procedure */
public BlockNode( Location loc, DeclNode.DeclListNode procedures,
StatementNode body) {
super( loc );
this.procedures = procedures;
this.body = body;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitBlockNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitBlockNode( this );
}
public DeclNode.DeclListNode getProcedures() {
return procedures;
}
public StatementNode getBody() {
return body;
}
public Scope getBlockLocals() {
return blockLocals;
}
public void setBlockLocals( Scope blockLocals ) {
this.blockLocals = blockLocals;
}
@Override
public String toString( int level ) {
return getProcedures().toString(level+1) +
newLine(level) + "BEGIN" +
newLine(level+1) + body.toString(level+1) +
newLine(level) + "END";
}
}
/** Statement node representing an erroneous statement. */
public static class ErrorNode extends StatementNode {
public ErrorNode( Location loc ) {
super( loc );
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitStatementErrorNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitStatementErrorNode( this );
}
@Override
public String toString( int level) {
return "ERROR";
}
}
public static class CaseStatementNode extends StatementNode {
private HashMap<ConstExp, StatementNode> cases;
private StatementNode defaultCase;
private ExpNode condition;
private List<ConstExp> labels;
private List<ConstExp> duplicates;
public CaseStatementNode( Location loc, ExpNode condition, HashMap<ConstExp, StatementNode> cases, List<ConstExp> labels, StatementNode defaultCase, List<ConstExp> duplicates ) {
super( loc );
this.cases = cases;
this.defaultCase = defaultCase;
this.condition = condition;
this.labels = labels;
this.duplicates = duplicates;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitCaseStatementNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitCaseStatementNode( this );
}
public List<ConstExp> getLabels() {
return this.labels;
}
public List<ConstExp> getDuplicates() {
return this.duplicates;
}
public ExpNode getCondition() {
return this.condition;
}
public void setCondition(ExpNode c) {
this.condition = c;
}
public StatementNode getDefaultCase() {
return defaultCase;
}
public HashMap<ConstExp, StatementNode> getCases() {
return cases;
}
@Override
public String toString( int level ) {
return "case";
}
}
public static class SkipNode extends StatementNode {
public SkipNode( Location loc ) {
super( loc );
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitSkipNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitSkipNode( this );
}
@Override
public String toString( int level ) {
return "skip";
}
}
/** Tree node representing an SingleAssign statement. */
public static class AssignmentNode extends StatementNode {
/** Tree node for expression on left hand side of an assignment. */
private ExpNode lValue;
/** Tree node for the expression to be assigned. */
private ExpNode exp;
public AssignmentNode( Location loc, ExpNode variable, ExpNode exp ) {
super( loc );
this.lValue = variable;
this.exp = exp;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitAssignmentNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitAssignmentNode( this );
}
public ExpNode getVariable() {
return lValue;
}
public void setVariable( ExpNode variable ) {
this.lValue = variable;
}
public ExpNode getExp() {
return exp;
}
public void setExp(ExpNode exp) {
this.exp = exp;
}
public String getVariableName() {
if( lValue instanceof ExpNode.VariableNode ) {
return
((ExpNode.VariableNode)lValue).getVariable().getIdent();
} else {
return "<noname>";
}
}
@Override
public String toString( int level ) {
return lValue.toString() + " := " + exp.toString();
}
}
/** Tree node representing an assignment statement. */
public static class MultiAssignNode extends StatementNode {
private List<AssignmentNode> assignments;
public MultiAssignNode( Location loc, List<AssignmentNode> assignments ) {
super( loc );
this.assignments = assignments;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitMultiAssignNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitMultiAssignNode( this );
}
public List<AssignmentNode> getAssignments() {
return this.assignments;
}
public List<AssignmentNode> getReverseAssignments() {
List<AssignmentNode> reversed = new ArrayList<AssignmentNode>();
for (AssignmentNode n : this.assignments) {
reversed.add(0, n);
}
return reversed;
}
@Override
public String toString( int level ) {
return "Multiple Assignment Node (" + this.assignments.toString() + ")";
}
}
/** Tree node representing a "write" statement. */
public static class WriteNode extends StatementNode {
private ExpNode exp;
public WriteNode( Location loc, ExpNode exp ) {
super( loc );
this.exp = exp;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitWriteNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitWriteNode( this );
}
public ExpNode getExp() {
return exp;
}
public void setExp( ExpNode exp ) {
this.exp = exp;
}
@Override
public String toString( int level ) {
return "WRITE " + exp.toString();
}
}
/** Tree node representing a "call" statement. */
public static class CallNode extends StatementNode {
private String id;
private SymEntry.ProcedureEntry procEntry;
public CallNode( Location loc, String id ) {
super( loc );
this.id = id;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitCallNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitCallNode( this );
}
public String getId() {
return id;
}
public SymEntry.ProcedureEntry getEntry() {
return procEntry;
}
public void setEntry(SymEntry.ProcedureEntry entry) {
this.procEntry = entry;
}
@Override
public String toString( int level ) {
String s = "CALL " + procEntry.getIdent() + "(";
return s + ")";
}
}
/** Tree node representing a statement list. */
public static class ListNode extends StatementNode {
private List<StatementNode> statements;
public ListNode( Location loc ) {
super( loc );
this.statements = new ArrayList<StatementNode>();
}
public void addStatement( StatementNode s ) {
statements.add( s );
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitStatementListNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitStatementListNode( this );
}
public List<StatementNode> getStatements() {
return statements;
}
@Override
public String toString( int level) {
String result = "";
String sep = "";
for( StatementNode s : statements ) {
result += sep + s.toString( level );
sep = ";" + newLine(level);
}
return result;
}
}
/** Tree node representing an "if" statement. */
public static class IfNode extends StatementNode {
private ExpNode condition;
private StatementNode thenStmt;
private StatementNode elseStmt;
public IfNode( Location loc, ExpNode condition,
StatementNode thenStmt, StatementNode elseStmt ) {
super( loc );
this.condition = condition;
this.thenStmt = thenStmt;
this.elseStmt = elseStmt;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitIfNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitIfNode( this );
}
public ExpNode getCondition() {
return condition;
}
public void setCondition( ExpNode cond ) {
this.condition = cond;
}
public StatementNode getThenStmt() {
return thenStmt;
}
public StatementNode getElseStmt() {
return elseStmt;
}
@Override
public String toString( int level ) {
return "IF " + condition.toString() + " THEN" +
newLine(level+1) + thenStmt.toString( level+1 ) +
newLine( level ) + "ELSE" +
newLine(level+1) + elseStmt.toString( level+1 );
}
}
/** Tree node representing a "while" statement. */
public static class WhileNode extends StatementNode {
private ExpNode condition;
private StatementNode loopStmt;
public WhileNode( Location loc, ExpNode condition,
StatementNode loopStmt ) {
super( loc );
this.condition = condition;
this.loopStmt = loopStmt;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitWhileNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitWhileNode( this );
}
public ExpNode getCondition() {
return condition;
}
public void setCondition( ExpNode cond ) {
this.condition = cond;
}
public StatementNode getLoopStmt() {
return loopStmt;
}
@Override
public String toString( int level ) {
return "WHILE " + condition.toString() + " DO" +
newLine(level+1) + loopStmt.toString( level+1 );
}
}
}
| r-portas/comp4403 | A1/src/tree/StatementNode.java | 3,550 | /** Statement node representing an erroneous statement. */ | block_comment | nl | package tree;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import syms.Scope;
import java_cup.runtime.ComplexSymbolFactory.Location;
import syms.SymEntry;
/**
* class StatementNode - Abstract syntax tree representation of statements.
* @version $Revision: 22 $ $Date: 2014-05-20 15:14:36 +1000 (Tue, 20 May 2014) $
* Classes defined within StatementNode extend it.
*/
public abstract class StatementNode {
/** Location in the input source program (line and column number effectively).
* All statements have a location within the original source code.
*/
private Location loc;
/** Constructor */
protected StatementNode( Location loc ) {
this.loc = loc;
}
public Location getLocation() {
return loc;
}
/** All statement nodes provide an accept method to implement the visitor
* pattern to traverse the tree.
* @param visitor class implementing the details of the particular
* traversal.
*/
public abstract void accept( StatementVisitor visitor );
/** All statement nodes provide a genCode method to implement the visitor
* pattern to traverse the tree for code generation.
* @param visitor class implementing the code generation
*/
public abstract Code genCode( StatementTransform<Code> visitor );
/** Debugging output of a statement at an indent level */
public abstract String toString( int level );
/** Debugging output at level 0 */
@Override
public String toString() {
return this.toString(0);
}
/** Returns a string with a newline followed by spaces of length 2n. */
public static String newLine( int n ) {
String indent = "\n";
while( n > 0) {
indent += " ";
n--;
}
return indent;
}
/** Node representing a Block consisting of declarations and
* body of a procedure, function, or the main program. */
public static class BlockNode extends StatementNode {
protected DeclNode.DeclListNode procedures;
protected StatementNode body;
protected Scope blockLocals;
/** Constructor for a block within a procedure */
public BlockNode( Location loc, DeclNode.DeclListNode procedures,
StatementNode body) {
super( loc );
this.procedures = procedures;
this.body = body;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitBlockNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitBlockNode( this );
}
public DeclNode.DeclListNode getProcedures() {
return procedures;
}
public StatementNode getBody() {
return body;
}
public Scope getBlockLocals() {
return blockLocals;
}
public void setBlockLocals( Scope blockLocals ) {
this.blockLocals = blockLocals;
}
@Override
public String toString( int level ) {
return getProcedures().toString(level+1) +
newLine(level) + "BEGIN" +
newLine(level+1) + body.toString(level+1) +
newLine(level) + "END";
}
}
/** Statement node representing<SUF>*/
public static class ErrorNode extends StatementNode {
public ErrorNode( Location loc ) {
super( loc );
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitStatementErrorNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitStatementErrorNode( this );
}
@Override
public String toString( int level) {
return "ERROR";
}
}
public static class CaseStatementNode extends StatementNode {
private HashMap<ConstExp, StatementNode> cases;
private StatementNode defaultCase;
private ExpNode condition;
private List<ConstExp> labels;
private List<ConstExp> duplicates;
public CaseStatementNode( Location loc, ExpNode condition, HashMap<ConstExp, StatementNode> cases, List<ConstExp> labels, StatementNode defaultCase, List<ConstExp> duplicates ) {
super( loc );
this.cases = cases;
this.defaultCase = defaultCase;
this.condition = condition;
this.labels = labels;
this.duplicates = duplicates;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitCaseStatementNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitCaseStatementNode( this );
}
public List<ConstExp> getLabels() {
return this.labels;
}
public List<ConstExp> getDuplicates() {
return this.duplicates;
}
public ExpNode getCondition() {
return this.condition;
}
public void setCondition(ExpNode c) {
this.condition = c;
}
public StatementNode getDefaultCase() {
return defaultCase;
}
public HashMap<ConstExp, StatementNode> getCases() {
return cases;
}
@Override
public String toString( int level ) {
return "case";
}
}
public static class SkipNode extends StatementNode {
public SkipNode( Location loc ) {
super( loc );
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitSkipNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitSkipNode( this );
}
@Override
public String toString( int level ) {
return "skip";
}
}
/** Tree node representing an SingleAssign statement. */
public static class AssignmentNode extends StatementNode {
/** Tree node for expression on left hand side of an assignment. */
private ExpNode lValue;
/** Tree node for the expression to be assigned. */
private ExpNode exp;
public AssignmentNode( Location loc, ExpNode variable, ExpNode exp ) {
super( loc );
this.lValue = variable;
this.exp = exp;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitAssignmentNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitAssignmentNode( this );
}
public ExpNode getVariable() {
return lValue;
}
public void setVariable( ExpNode variable ) {
this.lValue = variable;
}
public ExpNode getExp() {
return exp;
}
public void setExp(ExpNode exp) {
this.exp = exp;
}
public String getVariableName() {
if( lValue instanceof ExpNode.VariableNode ) {
return
((ExpNode.VariableNode)lValue).getVariable().getIdent();
} else {
return "<noname>";
}
}
@Override
public String toString( int level ) {
return lValue.toString() + " := " + exp.toString();
}
}
/** Tree node representing an assignment statement. */
public static class MultiAssignNode extends StatementNode {
private List<AssignmentNode> assignments;
public MultiAssignNode( Location loc, List<AssignmentNode> assignments ) {
super( loc );
this.assignments = assignments;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitMultiAssignNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitMultiAssignNode( this );
}
public List<AssignmentNode> getAssignments() {
return this.assignments;
}
public List<AssignmentNode> getReverseAssignments() {
List<AssignmentNode> reversed = new ArrayList<AssignmentNode>();
for (AssignmentNode n : this.assignments) {
reversed.add(0, n);
}
return reversed;
}
@Override
public String toString( int level ) {
return "Multiple Assignment Node (" + this.assignments.toString() + ")";
}
}
/** Tree node representing a "write" statement. */
public static class WriteNode extends StatementNode {
private ExpNode exp;
public WriteNode( Location loc, ExpNode exp ) {
super( loc );
this.exp = exp;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitWriteNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitWriteNode( this );
}
public ExpNode getExp() {
return exp;
}
public void setExp( ExpNode exp ) {
this.exp = exp;
}
@Override
public String toString( int level ) {
return "WRITE " + exp.toString();
}
}
/** Tree node representing a "call" statement. */
public static class CallNode extends StatementNode {
private String id;
private SymEntry.ProcedureEntry procEntry;
public CallNode( Location loc, String id ) {
super( loc );
this.id = id;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitCallNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitCallNode( this );
}
public String getId() {
return id;
}
public SymEntry.ProcedureEntry getEntry() {
return procEntry;
}
public void setEntry(SymEntry.ProcedureEntry entry) {
this.procEntry = entry;
}
@Override
public String toString( int level ) {
String s = "CALL " + procEntry.getIdent() + "(";
return s + ")";
}
}
/** Tree node representing a statement list. */
public static class ListNode extends StatementNode {
private List<StatementNode> statements;
public ListNode( Location loc ) {
super( loc );
this.statements = new ArrayList<StatementNode>();
}
public void addStatement( StatementNode s ) {
statements.add( s );
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitStatementListNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitStatementListNode( this );
}
public List<StatementNode> getStatements() {
return statements;
}
@Override
public String toString( int level) {
String result = "";
String sep = "";
for( StatementNode s : statements ) {
result += sep + s.toString( level );
sep = ";" + newLine(level);
}
return result;
}
}
/** Tree node representing an "if" statement. */
public static class IfNode extends StatementNode {
private ExpNode condition;
private StatementNode thenStmt;
private StatementNode elseStmt;
public IfNode( Location loc, ExpNode condition,
StatementNode thenStmt, StatementNode elseStmt ) {
super( loc );
this.condition = condition;
this.thenStmt = thenStmt;
this.elseStmt = elseStmt;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitIfNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitIfNode( this );
}
public ExpNode getCondition() {
return condition;
}
public void setCondition( ExpNode cond ) {
this.condition = cond;
}
public StatementNode getThenStmt() {
return thenStmt;
}
public StatementNode getElseStmt() {
return elseStmt;
}
@Override
public String toString( int level ) {
return "IF " + condition.toString() + " THEN" +
newLine(level+1) + thenStmt.toString( level+1 ) +
newLine( level ) + "ELSE" +
newLine(level+1) + elseStmt.toString( level+1 );
}
}
/** Tree node representing a "while" statement. */
public static class WhileNode extends StatementNode {
private ExpNode condition;
private StatementNode loopStmt;
public WhileNode( Location loc, ExpNode condition,
StatementNode loopStmt ) {
super( loc );
this.condition = condition;
this.loopStmt = loopStmt;
}
@Override
public void accept( StatementVisitor visitor ) {
visitor.visitWhileNode( this );
}
@Override
public Code genCode( StatementTransform<Code> visitor ) {
return visitor.visitWhileNode( this );
}
public ExpNode getCondition() {
return condition;
}
public void setCondition( ExpNode cond ) {
this.condition = cond;
}
public StatementNode getLoopStmt() {
return loopStmt;
}
@Override
public String toString( int level ) {
return "WHILE " + condition.toString() + " DO" +
newLine(level+1) + loopStmt.toString( level+1 );
}
}
}
| False | 2,885 | 9 | 2,928 | 11 | 3,325 | 9 | 2,928 | 11 | 3,616 | 12 | false | false | false | false | false | true |
1,850 | 206583_0 | package nello.controller;
import nello.model.NetworkMember;
import nello.model.User;
import nello.model.UsersTabModel;
import nello.observer.UsersTabObserver;
import nello.view.AlertBox;
import nello.view.ProfileView;
import javax.ws.rs.core.Response;
import java.util.logging.Level;
public class UsersTabController implements IController {
private MainController mainController;
private UsersTabModel usersTabModel;
public UsersTabController(MainController mainController, UsersTabModel usersTabModel) {
this.mainController = mainController;
this.usersTabModel = usersTabModel;
}
public void registerObserver(UsersTabObserver o){
usersTabModel.registerObserver(o);
}
public void onEditButtonClick(long id) {
HTTPController http = mainController.getHttpController();
Response response = http.get("/users/" + id);
switch (response.getStatus()){
case 200:
User u = response.readEntity(User.class);
mainController.getProfileController().setUser(u);
mainController.getStageController().displayView(new ProfileView());
break;
case 401:
mainController.getStageController().displayPopup(new AlertBox("Opgegeven ID is onbekend.", Level.FINE, 3));
break;
}
}
public void onDeleteButtonClick(long id) {
HTTPController http = mainController.getHttpController();
Response response = http.delete("/users/" + id);
System.out.println(response.getStatus());
switch (response.getStatus()){
case 200:
mainController.getUsersTabController().getUsersTabModel().setUserList(mainController.getUserController().listUsers());
// mainController.getStageController().displayPopup(new AlertBox("Gebruiker is verwijderd.", Level.FINE, 3));
break;
}
}
public UsersTabModel getUsersTabModel() {
return usersTabModel;
}
}
| VisserSanne/IPSEN2-Frontend | src/main/java/nello/controller/UsersTabController.java | 520 | // mainController.getStageController().displayPopup(new AlertBox("Gebruiker is verwijderd.", Level.FINE, 3)); | line_comment | nl | package nello.controller;
import nello.model.NetworkMember;
import nello.model.User;
import nello.model.UsersTabModel;
import nello.observer.UsersTabObserver;
import nello.view.AlertBox;
import nello.view.ProfileView;
import javax.ws.rs.core.Response;
import java.util.logging.Level;
public class UsersTabController implements IController {
private MainController mainController;
private UsersTabModel usersTabModel;
public UsersTabController(MainController mainController, UsersTabModel usersTabModel) {
this.mainController = mainController;
this.usersTabModel = usersTabModel;
}
public void registerObserver(UsersTabObserver o){
usersTabModel.registerObserver(o);
}
public void onEditButtonClick(long id) {
HTTPController http = mainController.getHttpController();
Response response = http.get("/users/" + id);
switch (response.getStatus()){
case 200:
User u = response.readEntity(User.class);
mainController.getProfileController().setUser(u);
mainController.getStageController().displayView(new ProfileView());
break;
case 401:
mainController.getStageController().displayPopup(new AlertBox("Opgegeven ID is onbekend.", Level.FINE, 3));
break;
}
}
public void onDeleteButtonClick(long id) {
HTTPController http = mainController.getHttpController();
Response response = http.delete("/users/" + id);
System.out.println(response.getStatus());
switch (response.getStatus()){
case 200:
mainController.getUsersTabController().getUsersTabModel().setUserList(mainController.getUserController().listUsers());
// mainController.getStageController().displayPopup(new AlertBox("Gebruiker<SUF>
break;
}
}
public UsersTabModel getUsersTabModel() {
return usersTabModel;
}
}
| False | 405 | 30 | 473 | 33 | 488 | 30 | 473 | 33 | 519 | 34 | false | false | false | false | false | true |
2,641 | 173289_1 | package Enums_Static_EenvoudigeClasses.oefPersoon;
import java.util.Arrays;
import java.util.List;
public class TestPersoon {
private static final Persoon[] data = {
new Persoon("Jan", "Van den Broecke"),
new Persoon("Jozef", "Vandenbroeke"),
new Persoon("Els", "Van Damme"),
new Persoon("Emma", "Devocht"),
new Persoon("Annick", "Devocht"),
new Persoon("Annie", "De Vocht"),
new Persoon("Frans", "D'Hooghe"),
new Persoon("Fons", "De Wilde"),
new Persoon("Magda", "De Haene"),
new Persoon("Julie", "Vermeulen"),
new Persoon("Charlotte", "Van Den Brande"),
new Persoon("Jean-Pierre", "Daemen"),
new Persoon("Bert", "Van Basten"),
new Persoon("Stien", "D'Haene"),
new Persoon("Sterre", "Vandenbrande"),
};
public static void main(String[] args) {
Personen personen = new Personen(Arrays.asList(data));
personen.sorteer();
List<Persoon> lijst = personen.getPersonen();
for (Persoon persoon : lijst) {
System.out.println(persoon);
}
}
}
// Haal de lijst op uit personen en print elk Persoon-object
// via de toString methode
| eliashkan/JavaExc | Enums_Static_EenvoudigeClasses/oefPersoon/TestPersoon.java | 394 | // via de toString methode | line_comment | nl | package Enums_Static_EenvoudigeClasses.oefPersoon;
import java.util.Arrays;
import java.util.List;
public class TestPersoon {
private static final Persoon[] data = {
new Persoon("Jan", "Van den Broecke"),
new Persoon("Jozef", "Vandenbroeke"),
new Persoon("Els", "Van Damme"),
new Persoon("Emma", "Devocht"),
new Persoon("Annick", "Devocht"),
new Persoon("Annie", "De Vocht"),
new Persoon("Frans", "D'Hooghe"),
new Persoon("Fons", "De Wilde"),
new Persoon("Magda", "De Haene"),
new Persoon("Julie", "Vermeulen"),
new Persoon("Charlotte", "Van Den Brande"),
new Persoon("Jean-Pierre", "Daemen"),
new Persoon("Bert", "Van Basten"),
new Persoon("Stien", "D'Haene"),
new Persoon("Sterre", "Vandenbrande"),
};
public static void main(String[] args) {
Personen personen = new Personen(Arrays.asList(data));
personen.sorteer();
List<Persoon> lijst = personen.getPersonen();
for (Persoon persoon : lijst) {
System.out.println(persoon);
}
}
}
// Haal de lijst op uit personen en print elk Persoon-object
// via de<SUF>
| False | 333 | 6 | 374 | 6 | 360 | 5 | 374 | 6 | 399 | 8 | false | false | false | false | false | true |
2,421 | 109794_3 | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package herddb.utils;
import java.nio.charset.StandardCharsets;
import io.netty.buffer.ByteBuf;
/**
* Utilities for write variable length values on {@link ByteBuf}.
*
* @author diego.salvi
*/
public class ByteBufUtils {
private static final boolean READ_FOLDED_VAR_INT = SystemProperties.getBooleanSystemProperty("herddb.vint.read.folded", false);
private static final boolean WRITE_FOLDED_VAR_INT = SystemProperties.getBooleanSystemProperty("herddb.vint.write.folded", false);
public static final void writeArray(ByteBuf buffer, byte[] array) {
writeVInt(buffer, array.length);
buffer.writeBytes(array);
}
public static final void writeArray(ByteBuf buffer, Bytes array) {
writeVInt(buffer, array.getLength());
buffer.writeBytes(array.getBuffer(), array.getOffset(), array.getLength());
}
public static final void writeArray(ByteBuf buffer, byte[] array, int offset, int length) {
writeVInt(buffer, length);
buffer.writeBytes(array, offset, length);
}
public static final void writeString(ByteBuf buffer, String string) {
writeArray(buffer, string.getBytes(StandardCharsets.UTF_8));
}
public static final void writeRawString(ByteBuf buffer, RawString string) {
writeArray(buffer, string.getData(), string.getOffset(), string.getLength());
}
public static final byte[] readArray(ByteBuf buffer) {
final int len = readVInt(buffer);
final byte[] array = new byte[len];
buffer.readBytes(array);
return array;
}
public static final String readString(ByteBuf buffer) {
final int len = readVInt(buffer);
final byte[] array = new byte[len];
buffer.readBytes(array);
return new String(array, StandardCharsets.UTF_8);
}
public static final RawString readRawString(ByteBuf buffer) {
final int len = readVInt(buffer);
final byte[] array = new byte[len];
buffer.readBytes(array);
return RawString.newPooledRawString(array, 0, len);
}
public static final RawString readUnpooledRawString(ByteBuf buffer) {
final int len = readVInt(buffer);
final byte[] array = new byte[len];
buffer.readBytes(array);
return RawString.newUnpooledRawString(array, 0, len);
}
public static final void skipArray(ByteBuf buffer) {
final int len = readVInt(buffer);
buffer.skipBytes(len);
}
public static final void writeVInt(ByteBuf buffer, int i) {
if (WRITE_FOLDED_VAR_INT) {
writeVIntFolded(buffer, i);
} else {
writeVIntUnfolded(buffer, i);
}
}
protected static final void writeVIntUnfolded(ByteBuf buffer, int i) {
if ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
if ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
if ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
if ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
}
}
}
}
buffer.writeByte((byte) i);
}
protected static final void writeVIntFolded(ByteBuf buffer, int i) {
while ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
}
buffer.writeByte((byte) i);
}
public static final int readVInt(ByteBuf buffer) {
return READ_FOLDED_VAR_INT ? readVIntFolded(buffer) : readVIntUnfolded(buffer);
}
protected static final int readVIntUnfolded(ByteBuf buffer) {
byte b = buffer.readByte();
int i = b & 0x7F;
if ((b & 0x80) != 0) {
b = buffer.readByte();
i |= (b & 0x7F) << 7;
if ((b & 0x80) != 0) {
b = buffer.readByte();
i |= (b & 0x7F) << 14;
if ((b & 0x80) != 0) {
b = buffer.readByte();
i |= (b & 0x7F) << 21;
if ((b & 0x80) != 0) {
b = buffer.readByte();
i |= (b & 0x7F) << 28;
}
}
}
}
return i;
}
protected static final int readVIntFolded(ByteBuf buffer) {
byte b = buffer.readByte();
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = buffer.readByte();
i |= (b & 0x7F) << shift;
}
return i;
}
public static final void writeZInt(ByteBuf buffer, int i) {
writeVInt(buffer, zigZagEncode(i));
}
public static final int readZInt(ByteBuf buffer) {
return zigZagDecode(readVInt(buffer));
}
public static final void writeVLong(ByteBuf buffer, long i) {
if (i < 0) {
throw new IllegalArgumentException("cannot write negative vLong (got: " + i + ")");
}
writeSignedVLong(buffer, i);
}
// write a potentially negative vLong
private static final void writeSignedVLong(ByteBuf buffer, long i) {
while ((i & ~0x7FL) != 0L) {
buffer.writeByte((byte) ((i & 0x7FL) | 0x80L));
i >>>= 7;
}
buffer.writeByte((byte) i);
}
public static final long readVLong(ByteBuf buffer) {
return readVLong(buffer, false);
}
private static final long readVLong(ByteBuf buffer, boolean allowNegative) {
byte b = buffer.readByte();
if (b >= 0) {
return b;
}
long i = b & 0x7FL;
b = buffer.readByte();
i |= (b & 0x7FL) << 7;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 14;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 21;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 28;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 35;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 42;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 49;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 56;
if (b >= 0) {
return i;
}
if (allowNegative) {
b = buffer.readByte();
i |= (b & 0x7FL) << 63;
if (b == 0 || b == 1) {
return i;
}
throw new IllegalArgumentException("Invalid vLong detected (more than 64 bits)");
} else {
throw new IllegalArgumentException("Invalid vLong detected (negative values disallowed)");
}
}
public static final void writeZLong(ByteBuf buffer, long i) {
writeVLong(buffer, zigZagEncode(i));
}
public static final long readZLong(ByteBuf buffer) {
return zigZagDecode(readVLong(buffer));
}
public static final void writeDouble(ByteBuf buffer, double i) {
buffer.writeLong(Double.doubleToLongBits(i));
}
public static final double readDouble(ByteBuf buffer) {
return Double.longBitsToDouble(buffer.readLong());
}
/**
* Same as {@link #zigZagEncode(long)} but on integers.
*/
private static final int zigZagEncode(int i) {
return (i >> 31) ^ (i << 1);
}
/**
* <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">Zig-zag</a>
* encode the provided long. Assuming the input is a signed long whose
* absolute value can be stored on <tt>n</tt> bits, the returned value will
* be an unsigned long that can be stored on <tt>n+1</tt> bits.
*/
private static final long zigZagEncode(long l) {
return (l >> 63) ^ (l << 1);
}
/**
* Decode an int previously encoded with {@link #zigZagEncode(int)}.
*/
private static final int zigZagDecode(int i) {
return ((i >>> 1) ^ -(i & 1));
}
/**
* Decode a long previously encoded with {@link #zigZagEncode(long)}.
*/
private static final long zigZagDecode(long l) {
return ((l >>> 1) ^ -(l & 1));
}
}
| codelipenghui/herddb | herddb-utils/src/main/java/herddb/utils/ByteBufUtils.java | 2,968 | /**
* Same as {@link #zigZagEncode(long)} but on integers.
*/ | block_comment | nl | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package herddb.utils;
import java.nio.charset.StandardCharsets;
import io.netty.buffer.ByteBuf;
/**
* Utilities for write variable length values on {@link ByteBuf}.
*
* @author diego.salvi
*/
public class ByteBufUtils {
private static final boolean READ_FOLDED_VAR_INT = SystemProperties.getBooleanSystemProperty("herddb.vint.read.folded", false);
private static final boolean WRITE_FOLDED_VAR_INT = SystemProperties.getBooleanSystemProperty("herddb.vint.write.folded", false);
public static final void writeArray(ByteBuf buffer, byte[] array) {
writeVInt(buffer, array.length);
buffer.writeBytes(array);
}
public static final void writeArray(ByteBuf buffer, Bytes array) {
writeVInt(buffer, array.getLength());
buffer.writeBytes(array.getBuffer(), array.getOffset(), array.getLength());
}
public static final void writeArray(ByteBuf buffer, byte[] array, int offset, int length) {
writeVInt(buffer, length);
buffer.writeBytes(array, offset, length);
}
public static final void writeString(ByteBuf buffer, String string) {
writeArray(buffer, string.getBytes(StandardCharsets.UTF_8));
}
public static final void writeRawString(ByteBuf buffer, RawString string) {
writeArray(buffer, string.getData(), string.getOffset(), string.getLength());
}
public static final byte[] readArray(ByteBuf buffer) {
final int len = readVInt(buffer);
final byte[] array = new byte[len];
buffer.readBytes(array);
return array;
}
public static final String readString(ByteBuf buffer) {
final int len = readVInt(buffer);
final byte[] array = new byte[len];
buffer.readBytes(array);
return new String(array, StandardCharsets.UTF_8);
}
public static final RawString readRawString(ByteBuf buffer) {
final int len = readVInt(buffer);
final byte[] array = new byte[len];
buffer.readBytes(array);
return RawString.newPooledRawString(array, 0, len);
}
public static final RawString readUnpooledRawString(ByteBuf buffer) {
final int len = readVInt(buffer);
final byte[] array = new byte[len];
buffer.readBytes(array);
return RawString.newUnpooledRawString(array, 0, len);
}
public static final void skipArray(ByteBuf buffer) {
final int len = readVInt(buffer);
buffer.skipBytes(len);
}
public static final void writeVInt(ByteBuf buffer, int i) {
if (WRITE_FOLDED_VAR_INT) {
writeVIntFolded(buffer, i);
} else {
writeVIntUnfolded(buffer, i);
}
}
protected static final void writeVIntUnfolded(ByteBuf buffer, int i) {
if ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
if ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
if ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
if ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
}
}
}
}
buffer.writeByte((byte) i);
}
protected static final void writeVIntFolded(ByteBuf buffer, int i) {
while ((i & ~0x7F) != 0) {
buffer.writeByte((byte) ((i & 0x7F) | 0x80));
i >>>= 7;
}
buffer.writeByte((byte) i);
}
public static final int readVInt(ByteBuf buffer) {
return READ_FOLDED_VAR_INT ? readVIntFolded(buffer) : readVIntUnfolded(buffer);
}
protected static final int readVIntUnfolded(ByteBuf buffer) {
byte b = buffer.readByte();
int i = b & 0x7F;
if ((b & 0x80) != 0) {
b = buffer.readByte();
i |= (b & 0x7F) << 7;
if ((b & 0x80) != 0) {
b = buffer.readByte();
i |= (b & 0x7F) << 14;
if ((b & 0x80) != 0) {
b = buffer.readByte();
i |= (b & 0x7F) << 21;
if ((b & 0x80) != 0) {
b = buffer.readByte();
i |= (b & 0x7F) << 28;
}
}
}
}
return i;
}
protected static final int readVIntFolded(ByteBuf buffer) {
byte b = buffer.readByte();
int i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = buffer.readByte();
i |= (b & 0x7F) << shift;
}
return i;
}
public static final void writeZInt(ByteBuf buffer, int i) {
writeVInt(buffer, zigZagEncode(i));
}
public static final int readZInt(ByteBuf buffer) {
return zigZagDecode(readVInt(buffer));
}
public static final void writeVLong(ByteBuf buffer, long i) {
if (i < 0) {
throw new IllegalArgumentException("cannot write negative vLong (got: " + i + ")");
}
writeSignedVLong(buffer, i);
}
// write a potentially negative vLong
private static final void writeSignedVLong(ByteBuf buffer, long i) {
while ((i & ~0x7FL) != 0L) {
buffer.writeByte((byte) ((i & 0x7FL) | 0x80L));
i >>>= 7;
}
buffer.writeByte((byte) i);
}
public static final long readVLong(ByteBuf buffer) {
return readVLong(buffer, false);
}
private static final long readVLong(ByteBuf buffer, boolean allowNegative) {
byte b = buffer.readByte();
if (b >= 0) {
return b;
}
long i = b & 0x7FL;
b = buffer.readByte();
i |= (b & 0x7FL) << 7;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 14;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 21;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 28;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 35;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 42;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 49;
if (b >= 0) {
return i;
}
b = buffer.readByte();
i |= (b & 0x7FL) << 56;
if (b >= 0) {
return i;
}
if (allowNegative) {
b = buffer.readByte();
i |= (b & 0x7FL) << 63;
if (b == 0 || b == 1) {
return i;
}
throw new IllegalArgumentException("Invalid vLong detected (more than 64 bits)");
} else {
throw new IllegalArgumentException("Invalid vLong detected (negative values disallowed)");
}
}
public static final void writeZLong(ByteBuf buffer, long i) {
writeVLong(buffer, zigZagEncode(i));
}
public static final long readZLong(ByteBuf buffer) {
return zigZagDecode(readVLong(buffer));
}
public static final void writeDouble(ByteBuf buffer, double i) {
buffer.writeLong(Double.doubleToLongBits(i));
}
public static final double readDouble(ByteBuf buffer) {
return Double.longBitsToDouble(buffer.readLong());
}
/**
* Same as {@link<SUF>*/
private static final int zigZagEncode(int i) {
return (i >> 31) ^ (i << 1);
}
/**
* <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">Zig-zag</a>
* encode the provided long. Assuming the input is a signed long whose
* absolute value can be stored on <tt>n</tt> bits, the returned value will
* be an unsigned long that can be stored on <tt>n+1</tt> bits.
*/
private static final long zigZagEncode(long l) {
return (l >> 63) ^ (l << 1);
}
/**
* Decode an int previously encoded with {@link #zigZagEncode(int)}.
*/
private static final int zigZagDecode(int i) {
return ((i >>> 1) ^ -(i & 1));
}
/**
* Decode a long previously encoded with {@link #zigZagEncode(long)}.
*/
private static final long zigZagDecode(long l) {
return ((l >>> 1) ^ -(l & 1));
}
}
| False | 2,457 | 20 | 2,640 | 21 | 2,800 | 22 | 2,640 | 21 | 3,071 | 24 | false | false | false | false | false | true |
2,293 | 17465_3 | package gretig.datastructuur;
import gretig.datastructuur.Graaf;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by brent on 10/8/16.
*/
public class GraafDecoder {
private InputStream is;
private boolean done;
private int bytesize;
public GraafDecoder(InputStream is) throws IOException {
this.is = is;
done = false;
}
/** Decodeer de grafen één voor één.
* @return gf lijst van alle grafen
* @throws IOException fout bij het lezen
*/
public ArrayList<Graaf> decodeGrafen() throws IOException {
ArrayList<Graaf> gf = new ArrayList<>();
while(!done){
this.bytesize = is.read();
int toppen = readNumber();
int bogen = readNumber();
if(bytesize==-1||toppen==-1||bogen==-1) break;
gf.add(decodeGraaf(toppen, bogen));
}
return gf;
}
/**
* Lees het volgende getal in volgens de bytesize.
* @return answer: ByteDecoded number
* @throws IOException fout bij lezen
*/
public int readNumber() throws IOException {
int answer = 0;
for (int i=0; i<bytesize;i++){
int b=is.read();
if(b==-1){
return -1;
}
answer+=b<<(8*i);
}
return answer;
}
/** Verwerk 1 graaf.
* @param toppen: aantal toppen
* @param bogen: aantal bogen
* @return g: de volledige graaf
* @throws IOException
*/
public Graaf decodeGraaf(int toppen, int bogen) throws IOException {
int b;
int teller=0;
Graaf g = new Graaf(toppen, bogen);
g.init_next();
while((b=readNumber())!=-1){
if(b==0){
teller++;
if(teller>=toppen) break;
g.init_next();
} else {
g.add_boog(b);
}
}
if (b==-1)
done=true;
return g;
}
}
| brent-vw/Greedy-Cycles | src/gretig/datastructuur/GraafDecoder.java | 640 | /** Verwerk 1 graaf.
* @param toppen: aantal toppen
* @param bogen: aantal bogen
* @return g: de volledige graaf
* @throws IOException
*/ | block_comment | nl | package gretig.datastructuur;
import gretig.datastructuur.Graaf;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by brent on 10/8/16.
*/
public class GraafDecoder {
private InputStream is;
private boolean done;
private int bytesize;
public GraafDecoder(InputStream is) throws IOException {
this.is = is;
done = false;
}
/** Decodeer de grafen één voor één.
* @return gf lijst van alle grafen
* @throws IOException fout bij het lezen
*/
public ArrayList<Graaf> decodeGrafen() throws IOException {
ArrayList<Graaf> gf = new ArrayList<>();
while(!done){
this.bytesize = is.read();
int toppen = readNumber();
int bogen = readNumber();
if(bytesize==-1||toppen==-1||bogen==-1) break;
gf.add(decodeGraaf(toppen, bogen));
}
return gf;
}
/**
* Lees het volgende getal in volgens de bytesize.
* @return answer: ByteDecoded number
* @throws IOException fout bij lezen
*/
public int readNumber() throws IOException {
int answer = 0;
for (int i=0; i<bytesize;i++){
int b=is.read();
if(b==-1){
return -1;
}
answer+=b<<(8*i);
}
return answer;
}
/** Verwerk 1 graaf.<SUF>*/
public Graaf decodeGraaf(int toppen, int bogen) throws IOException {
int b;
int teller=0;
Graaf g = new Graaf(toppen, bogen);
g.init_next();
while((b=readNumber())!=-1){
if(b==0){
teller++;
if(teller>=toppen) break;
g.init_next();
} else {
g.add_boog(b);
}
}
if (b==-1)
done=true;
return g;
}
}
| True | 504 | 51 | 564 | 53 | 579 | 48 | 564 | 53 | 636 | 53 | false | false | false | false | false | true |
705 | 10414_2 | import lejos.nxt.Motor;
import lejos.nxt.NXTRegulatedMotor;
public class Dispenser extends Thread {
public void geefGeld(int bedrag){
int a10 = 0;
int a20 = 0;
int a50 = 0;
NXTRegulatedMotor m10 = Motor.A;
NXTRegulatedMotor m20 = Motor.B;
NXTRegulatedMotor m50 = Motor.C;
while(bedrag > 0){
if(bedrag >= 50){
a50 += 1;
bedrag -= 50;
}
else if (bedrag >= 20&& bedrag < 50){
a20 += 1;
bedrag -= 20;
}
else{
a10 += 1;
bedrag -= 10;
}
}
dispense(m50,a50);
dispense(m20,a20);
dispense(m10,a10);
}
public static void dispense(NXTRegulatedMotor m, int aantal){
int tijd = 1100;
m.backward(); // geld gaat voor uit
try {
sleep(tijd*aantal);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.stop();
m.forward(); //geld gaat terug in automaat
}
} | Horofic/ATM | client/Dispenser.java | 403 | //geld gaat terug in automaat | line_comment | nl | import lejos.nxt.Motor;
import lejos.nxt.NXTRegulatedMotor;
public class Dispenser extends Thread {
public void geefGeld(int bedrag){
int a10 = 0;
int a20 = 0;
int a50 = 0;
NXTRegulatedMotor m10 = Motor.A;
NXTRegulatedMotor m20 = Motor.B;
NXTRegulatedMotor m50 = Motor.C;
while(bedrag > 0){
if(bedrag >= 50){
a50 += 1;
bedrag -= 50;
}
else if (bedrag >= 20&& bedrag < 50){
a20 += 1;
bedrag -= 20;
}
else{
a10 += 1;
bedrag -= 10;
}
}
dispense(m50,a50);
dispense(m20,a20);
dispense(m10,a10);
}
public static void dispense(NXTRegulatedMotor m, int aantal){
int tijd = 1100;
m.backward(); // geld gaat voor uit
try {
sleep(tijd*aantal);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.stop();
m.forward(); //geld gaat<SUF>
}
} | True | 337 | 9 | 385 | 11 | 378 | 8 | 385 | 11 | 471 | 11 | false | false | false | false | false | true |
4,391 | 96573_0 | package org.janssen.scoreboard;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import org.janssen.scoreboard.task.NewGameTask;
import org.janssen.scoreboard.task.OnTaskListener;
import static org.janssen.scoreboard.Constants.AUTH_TOKEN;
import static org.janssen.scoreboard.Constants.COURT;
import static org.janssen.scoreboard.Constants.GAME;
import static org.janssen.scoreboard.Constants.MIRRORED;
/**
* Info voor nieuwe wedstrijd.
*
* Created by stephan on 16/06/13.
*/
public class NewGameActivity extends ImmersiveStickyActivity implements OnTaskListener {
private static final int COURT_B = 1;
private static final int SENIOREN = 0;
private String authToken;
/**
* The tag used to log to adb console.
*/
private static final String TAG = "NewGameActivity";
private ProgressBar progressBar;
private EditText teamAEdit;
private EditText teamBEdit;
private String teamA;
private String teamB;
private Integer selectedCourt;
private int gameType;
private int ageCategory;
private boolean mirroring = false;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_new_game);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
authToken = bundle.getString(AUTH_TOKEN);
selectedCourt = (Integer) bundle.get(COURT);
} else {
Toast.makeText(getApplicationContext(), "No court selected, restart", Toast.LENGTH_LONG).show();
return;
}
teamAEdit = findViewById(R.id.teamA);
teamAEdit.setText(R.string.oostkamp);
teamBEdit = findViewById(R.id.teamB);
teamBEdit.setText(R.string.bezoekers);
progressBar = findViewById(R.id.progressBar3);
// Game Type
Spinner gameTypeSpinner = findViewById(R.id.gameType);
ArrayAdapter<CharSequence> adapterGameTypeSpinner
= ArrayAdapter.createFromResource(this, R.array.game_types, android.R.layout.simple_spinner_item);
adapterGameTypeSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
gameTypeSpinner.setAdapter(adapterGameTypeSpinner);
gameTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
gameType = pos;
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
// Age Category
Spinner ageCategorySpinner = findViewById(R.id.ageCategory);
ArrayAdapter<CharSequence> adapterAgeCategorySpinner
= ArrayAdapter.createFromResource(this, R.array.age_category, android.R.layout.simple_spinner_item);
adapterAgeCategorySpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
ageCategorySpinner.setAdapter(adapterAgeCategorySpinner);
ageCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
ageCategory = pos;
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
public void createNewGame(View view) {
Log.i(TAG, "create new game");
teamA = teamAEdit.getText().toString();
teamB = teamBEdit.getText().toString();
if (TextUtils.isEmpty(teamA) ||
TextUtils.isEmpty(teamB)) {
Toast.makeText(getApplicationContext(), "Provide team names", Toast.LENGTH_LONG).show();
} else {
if (ageCategory == SENIOREN &&
selectedCourt == COURT_B) {
final AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setTitle("Boodschap");
dialog.setMessage("Wens je 2 scoreborden te gebruiken?");
dialog.setCancelable(false);
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ja", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
startNewGame(true);
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Nee", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
startNewGame(false);
}
});
dialog.setIcon(android.R.drawable.ic_dialog_alert);
dialog.show();
} else {
startNewGame(false);
}
}
}
private void startNewGame(final boolean isMirrored) {
mirroring = isMirrored;
// Show a progress dialog, and kick off a background task to perform the new game attempt
showProgressBar();
new NewGameTask(this, teamA, teamB, gameType, ageCategory, selectedCourt, mirroring, authToken).execute();
}
/**
* Called when the new game creation process completes.
*/
@Override
public void onTaskCompleted(final String result) {
hideProgressBar();
if (result == null ||
result.contains("connect timed out")) {
Toast.makeText(getApplicationContext(), "Geen connectie met scorebord", Toast.LENGTH_LONG).show();
} else {
// Show count down
Intent intent = new Intent(getApplicationContext(), CountDownActivity.class);
intent.putExtra(MIRRORED, mirroring);
intent.putExtra(GAME, result);
intent.putExtra(AUTH_TOKEN, authToken);
intent.putExtra(COURT, selectedCourt);
startActivity(intent);
}
}
@Override
public void onTaskCancelled() {
hideProgressBar();
}
private void hideProgressBar() {
progressBar.setVisibility(View.INVISIBLE);
}
private void showProgressBar() {
progressBar.setVisibility(View.VISIBLE);
}
}
| stephanj/AndroidRPIScoreboard | app/src/main/java/org/janssen/scoreboard/NewGameActivity.java | 1,861 | /**
* Info voor nieuwe wedstrijd.
*
* Created by stephan on 16/06/13.
*/ | block_comment | nl | package org.janssen.scoreboard;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import org.janssen.scoreboard.task.NewGameTask;
import org.janssen.scoreboard.task.OnTaskListener;
import static org.janssen.scoreboard.Constants.AUTH_TOKEN;
import static org.janssen.scoreboard.Constants.COURT;
import static org.janssen.scoreboard.Constants.GAME;
import static org.janssen.scoreboard.Constants.MIRRORED;
/**
* Info voor nieuwe<SUF>*/
public class NewGameActivity extends ImmersiveStickyActivity implements OnTaskListener {
private static final int COURT_B = 1;
private static final int SENIOREN = 0;
private String authToken;
/**
* The tag used to log to adb console.
*/
private static final String TAG = "NewGameActivity";
private ProgressBar progressBar;
private EditText teamAEdit;
private EditText teamBEdit;
private String teamA;
private String teamB;
private Integer selectedCourt;
private int gameType;
private int ageCategory;
private boolean mirroring = false;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_new_game);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
authToken = bundle.getString(AUTH_TOKEN);
selectedCourt = (Integer) bundle.get(COURT);
} else {
Toast.makeText(getApplicationContext(), "No court selected, restart", Toast.LENGTH_LONG).show();
return;
}
teamAEdit = findViewById(R.id.teamA);
teamAEdit.setText(R.string.oostkamp);
teamBEdit = findViewById(R.id.teamB);
teamBEdit.setText(R.string.bezoekers);
progressBar = findViewById(R.id.progressBar3);
// Game Type
Spinner gameTypeSpinner = findViewById(R.id.gameType);
ArrayAdapter<CharSequence> adapterGameTypeSpinner
= ArrayAdapter.createFromResource(this, R.array.game_types, android.R.layout.simple_spinner_item);
adapterGameTypeSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
gameTypeSpinner.setAdapter(adapterGameTypeSpinner);
gameTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
gameType = pos;
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
// Age Category
Spinner ageCategorySpinner = findViewById(R.id.ageCategory);
ArrayAdapter<CharSequence> adapterAgeCategorySpinner
= ArrayAdapter.createFromResource(this, R.array.age_category, android.R.layout.simple_spinner_item);
adapterAgeCategorySpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
ageCategorySpinner.setAdapter(adapterAgeCategorySpinner);
ageCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
ageCategory = pos;
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
public void createNewGame(View view) {
Log.i(TAG, "create new game");
teamA = teamAEdit.getText().toString();
teamB = teamBEdit.getText().toString();
if (TextUtils.isEmpty(teamA) ||
TextUtils.isEmpty(teamB)) {
Toast.makeText(getApplicationContext(), "Provide team names", Toast.LENGTH_LONG).show();
} else {
if (ageCategory == SENIOREN &&
selectedCourt == COURT_B) {
final AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setTitle("Boodschap");
dialog.setMessage("Wens je 2 scoreborden te gebruiken?");
dialog.setCancelable(false);
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ja", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
startNewGame(true);
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Nee", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int buttonId) {
startNewGame(false);
}
});
dialog.setIcon(android.R.drawable.ic_dialog_alert);
dialog.show();
} else {
startNewGame(false);
}
}
}
private void startNewGame(final boolean isMirrored) {
mirroring = isMirrored;
// Show a progress dialog, and kick off a background task to perform the new game attempt
showProgressBar();
new NewGameTask(this, teamA, teamB, gameType, ageCategory, selectedCourt, mirroring, authToken).execute();
}
/**
* Called when the new game creation process completes.
*/
@Override
public void onTaskCompleted(final String result) {
hideProgressBar();
if (result == null ||
result.contains("connect timed out")) {
Toast.makeText(getApplicationContext(), "Geen connectie met scorebord", Toast.LENGTH_LONG).show();
} else {
// Show count down
Intent intent = new Intent(getApplicationContext(), CountDownActivity.class);
intent.putExtra(MIRRORED, mirroring);
intent.putExtra(GAME, result);
intent.putExtra(AUTH_TOKEN, authToken);
intent.putExtra(COURT, selectedCourt);
startActivity(intent);
}
}
@Override
public void onTaskCancelled() {
hideProgressBar();
}
private void hideProgressBar() {
progressBar.setVisibility(View.INVISIBLE);
}
private void showProgressBar() {
progressBar.setVisibility(View.VISIBLE);
}
}
| True | 1,259 | 28 | 1,516 | 34 | 1,584 | 29 | 1,516 | 34 | 1,821 | 32 | false | false | false | false | false | true |
1,412 | 31192_9 |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class DemoWorld extends World {
// Declareren van CollisionEngine
private CollisionEngine ce;
// Declareren van TileEngine
private TileEngine te;
/**
* Constructor for objects of class MyWorld.
*
*/
public DemoWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("bg.png");
int[][] map = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},};
// initialiseren van de TileEngine klasse om de map aan de world toe te voegen
te = new TileEngine(this, 60, 60);
te.setTileFactory(new DemoTileFactory());
te.setMap(map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
DemoHero hero = new DemoHero(ce, te);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 300, 200);
addObject(new Enemy(150), 1170, 410);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
}
@Override
public void act() {
ce.update();
}
}
| ROCMondriaanTIN/project-greenfoot-game-gijsdl | DemoWorld.java | 3,196 | // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. | line_comment | nl |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class DemoWorld extends World {
// Declareren van CollisionEngine
private CollisionEngine ce;
// Declareren van TileEngine
private TileEngine te;
/**
* Constructor for objects of class MyWorld.
*
*/
public DemoWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("bg.png");
int[][] map = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},};
// initialiseren van de TileEngine klasse om de map aan de world toe te voegen
te = new TileEngine(this, 60, 60);
te.setTileFactory(new DemoTileFactory());
te.setMap(map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Initialiseren van<SUF>
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
DemoHero hero = new DemoHero(ce, te);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 300, 200);
addObject(new Enemy(150), 1170, 410);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
}
@Override
public void act() {
ce.update();
}
}
| True | 3,423 | 24 | 3,463 | 24 | 3,459 | 20 | 3,463 | 24 | 3,546 | 25 | false | false | false | false | false | true |
4,672 | 18737_11 | package linkedlist;
/**
* 1)单链表的插入、删除、查找操作;
* 2)链表中存储的是int类型的数据;
*
* Author:Zheng
*/
public class SinglyLinkedList {
private Node head = null;
public Node findByValue(int value) {
Node p = head;
while (p != null && p.data != value) {
p = p.next;
}
return p;
}
public Node findByIndex(int index) {
Node p = head;
int pos = 0;
while (p != null && pos != index) {
p = p.next;
++pos;
}
return p;
}
//无头结点
//表头部插入
//这种操作将于输入的顺序相反,逆序
public void insertToHead(int value) {
Node newNode = new Node(value, null);
insertToHead(newNode);
}
public void insertToHead(Node newNode) {
if (head == null) {
head = newNode;
} else {
newNode.next = head;
head = newNode;
}
}
//顺序插入
//链表尾部插入
public void insertTail(int value){
Node newNode = new Node(value, null);
//空链表,可以插入新节点作为head,也可以不操作
if (head == null){
head = newNode;
}else{
Node q = head;
while(q.next != null){
q = q.next;
}
newNode.next = q.next;
q.next = newNode;
}
}
public void insertAfter(Node p, int value) {
Node newNode = new Node(value, null);
insertAfter(p, newNode);
}
public void insertAfter(Node p, Node newNode) {
if (p == null) return;
newNode.next = p.next;
p.next = newNode;
}
public void insertBefore(Node p, int value) {
Node newNode = new Node(value, null);
insertBefore(p, newNode);
}
public void insertBefore(Node p, Node newNode) {
if (p == null) return;
if (head == p) {
insertToHead(newNode);
return;
}
Node q = head;
while (q != null && q.next != p) {
q = q.next;
}
if (q == null) {
return;
}
newNode.next = p;
q.next = newNode;
}
public void deleteByNode(Node p) {
if (p == null || head == null) return;
if (p == head) {
head = head.next;
return;
}
Node q = head;
while (q != null && q.next != p) {
q = q.next;
}
if (q == null) {
return;
}
q.next = q.next.next;
}
public void deleteByValue(int value) {
if (head == null) return;
Node p = head;
Node q = null;
while (p != null && p.data != value) {
q = p;
p = p.next;
}
if (p == null) return;
if (q == null) {
head = head.next;
} else {
q.next = q.next.next;
}
// 可重复删除指定value的代码
/*
if (head != null && head.data == value) {
head = head.next;
}
Node pNode = head;
while (pNode != null) {
if (pNode.next.data == data) {
pNode.next = pNode.next.next;
continue;
}
pNode = pNode.next;
}
*/
}
public void printAll() {
Node p = head;
while (p != null) {
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();
}
//判断true or false
public boolean TFResult(Node left, Node right){
Node l = left;
Node r = right;
boolean flag=true;
System.out.println("left_:"+l.data);
System.out.println("right_:"+r.data);
while(l != null && r != null){
if (l.data == r.data){
l = l.next;
r = r.next;
continue;
}else{
flag=false;
break;
}
}
System.out.println("什么结果");
return flag;
/* if (l==null && r==null){
System.out.println("什么结果");
return true;
}else{
return false;
}*/
}
// 判断是否为回文
public boolean palindrome(){
if (head == null){
return false;
}else{
System.out.println("开始执行找到中间节点");
Node p = head;
Node q = head;
if (p.next == null){
System.out.println("只有一个元素");
return true;
}
while( q.next != null && q.next.next != null){
p = p.next;
q = q.next.next;
}
System.out.println("中间节点" + p.data);
System.out.println("开始执行奇数节点的回文判断");
Node leftLink = null;
Node rightLink = null;
if(q.next == null){
// p 一定为整个链表的中点,且节点数目为奇数
rightLink = p.next;
leftLink = inverseLinkList(p).next;
System.out.println("左边第一个节点"+leftLink.data);
System.out.println("右边第一个节点"+rightLink.data);
}else{
//p q 均为中点
rightLink = p.next;
leftLink = inverseLinkList(p);
}
return TFResult(leftLink, rightLink);
}
}
//带结点的链表翻转
public Node inverseLinkList_head(Node p){
// Head 为新建的一个头结点
Node Head = new Node(9999,null);
// p 为原来整个链表的头结点,现在Head指向 整个链表
Head.next = p;
/*
带头结点的链表翻转等价于
从第二个元素开始重新头插法建立链表
*/
Node Cur = p.next;
p.next = null;
Node next = null;
while(Cur != null){
next = Cur.next;
Cur.next = Head.next;
Head.next = Cur;
System.out.println("first " + Head.data);
Cur = next;
}
// 返回左半部分的中点之前的那个节点
// 从此处开始同步像两边比较
return Head;
}
//无头结点的链表翻转
public Node inverseLinkList(Node p){
Node pre = null;
Node r = head;
System.out.println("z---" + r.data);
Node next= null;
while(r !=p){
next = r.next;
r.next = pre;
pre = r;
r = next;
}
r.next = pre;
// 返回左半部分的中点之前的那个节点
// 从此处开始同步像两边比较
return r;
}
public static Node createNode(int value) {
return new Node(value, null);
}
public static class Node {
private int data;
private Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
}
public static void main(String[]args){
SinglyLinkedList link = new SinglyLinkedList();
System.out.println("hello");
//int data[] = {1};
//int data[] = {1,2};
//int data[] = {1,2,3,1};
//int data[] = {1,2,5};
//int data[] = {1,2,2,1};
// int data[] = {1,2,5,2,1};
int data[] = {1,2,5,3,1};
for(int i =0; i < data.length; i++){
//link.insertToHead(data[i]);
link.insertTail(data[i]);
}
// link.printAll();
// Node p = link.inverseLinkList_head(link.head);
// while(p != null){
// System.out.println("aa"+p.data);
// p = p.next;
// }
System.out.println("打印原始:");
link.printAll();
if (link.palindrome()){
System.out.println("回文");
}else{
System.out.println("不是回文");
}
}
}
| wangzheng0822/algo | java/06_linkedlist/SinglyLinkedList.java | 2,437 | // Node p = link.inverseLinkList_head(link.head); | line_comment | nl | package linkedlist;
/**
* 1)单链表的插入、删除、查找操作;
* 2)链表中存储的是int类型的数据;
*
* Author:Zheng
*/
public class SinglyLinkedList {
private Node head = null;
public Node findByValue(int value) {
Node p = head;
while (p != null && p.data != value) {
p = p.next;
}
return p;
}
public Node findByIndex(int index) {
Node p = head;
int pos = 0;
while (p != null && pos != index) {
p = p.next;
++pos;
}
return p;
}
//无头结点
//表头部插入
//这种操作将于输入的顺序相反,逆序
public void insertToHead(int value) {
Node newNode = new Node(value, null);
insertToHead(newNode);
}
public void insertToHead(Node newNode) {
if (head == null) {
head = newNode;
} else {
newNode.next = head;
head = newNode;
}
}
//顺序插入
//链表尾部插入
public void insertTail(int value){
Node newNode = new Node(value, null);
//空链表,可以插入新节点作为head,也可以不操作
if (head == null){
head = newNode;
}else{
Node q = head;
while(q.next != null){
q = q.next;
}
newNode.next = q.next;
q.next = newNode;
}
}
public void insertAfter(Node p, int value) {
Node newNode = new Node(value, null);
insertAfter(p, newNode);
}
public void insertAfter(Node p, Node newNode) {
if (p == null) return;
newNode.next = p.next;
p.next = newNode;
}
public void insertBefore(Node p, int value) {
Node newNode = new Node(value, null);
insertBefore(p, newNode);
}
public void insertBefore(Node p, Node newNode) {
if (p == null) return;
if (head == p) {
insertToHead(newNode);
return;
}
Node q = head;
while (q != null && q.next != p) {
q = q.next;
}
if (q == null) {
return;
}
newNode.next = p;
q.next = newNode;
}
public void deleteByNode(Node p) {
if (p == null || head == null) return;
if (p == head) {
head = head.next;
return;
}
Node q = head;
while (q != null && q.next != p) {
q = q.next;
}
if (q == null) {
return;
}
q.next = q.next.next;
}
public void deleteByValue(int value) {
if (head == null) return;
Node p = head;
Node q = null;
while (p != null && p.data != value) {
q = p;
p = p.next;
}
if (p == null) return;
if (q == null) {
head = head.next;
} else {
q.next = q.next.next;
}
// 可重复删除指定value的代码
/*
if (head != null && head.data == value) {
head = head.next;
}
Node pNode = head;
while (pNode != null) {
if (pNode.next.data == data) {
pNode.next = pNode.next.next;
continue;
}
pNode = pNode.next;
}
*/
}
public void printAll() {
Node p = head;
while (p != null) {
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();
}
//判断true or false
public boolean TFResult(Node left, Node right){
Node l = left;
Node r = right;
boolean flag=true;
System.out.println("left_:"+l.data);
System.out.println("right_:"+r.data);
while(l != null && r != null){
if (l.data == r.data){
l = l.next;
r = r.next;
continue;
}else{
flag=false;
break;
}
}
System.out.println("什么结果");
return flag;
/* if (l==null && r==null){
System.out.println("什么结果");
return true;
}else{
return false;
}*/
}
// 判断是否为回文
public boolean palindrome(){
if (head == null){
return false;
}else{
System.out.println("开始执行找到中间节点");
Node p = head;
Node q = head;
if (p.next == null){
System.out.println("只有一个元素");
return true;
}
while( q.next != null && q.next.next != null){
p = p.next;
q = q.next.next;
}
System.out.println("中间节点" + p.data);
System.out.println("开始执行奇数节点的回文判断");
Node leftLink = null;
Node rightLink = null;
if(q.next == null){
// p 一定为整个链表的中点,且节点数目为奇数
rightLink = p.next;
leftLink = inverseLinkList(p).next;
System.out.println("左边第一个节点"+leftLink.data);
System.out.println("右边第一个节点"+rightLink.data);
}else{
//p q 均为中点
rightLink = p.next;
leftLink = inverseLinkList(p);
}
return TFResult(leftLink, rightLink);
}
}
//带结点的链表翻转
public Node inverseLinkList_head(Node p){
// Head 为新建的一个头结点
Node Head = new Node(9999,null);
// p 为原来整个链表的头结点,现在Head指向 整个链表
Head.next = p;
/*
带头结点的链表翻转等价于
从第二个元素开始重新头插法建立链表
*/
Node Cur = p.next;
p.next = null;
Node next = null;
while(Cur != null){
next = Cur.next;
Cur.next = Head.next;
Head.next = Cur;
System.out.println("first " + Head.data);
Cur = next;
}
// 返回左半部分的中点之前的那个节点
// 从此处开始同步像两边比较
return Head;
}
//无头结点的链表翻转
public Node inverseLinkList(Node p){
Node pre = null;
Node r = head;
System.out.println("z---" + r.data);
Node next= null;
while(r !=p){
next = r.next;
r.next = pre;
pre = r;
r = next;
}
r.next = pre;
// 返回左半部分的中点之前的那个节点
// 从此处开始同步像两边比较
return r;
}
public static Node createNode(int value) {
return new Node(value, null);
}
public static class Node {
private int data;
private Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
}
public static void main(String[]args){
SinglyLinkedList link = new SinglyLinkedList();
System.out.println("hello");
//int data[] = {1};
//int data[] = {1,2};
//int data[] = {1,2,3,1};
//int data[] = {1,2,5};
//int data[] = {1,2,2,1};
// int data[] = {1,2,5,2,1};
int data[] = {1,2,5,3,1};
for(int i =0; i < data.length; i++){
//link.insertToHead(data[i]);
link.insertTail(data[i]);
}
// link.printAll();
// Node p<SUF>
// while(p != null){
// System.out.println("aa"+p.data);
// p = p.next;
// }
System.out.println("打印原始:");
link.printAll();
if (link.palindrome()){
System.out.println("回文");
}else{
System.out.println("不是回文");
}
}
}
| False | 1,919 | 12 | 2,073 | 16 | 2,323 | 16 | 2,073 | 16 | 2,641 | 17 | false | false | false | false | false | true |
2,414 | 18652_3 | /*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* QNX Software System
* Anton Leherbauer (Wind River Systems)
* Sergey Prigogin (Google)
* James Blackburn (Broadcom Corp.)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.build;
import org.eclipse.cdt.core.resources.ACBuilder;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.preferences.PreferencesMessages;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
/**
* The page for top-level build preferences
*/
public class BuildPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final int GROUP_VINDENT = 5;
private static final int GROUP_HINDENT = 20;
private Button buildActive, buildAll, buildOnlyOnRefChange;
public BuildPreferencePage() {
super();
setPreferenceStore(CUIPlugin.getDefault().getPreferenceStore());
setDescription(PreferencesMessages.CBuildPreferencePage_description);
}
@Override
public void createControl(Composite parent) {
super.createControl(parent);
PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), ICHelpContextIds.C_PREF_PAGE);
}
@Override
protected Control createContents(Composite parent) {
initializeDialogUnits(parent);
Composite container = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth = 0;
layout.verticalSpacing = convertVerticalDLUsToPixels(10);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
container.setLayout(layout);
// Build either default configuration or all.
Group gr = addGroup(container, PreferencesMessages.CPluginPreferencePage_build_scope);
Label l1 = new Label(gr, SWT.NONE);
l1.setText(PreferencesMessages.CPluginPreferencePage_1);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = GROUP_VINDENT;
l1.setLayoutData(gd);
boolean needAllConfigBuild = ACBuilder.needAllConfigBuild();
buildActive = new Button(gr, SWT.RADIO);
buildActive.setText(PreferencesMessages.CPluginPreferencePage_2);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = GROUP_VINDENT;
gd.horizontalIndent = GROUP_HINDENT;
buildActive.setLayoutData(gd);
buildActive.setSelection(!needAllConfigBuild);
buildAll = new Button(gr, SWT.RADIO);
buildAll.setText(PreferencesMessages.CPluginPreferencePage_3);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent = GROUP_HINDENT;
buildAll.setLayoutData(gd);
buildAll.setSelection(needAllConfigBuild);
addNote(gr, PreferencesMessages.CPluginPreferencePage_4);
// Building project dependencies.
Group gr2 = addGroup(container, PreferencesMessages.CPluginPreferencePage_building_configurations);
buildOnlyOnRefChange = new Button(gr2, SWT.CHECK);
buildOnlyOnRefChange.setText(PreferencesMessages.CPluginPreferencePage_7);
GridData gd2 = new GridData(GridData.FILL_HORIZONTAL);
gd2.verticalIndent = GROUP_VINDENT;
buildOnlyOnRefChange.setLayoutData(gd2);
buildOnlyOnRefChange.setSelection(ACBuilder.buildConfigResourceChanges());
Dialog.applyDialogFont(container);
return container;
}
private void addNote(Group parent, String noteMessage) {
Composite noteControl = createNoteComposite(JFaceResources.getDialogFont(), parent,
PreferencesMessages.CPluginPreferencePage_note, noteMessage);
GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.verticalIndent = GROUP_VINDENT;
noteControl.setLayoutData(gd);
}
@Override
protected Composite createNoteComposite(Font font, Composite composite, String title, String message) {
Composite messageComposite = super.createNoteComposite(font, composite, title, message);
Control[] children = messageComposite.getChildren();
if (children.length == 2 && (children[1] instanceof Label)) {
// this is temporary fix for problem that 3 line note does not displayed properly within the group
Label messageLabel = (Label) children[1];
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint = 500;
messageLabel.setLayoutData(gd);
}
return messageComposite;
}
private Group addGroup(Composite parent, String label) {
return addGroup(parent, label, 1);
}
private Group addGroup(Composite parent, String label, int numColumns) {
Group group = new Group(parent, SWT.NONE);
group.setText(label);
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(new GridLayout(numColumns, false));
return group;
}
/**
* @see IWorkbenchPreferencePage#init
*/
@Override
public void init(IWorkbench workbench) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
@Override
public boolean performOk() {
if (!super.performOk())
return false;
// tell the Core Plugin about this preference
ACBuilder.setAllConfigBuild(buildAll.getSelection());
ACBuilder.setBuildConfigResourceChanges(buildOnlyOnRefChange.getSelection());
return true;
}
@Override
protected void performDefaults() {
ACBuilder.setAllConfigBuild(false);
ACBuilder.setBuildConfigResourceChanges(false);
buildActive.setSelection(true);
buildAll.setSelection(false);
buildOnlyOnRefChange.setSelection(false);
super.performDefaults();
}
}
| cmorty/cdt | core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/build/BuildPreferencePage.java | 2,049 | // Building project dependencies. | line_comment | nl | /*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* QNX Software System
* Anton Leherbauer (Wind River Systems)
* Sergey Prigogin (Google)
* James Blackburn (Broadcom Corp.)
*******************************************************************************/
package org.eclipse.cdt.internal.ui.build;
import org.eclipse.cdt.core.resources.ACBuilder;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.preferences.PreferencesMessages;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
/**
* The page for top-level build preferences
*/
public class BuildPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final int GROUP_VINDENT = 5;
private static final int GROUP_HINDENT = 20;
private Button buildActive, buildAll, buildOnlyOnRefChange;
public BuildPreferencePage() {
super();
setPreferenceStore(CUIPlugin.getDefault().getPreferenceStore());
setDescription(PreferencesMessages.CBuildPreferencePage_description);
}
@Override
public void createControl(Composite parent) {
super.createControl(parent);
PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), ICHelpContextIds.C_PREF_PAGE);
}
@Override
protected Control createContents(Composite parent) {
initializeDialogUnits(parent);
Composite container = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth = 0;
layout.verticalSpacing = convertVerticalDLUsToPixels(10);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
container.setLayout(layout);
// Build either default configuration or all.
Group gr = addGroup(container, PreferencesMessages.CPluginPreferencePage_build_scope);
Label l1 = new Label(gr, SWT.NONE);
l1.setText(PreferencesMessages.CPluginPreferencePage_1);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = GROUP_VINDENT;
l1.setLayoutData(gd);
boolean needAllConfigBuild = ACBuilder.needAllConfigBuild();
buildActive = new Button(gr, SWT.RADIO);
buildActive.setText(PreferencesMessages.CPluginPreferencePage_2);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalIndent = GROUP_VINDENT;
gd.horizontalIndent = GROUP_HINDENT;
buildActive.setLayoutData(gd);
buildActive.setSelection(!needAllConfigBuild);
buildAll = new Button(gr, SWT.RADIO);
buildAll.setText(PreferencesMessages.CPluginPreferencePage_3);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent = GROUP_HINDENT;
buildAll.setLayoutData(gd);
buildAll.setSelection(needAllConfigBuild);
addNote(gr, PreferencesMessages.CPluginPreferencePage_4);
// Building project<SUF>
Group gr2 = addGroup(container, PreferencesMessages.CPluginPreferencePage_building_configurations);
buildOnlyOnRefChange = new Button(gr2, SWT.CHECK);
buildOnlyOnRefChange.setText(PreferencesMessages.CPluginPreferencePage_7);
GridData gd2 = new GridData(GridData.FILL_HORIZONTAL);
gd2.verticalIndent = GROUP_VINDENT;
buildOnlyOnRefChange.setLayoutData(gd2);
buildOnlyOnRefChange.setSelection(ACBuilder.buildConfigResourceChanges());
Dialog.applyDialogFont(container);
return container;
}
private void addNote(Group parent, String noteMessage) {
Composite noteControl = createNoteComposite(JFaceResources.getDialogFont(), parent,
PreferencesMessages.CPluginPreferencePage_note, noteMessage);
GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.verticalIndent = GROUP_VINDENT;
noteControl.setLayoutData(gd);
}
@Override
protected Composite createNoteComposite(Font font, Composite composite, String title, String message) {
Composite messageComposite = super.createNoteComposite(font, composite, title, message);
Control[] children = messageComposite.getChildren();
if (children.length == 2 && (children[1] instanceof Label)) {
// this is temporary fix for problem that 3 line note does not displayed properly within the group
Label messageLabel = (Label) children[1];
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint = 500;
messageLabel.setLayoutData(gd);
}
return messageComposite;
}
private Group addGroup(Composite parent, String label) {
return addGroup(parent, label, 1);
}
private Group addGroup(Composite parent, String label, int numColumns) {
Group group = new Group(parent, SWT.NONE);
group.setText(label);
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(new GridLayout(numColumns, false));
return group;
}
/**
* @see IWorkbenchPreferencePage#init
*/
@Override
public void init(IWorkbench workbench) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
@Override
public boolean performOk() {
if (!super.performOk())
return false;
// tell the Core Plugin about this preference
ACBuilder.setAllConfigBuild(buildAll.getSelection());
ACBuilder.setBuildConfigResourceChanges(buildOnlyOnRefChange.getSelection());
return true;
}
@Override
protected void performDefaults() {
ACBuilder.setAllConfigBuild(false);
ACBuilder.setBuildConfigResourceChanges(false);
buildActive.setSelection(true);
buildAll.setSelection(false);
buildOnlyOnRefChange.setSelection(false);
super.performDefaults();
}
}
| False | 1,439 | 5 | 1,798 | 5 | 1,770 | 5 | 1,798 | 5 | 2,152 | 5 | false | false | false | false | false | true |
383 | 65066_6 | package com.nhlstenden.amazonsimulatie.tests;
import com.nhlstenden.amazonsimulatie.models.Model;
import com.nhlstenden.amazonsimulatie.models.Object3D;
import com.nhlstenden.amazonsimulatie.views.DefaultWebSocketView;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultWebSocketViewTests {
/**
* De code hieronder is een voorbeeld van een test in Java. Je schrijf per class die je wilt testen
* een testclass zoals deze. Daarin zet je al je testfuncties. Vaak schrijf je per methode (of functie)
* die je wilt testen een methode zoals deze hieronder. Kijk in de methode naar de genummerde comments.
* Om de test het beste te begrijpen, begin je vanaf comment #1.
*/
@Test
public void testUpdateSignal() throws Exception {
/**
* Comment #2
* Deze code hieronder hebben we nodig om de DefaultWebSocketView van comment 1 te kunnen maken.
* Dat onderdeel van de software heeft een zogenaamde WebSocketSession nodig (een onderdeel waarmee
* informatie via een websocket naar de webbrowser kan worden verstuurd). Een WebSocketSession is
* normaal gesproken een onderdeel van het websocket systeem van onze server, en we kunnen niet
* zomaar een WebSocketSession aanmaken wanneer er geen server draait, laat staan geen browser is.
* Om dit toch te kunnen gebruiken, 'mocken' we de class WebSocketSession. Dit mocken betekent dat
* we als het ware een 'nep' versie van het object maken. Deze 'mockSession'n (zie hieronder) is
* een object dat wel alle methoden heeft van een echte WebSocketSession, maar de methoden doen
* simpelweg niks. Hierdoor kun je code die een WebSocketSession nodig heeft, toch laten werken.
* Ga nu naar comment #3.
*/
WebSocketSession mockSession = mock(WebSocketSession.class);
/**
* Comment #3
* De code hieronder is eigenlijk de invulling van een methode van WebSocketSession. Zoals je in
* comment #2 las, is de het object mockSession een 'lege' WebSocketSession. De methoden bestaan dus
* wel, maar doen in feite niks. Hieronder wordt een invulling gegeven. De when() functie is onderdeel
* van het systeem om te mocken, en zegt hier wanneer de methode .isOpen() wordt aangeroepen op het object
* mockSession, dan moet er iets gebeuren. Wat er moet gebeuren staat achter de when() methode, in de
* vorm van .thenReturn(true). De hele regel code betekent nu dat wanneer .isOpen() wordt aangeroepen
* op mockSession, dan moet deze methode altijd de waarde true teruggeven. Dit onderdeel is nodig omdat
* de view in de update methode gebruikmaakt van de .isOpen() methode. Ga nu naar comment #4.
*/
when(mockSession.isOpen()).thenReturn(true);
/**
* Comment 4
* De code hieronder is misschien wat onduidelijk. Wat we hier doen, is het injecteren van testcode binnen
* het mockSession object. Dit doen we omdat mockSession gebruikt wordt om het JSON pakketje te versturen.
* Dit object krijgt dus sowieso de JSON tekst te zien. Dit gebeurd in de methode .sendMessage(). Hier wordt
* een tekstbericht verstuurd naar de browser. In dit bericht zit de JSON code. Hier kunnen we dus een test
* injecteren om de validiteit van de JSON de controleren. Dit is ook wat hieronder gebeurd. De methode
* doAnwser hieronder zorgt ervoor dat de code die daarin wordt gegeven wordt uitgevoerd wanneer de
* methode .sendMessage wordt aangeroepen. Het onderdeel daarna met 'new TextMessage(anyString())'
* betekent dat die nieuwe code moet worden uitgevoerd voor de methode .sendMessage(), wanneer er
* aan .sendMessage() een object TextMessage wordt meegegeven waar elke bedenkbare string in mag
* zitten (vandaar de anyString()). Ga nu naar comment #5.
*/
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
/**
* Comment #5
* Deze code hieronder is de daadwerkelijke testcode. De methode assertThat() controleert of iets dat je opgeeft
* dat waar moet zijn, daadwerkelijk ook zo is. In dit geval wordt gecontroleerd of het binnengekomen object
* TextMessage (zit op index 0 van args) een JSON string in zich heeft die gelijk is aan de opgegeven string
* daar rechts van. Via de is() methode wordt aangegeven dat beide strings gelijk moeten zijn. De JSON wordt
* gemaakt van een Object3D dat geupdate wordt (zie update methode in de DefaultWebSocketView class). In de
* JSON code hieronder zie je dat voor elke parameter in de JSON een standaardwaarde is ingevoerd. Ga nu naar
* comment #6 om te zien hoe we ervoor zorgen dat de update() methode ook gebruiktmaakt van die standaardwaarden.
*/
assertThat(((TextMessage)args[0]).getPayload(), is("{\"command\": \"object_update\",\"parameters\": {\"uuid\":\"unique_string\",\"type\":\"type_here\",\"x\":0.0,\"y\":0.0,\"z\":0.0,\"rotationX\":0.0,\"rotationY\":0.0,\"rotationZ\":0.0,\"status\":\"status_here\"}}"));
return null;
}
}).when(mockSession).sendMessage(new TextMessage(anyString()));
/**
* Comment #1
* De testfunctie waar we nu inzitten heet testUpdateSignal. Dit updatesignal slaat op het updaten van een
* view binnen de simulatie. Wanneer dat gebeurd, wordt er een JSON pakketje naar de webbrowser van die
* view gestuurd. We gaan dit systeem simuleren om zo de validiteit van de JSON te kunnen testen. Daarvoor
* hebben we eerst een nieuwe view nodig. Die wordt hieronder aangemaakt. Om een DefaultWebSocketView aan te
* maken, hebben we iets van een websocket nodig (in dit geval een sessie, zie de projectcode). Zie comment #2.
*/
DefaultWebSocketView view = new DefaultWebSocketView(mockSession);
/**
* Commeent #6
* Hieronder wordt een Object3D aangemaakt. Dit doen we omdat de view.update() methode een Object3D nodig heeft.
* Voor een Object3D geldt ook dat een simulatie nodig is om een Object3D object te kunnen krijgen. Omdat we de
* simulatie niet draaien, mocken we een Object3D. We maken er dus als het ware eentje na. Hier voeren we de
* standaardwaarden in die de JSON code bij comment #5 gebruikt om te controleren of de .update() methode van
* view werkt. Ga nu naar comment #7 om te zien welke code de test in zijn werk zet.
*/
Object3D mockObj3D = mock(Object3D.class);
when(mockObj3D.getUUID()).thenReturn("unique_string");
when(mockObj3D.getType()).thenReturn("type_here");
when(mockObj3D.getX()).thenReturn(0.0);
when(mockObj3D.getY()).thenReturn(0.0);
when(mockObj3D.getZ()).thenReturn(0.0);
when(mockObj3D.getRotationX()).thenReturn(0.0);
when(mockObj3D.getRotationY()).thenReturn(0.0);
when(mockObj3D.getRotationZ()).thenReturn(0.0);
when(mockObj3D.getStatus()).thenReturn("status_here");
/**
* Comment #7
* De code hieronder activeert de .update() methode van view. Deze methode maakt van een Object3D (hier mockObj3D)
* een JSON pakket en verstuurd deze via een websocket connectie. In de websocket connectie hebben we onze testcode
* geïnjecteerd, en dit betekent dat dan de test ook zal worden uitgoerd.
*/
view.update(Model.UPDATE_COMMAND, mockObj3D);
}
} | Damiaen/AmazonSimulatie | src/test/java/com/nhlstenden/amazonsimulatie/tests/DefaultWebSocketViewTests.java | 2,315 | /**
* Commeent #6
* Hieronder wordt een Object3D aangemaakt. Dit doen we omdat de view.update() methode een Object3D nodig heeft.
* Voor een Object3D geldt ook dat een simulatie nodig is om een Object3D object te kunnen krijgen. Omdat we de
* simulatie niet draaien, mocken we een Object3D. We maken er dus als het ware eentje na. Hier voeren we de
* standaardwaarden in die de JSON code bij comment #5 gebruikt om te controleren of de .update() methode van
* view werkt. Ga nu naar comment #7 om te zien welke code de test in zijn werk zet.
*/ | block_comment | nl | package com.nhlstenden.amazonsimulatie.tests;
import com.nhlstenden.amazonsimulatie.models.Model;
import com.nhlstenden.amazonsimulatie.models.Object3D;
import com.nhlstenden.amazonsimulatie.views.DefaultWebSocketView;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultWebSocketViewTests {
/**
* De code hieronder is een voorbeeld van een test in Java. Je schrijf per class die je wilt testen
* een testclass zoals deze. Daarin zet je al je testfuncties. Vaak schrijf je per methode (of functie)
* die je wilt testen een methode zoals deze hieronder. Kijk in de methode naar de genummerde comments.
* Om de test het beste te begrijpen, begin je vanaf comment #1.
*/
@Test
public void testUpdateSignal() throws Exception {
/**
* Comment #2
* Deze code hieronder hebben we nodig om de DefaultWebSocketView van comment 1 te kunnen maken.
* Dat onderdeel van de software heeft een zogenaamde WebSocketSession nodig (een onderdeel waarmee
* informatie via een websocket naar de webbrowser kan worden verstuurd). Een WebSocketSession is
* normaal gesproken een onderdeel van het websocket systeem van onze server, en we kunnen niet
* zomaar een WebSocketSession aanmaken wanneer er geen server draait, laat staan geen browser is.
* Om dit toch te kunnen gebruiken, 'mocken' we de class WebSocketSession. Dit mocken betekent dat
* we als het ware een 'nep' versie van het object maken. Deze 'mockSession'n (zie hieronder) is
* een object dat wel alle methoden heeft van een echte WebSocketSession, maar de methoden doen
* simpelweg niks. Hierdoor kun je code die een WebSocketSession nodig heeft, toch laten werken.
* Ga nu naar comment #3.
*/
WebSocketSession mockSession = mock(WebSocketSession.class);
/**
* Comment #3
* De code hieronder is eigenlijk de invulling van een methode van WebSocketSession. Zoals je in
* comment #2 las, is de het object mockSession een 'lege' WebSocketSession. De methoden bestaan dus
* wel, maar doen in feite niks. Hieronder wordt een invulling gegeven. De when() functie is onderdeel
* van het systeem om te mocken, en zegt hier wanneer de methode .isOpen() wordt aangeroepen op het object
* mockSession, dan moet er iets gebeuren. Wat er moet gebeuren staat achter de when() methode, in de
* vorm van .thenReturn(true). De hele regel code betekent nu dat wanneer .isOpen() wordt aangeroepen
* op mockSession, dan moet deze methode altijd de waarde true teruggeven. Dit onderdeel is nodig omdat
* de view in de update methode gebruikmaakt van de .isOpen() methode. Ga nu naar comment #4.
*/
when(mockSession.isOpen()).thenReturn(true);
/**
* Comment 4
* De code hieronder is misschien wat onduidelijk. Wat we hier doen, is het injecteren van testcode binnen
* het mockSession object. Dit doen we omdat mockSession gebruikt wordt om het JSON pakketje te versturen.
* Dit object krijgt dus sowieso de JSON tekst te zien. Dit gebeurd in de methode .sendMessage(). Hier wordt
* een tekstbericht verstuurd naar de browser. In dit bericht zit de JSON code. Hier kunnen we dus een test
* injecteren om de validiteit van de JSON de controleren. Dit is ook wat hieronder gebeurd. De methode
* doAnwser hieronder zorgt ervoor dat de code die daarin wordt gegeven wordt uitgevoerd wanneer de
* methode .sendMessage wordt aangeroepen. Het onderdeel daarna met 'new TextMessage(anyString())'
* betekent dat die nieuwe code moet worden uitgevoerd voor de methode .sendMessage(), wanneer er
* aan .sendMessage() een object TextMessage wordt meegegeven waar elke bedenkbare string in mag
* zitten (vandaar de anyString()). Ga nu naar comment #5.
*/
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
/**
* Comment #5
* Deze code hieronder is de daadwerkelijke testcode. De methode assertThat() controleert of iets dat je opgeeft
* dat waar moet zijn, daadwerkelijk ook zo is. In dit geval wordt gecontroleerd of het binnengekomen object
* TextMessage (zit op index 0 van args) een JSON string in zich heeft die gelijk is aan de opgegeven string
* daar rechts van. Via de is() methode wordt aangegeven dat beide strings gelijk moeten zijn. De JSON wordt
* gemaakt van een Object3D dat geupdate wordt (zie update methode in de DefaultWebSocketView class). In de
* JSON code hieronder zie je dat voor elke parameter in de JSON een standaardwaarde is ingevoerd. Ga nu naar
* comment #6 om te zien hoe we ervoor zorgen dat de update() methode ook gebruiktmaakt van die standaardwaarden.
*/
assertThat(((TextMessage)args[0]).getPayload(), is("{\"command\": \"object_update\",\"parameters\": {\"uuid\":\"unique_string\",\"type\":\"type_here\",\"x\":0.0,\"y\":0.0,\"z\":0.0,\"rotationX\":0.0,\"rotationY\":0.0,\"rotationZ\":0.0,\"status\":\"status_here\"}}"));
return null;
}
}).when(mockSession).sendMessage(new TextMessage(anyString()));
/**
* Comment #1
* De testfunctie waar we nu inzitten heet testUpdateSignal. Dit updatesignal slaat op het updaten van een
* view binnen de simulatie. Wanneer dat gebeurd, wordt er een JSON pakketje naar de webbrowser van die
* view gestuurd. We gaan dit systeem simuleren om zo de validiteit van de JSON te kunnen testen. Daarvoor
* hebben we eerst een nieuwe view nodig. Die wordt hieronder aangemaakt. Om een DefaultWebSocketView aan te
* maken, hebben we iets van een websocket nodig (in dit geval een sessie, zie de projectcode). Zie comment #2.
*/
DefaultWebSocketView view = new DefaultWebSocketView(mockSession);
/**
* Commeent #6
<SUF>*/
Object3D mockObj3D = mock(Object3D.class);
when(mockObj3D.getUUID()).thenReturn("unique_string");
when(mockObj3D.getType()).thenReturn("type_here");
when(mockObj3D.getX()).thenReturn(0.0);
when(mockObj3D.getY()).thenReturn(0.0);
when(mockObj3D.getZ()).thenReturn(0.0);
when(mockObj3D.getRotationX()).thenReturn(0.0);
when(mockObj3D.getRotationY()).thenReturn(0.0);
when(mockObj3D.getRotationZ()).thenReturn(0.0);
when(mockObj3D.getStatus()).thenReturn("status_here");
/**
* Comment #7
* De code hieronder activeert de .update() methode van view. Deze methode maakt van een Object3D (hier mockObj3D)
* een JSON pakket en verstuurd deze via een websocket connectie. In de websocket connectie hebben we onze testcode
* geïnjecteerd, en dit betekent dat dan de test ook zal worden uitgoerd.
*/
view.update(Model.UPDATE_COMMAND, mockObj3D);
}
} | True | 2,045 | 167 | 2,272 | 186 | 2,003 | 154 | 2,272 | 186 | 2,393 | 184 | false | false | false | false | false | true |
3,658 | 31698_0 | package Symbols;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.io.StringReader;
public class Tokenizer {
public Tokenizer(Reader inStream) {
numOfErrors = 0;
currentChar = '\0';
currentLine = 1;
inputStream = new PushbackReader(inStream);
}
private static final int SLASH_SLASH = 0;
private static final int SLASH_STAR = 1;
private static final char NEW_LINE = '\n';
private PushbackReader inputStream;
private char currentChar;
private int currentLine;
private int numOfErrors;
public int getLineNumber() {
return currentLine;
}
public int getErrorCount() {
return numOfErrors;
}
public char getNextOpenClose() {
while (nextChar()) {
if (currentChar == '/') {
processSlash();
} else if (currentChar == '\'' || currentChar == '"') {
skipQuote(currentChar);
} else if (currentChar == '(' || currentChar == '[' || currentChar == '{' ||
currentChar == ')' || currentChar == ']' || currentChar == '}') {
return currentChar;
}
}
return '\0';
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
while (nextChar()) {
result.append(currentChar);
}
inputStream = new PushbackReader(new StringReader(result.toString())); // Niet de mooiste manier, werkt voor nu.
return result.toString();
}
//public char getNextID() {
/* Figure 12.29 */
//}
private boolean nextChar() {
try {
int currentCharValue = inputStream.read();
if (currentCharValue == -1) {
return false;
}
currentChar = (char) currentCharValue;
if (currentChar == NEW_LINE) {
currentLine++;
}
return true;
} catch (IOException e) {
return false;
}
}
private void putBackChar() {
if (currentChar == NEW_LINE) {
currentLine--;
}
try {
inputStream.unread((int) currentChar);
} catch (IOException e) {
// Swallow
}
}
private void skipComment(int start) {
if (start == SLASH_SLASH) {
while (nextChar() && (currentChar != '\n'))
;
return;
}
boolean state = false;
while (nextChar()) {
if (state && currentChar == '/') {
return;
}
state = currentChar == '*';
}
numOfErrors++;
System.out.println("Unterminated comment!");
}
private void skipQuote(char quoteType) {
while (nextChar()) {
if (currentChar == quoteType) {
return;
}
if (currentChar == NEW_LINE) {
numOfErrors++;
System.out.println(String.format(
"Missing closed quote at line %s",
currentLine));
} else if (currentChar == '\\') {
nextChar();
}
}
}
private void processSlash() {
if (nextChar()) {
if (currentChar == '*') {
if (nextChar() && currentChar != '*') {
putBackChar();
}
skipComment(SLASH_STAR);
} else if (currentChar == '/') {
skipComment(SLASH_SLASH);
} else if (currentChar != NEW_LINE) {
putBackChar();
}
}
}
//private static final boolean isIdChar(char ch) {
/* Figure 12.27 */
//}
//private String getRemainingString() {
/* Figure 12.28 */
//}
} | mikederksen/Algorithms | src/main/java/Symbols/Tokenizer.java | 1,050 | // Niet de mooiste manier, werkt voor nu. | line_comment | nl | package Symbols;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.io.StringReader;
public class Tokenizer {
public Tokenizer(Reader inStream) {
numOfErrors = 0;
currentChar = '\0';
currentLine = 1;
inputStream = new PushbackReader(inStream);
}
private static final int SLASH_SLASH = 0;
private static final int SLASH_STAR = 1;
private static final char NEW_LINE = '\n';
private PushbackReader inputStream;
private char currentChar;
private int currentLine;
private int numOfErrors;
public int getLineNumber() {
return currentLine;
}
public int getErrorCount() {
return numOfErrors;
}
public char getNextOpenClose() {
while (nextChar()) {
if (currentChar == '/') {
processSlash();
} else if (currentChar == '\'' || currentChar == '"') {
skipQuote(currentChar);
} else if (currentChar == '(' || currentChar == '[' || currentChar == '{' ||
currentChar == ')' || currentChar == ']' || currentChar == '}') {
return currentChar;
}
}
return '\0';
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
while (nextChar()) {
result.append(currentChar);
}
inputStream = new PushbackReader(new StringReader(result.toString())); // Niet de<SUF>
return result.toString();
}
//public char getNextID() {
/* Figure 12.29 */
//}
private boolean nextChar() {
try {
int currentCharValue = inputStream.read();
if (currentCharValue == -1) {
return false;
}
currentChar = (char) currentCharValue;
if (currentChar == NEW_LINE) {
currentLine++;
}
return true;
} catch (IOException e) {
return false;
}
}
private void putBackChar() {
if (currentChar == NEW_LINE) {
currentLine--;
}
try {
inputStream.unread((int) currentChar);
} catch (IOException e) {
// Swallow
}
}
private void skipComment(int start) {
if (start == SLASH_SLASH) {
while (nextChar() && (currentChar != '\n'))
;
return;
}
boolean state = false;
while (nextChar()) {
if (state && currentChar == '/') {
return;
}
state = currentChar == '*';
}
numOfErrors++;
System.out.println("Unterminated comment!");
}
private void skipQuote(char quoteType) {
while (nextChar()) {
if (currentChar == quoteType) {
return;
}
if (currentChar == NEW_LINE) {
numOfErrors++;
System.out.println(String.format(
"Missing closed quote at line %s",
currentLine));
} else if (currentChar == '\\') {
nextChar();
}
}
}
private void processSlash() {
if (nextChar()) {
if (currentChar == '*') {
if (nextChar() && currentChar != '*') {
putBackChar();
}
skipComment(SLASH_STAR);
} else if (currentChar == '/') {
skipComment(SLASH_SLASH);
} else if (currentChar != NEW_LINE) {
putBackChar();
}
}
}
//private static final boolean isIdChar(char ch) {
/* Figure 12.27 */
//}
//private String getRemainingString() {
/* Figure 12.28 */
//}
} | True | 821 | 13 | 871 | 15 | 974 | 11 | 871 | 15 | 1,069 | 15 | false | false | false | false | false | true |
2,257 | 174542_15 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pt.ua.ieeta.nero.corpus;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.commons.lang.StringEscapeUtils;
import pt.ua.tm.gimli.external.gdep.GDepParser;
/**
*
* @author david
*/
public class FilterSilverStandardCorpus {
private static String XML_SENTENCE = "s";
private static String XML_ANNOTATION = "e";
private static int numSentences;
private static int MAX_SENTENCES = 100000;
private static void readFile(File file, ArrayList<String> sentences) throws IOException, XMLStreamException {
GZIPInputStream f = new GZIPInputStream(new FileInputStream(file));
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
XMLEventReader eventReader = inputFactory.createXMLEventReader(f);
// Helpers
boolean inSentence = false;
boolean hasAnnotation = false;
int count = 0;
StringBuilder sb = new StringBuilder();
String s;
// Read the XML document
while (eventReader.hasNext()) {
if (numSentences > MAX_SENTENCES) {
break;
}
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
if (startElement.getName().getLocalPart() == XML_SENTENCE) {
sb = new StringBuilder();
inSentence = true;
hasAnnotation = false;
count = 0;
}
if (startElement.getName().getLocalPart() == XML_ANNOTATION) {
hasAnnotation = true;
event = eventReader.nextEvent();
count++;
}
}
if (inSentence) {
if (event.isCharacters()) {
sb.append(event.asCharacters().getData());
}
}
if (event.isEndElement()) {
EndElement endElement = event.asEndElement();
if (endElement.getName().getLocalPart() == XML_SENTENCE) {
inSentence = false;
if (hasAnnotation && count >= 2) {
//if (!hasAnnotation) {
s = sb.toString().trim();
s = StringEscapeUtils.unescapeXml(s);
numSentences++;
// Customize tokenisation
//s = s.replaceAll("/", " / ");
//s = s.replaceAll("-", " - ");
//s = s.replaceAll("[.]", " . ");
//s = s.replaceAll("//s+", " ");
sentences.add(s);
}
}
}
}
}
public static void main(String[] args) {
try {
ArrayList<String> sentences = new ArrayList<String>();
numSentences = 0;
File inputDir = new File("/Users/david/Downloads/calbc/fixed/");
File[] files = inputDir.listFiles();
for (File f : files) {
System.out.println(f.getName());
readFile(f, sentences);
}
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream("resources/corpus/silver/2_100k.gz"));
//String[] tokens;
//Tokenizer tokenizer = new Tokenizer(false);
GDepParser parser = new GDepParser(true, false);
parser.launch();
List<Object> result;
String[] parts;
String token_parsing, token, lemma, pos, chunk;
//tokenizer.launch();
for (String sentence : sentences) {
//sentence = sentence.replaceAll("/", " / ");
//sentence = sentence.replaceAll("-", " - ");
//sentence = sentence.replaceAll("[.]", " . ");
//sentence = sentence.replaceAll("//s+", " ");
//tokens = tokenizer.tokenize(sentence);
result = parser.parse(sentence);
for (Object o:result){
token_parsing = (String) o;
parts = token_parsing.split("\t");
token = parts[1];
lemma = parts[2];
pos = parts[3];
chunk = parts[4];
out.write(token.getBytes());
out.write("\t".getBytes());
out.write("LEMMA=".getBytes());
out.write(lemma.getBytes());
out.write("\t".getBytes());
out.write("POS=".getBytes());
out.write(pos.getBytes());
out.write("\t".getBytes());
out.write("CHUNK=".getBytes());
out.write(chunk.getBytes());
out.write("\t".getBytes());
out.write("O".getBytes());
out.write("\n".getBytes());
}
/*for (String t : tokens) {
out.write(t.getBytes());
out.write("\t".getBytes());
out.write("O".getBytes());
out.write("\n".getBytes());
}*/
out.write("\n".getBytes());
}
out.close();
parser.terminate();
}
catch (Exception ex) {
ex.printStackTrace();
return;
}
}
}
| bioinformatics-ua/NERO | src/pt/ua/ieeta/nero/corpus/FilterSilverStandardCorpus.java | 1,652 | //tokens = tokenizer.tokenize(sentence); | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pt.ua.ieeta.nero.corpus;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.commons.lang.StringEscapeUtils;
import pt.ua.tm.gimli.external.gdep.GDepParser;
/**
*
* @author david
*/
public class FilterSilverStandardCorpus {
private static String XML_SENTENCE = "s";
private static String XML_ANNOTATION = "e";
private static int numSentences;
private static int MAX_SENTENCES = 100000;
private static void readFile(File file, ArrayList<String> sentences) throws IOException, XMLStreamException {
GZIPInputStream f = new GZIPInputStream(new FileInputStream(file));
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
XMLEventReader eventReader = inputFactory.createXMLEventReader(f);
// Helpers
boolean inSentence = false;
boolean hasAnnotation = false;
int count = 0;
StringBuilder sb = new StringBuilder();
String s;
// Read the XML document
while (eventReader.hasNext()) {
if (numSentences > MAX_SENTENCES) {
break;
}
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
if (startElement.getName().getLocalPart() == XML_SENTENCE) {
sb = new StringBuilder();
inSentence = true;
hasAnnotation = false;
count = 0;
}
if (startElement.getName().getLocalPart() == XML_ANNOTATION) {
hasAnnotation = true;
event = eventReader.nextEvent();
count++;
}
}
if (inSentence) {
if (event.isCharacters()) {
sb.append(event.asCharacters().getData());
}
}
if (event.isEndElement()) {
EndElement endElement = event.asEndElement();
if (endElement.getName().getLocalPart() == XML_SENTENCE) {
inSentence = false;
if (hasAnnotation && count >= 2) {
//if (!hasAnnotation) {
s = sb.toString().trim();
s = StringEscapeUtils.unescapeXml(s);
numSentences++;
// Customize tokenisation
//s = s.replaceAll("/", " / ");
//s = s.replaceAll("-", " - ");
//s = s.replaceAll("[.]", " . ");
//s = s.replaceAll("//s+", " ");
sentences.add(s);
}
}
}
}
}
public static void main(String[] args) {
try {
ArrayList<String> sentences = new ArrayList<String>();
numSentences = 0;
File inputDir = new File("/Users/david/Downloads/calbc/fixed/");
File[] files = inputDir.listFiles();
for (File f : files) {
System.out.println(f.getName());
readFile(f, sentences);
}
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream("resources/corpus/silver/2_100k.gz"));
//String[] tokens;
//Tokenizer tokenizer = new Tokenizer(false);
GDepParser parser = new GDepParser(true, false);
parser.launch();
List<Object> result;
String[] parts;
String token_parsing, token, lemma, pos, chunk;
//tokenizer.launch();
for (String sentence : sentences) {
//sentence = sentence.replaceAll("/", " / ");
//sentence = sentence.replaceAll("-", " - ");
//sentence = sentence.replaceAll("[.]", " . ");
//sentence = sentence.replaceAll("//s+", " ");
//tokens =<SUF>
result = parser.parse(sentence);
for (Object o:result){
token_parsing = (String) o;
parts = token_parsing.split("\t");
token = parts[1];
lemma = parts[2];
pos = parts[3];
chunk = parts[4];
out.write(token.getBytes());
out.write("\t".getBytes());
out.write("LEMMA=".getBytes());
out.write(lemma.getBytes());
out.write("\t".getBytes());
out.write("POS=".getBytes());
out.write(pos.getBytes());
out.write("\t".getBytes());
out.write("CHUNK=".getBytes());
out.write(chunk.getBytes());
out.write("\t".getBytes());
out.write("O".getBytes());
out.write("\n".getBytes());
}
/*for (String t : tokens) {
out.write(t.getBytes());
out.write("\t".getBytes());
out.write("O".getBytes());
out.write("\n".getBytes());
}*/
out.write("\n".getBytes());
}
out.close();
parser.terminate();
}
catch (Exception ex) {
ex.printStackTrace();
return;
}
}
}
| False | 1,148 | 7 | 1,301 | 9 | 1,424 | 9 | 1,301 | 9 | 1,619 | 13 | false | false | false | false | false | true |
4,825 | 172296_1 | package competition.practice.round1C2016;
import competition.utility.MyIn;
import competition.utility.MyOut;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.PriorityQueue;
/**
* Created by zzt on 5/8/16.
* <p>
* Usage:
*/
public class Senators {
public static void main(String[] args) {
MyIn in;
MyOut out = new MyOut("res");
try {
in = new MyIn("testCase/senator-large.in");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
int trail = in.nextInt();
in.nextLine();
String res;
for (int i = 0; i < trail; i++) {
in.nextLine();
res = eva(in.oneLineToInt(" "));
out.println("Case #" + (i + 1) + ": " + res);
}
}
static class Party implements Comparable<Party> {
final int num;
final char c;
public Party(int num, char c) {
this.num = num;
this.c = c;
}
@Override
public int compareTo(Party o) {
return -Integer.compare(num, o.num);
}
}
private static String eva(ArrayList<Integer> list) {
char c = 'A';
int sum = 0;
PriorityQueue<Party> parties = new PriorityQueue<>(list.size());
for (Integer integer : list) {
parties.add(new Party(integer, c++));
sum += integer;
}
StringBuilder res = new StringBuilder();
while (!parties.isEmpty()) {
final Party max = parties.poll();
Party sec;
if ((sec = parties.poll()) != null) {
res.append(sec.c);
if (sec.num > 1) {
parties.add(new Party(sec.num - 1, sec.c));
}
}
res.append(max.c).append(" ");
if (max.num > 1) {
parties.add(new Party(max.num - 1, max.c));
}
}
if (sum % 2 != 0) {// swap last two elements?
final String substring = res.substring(res.length() - 5);
final StringBuilder tmp = res.delete(res.length() - 5, res.length());
tmp.append(substring.substring(3)).append(substring.substring(0, 3));
res = tmp;
}
return res.toString();
}
}
| zzt93/Daily-pracitce | java/algo/src/main/java/competition/practice/round1C2016/Senators.java | 714 | // swap last two elements? | line_comment | nl | package competition.practice.round1C2016;
import competition.utility.MyIn;
import competition.utility.MyOut;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.PriorityQueue;
/**
* Created by zzt on 5/8/16.
* <p>
* Usage:
*/
public class Senators {
public static void main(String[] args) {
MyIn in;
MyOut out = new MyOut("res");
try {
in = new MyIn("testCase/senator-large.in");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
int trail = in.nextInt();
in.nextLine();
String res;
for (int i = 0; i < trail; i++) {
in.nextLine();
res = eva(in.oneLineToInt(" "));
out.println("Case #" + (i + 1) + ": " + res);
}
}
static class Party implements Comparable<Party> {
final int num;
final char c;
public Party(int num, char c) {
this.num = num;
this.c = c;
}
@Override
public int compareTo(Party o) {
return -Integer.compare(num, o.num);
}
}
private static String eva(ArrayList<Integer> list) {
char c = 'A';
int sum = 0;
PriorityQueue<Party> parties = new PriorityQueue<>(list.size());
for (Integer integer : list) {
parties.add(new Party(integer, c++));
sum += integer;
}
StringBuilder res = new StringBuilder();
while (!parties.isEmpty()) {
final Party max = parties.poll();
Party sec;
if ((sec = parties.poll()) != null) {
res.append(sec.c);
if (sec.num > 1) {
parties.add(new Party(sec.num - 1, sec.c));
}
}
res.append(max.c).append(" ");
if (max.num > 1) {
parties.add(new Party(max.num - 1, max.c));
}
}
if (sum % 2 != 0) {// swap last<SUF>
final String substring = res.substring(res.length() - 5);
final StringBuilder tmp = res.delete(res.length() - 5, res.length());
tmp.append(substring.substring(3)).append(substring.substring(0, 3));
res = tmp;
}
return res.toString();
}
}
| False | 524 | 6 | 609 | 6 | 660 | 6 | 609 | 6 | 708 | 6 | false | false | false | false | false | true |
2,655 | 151816_1 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package annotatieviewer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* de hoofdclass met opslag en verwerking van gegevens
* @author emilvanamerongen, (Tjeerd van der Veen)
*/
public class Data_opslag_en_verwerking {
/**
* hoofdopslag van de huidige DNA sequentie
*/
public static String sequence = "empty";
/**
* opslag van substrings van de huidige DNA sequentie
*/
public static HashMap<Integer, String> substrings = new HashMap<>();
/**
* opslag van de forward substrings van de huidige aminozuur sequentie
*/
public static HashMap<Integer, String> aminosubstrings = new HashMap<>();
/**
* opslag van de reverse substrings van de huidige aminozuur sequentie
*/
public static HashMap<Integer, String> aminosubstringsreverse = new HashMap<>();
/**
* opslag van annotatie in een arraylist met gene objecten (gekozen voor arraylist omdat hashmaps bugs veroorzaakte)
*/
public static List<Gene> genes = new ArrayList<Gene>();
/**
* hoofdopslag van de huidige aminozuur sequentie
*/
public static String AminoSequence;
/**
* oplag van de reverse aminozuur sequentie
*/
public static String AminoSequencereverse;
/**
* keuze tussen DNA sequentie weergave of aminozuursequentie weergave, opgeslagen als boolean
*/
public static Boolean dnaorprotein = false;
/**
*
* initiates the project
* @param args the command line arguments
*/
public static void main(String[] args) {
init();
}
/**
* initiates the GUI
*/
public static void init(){
new Annotation_viewer_GUI().setVisible(true);
}
/**
* sla een nieuwe sequentie op en verwerk deze naar verschillende type opslag objecten
* @param newsequence die nieuwe DNA sequentie
*/
public static void setsequence(String newsequence){
// filter alle nextline en spaties uit de DNA sequentie
sequence = newsequence.replace("\n", "").replace(" ", "").replace("\r","");
// maak substrings van de DNA sequentie
substrings = Sequencetools.createsubstrings(sequence);
// vertaal de sequentie naar aminozuren
AminoSequence = Sequencetools.TranslateSequence(sequence);
// vertaal de complementaire sequentie naar aminozuren
AminoSequencereverse = Sequencetools.TranslateSequence(Sequencetools.complement(sequence));
// maak substrings van de aminozuursequentie
aminosubstrings = Sequencetools.createsubstrings(AminoSequence);
// maak substrings van de complementaire aminozuursequentie
aminosubstringsreverse = Sequencetools.createsubstrings(AminoSequencereverse);
// visualiseer de nieuwe data
Annotation_viewer_GUI.visualise();
}
/**
* sla nieuwe annotatie gene objecten op in de Arraylist met genen
* @param newgenes nieuwe list met genen die opgeslagen moeten worden
*/
public static void setgenes(List<Gene> newgenes){
genes.addAll(newgenes);
// visualiseer de nieuwe data
Annotation_viewer_GUI.visualise();
}
}
| emilvanamerongen/annotatieviewer | src/annotatieviewer/Data_opslag_en_verwerking.java | 1,003 | /**
* de hoofdclass met opslag en verwerking van gegevens
* @author emilvanamerongen, (Tjeerd van der Veen)
*/ | block_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package annotatieviewer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* de hoofdclass met<SUF>*/
public class Data_opslag_en_verwerking {
/**
* hoofdopslag van de huidige DNA sequentie
*/
public static String sequence = "empty";
/**
* opslag van substrings van de huidige DNA sequentie
*/
public static HashMap<Integer, String> substrings = new HashMap<>();
/**
* opslag van de forward substrings van de huidige aminozuur sequentie
*/
public static HashMap<Integer, String> aminosubstrings = new HashMap<>();
/**
* opslag van de reverse substrings van de huidige aminozuur sequentie
*/
public static HashMap<Integer, String> aminosubstringsreverse = new HashMap<>();
/**
* opslag van annotatie in een arraylist met gene objecten (gekozen voor arraylist omdat hashmaps bugs veroorzaakte)
*/
public static List<Gene> genes = new ArrayList<Gene>();
/**
* hoofdopslag van de huidige aminozuur sequentie
*/
public static String AminoSequence;
/**
* oplag van de reverse aminozuur sequentie
*/
public static String AminoSequencereverse;
/**
* keuze tussen DNA sequentie weergave of aminozuursequentie weergave, opgeslagen als boolean
*/
public static Boolean dnaorprotein = false;
/**
*
* initiates the project
* @param args the command line arguments
*/
public static void main(String[] args) {
init();
}
/**
* initiates the GUI
*/
public static void init(){
new Annotation_viewer_GUI().setVisible(true);
}
/**
* sla een nieuwe sequentie op en verwerk deze naar verschillende type opslag objecten
* @param newsequence die nieuwe DNA sequentie
*/
public static void setsequence(String newsequence){
// filter alle nextline en spaties uit de DNA sequentie
sequence = newsequence.replace("\n", "").replace(" ", "").replace("\r","");
// maak substrings van de DNA sequentie
substrings = Sequencetools.createsubstrings(sequence);
// vertaal de sequentie naar aminozuren
AminoSequence = Sequencetools.TranslateSequence(sequence);
// vertaal de complementaire sequentie naar aminozuren
AminoSequencereverse = Sequencetools.TranslateSequence(Sequencetools.complement(sequence));
// maak substrings van de aminozuursequentie
aminosubstrings = Sequencetools.createsubstrings(AminoSequence);
// maak substrings van de complementaire aminozuursequentie
aminosubstringsreverse = Sequencetools.createsubstrings(AminoSequencereverse);
// visualiseer de nieuwe data
Annotation_viewer_GUI.visualise();
}
/**
* sla nieuwe annotatie gene objecten op in de Arraylist met genen
* @param newgenes nieuwe list met genen die opgeslagen moeten worden
*/
public static void setgenes(List<Gene> newgenes){
genes.addAll(newgenes);
// visualiseer de nieuwe data
Annotation_viewer_GUI.visualise();
}
}
| True | 851 | 39 | 902 | 39 | 867 | 34 | 902 | 39 | 1,003 | 40 | false | false | false | false | false | true |
4,169 | 781_12 | //jDownloader - Downloadmanager_x000D_
//Copyright (C) 2009 JD-Team [email protected]_x000D_
//_x000D_
//This program is free software: you can redistribute it and/or modify_x000D_
//it under the terms of the GNU General Public License as published by_x000D_
//the Free Software Foundation, either version 3 of the License, or_x000D_
//(at your option) any later version._x000D_
//_x000D_
//This program is distributed in the hope that it will be useful,_x000D_
//but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_
//GNU General Public License for more details._x000D_
//_x000D_
//You should have received a copy of the GNU General Public License_x000D_
//along with this program. If not, see <http://www.gnu.org/licenses/>._x000D_
package jd.plugins.decrypter;_x000D_
_x000D_
import java.util.ArrayList;_x000D_
import java.util.HashMap;_x000D_
_x000D_
import jd.PluginWrapper;_x000D_
import jd.controlling.ProgressController;_x000D_
import jd.plugins.CryptedLink;_x000D_
import jd.plugins.DecrypterPlugin;_x000D_
import jd.plugins.DownloadLink;_x000D_
import jd.plugins.PluginForDecrypt;_x000D_
_x000D_
@DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "deredactie.be", "sporza.be", "cobra.canvas.be" }, urls = { "https?://([a-z0-9]+\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "https?://(?:[a-z0-9]+\\.)?sporza\\.be/.*?/(?:mediatheek|videozone).+", "https?://cobra\\.canvas\\.be/.*?/(?:mediatheek|videozone).+" })_x000D_
public class DeredactieBe extends PluginForDecrypt {_x000D_
public DeredactieBe(PluginWrapper wrapper) {_x000D_
super(wrapper);_x000D_
}_x000D_
_x000D_
public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception {_x000D_
ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();_x000D_
String parameter = param.toString();_x000D_
this.setBrowserExclusive();_x000D_
br.setFollowRedirects(true);_x000D_
br.getPage(parameter);_x000D_
if (br.getHttpConnection().getResponseCode() == 404 || br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) {_x000D_
decryptedLinks.add(this.createOfflinelink(parameter));_x000D_
return decryptedLinks;_x000D_
}_x000D_
HashMap<String, String> mediaValue = new HashMap<String, String>();_x000D_
for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) {_x000D_
mediaValue.put(s[0], s[1]);_x000D_
}_x000D_
final String finalurl = (mediaValue == null || mediaValue.size() == 0) ? null : mediaValue.get("src");_x000D_
if (finalurl == null) {_x000D_
try {_x000D_
decryptedLinks.add(this.createOfflinelink(parameter));_x000D_
} catch (final Throwable t) {_x000D_
logger.info("Offline Link: " + parameter);_x000D_
}_x000D_
return decryptedLinks;_x000D_
}_x000D_
if (finalurl.contains("youtube.com")) {_x000D_
decryptedLinks.add(createDownloadlink(finalurl));_x000D_
} else {_x000D_
decryptedLinks.add(createDownloadlink(parameter.replace(".be/", "decrypted.be/")));_x000D_
}_x000D_
return decryptedLinks;_x000D_
}_x000D_
_x000D_
/* NO OVERRIDE!! */_x000D_
public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) {_x000D_
return false;_x000D_
}_x000D_
} | ribonuclecode/jd | src/jd/plugins/decrypter/DeredactieBe.java | 1,019 | //([a-z0-9]+\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "https?://(?:[a-z0-9]+\\.)?sporza\\.be/.*?/(?:mediatheek|videozone).+", "https?://cobra\\.canvas\\.be/.*?/(?:mediatheek|videozone).+" })_x000D_ | line_comment | nl | //jDownloader - Downloadmanager_x000D_
//Copyright (C) 2009 JD-Team [email protected]_x000D_
//_x000D_
//This program is free software: you can redistribute it and/or modify_x000D_
//it under the terms of the GNU General Public License as published by_x000D_
//the Free Software Foundation, either version 3 of the License, or_x000D_
//(at your option) any later version._x000D_
//_x000D_
//This program is distributed in the hope that it will be useful,_x000D_
//but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_
//GNU General Public License for more details._x000D_
//_x000D_
//You should have received a copy of the GNU General Public License_x000D_
//along with this program. If not, see <http://www.gnu.org/licenses/>._x000D_
package jd.plugins.decrypter;_x000D_
_x000D_
import java.util.ArrayList;_x000D_
import java.util.HashMap;_x000D_
_x000D_
import jd.PluginWrapper;_x000D_
import jd.controlling.ProgressController;_x000D_
import jd.plugins.CryptedLink;_x000D_
import jd.plugins.DecrypterPlugin;_x000D_
import jd.plugins.DownloadLink;_x000D_
import jd.plugins.PluginForDecrypt;_x000D_
_x000D_
@DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "deredactie.be", "sporza.be", "cobra.canvas.be" }, urls = { "https?://([a-z0-9]+\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "https?://(?:[a-z0-9]+\\.)?sporza\\.be/.*?/(?:mediatheek|videozone).+",<SUF>
public class DeredactieBe extends PluginForDecrypt {_x000D_
public DeredactieBe(PluginWrapper wrapper) {_x000D_
super(wrapper);_x000D_
}_x000D_
_x000D_
public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception {_x000D_
ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();_x000D_
String parameter = param.toString();_x000D_
this.setBrowserExclusive();_x000D_
br.setFollowRedirects(true);_x000D_
br.getPage(parameter);_x000D_
if (br.getHttpConnection().getResponseCode() == 404 || br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) {_x000D_
decryptedLinks.add(this.createOfflinelink(parameter));_x000D_
return decryptedLinks;_x000D_
}_x000D_
HashMap<String, String> mediaValue = new HashMap<String, String>();_x000D_
for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) {_x000D_
mediaValue.put(s[0], s[1]);_x000D_
}_x000D_
final String finalurl = (mediaValue == null || mediaValue.size() == 0) ? null : mediaValue.get("src");_x000D_
if (finalurl == null) {_x000D_
try {_x000D_
decryptedLinks.add(this.createOfflinelink(parameter));_x000D_
} catch (final Throwable t) {_x000D_
logger.info("Offline Link: " + parameter);_x000D_
}_x000D_
return decryptedLinks;_x000D_
}_x000D_
if (finalurl.contains("youtube.com")) {_x000D_
decryptedLinks.add(createDownloadlink(finalurl));_x000D_
} else {_x000D_
decryptedLinks.add(createDownloadlink(parameter.replace(".be/", "decrypted.be/")));_x000D_
}_x000D_
return decryptedLinks;_x000D_
}_x000D_
_x000D_
/* NO OVERRIDE!! */_x000D_
public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) {_x000D_
return false;_x000D_
}_x000D_
} | False | 1,204 | 121 | 1,306 | 122 | 1,335 | 125 | 1,306 | 122 | 1,485 | 148 | false | false | false | false | false | true |
739 | 6351_25 | package org.ivdnt.fcs.results;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* This class is used to store FCS keywords in context (kwic) as part of the
* ResultSet (which is part of a FcsSearchResultSet = main result object)
*
* @author jesse
*
*/
public class Kwic {
// A Kwic (keyword in context) is a list of words in which a match was found
// so it consists of [a left context], [a match], and [a right context]
//
// The tokens of those 3 parts are stored together in lists, each of which
// represents one property.
// So, for a given token at position X, we can retrieve the value of a given
// property
// by accessing the corresponding list at the same position X
//
// (t.i. we have one sorted list for each single property, so there are as many
// lists
// as properties)
//
// To be able to recognize each part, the Kwic object has
// hitStart and hitEnd, which indicate the borders of the [match part]
// = start and end position of a keyword, within its context
private int hitStart;
private int hitEnd;
// default property
private String defaultProperty = "word";
// the list contains the names of all the properties contained in our Kwic
// object
private List<String> tokenPropertyNames = new ArrayList<>();
// this maps a property name to a sorted list of token properties
// (sorted, as the list represents the tokens on the result string)
private Map<String, List<String>> tokenProperties = new ConcurrentHashMap<>();
// metadata
private Map<String, String> metadata = new ConcurrentHashMap<>(); // considering the size of opensonar metadata,
// probably better to introduce separate
// document objects
// private Document document = null;
// -----------------------------------------------------------------------------------
// add a new property name to all tokens
public void addTokenProperty(String propertyName) {
// register the property name
// and
// add the property to all tokens
if (!this.tokenPropertyNames.contains(propertyName)) {
this.addTokenPropertyName(propertyName);
List<String> propertyValues = new ArrayList<>(this.size());
for (int i = 0; i < this.size(); i++) {
propertyValues.add(null);
}
this.setTokenProperties(propertyName, propertyValues);
}
}
// -----------------------------------------------------------------------------------
// getters
public void addTokenPropertyName(String pname) {
this.tokenPropertyNames.add(pname);
}
public void addTokenPropertyNames(Set<String> pnames) {
this.tokenPropertyNames.addAll(pnames);
}
public String get(String pname, int i) {
return getLayer(pname).get(i);
}
public String getDefaultProperty() {
return this.defaultProperty;
}
public int getHitEnd() {
return this.hitEnd;
}
public int getHitStart() {
return this.hitStart;
}
public List<String> getLayer(String propertyName) {
return this.tokenProperties.get(propertyName);
}
public URI getLayerURL(String pname) {
try {
return new URI("http://www.ivdnt.org/annotation-layers/" + pname);
} catch (Exception e) {
throw new NullPointerException("Unable to get layer URL for " + pname + ". " + e);
}
}
public Map<String, String> getMetadata() {
return this.metadata;
}
// synonym of getLayer
public List<String> getPropertyValues(String propertyName) {
return getLayer(propertyName);
}
public List<String> getTokenPropertyNames() {
return this.tokenPropertyNames;
}
public String getWord(int i) {
return this.tokenProperties.get(defaultProperty).get(i);
}
// -----------------------------------------------------------------------------------
// setters
public void setHitEnd(int hitEnd) {
this.hitEnd = hitEnd;
}
public void setHitStart(int hitStart) {
this.hitStart = hitStart;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
// set one property for all tokens at once
// eg. the pos-tag of all tokens of a sentence
public void setTokenProperties(String pname, List<String> properties) {
this.tokenProperties.put(pname, properties);
}
// modify the value of a property for token at position X
public void setTokenPropertyAt(String propertyName, String property, int index) {
List<String> propertyValues = this.getLayer(propertyName);
if (propertyValues.size() == 0)
propertyValues = new ArrayList<>(this.getTokenPropertyNames().size());
propertyValues.set(index, property);
this.setTokenProperties(propertyName, propertyValues);
}
public int size() {
return words().size();
}
public String toString() {
List<String> tokens = new ArrayList<String>();
List<String> words = words();
for (int i = 0; i < words.size(); i++) {
String p = (this.hitStart <= i && i <= this.hitEnd) ? ">>" : "";
tokens.add(p + words.get(i));
}
String s = String.format("Kwic(%d,%d):", this.hitStart, this.hitEnd);
return s + tokens.toString();
}
public Kwic translatePrefixes(Map<String, String> map) {
map.forEach((k, v) -> {
this.tokenProperties.put(v, this.tokenProperties.get(k));
this.tokenProperties.remove(k);
});
this.tokenPropertyNames = this.tokenPropertyNames.stream().map(p -> map.containsKey(p) ? map.get(p) : p)
.collect(Collectors.toList());
return this;
}
// -----------------------------------------------------------------------------------
public List<String> words() {
return this.tokenProperties.get(defaultProperty);
}
// -----------------------------------------------------------------------------------
}
/**
* Wat gaan we met metadata doen? In een CMDI profiel stoppen? Hoe halen we dat
* op bij nederlab? Voor blacklab server zelf maken uit de aanwezige metadata.
* https://www.clarin.eu/sites/default/files/CE-2014-0317-CLARIN_FCS_Specification_DataViews_1_0.pdf:
*
* <!-- potential @pid and @ref attributes omitted -->
* <fcs:DataView type="application/x-cmdi+xml">
* <cmdi:CMD xmlns:cmdi="http://www.clarin.eu/cmd/" CMDVersion="1.1"> <!--
* content omitted --> </cmdi:CMD> </fcs:DataView> <!-- potential @pid attribute
* omitted --> <fcs:DataView type="application/x-cmdi+xml" ref=
* "http://repos.example.org/resources/4711/0815.cmdi" />
*/
| INL/clariah-fcs-endpoints | src/main/java/org/ivdnt/fcs/results/Kwic.java | 1,899 | /**
* Wat gaan we met metadata doen? In een CMDI profiel stoppen? Hoe halen we dat
* op bij nederlab? Voor blacklab server zelf maken uit de aanwezige metadata.
* https://www.clarin.eu/sites/default/files/CE-2014-0317-CLARIN_FCS_Specification_DataViews_1_0.pdf:
*
* <!-- potential @pid and @ref attributes omitted -->
* <fcs:DataView type="application/x-cmdi+xml">
* <cmdi:CMD xmlns:cmdi="http://www.clarin.eu/cmd/" CMDVersion="1.1"> <!--
* content omitted --> </cmdi:CMD> </fcs:DataView> <!-- potential @pid attribute
* omitted --> <fcs:DataView type="application/x-cmdi+xml" ref=
* "http://repos.example.org/resources/4711/0815.cmdi" />
*/ | block_comment | nl | package org.ivdnt.fcs.results;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* This class is used to store FCS keywords in context (kwic) as part of the
* ResultSet (which is part of a FcsSearchResultSet = main result object)
*
* @author jesse
*
*/
public class Kwic {
// A Kwic (keyword in context) is a list of words in which a match was found
// so it consists of [a left context], [a match], and [a right context]
//
// The tokens of those 3 parts are stored together in lists, each of which
// represents one property.
// So, for a given token at position X, we can retrieve the value of a given
// property
// by accessing the corresponding list at the same position X
//
// (t.i. we have one sorted list for each single property, so there are as many
// lists
// as properties)
//
// To be able to recognize each part, the Kwic object has
// hitStart and hitEnd, which indicate the borders of the [match part]
// = start and end position of a keyword, within its context
private int hitStart;
private int hitEnd;
// default property
private String defaultProperty = "word";
// the list contains the names of all the properties contained in our Kwic
// object
private List<String> tokenPropertyNames = new ArrayList<>();
// this maps a property name to a sorted list of token properties
// (sorted, as the list represents the tokens on the result string)
private Map<String, List<String>> tokenProperties = new ConcurrentHashMap<>();
// metadata
private Map<String, String> metadata = new ConcurrentHashMap<>(); // considering the size of opensonar metadata,
// probably better to introduce separate
// document objects
// private Document document = null;
// -----------------------------------------------------------------------------------
// add a new property name to all tokens
public void addTokenProperty(String propertyName) {
// register the property name
// and
// add the property to all tokens
if (!this.tokenPropertyNames.contains(propertyName)) {
this.addTokenPropertyName(propertyName);
List<String> propertyValues = new ArrayList<>(this.size());
for (int i = 0; i < this.size(); i++) {
propertyValues.add(null);
}
this.setTokenProperties(propertyName, propertyValues);
}
}
// -----------------------------------------------------------------------------------
// getters
public void addTokenPropertyName(String pname) {
this.tokenPropertyNames.add(pname);
}
public void addTokenPropertyNames(Set<String> pnames) {
this.tokenPropertyNames.addAll(pnames);
}
public String get(String pname, int i) {
return getLayer(pname).get(i);
}
public String getDefaultProperty() {
return this.defaultProperty;
}
public int getHitEnd() {
return this.hitEnd;
}
public int getHitStart() {
return this.hitStart;
}
public List<String> getLayer(String propertyName) {
return this.tokenProperties.get(propertyName);
}
public URI getLayerURL(String pname) {
try {
return new URI("http://www.ivdnt.org/annotation-layers/" + pname);
} catch (Exception e) {
throw new NullPointerException("Unable to get layer URL for " + pname + ". " + e);
}
}
public Map<String, String> getMetadata() {
return this.metadata;
}
// synonym of getLayer
public List<String> getPropertyValues(String propertyName) {
return getLayer(propertyName);
}
public List<String> getTokenPropertyNames() {
return this.tokenPropertyNames;
}
public String getWord(int i) {
return this.tokenProperties.get(defaultProperty).get(i);
}
// -----------------------------------------------------------------------------------
// setters
public void setHitEnd(int hitEnd) {
this.hitEnd = hitEnd;
}
public void setHitStart(int hitStart) {
this.hitStart = hitStart;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
// set one property for all tokens at once
// eg. the pos-tag of all tokens of a sentence
public void setTokenProperties(String pname, List<String> properties) {
this.tokenProperties.put(pname, properties);
}
// modify the value of a property for token at position X
public void setTokenPropertyAt(String propertyName, String property, int index) {
List<String> propertyValues = this.getLayer(propertyName);
if (propertyValues.size() == 0)
propertyValues = new ArrayList<>(this.getTokenPropertyNames().size());
propertyValues.set(index, property);
this.setTokenProperties(propertyName, propertyValues);
}
public int size() {
return words().size();
}
public String toString() {
List<String> tokens = new ArrayList<String>();
List<String> words = words();
for (int i = 0; i < words.size(); i++) {
String p = (this.hitStart <= i && i <= this.hitEnd) ? ">>" : "";
tokens.add(p + words.get(i));
}
String s = String.format("Kwic(%d,%d):", this.hitStart, this.hitEnd);
return s + tokens.toString();
}
public Kwic translatePrefixes(Map<String, String> map) {
map.forEach((k, v) -> {
this.tokenProperties.put(v, this.tokenProperties.get(k));
this.tokenProperties.remove(k);
});
this.tokenPropertyNames = this.tokenPropertyNames.stream().map(p -> map.containsKey(p) ? map.get(p) : p)
.collect(Collectors.toList());
return this;
}
// -----------------------------------------------------------------------------------
public List<String> words() {
return this.tokenProperties.get(defaultProperty);
}
// -----------------------------------------------------------------------------------
}
/**
* Wat gaan we<SUF>*/
| True | 1,492 | 205 | 1,808 | 240 | 1,811 | 224 | 1,808 | 240 | 2,040 | 243 | false | true | true | true | true | false |