repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
tmm-ms/DS503 | homework/01/_01/src/main/java/ds503/Job2.java | 3478 | package ds503;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Job2 {
public static class TransactionMapper extends Mapper<Object, Text, Text, Text>{
private final static Text customerId = new Text();
private Text transaction = new Text();
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String transactionString = value.toString();
String[] transactionData = transactionString.split(",");
customerId.set(transactionData[1]);
transaction.set(value);
context.write(customerId, transaction);
}
}
public static class TransactionReducer extends Reducer<Text, Text, Text, Text> {
private class CustomerItem {
String customerId;
int numTransactions;
float totalSum;
CustomerItem(String customerId, int numTransactions, float totalSum) {
this.customerId = customerId;
this.numTransactions = numTransactions;
this.totalSum = totalSum;
}
}
private List<CustomerItem> customers = new ArrayList<CustomerItem>();
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
Iterator<Text> iter = values.iterator();
int numTransactions = 0;
float totalSum = 0;
while (iter.hasNext()) {
String transactionString = iter.next().toString();
String[] transactionData = transactionString.split(",");
numTransactions += 1;
float sum = Float.parseFloat(transactionData[2]);
totalSum += sum;
}
CustomerItem customerItem = new CustomerItem(key.toString(), numTransactions, totalSum);
customers.add(customerItem);
}
protected void cleanup(Context context) throws IOException, InterruptedException {
for (CustomerItem customerItem : customers) {
Text keyOut = new Text(customerItem.customerId);
String joinString = String.format(",%s,%s", customerItem.numTransactions, customerItem.totalSum);
Text valueOut = new Text(joinString);
context.write(keyOut, valueOut);
}
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "job 2");
job.setJarByClass(Job2.class);
job.setMapperClass(TransactionMapper.class);
job.setCombinerClass(TransactionReducer.class);
job.setReducerClass(TransactionReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemover/azure-resourcemanager-resourcemover/src/main/java/com/azure/resourcemanager/resourcemover/models/UnresolvedDependencyCollection.java | 3382 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.resourcemover.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.resourcemover.fluent.models.UnresolvedDependencyInner;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** Unresolved dependency collection. */
@Fluent
public final class UnresolvedDependencyCollection {
@JsonIgnore private final ClientLogger logger = new ClientLogger(UnresolvedDependencyCollection.class);
/*
* Gets or sets the list of unresolved dependencies.
*/
@JsonProperty(value = "value")
private List<UnresolvedDependencyInner> value;
/*
* Gets or sets the value of next link.
*/
@JsonProperty(value = "nextLink")
private String nextLink;
/*
* Gets or sets the list of summary items and the field on which summary is
* done.
*/
@JsonProperty(value = "summaryCollection", access = JsonProperty.Access.WRITE_ONLY)
private SummaryCollection summaryCollection;
/*
* Gets the total count.
*/
@JsonProperty(value = "totalCount", access = JsonProperty.Access.WRITE_ONLY)
private Long totalCount;
/**
* Get the value property: Gets or sets the list of unresolved dependencies.
*
* @return the value value.
*/
public List<UnresolvedDependencyInner> value() {
return this.value;
}
/**
* Set the value property: Gets or sets the list of unresolved dependencies.
*
* @param value the value value to set.
* @return the UnresolvedDependencyCollection object itself.
*/
public UnresolvedDependencyCollection withValue(List<UnresolvedDependencyInner> value) {
this.value = value;
return this;
}
/**
* Get the nextLink property: Gets or sets the value of next link.
*
* @return the nextLink value.
*/
public String nextLink() {
return this.nextLink;
}
/**
* Set the nextLink property: Gets or sets the value of next link.
*
* @param nextLink the nextLink value to set.
* @return the UnresolvedDependencyCollection object itself.
*/
public UnresolvedDependencyCollection withNextLink(String nextLink) {
this.nextLink = nextLink;
return this;
}
/**
* Get the summaryCollection property: Gets or sets the list of summary items and the field on which summary is
* done.
*
* @return the summaryCollection value.
*/
public SummaryCollection summaryCollection() {
return this.summaryCollection;
}
/**
* Get the totalCount property: Gets the total count.
*
* @return the totalCount value.
*/
public Long totalCount() {
return this.totalCount;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (value() != null) {
value().forEach(e -> e.validate());
}
if (summaryCollection() != null) {
summaryCollection().validate();
}
}
}
| mit |
Azure/azure-sdk-for-java | sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationUpdateSamples.java | 1610 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.applicationinsights.generated;
import com.azure.core.util.Context;
import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccounts;
import com.azure.resourcemanager.applicationinsights.models.StorageType;
/** Samples for ComponentLinkedStorageAccountsOperation Update. */
public final class ComponentLinkedStorageAccountsOperationUpdateSamples {
/*
* x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2020-03-01-preview/examples/ComponentLinkedStorageAccountsUpdate.json
*/
/**
* Sample code: ComponentLinkedStorageAccountsUpdate.
*
* @param manager Entry point to ApplicationInsightsManager.
*/
public static void componentLinkedStorageAccountsUpdate(
com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) {
ComponentLinkedStorageAccounts resource =
manager
.componentLinkedStorageAccountsOperations()
.getWithResponse("someResourceGroupName", "myComponent", StorageType.SERVICE_PROFILER, Context.NONE)
.getValue();
resource
.update()
.withLinkedStorageAccount(
"/subscriptions/86dc51d3-92ed-4d7e-947a-775ea79b4918/resourceGroups/someResourceGroupName/providers/Microsoft.Storage/storageAccounts/storageaccountname")
.apply();
}
}
| mit |
nunows/agenda-cultural | AC_Android/src/moss/idsca/ac/eventos/EventosDetail.java | 1446 | package moss.idsca.ac.eventos;
import ws.Evento;
import moss.idsca.ac.App;
import moss.idsca.ac.R;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;
public class EventosDetail extends Activity {
private App app;
private Evento evento;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (App) getApplication();
setContentView(R.layout.evento_detail);
WebView webview = (WebView) findViewById(R.id.webView1);
TextView txtNome = (TextView) findViewById(R.id.txtNome);
TextView txtData = (TextView) findViewById(R.id.txtData);
TextView txtLocalNome = (TextView) findViewById(R.id.txtLocalNome);
TextView txtLocalMorada = (TextView) findViewById(R.id.txtLocalMorada);
evento = app.getEvento();
txtNome.setText(evento.getNome());
txtData.setText(evento.getDatahora());
txtLocalNome.setText(evento.getLocal().getNome());
txtLocalMorada.setText(evento.getLocal().getMorada());
webview.loadUrl(evento.getImagemUrl());
}
public void showMap(View view) {
String url = "http://maps.google.com/maps?q="
+ evento.getLocal().getLatitude() + ","
+ evento.getLocal().getLongitude()+"&t=m&z=16&vpsrc=0";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}
| mit |
TongqiLiu/leetcode | Algorithms/Java/src/ArrayTransformation/ArrayTransformation.java | 936 | package src.ArrayTransformation;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author mingqiao
* @Date 2020/3/2
*/
public class ArrayTransformation {
/**
* 模拟一下
*
* @param arr
* @return
*/
public List<Integer> transformArray(int[] arr) {
int n = arr.length;
boolean flag;
do {
flag = false;
int tmp[] = Arrays.copyOf(arr, n);
for (int i = 1; i < n - 1; i++) {
if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) {
tmp[i]++;
flag = true;
} else if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
tmp[i]--;
flag = true;
}
}
arr = tmp;
} while (flag);
return Arrays.stream(arr).boxed().collect(Collectors.toList());
}
}
| mit |
billhj/Etoile-java | Util/src/vib/core/util/audio/AudioPerformer.java | 343 | /*
* This file is part of VIB (Virtual Interactive Behaviour).
*/
package vib.core.util.audio;
import vib.core.util.Mode;
import vib.core.util.id.ID;
import java.util.List;
/**
*
* @author Andre-Marie Pez
*/
public interface AudioPerformer {
public void performAudios(List<Audio> audios, ID requestId, Mode mode);
}
| mit |
bg1bgst333/Sample | android/WebView/setWebChromeClient/src/WebView/WebView_/gen/com/bgstation0/android/sample/webview_/R.java | 2071 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.bgstation0.android.sample.webview_;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int loadbutton=0x7f060001;
public static final int progresstextview=0x7f060002;
public static final int urlbar=0x7f060000;
public static final int webview=0x7f060003;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int hello_world=0x7f040001;
public static final int loadbutton_text=0x7f040002;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f050000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f050001;
}
}
| mit |
ByeongGi/Koata_Java | Java0827/src/ex1/Ex2_HasaOrder.java | 519 | package ex1;
// @author kosta, 2015. 8. 27 , 오전 9:14:58 , Ex2_HasaOrder
public class Ex2_HasaOrder {
private Ex2_HasaTarget ht;
// Targer 객체의 주소값을 멤버 필드로 선언.
public Ex2_HasaOrder() {
// 현재 객체가 생성될때 Targer객체를 생성해서
// 초기화 한다.
ht = new Ex2_HasaTarget(this); // Has a 관계
}
public Ex2_HasaTarget getHt() {
return ht;
}
public String orderMetheod(){
return "Order";
}
}
| mit |
iObsidian/ProjectRR | src/realmrelay/packets/client/BuyPacket.java | 441 | package realmrelay.packets.client;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import realmrelay.packets.Packet;
public class BuyPacket extends Packet {
public int objectId;
@Override
public void parseFromInput(DataInput in) throws IOException {
this.objectId = in.readInt();
}
@Override
public void writeToOutput(DataOutput out) throws IOException {
out.writeInt(this.objectId);
}
}
| mit |
don82berlin/socketeer | src/main/java/de/logicalco/socketeer/server/CommandHandler.java | 1127 | package de.logicalco.socketeer.server;
import com.google.common.base.Optional;
/**
* Interface for the handler that evaluates the commands and optionally sends back content.
* <b>Note</b> : A command handler is shared by all sessions therefore it has to be thread-safe.
*/
public interface CommandHandler {
/**
* This is the opening pharse sent by the server when a session is started.
* Optinal#absent should be returned for no opening phrase.
*
* @return Opening phrase or Optional#absent
*/
Optional<byte[]> getOpener();
/**
* Return the application's name.
*
* @return The application's name.
*/
byte[] getAppName();
/**
* Handle the command and optinally send back a response.
*
* @param command Command to handle.
* @return Response to send back to the client.
*/
Optional<byte[]> handle(byte[] command);
/**
* The escape sequence is a string that destroys the current session on server side (and the connection too).
*
* @return Escape sequence.
*/
byte[] getEscapeSeq();
}
| mit |
lmarinov/Exercise-repo | Java_study_materials/JavaOOP_2021/EXAM_PREPARATION_I/BlueOrigin/src/main/java/blueOrigin/Spaceship.java | 2193 | package blueOrigin;
import java.util.ArrayList;
import java.util.Collection;
public class Spaceship {
private static final String INVALID_SPACESHIP_NAME = "Invalid spaceship name!";
private static final String INVALID_CAPACITY = "Invalid capacity!";
private static final String SPACESHIP_FULL = "Spaceship is full!";
private static final String ASTRONAUT_EXIST = "Astronaut %s is already in!";
private static final int ZERO_CAPACITY = 0;
private int capacity;
private String name;
private Collection<Astronaut> astronauts;
public Spaceship(String name, int capacity) {
this.setName(name);
this.setCapacity(capacity);
this.astronauts = new ArrayList<>();
}
public int getCount() {
return this.astronauts.size();
}
public String getName() {
return this.name;
}
public int getCapacity() {
return this.capacity;
}
public void add(Astronaut astronaut) {
if (astronauts.size() == this.getCapacity()) {
throw new IllegalArgumentException(SPACESHIP_FULL);
}
boolean astronautExists = this.astronauts
.stream()
.anyMatch(a -> a.getName().equals(astronaut.getName()));
if (astronautExists) {
throw new IllegalArgumentException(String.format(ASTRONAUT_EXIST, astronaut.getName()));
}
this.astronauts.add(astronaut);
}
public boolean remove(String astronautName) {
Astronaut astronaut = this.astronauts
.stream()
.filter(a -> a.getName().equals(astronautName))
.findFirst()
.orElse(null);
boolean isRemove = this.astronauts.remove(astronaut);
return isRemove;
}
private void setCapacity(int capacity) {
if (capacity < ZERO_CAPACITY) {
throw new IllegalArgumentException(INVALID_CAPACITY);
}
this.capacity = capacity;
}
private void setName(String name) {
if (name == null || name.trim().isEmpty()) {
throw new NullPointerException(INVALID_SPACESHIP_NAME);
}
this.name = name;
}
}
| mit |
SH4DY/swazam | Swazam Android Client/src/at/saws2013/szazam/RecognitionActivity.java | 11169 | package at.saws2013.szazam;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import ac.at.tuwien.infosys.swa.audio.Fingerprint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
import at.saws2013.szazam.entities.Request;
import at.saws2013.szazam.fingerprint.IFingerPrintSystem;
import at.saws2013.szazam.fingerprint.impl.FingerPrintCreator;
import at.saws2013.szazam.media.IAudioFilePicker;
import at.saws2013.szazam.media.IAudioRecorder;
import at.saws2013.szazam.media.impl.AudioFilePicker;
import at.saws2013.szazam.media.impl.AudioRecorder;
import at.saws2013.szazam.store.IAuthStore;
import at.saws2013.szazam.store.impl.AuthStore;
import at.saws2013.szazam.store.impl.RequestStore;
import at.saws2013.szazam.ui.ViewTools;
import at.saws2013.szazam.volley.CustomVolleyStringRequest;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
import de.passsy.holocircularprogressbar.HoloCircularProgressBar;
/**
* RecognitionActivity is the application's main Activity.
* It will be launched when the app starts and allows to create
* a fingerprint by either record some sound using the phone's
* microphone of by picking a audio on the phone.
*
* @author René
*
*/
public class RecognitionActivity extends Activity {
private static final float RECORD_DURATION = 20000;
private static final float MAX_PROGRESS = 1000;
private static final String LOG_TAG = "Swazam";
private static String mFileName;
private HoloCircularProgressBar progress;
private ProgressBar progress_loading;
private ImageButton imgbtn_pick_file, imgbtn_record;
private Fingerprint fingerprint;
private AudioSampleWorker fingerprintWorkerTask;
private IAuthStore authStore;
private CustomVolleyStringRequest recognitionRequest;
private IAudioFilePicker mAudioFilePicker;
private IAudioRecorder mAudioRecorder;
private boolean filepick;
private App app;
private CountDownTimer timer;
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("filepick", filepick);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
filepick = savedInstanceState.getBoolean("filepick");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recognition);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
app = (App) getApplication();
authStore = AuthStore.getInstance(getApplicationContext());
initHelpers();
initViews();
initTimer();
}
@Override
protected void onResume() {
super.onResume();
// Start the login procedure if there is no token
if (authStore.getToken() == null){
login();
}
}
/**
* Start the LoginActivity by intent
*/
private void login(){
Intent i = new Intent(RecognitionActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i;
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.menu_requests:
getRequestHistory();
return true;
case R.id.action_settings:
i = new Intent(RecognitionActivity.this, SettingsActivity.class);
startActivity(i);
return true;
case R.id.menu_transactions:
getTransactionHistory();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Start the HisoryActivity and put TRANSACTIONS
* as intent extra
*/
private void getTransactionHistory() {
Intent i = new Intent(RecognitionActivity.this, HistoryActivity.class);
i.putExtra(HistoryActivity.HISTORY_TYPE, HistoryActivity.TRANSACTIONS);
startActivity(i);
}
/**
* Start the HisoryActivity and put REQUESTS
* as intent extra
*/
private void getRequestHistory() {
Intent i = new Intent(RecognitionActivity.this, HistoryActivity.class);
i.putExtra(HistoryActivity.HISTORY_TYPE, HistoryActivity.REQUESTS);
startActivity(i);
}
/**
* Initialize all needed components
*/
private void initHelpers(){
mFileName = getDefaultTrackLocation();
mAudioFilePicker = new AudioFilePicker(RecognitionActivity.this);
mAudioRecorder = new AudioRecorder(RecognitionActivity.this);
}
private String getDefaultTrackLocation(){
return getFilesDir() + File.separator + "audiotrack.3gp";
}
/**
* Start the file-pick procedure to select an audio file from
* disc
*
* @param v Button defined in activity_recognition layout
*/
public void pickAudioFile(View v) {
filepick = true;
mAudioFilePicker.startPickIntent(RecognitionActivity.this);
}
@Override
public void onPause() {
super.onPause();
mAudioRecorder.release();
if (fingerprintWorkerTask != null) {
fingerprintWorkerTask.cancel(true);
}
// Cancel all running volley requests in order to not block the network
app.getVolleyQueue().cancelAll(RecognitionActivity.class.getName());
if (timer != null) {
timer.cancel();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
/*
* if a previous audio-pick intent has been started create a
* fingerprint using the received data
*/
case AudioFilePicker.AUDIO_FILE_PICKER_REQUEST:
if (resultCode == Activity.RESULT_OK) {
if (null != mAudioFilePicker) {
createFingerPrint(mAudioFilePicker.getAudioTrackPath(data));
}
}
break;
}
}
private void createFingerPrint(String path) {
if (null != path) {
fingerprintWorkerTask = new AudioSampleWorker(path);
fingerprintWorkerTask
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
/**
* Instantiate all views
*/
private void initViews() {
progress = (HoloCircularProgressBar) findViewById(R.id.progress);
progress.setMarkerEnabled(false);
progress.setProgress(0f);
progress_loading = (ProgressBar) findViewById(R.id.progress_loading);
imgbtn_pick_file = (ImageButton) findViewById(R.id.imgbtn_pick_file);
imgbtn_record = (ImageButton) findViewById(R.id.imgbtn_record);
}
/**
* Initialize a timer which will stop the audio-recording
* if the record_duration has terminated
*/
private void initTimer() {
timer = new CountDownTimer((long) RECORD_DURATION, 25) {
public void onTick(long millisUntilFinished) {
progress.setProgress(((RECORD_DURATION - millisUntilFinished) * 10000)
/ (RECORD_DURATION * MAX_PROGRESS) / 10.2f + 0.025f);
}
public void onFinish() {
stopRecording();
createFingerPrint(mFileName);
}
};
}
/**
* Method which will be called by the record button
*
* @param v Button which is defined in activity_recognition layout
*/
public void recordSample(View v) {
Log.d(LOG_TAG, "start recording");
timer.start();
ViewTools.disableViews(imgbtn_pick_file, imgbtn_record);
mAudioRecorder.startRecording(mFileName);
}
private void stopRecording() {
ViewTools.enableViews(imgbtn_pick_file, imgbtn_record);
mAudioRecorder.stopRecording();
}
/**
* Worker-task which creates a fingerprint off the UI task
* due to Android design-guidelines this has to be an inner class
*
* @author René
*
*/
private class AudioSampleWorker extends AsyncTask<Void, Float, Integer> {
private String fileName;
private IFingerPrintSystem fingerprintCreator;
public AudioSampleWorker(String fileName) {
this.fileName = fileName;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progress_loading.setVisibility(View.VISIBLE);
fingerprintCreator = new FingerPrintCreator(RecognitionActivity.this);
ViewTools.disableViews(imgbtn_pick_file, imgbtn_record);
}
@Override
protected Integer doInBackground(Void... params) {
fingerprint = fingerprintCreator.createFingerprintFromFilePath(fileName);
return 1;
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (null != fingerprint){
Crouton.makeText(RecognitionActivity.this, getString(R.string.fingerprint_created), Style.INFO).show();
} else {
Crouton.makeText(RecognitionActivity.this, getString(R.string.error_creating_fingerprint), Style.ALERT).show();
}
progress_loading.setVisibility(View.GONE);
ViewTools.enableViews(imgbtn_pick_file, imgbtn_record);
filepick = false;
makeRecognitionRequest(fingerprint);
}
}
/**
* Send a recognition-request to the server using a custom volley
* request
*
* On a successful request, store the request on disk using the
* RequestStore
*
* Notify the user if the request was not successful
*
* @param fingerprint2
*/
public void makeRecognitionRequest(Fingerprint fingerprint2) {
final Gson gson = new Gson();
//Long id = System.currentTimeMillis();
//Request request = new Request(id, fingerprint2.toString(), "null", DateUtils.formatDateTime(getApplicationContext(), id, (DateUtils.FORMAT_24HOUR | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE)));
Map<String, String> params = new HashMap<String, String>();
params.put("token", AuthStore.getInstance(getApplicationContext()).getToken());
params.put("fingerprint", fingerprint2.toString());
recognitionRequest = new CustomVolleyStringRequest(Method.POST, app.getHostFromSettings() + "/request",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
RequestStore.getInstance(getApplicationContext()).storeRequest(gson.fromJson(response.toString(), Request.class));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error sending request to server", Toast.LENGTH_SHORT).show();
}
}, params);
recognitionRequest.setTag(RecognitionActivity.class.getName());
app.getVolleyQueue().add(recognitionRequest);
}
}
| mit |
greenlover1991/rms | src/rms/models/management/MenuCategoryDBTable.java | 2343 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package rms.models.management;
import rms.models.DBTable;
/**
*
* @author Mark Taveros
*/
public class MenuCategoryDBTable extends DBTable{
public static final String TABLE_NAME = "menu_categories";
public static final String ID = "id";
public static final String NAME = "name";
public static final String DESCRIPTION = "description";
public static final String STATUS = "status";
public static final String ALIAS_ID = "ID";
public static final String ALIAS_NAME = "Menu Category";
public static final String ALIAS_DESCRIPTION = "Description";
public static final String ALIAS_STATUS = "Status";
private static final String[] columns = {NAME,ID, DESCRIPTION, STATUS};
private static final String[] columnsAliases = {ALIAS_NAME, ALIAS_ID, ALIAS_DESCRIPTION, ALIAS_STATUS};
private static final String[] primaryColumns = {ID};
private static final String[] uniqueColumns = {ID};
private static final String[] invisibleColumns = {ALIAS_ID, ALIAS_STATUS};
private static final String[] uneditableColumns = {ID, STATUS};
private static final String[] nonNullableColumns = {NAME, STATUS};
private static MenuCategoryDBTable INSTANCE;
private MenuCategoryDBTable(){}
public static MenuCategoryDBTable getInstance(){
if(INSTANCE == null)
INSTANCE = new MenuCategoryDBTable();
return INSTANCE;
}
@Override
public String getTableName() {
return TABLE_NAME;
}
@Override
public String[] getColumns() {
return columns;
}
@Override
public String[] getPrimaryColumns() {
return primaryColumns;
}
@Override
public String[] getUniqueColumns() {
return uniqueColumns;
}
@Override
public String[] getColumnsDefaultAliases() {
return columnsAliases;
}
@Override
public String[] getInvisibleColumns() {
return invisibleColumns;
}
@Override
public String[] getNonNullableColumns() {
return nonNullableColumns;
}
@Override
public String[] getUneditableColumns() {
return uneditableColumns;
}
} | mit |
Innovimax-SARL/mix-them | src/main/java/innovimax/mixthem/io/IToken.java | 1044 | package innovimax.mixthem.io;
import java.io.InputStream;
import java.io.Reader;
/**
* This interface provides for any token representation.
* @author Innovimax
* @version 1.0
*/
public interface IToken {
/**
* Indicates if token is empty.
* @return True if token is empty
*/
boolean isEmpty();
/**
* Returns the token value as a byte.
* @return The byte value
*/
byte asByte();
/**
* Returns the token value as a character.
* @return The character value
*/
int asCharacter();
/**
* Returns the token value as a byte array.
* @return The byte array
*/
byte[] asByteArray();
/**
* Returns the token value as a character array.
* @return The character array
*/
char[] asCharacterArray();
/**
* Returns the token value as a string.
* @return The string value
*/
String asString();
/**
* Returns the parameter value as a file input stream.
* @return The file input stream
*/
InputStream asInputStream();
/**
* Returns the parameter value as a file reader.
* @return The file reader
*/
Reader asReader();
}
| mit |
ExtraCells/ExtraCells1 | src/main/java/extracells/handler/FluidBusInventoryHandler.java | 11087 | package extracells.handler;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import appeng.api.IAEItemStack;
import appeng.api.IItemList;
import appeng.api.Util;
import appeng.api.config.FuzzyMode;
import appeng.api.config.ItemFlow;
import appeng.api.config.ListMode;
import appeng.api.me.util.IGridInterface;
import appeng.api.me.util.IMEInventoryHandler;
import extracells.ItemEnum;
public class FluidBusInventoryHandler implements IMEInventoryHandler
{
public IFluidHandler tank;
ForgeDirection facing;
public int priority;
List<ItemStack> filter;
public TileEntity updateTarget;
public IGridInterface grid;
public IMEInventoryHandler parent;
public FluidBusInventoryHandler(IFluidHandler tank, ForgeDirection facing, int priority, List<ItemStack> filter)
{
this.tank = tank;
this.facing = facing;
this.priority = priority;
this.filter = filter;
}
@Override
public long storedItemTypes()
{
if (tank != null && getTankInfo(tank) != null)
{
return getTankInfo(tank)[0].fluid != null ? 1 : 0;
}
return 0;
}
@Override
public long storedItemCount()
{
if (tank != null && getTankInfo(tank) != null)
{
return getTankInfo(tank)[0].fluid.amount;
}
return 0;
}
@Override
public long remainingItemCount()
{
if (tank != null && getTankInfo(tank) != null && getTankInfo(tank)[0].fluid != null)
{
return getTankInfo(tank)[0].capacity - getTankInfo(tank)[0].fluid.amount;
}
return 0;
}
@Override
public long remainingItemTypes()
{
if (tank != null && getTankInfo(tank) != null && getTankInfo(tank)[0].fluid == null)
{
return 1;
}
return 0;
}
@Override
public boolean containsItemType(IAEItemStack aeitemstack)
{
if (aeitemstack != null && tank != null && getTankInfo(tank) != null && getTankInfo(tank)[0] != null && getTankInfo(tank)[0].fluid != null)
{
if (getTankInfo(tank)[0].fluid == null)
return false;
return aeitemstack.getItem() == ItemEnum.FLUIDDISPLAY.getItemInstance() && aeitemstack.getItemDamage() == getTankInfo(tank)[0].fluid.fluidID;
}
return false;
}
@Override
public long getTotalItemTypes()
{
return 1;
}
@Override
public long countOfItemType(IAEItemStack aeitemstack)
{
if (tank != null && getTankInfo(tank) != null && getTankInfo(tank)[0] != null && getTankInfo(tank)[0].fluid != null)
{
return aeitemstack.getItem() == ItemEnum.FLUIDDISPLAY.getItemInstance() ? aeitemstack.getItemDamage() == getTankInfo(tank)[0].fluid.fluidID ? getTankInfo(tank)[0].fluid.amount : 0 : 0;
}
return 0;
}
@Override
public IAEItemStack addItems(IAEItemStack input)
{
IAEItemStack addedStack = input.copy();
if (input.getItem() == ItemEnum.FLUIDDISPLAY.getItemInstance() && (!isPreformatted() || (isPreformatted() && isItemInPreformattedItems(input.getItemStack()))))
{
if (tank != null)
{
if (getTankInfo(tank) == null || getTankInfo(tank)[0].fluid == null || FluidRegistry.getFluid(input.getItemDamage()) == tank.getTankInfo(facing)[0].fluid.getFluid())
{
int filled = 0;
for (long i = 0; i < input.getStackSize() / 25; i++)
{
filled += tank.fill(facing, new FluidStack(input.getItemDamage(), 25), true);
}
int remainder = (int) (input.getStackSize() - ((input.getStackSize() / 25) * 25));
if (remainder > 0)
{
filled += tank.fill(facing, new FluidStack(input.getItemDamage(), remainder), true);
}
addedStack.setStackSize(input.getStackSize() - filled);
((TileEntity) tank).onInventoryChanged();
if (addedStack != null && addedStack.getStackSize() == 0)
addedStack = null;
return addedStack;
}
}
}
return addedStack;
}
@Override
public IAEItemStack extractItems(IAEItemStack request)
{
IAEItemStack removedStack = request.copy();
if (request.getItem() == ItemEnum.FLUIDDISPLAY.getItemInstance() && tank != null)
{
if (getTankInfo(tank) != null && getTankInfo(tank)[0].fluid != null && FluidRegistry.getFluid(request.getItemDamage()) == getTankInfo(tank)[0].fluid.getFluid())
{
long drainedAmount = 0;
for (long i = 0; i < request.getStackSize() / 25; i++)
{
FluidStack drainedStack = tank.drain(facing, 25, true);
if (drainedStack != null && drainedStack.amount != 0)
drainedAmount += drainedStack.amount;
}
int remainder = (int) (request.getStackSize() - ((request.getStackSize() / 25) * 25));
if (remainder > 0)
{
FluidStack drainedStack = tank.drain(facing, remainder, true);
if (drainedStack != null && drainedStack.amount != 0)
drainedAmount += drainedStack.amount;
}
((TileEntity) tank).onInventoryChanged();
if (drainedAmount == 0)
{
return null;
} else
{
removedStack.setStackSize(drainedAmount);
}
return removedStack;
}
}
return null;
}
@Override
public IItemList getAvailableItems(IItemList out)
{
if (tank != null)
{
if (getTankInfo(tank) != null && getTankInfo(tank)[0].fluid != null && getTankInfo(tank)[0].fluid.getFluid() != null)
{
IAEItemStack currentItemStack = Util.createItemStack(new ItemStack(ItemEnum.FLUIDDISPLAY.getItemInstance(), 1, getTankInfo(tank)[0].fluid.getFluid().getID()));
currentItemStack.setStackSize(getTankInfo(tank)[0].fluid.amount);
out.add(currentItemStack);
}
}
return out;
}
public boolean isItemInPreformattedItems(ItemStack request)
{
for (ItemStack itemstack : getPreformattedItems())
{
if (itemstack.getItem() == request.getItem() && itemstack.getItemDamage() == request.getItemDamage())
return true;
}
return false;
}
@Override
public IItemList getAvailableItems()
{
return getAvailableItems(Util.createItemList());
}
@Override
public IAEItemStack calculateItemAddition(IAEItemStack input)
{
IAEItemStack addedStack = input.copy();
if (input.getItem() == ItemEnum.FLUIDDISPLAY.getItemInstance() && (!isPreformatted() || (isPreformatted() && isItemInPreformattedItems(input.getItemStack()))))
{
if (tank != null)
{
if (getTankInfo(tank) != null && (getTankInfo(tank)[0].fluid == null || FluidRegistry.getFluid(input.getItemDamage()) == getTankInfo(tank)[0].fluid.getFluid()))
{
int filled = 0;
for (long i = 0; i < input.getStackSize() / 25; i++)
{
filled += tank.fill(facing, new FluidStack(input.getItemDamage(), 25), false);
}
int remainder = (int) (input.getStackSize() - ((input.getStackSize() / 25) * 25));
if (remainder > 0)
{
filled += tank.fill(facing, new FluidStack(input.getItemDamage(), remainder), false);
}
addedStack.setStackSize(input.getStackSize() - filled);
((TileEntity) tank).onInventoryChanged();
if (addedStack != null && addedStack.getStackSize() == 0)
addedStack = null;
return addedStack;
}
}
}
return addedStack;
}
@Override
public long getAvailableSpaceByItem(IAEItemStack itemstack, long maxNeeded)
{
if (itemstack != null)
{
if (remainingItemCount() > 0)
{
return itemstack.getItem() == ItemEnum.FLUIDDISPLAY.getItemInstance() ? remainingItemCount() : 0;
} else
{
for (IAEItemStack stack : this.getAvailableItems())
{
if (stack != null && stack.getItem() == itemstack.getItem() && stack.getItemDamage() == itemstack.getItemDamage())
return remainingItemCount();
}
}
}
return 0;
}
@Override
public int getPriority()
{
return priority;
}
@Override
public void setPriority(int priority)
{
this.priority = priority;
}
@Override
public long totalBytes()
{
if (tank != null)
{
return getTankInfo(tank) != null ? getTankInfo(tank)[0].capacity : 0;
}
return 0;
}
@Override
public long freeBytes()
{
if (tank != null && getTankInfo(tank) != null)
{
return getTankInfo(tank)[0].fluid != null ? getTankInfo(tank)[0].capacity - getTankInfo(tank)[0].fluid.amount : getTankInfo(tank)[0].capacity;
}
return 0;
}
@Override
public long usedBytes()
{
if (tank != null)
{
return getTankInfo(tank) != null ? getTankInfo(tank)[0].fluid.amount : 0;
}
return 0;
}
public FluidTankInfo[] getTankInfo(IFluidHandler tank)
{
if (tank != null)
{
if (tank.getTankInfo(facing) != null && tank.getTankInfo(facing).length != 0)
{
return tank.getTankInfo(facing);
} else if (tank.getTankInfo(ForgeDirection.UNKNOWN) != null && tank.getTankInfo(ForgeDirection.UNKNOWN).length != 0)
{
return tank.getTankInfo(ForgeDirection.UNKNOWN);
}
}
return null;
}
@Override
public long unusedItemCount()
{
return freeBytes();
}
@Override
public boolean canHoldNewItem()
{
return getAvailableItems().getItems().isEmpty();
}
@Override
public void setUpdateTarget(TileEntity e)
{
this.updateTarget = e;
}
@Override
public List<ItemStack> getPreformattedItems()
{
return filter;
}
@Override
public boolean isPreformatted()
{
return !filter.isEmpty();
}
@Override
public boolean isFuzzyPreformatted()
{
return false;
}
@Override
public void setFuzzyPreformatted(boolean nf)
{
// Fuzzy on Fluids? I don't think so.
}
@Override
public void setName(String name)
{
// A name for a Storagebus? NO!
}
@Override
public String getName()
{
// A name for a Storagebus? NO!
return "";
}
@Override
public void setGrid(IGridInterface grid)
{
this.grid = grid;
}
@Override
public IGridInterface getGrid()
{
return grid;
}
@Override
public void setParent(IMEInventoryHandler parent)
{
this.parent = parent;
}
@Override
public IMEInventoryHandler getParent()
{
return parent;
}
@Override
public void removeGrid(IGridInterface grid, IMEInventoryHandler ignore, List<IMEInventoryHandler> duplicates)
{
// Algo told me to do nothing here :P
}
@Override
public void validate(List<IMEInventoryHandler> duplicates)
{
// Algo told me to do nothing here :P
}
@Override
public boolean canAccept(IAEItemStack input)
{
if (input != null && input.getItem() == ItemEnum.FLUIDDISPLAY.getItemInstance())
{
if (getAvailableItems() != null)
{
for (IAEItemStack current : getAvailableItems())
{
if (current == null || current.getItemDamage() == input.getItemDamage())
return true;
}
if (getAvailableItems().size() == 0)
return true;
} else
{
return true;
}
}
return false;
}
@Override
public ItemFlow getFlow()
{
return ItemFlow.READ_WRITE;
}
@Override
public void setFlow(ItemFlow p)
{
// Nothing
}
@Override
public FuzzyMode getFuzzyModePreformatted()
{
return FuzzyMode.Percent_99;
}
@Override
public void setPreformattedItems(IItemList in, FuzzyMode mode, ListMode m)
{
// Setting it in the Inventory
}
@Override
public ListMode getListMode()
{
return ListMode.BLACKLIST;
}
}
| mit |
badoualy/kotlogram | tl/src/main/java/com/github/badoualy/telegram/tl/api/TLDocument.java | 5482 | package com.github.badoualy.telegram.tl.api;
import com.github.badoualy.telegram.tl.TLContext;
import com.github.badoualy.telegram.tl.core.TLVector;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static com.github.badoualy.telegram.tl.StreamUtils.readInt;
import static com.github.badoualy.telegram.tl.StreamUtils.readLong;
import static com.github.badoualy.telegram.tl.StreamUtils.readTLObject;
import static com.github.badoualy.telegram.tl.StreamUtils.readTLString;
import static com.github.badoualy.telegram.tl.StreamUtils.readTLVector;
import static com.github.badoualy.telegram.tl.StreamUtils.writeInt;
import static com.github.badoualy.telegram.tl.StreamUtils.writeLong;
import static com.github.badoualy.telegram.tl.StreamUtils.writeString;
import static com.github.badoualy.telegram.tl.StreamUtils.writeTLObject;
import static com.github.badoualy.telegram.tl.StreamUtils.writeTLVector;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT64;
import static com.github.badoualy.telegram.tl.TLObjectUtils.computeTLStringSerializedSize;
/**
* @author Yannick Badoual yann.badoual@gmail.com
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
public class TLDocument extends TLAbsDocument {
public static final int CONSTRUCTOR_ID = 0x87232bc7;
protected long accessHash;
protected int date;
protected String mimeType;
protected int size;
protected TLAbsPhotoSize thumb;
protected int dcId;
protected int version;
protected TLVector<TLAbsDocumentAttribute> attributes;
private final String _constructor = "document#87232bc7";
public TLDocument() {
}
public TLDocument(long id, long accessHash, int date, String mimeType, int size, TLAbsPhotoSize thumb, int dcId, int version, TLVector<TLAbsDocumentAttribute> attributes) {
this.id = id;
this.accessHash = accessHash;
this.date = date;
this.mimeType = mimeType;
this.size = size;
this.thumb = thumb;
this.dcId = dcId;
this.version = version;
this.attributes = attributes;
}
@Override
public void serializeBody(OutputStream stream) throws IOException {
writeLong(id, stream);
writeLong(accessHash, stream);
writeInt(date, stream);
writeString(mimeType, stream);
writeInt(size, stream);
writeTLObject(thumb, stream);
writeInt(dcId, stream);
writeInt(version, stream);
writeTLVector(attributes, stream);
}
@Override
@SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
public void deserializeBody(InputStream stream, TLContext context) throws IOException {
id = readLong(stream);
accessHash = readLong(stream);
date = readInt(stream);
mimeType = readTLString(stream);
size = readInt(stream);
thumb = readTLObject(stream, context, TLAbsPhotoSize.class, -1);
dcId = readInt(stream);
version = readInt(stream);
attributes = readTLVector(stream, context);
}
@Override
public int computeSerializedSize() {
int size = SIZE_CONSTRUCTOR_ID;
size += SIZE_INT64;
size += SIZE_INT64;
size += SIZE_INT32;
size += computeTLStringSerializedSize(mimeType);
size += SIZE_INT32;
size += thumb.computeSerializedSize();
size += SIZE_INT32;
size += SIZE_INT32;
size += attributes.computeSerializedSize();
return size;
}
@Override
public String toString() {
return _constructor;
}
@Override
public int getConstructorId() {
return CONSTRUCTOR_ID;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getAccessHash() {
return accessHash;
}
public void setAccessHash(long accessHash) {
this.accessHash = accessHash;
}
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public TLAbsPhotoSize getThumb() {
return thumb;
}
public void setThumb(TLAbsPhotoSize thumb) {
this.thumb = thumb;
}
public int getDcId() {
return dcId;
}
public void setDcId(int dcId) {
this.dcId = dcId;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public TLVector<TLAbsDocumentAttribute> getAttributes() {
return attributes;
}
public void setAttributes(TLVector<TLAbsDocumentAttribute> attributes) {
this.attributes = attributes;
}
@Override
public final boolean isEmpty() {
return false;
}
@Override
public final boolean isNotEmpty() {
return true;
}
@Override
public final TLDocument getAsDocument() {
return this;
}
}
| mit |
tonysparks/leola | src/leola/ast/ASTNodeVisitor.java | 2490 | /*
Leola Programming Language
Author: Tony Sparks
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Node Visitor
*
* @author Tony
*
*/
public interface ASTNodeVisitor {
void visit(SubscriptGetExpr s) throws EvalException;
void visit(SubscriptSetExpr s) throws EvalException;
void visit(ArrayDeclExpr s) throws EvalException;
void visit(MapDeclExpr s) throws EvalException;
void visit(AssignmentExpr s) throws EvalException;
void visit(BinaryExpr s) throws EvalException;
void visit(BooleanExpr s) throws EvalException;
void visit(BreakStmt s) throws EvalException;
void visit(CaseExpr s) throws EvalException;
void visit(ClassDeclStmt s) throws EvalException;
void visit(BlockStmt s) throws EvalException;
void visit(ContinueStmt s) throws EvalException;
void visit(DecoratorExpr s) throws EvalException;
void visit(NamespaceStmt s) throws EvalException;
void visit(CatchStmt s) throws EvalException;
void visit(RealExpr s) throws EvalException;
void visit(IntegerExpr s) throws EvalException;
void visit(LongExpr s) throws EvalException;
void visit(ProgramStmt s) throws EvalException;
void visit(IsExpr s) throws EvalException;
void visit(EmptyStmt s) throws EvalException;
void visit(GenDefExpr s) throws EvalException;
void visit(FuncDefExpr s) throws EvalException;
void visit(FuncInvocationExpr s) throws EvalException;
void visit(IfStmt s) throws EvalException;
void visit(NamespaceGetExpr s) throws EvalException;
void visit(NamespaceSetExpr s) throws EvalException;
void visit(ElvisGetExpr s) throws EvalException;
void visit(GetExpr s) throws EvalException;
void visit(SetExpr s) throws EvalException;
void visit(NamedParameterExpr s) throws EvalException;
void visit(NewExpr s) throws EvalException;
void visit(NullExpr s) throws EvalException;
void visit(ReturnStmt s) throws EvalException;
void visit(YieldStmt s) throws EvalException;
void visit(StringExpr s) throws EvalException;
void visit(SwitchStmt s) throws EvalException;
void visit(TryStmt s) throws EvalException;
void visit(ThrowStmt s) throws EvalException;
void visit(UnaryExpr s) throws EvalException;
void visit(VarDeclStmt s) throws EvalException;
void visit(VarExpr s) throws EvalException;
void visit(WhileStmt s) throws EvalException;
}
| mit |
sjsucohort6/amigo-chatbot | chatbot-service/src/main/java/edu/sjsu/amigo/chatbot/jobs/ChatbotMessageProcessorJob.java | 1522 | /*
* Copyright (c) 2017 San Jose State University.
*
* 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.
*/
package edu.sjsu.amigo.chatbot.jobs;
import edu.sjsu.amigo.chatbot.msg.MessageProcessor;
import edu.sjsu.amigo.mp.model.Message;
import edu.sjsu.amigo.scheduler.jobs.JobConstants;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* @author rwatsh on 4/23/17.
*/
public class ChatbotMessageProcessorJob implements Job {
private Message message;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
try {
JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
message = (Message)jobDataMap.get(JobConstants.JOB_PARAM_MESSAGE);
MessageProcessor.processMessage(message);
} catch( Exception e) {
throw new JobExecutionException(e);
}
}
}
| mit |
xreztento/codesearch | codesearch_frontend/src/main/java/org/xreztento/tools/codesearch/frontend/engine/CodeResult.java | 387 | package org.xreztento.tools.codesearch.frontend.engine;
public class CodeResult {
private String file;
private CodeFragment fragment;
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public CodeFragment getFragment() {
return fragment;
}
public void setFragment(CodeFragment fragment) {
this.fragment = fragment;
}
}
| mit |
redpelicans/react-native-android-boilerplate | android/app/src/main/java/MainActivity.java | 1581 | package com.example.myapp;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;
import java.util.List;
import co.apptailor.googlesignin.RNGoogleSigninModule;
import co.apptailor.googlesignin.RNGoogleSigninPackage;
import com.oblador.vectoricons.VectorIconsPackage;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "ReactNativeApp";
}
/**
* Returns whether dev mode should be enabled.
* This enables e.g. the dev menu.
*/
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new RNGoogleSigninPackage(this),
new VectorIconsPackage(),
new MainReactPackage()
);
}
@Override
public void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
if (requestCode == RNGoogleSigninModule.RC_SIGN_IN) {
RNGoogleSigninModule.onActivityResult(data);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| mit |
richard-roberts/SOMns | src/som/interpreter/actors/SuspendExecutionNode.java | 759 | package som.interpreter.actors;
import com.oracle.truffle.api.debug.DebuggerTags.AlwaysHalt;
import com.oracle.truffle.api.dsl.Specialization;
import som.interpreter.nodes.nary.UnaryExpressionNode;
public abstract class SuspendExecutionNode extends UnaryExpressionNode {
private int skipFrames;
SuspendExecutionNode(final int skipFrames) {
this.skipFrames = skipFrames;
}
@Specialization
public final Object doSAbstractObject(final Object receiver) {
return receiver;
}
@Override
protected boolean isTaggedWithIgnoringEagerness(final Class<?> tag) {
if (tag == AlwaysHalt.class) {
return true;
}
return super.isTaggedWithIgnoringEagerness(tag);
}
public int getSkipFrames() {
return skipFrames;
}
}
| mit |
jfizz/shirtsio-java | src/main/java/com/shirtsio/model/Quote.java | 2626 | package com.shirtsio.model;
import org.codehaus.jackson.annotate.JsonProperty;
import java.math.BigDecimal;
public class Quote {
@JsonProperty("print_type")
private String printType;
private BigDecimal discount;
private String[] warnings;
private BigDecimal total;
@JsonProperty("shipping_price")
private BigDecimal shippingPrice;
private BigDecimal subtotal;
@JsonProperty("sales_tax")
private BigDecimal salesTax;
@JsonProperty("garment_breakdown")
private GarmentBreakdown[] garmentBreakdowns;
public BigDecimal getDiscount() {
return discount;
}
public void setDiscount(BigDecimal discount) {
this.discount = discount;
}
public GarmentBreakdown[] getGarmentBreakdowns() {
return garmentBreakdowns;
}
public void setGarmentBreakdowns(GarmentBreakdown[] garmentBreakdowns) {
this.garmentBreakdowns = garmentBreakdowns;
}
public String getPrintType() {
return printType;
}
public void setPrintType(String printType) {
this.printType = printType;
}
public BigDecimal getSalesTax() {
return salesTax;
}
public void setSalesTax(BigDecimal salesTax) {
this.salesTax = salesTax;
}
public BigDecimal getShippingPrice() {
return shippingPrice;
}
public void setShippingPrice(BigDecimal shippingPrice) {
this.shippingPrice = shippingPrice;
}
public BigDecimal getSubtotal() {
return subtotal;
}
public void setSubtotal(BigDecimal subtotal) {
this.subtotal = subtotal;
}
public BigDecimal getTotal() {
return total;
}
public void setTotal(BigDecimal total) {
this.total = total;
}
public String[] getWarnings() {
return warnings;
}
public void setWarnings(String[] warnings) {
this.warnings = warnings;
}
}
class GarmentBreakdown {
@JsonProperty("price_per_shirt")
private BigDecimal pricePerShirt;
@JsonProperty("num_shirts")
private int numShirts;
private BigDecimal subtotal;
public int getNumShirts() {
return numShirts;
}
public void setNumShirts(int numShirts) {
this.numShirts = numShirts;
}
public BigDecimal getPricePerShirt() {
return pricePerShirt;
}
public void setPricePerShirt(BigDecimal pricePerShirt) {
this.pricePerShirt = pricePerShirt;
}
public BigDecimal getSubtotal() {
return subtotal;
}
public void setSubtotal(BigDecimal subtotal) {
this.subtotal = subtotal;
}
} | mit |
ad-tech-group/openssp | open-ssp-parent/open-ssp-openrtb/src/main/java/openrtb/bidrequest/model/Banner.java | 2989 | package openrtb.bidrequest.model;
import java.util.List;
import com.google.gson.annotations.Since;
/**
* @author André Schmer
* @see OpenRTB-API-Specification #section Banner Object
* @version 2.1, 2.2, 2.3
*/
public final class Banner implements Cloneable {
// required
private int w;
private int h;
private String id;
// optional
private int pos;
private List<Integer> btype;// blocked creative types
private List<Integer> battr;
private String[] mimes;// commaseparated list
private int topframe = 0;
private int[] expdir; // expandable directions 1-6
private int[] api;
private Object ext;
@Since(2.2)
private int wmax;
@Since(2.2)
private int hmax;
@Since(2.2)
private int wmin;
@Since(2.2)
private int hmin;
public Banner() {}
public String getId() {
return id;
}
public int getW() {
return w;
}
public void setW(final int w) {
this.w = w;
}
public int getH() {
return h;
}
public void setH(final int h) {
this.h = h;
}
public String[] getMimes() {
return mimes;
}
public void setMimes(final String[] mimes) {
this.mimes = mimes;
}
public void setId(final String id) {
this.id = id;
}
public int[] getExpdir() {
return expdir;
}
public void setExpdir(final int[] expdir) {
this.expdir = expdir;
}
public int getPos() {
return pos;
}
public void setPos(final int pos) {
this.pos = pos;
}
public List<Integer> getBtype() {
return btype;
}
public void setBtype(final List<Integer> btype) {
this.btype = btype;
}
public List<Integer> getBattr() {
return battr;
}
public void setBattr(final List<Integer> battr) {
this.battr = battr;
}
public int getTopframe() {
return topframe;
}
public void setTopframe(final int topframe) {
this.topframe = topframe;
}
public int[] getApi() {
return api;
}
public void setApi(final int[] api) {
this.api = api;
}
public Object getExt() {
return ext;
}
public void setExt(final Object ext) {
this.ext = ext;
}
public int getWmax() {
return wmax;
}
public void setWmax(final int wmax) {
this.wmax = wmax;
}
public int getHmax() {
return hmax;
}
public void setHmax(final int hmax) {
this.hmax = hmax;
}
public int getWmin() {
return wmin;
}
public void setWmin(final int wmin) {
this.wmin = wmin;
}
public int getHmin() {
return hmin;
}
public void setHmin(final int hmin) {
this.hmin = hmin;
}
@Override
public Banner clone() {
try {
final Banner clone = (Banner) super.clone();
return clone;
} catch (final CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public static class Builder {
private final Banner banner;
public Builder() {
banner = new Banner();
}
public Builder setId(final String id) {
banner.setId(id);
return this;
}
public Builder addAllBattr(final List<Integer> allBattr) {
banner.setBattr(allBattr);
return this;
}
public Banner build() {
return banner;
}
}
}
| mit |
sdl/Testy | src/main/java/com/sdl/selenium/extjs4/window/XTool.java | 1180 | package com.sdl.selenium.extjs4.window;
import com.sdl.selenium.web.WebLocator;
public interface XTool {
WebLocator getView();
/**
* click on element with class "x-tool-" + suffix
*
* @param suffix element
* @return true | false
*/
default boolean clickOnTool(String suffix) {
WebLocator toolElement = getToolEl(suffix).setVisibility(true);
return toolElement.click();
}
default WebLocator getToolEl(String suffix) {
return new WebLocator(getView()).setClasses("x-tool-" + suffix);
}
default boolean close() {
return clickOnTool("close");
}
default boolean maximize() {
return clickOnTool("maximize");
}
default boolean restore() {
return clickOnTool("restore");
}
default boolean minimize() {
return clickOnTool("minimize");
}
default boolean toggle() {
return clickOnTool("toggle");
}
default boolean plus() {
return clickOnTool("plus");
}
default boolean collapse() {
return clickOnTool("collapse");
}
default boolean expand() {
return clickOnTool("expand");
}
}
| mit |
leoliew/EasemobSample | src/com/easemob/chatuidemo/activity/BlacklistActivity.java | 3978 | package com.easemob.chatuidemo.activity;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.easemob.chat.EMContactManager;
import com.easemob.chatuidemo.R;
import com.easemob.exceptions.EaseMobException;
/**
* 黑名单列表页面
*
*/
public class BlacklistActivity extends Activity {
private ListView listView;
private BlacklistAdapater adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_black_list);
listView = (ListView) findViewById(R.id.list);
// 从本地获取黑名单
List<String> blacklist = EMContactManager.getInstance().getBlackListUsernames();
// 显示黑名单列表
if (blacklist != null) {
Collections.sort(blacklist);
adapter = new BlacklistAdapater(this, 1, blacklist);
listView.setAdapter(adapter);
}
// 注册上下文菜单
registerForContextMenu(listView);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.remove_from_blacklist, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == R.id.remove) {
final String tobeRemoveUser = adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
// 把目标user移出黑名单
removeOutBlacklist(tobeRemoveUser);
return true;
}
return super.onContextItemSelected(item);
}
/**
* 移出黑民单
*
* @param tobeRemoveUser
*/
void removeOutBlacklist(final String tobeRemoveUser) {
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage(getString(R.string.be_removing));
pd.setCanceledOnTouchOutside(false);
pd.show();
new Thread(new Runnable() {
public void run() {
try {
// 移出黑民单
EMContactManager.getInstance().deleteUserFromBlackList(tobeRemoveUser);
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
adapter.remove(tobeRemoveUser);
}
});
} catch (EaseMobException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
Toast.makeText(getApplicationContext(), R.string.Removed_from_the_failure, 0).show();
}
});
}
}
}).start();
}
/**
* adapter
*
*/
private class BlacklistAdapater extends ArrayAdapter<String> {
public BlacklistAdapater(Context context, int textViewResourceId, List<String> objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(getContext(), R.layout.row_contact, null);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(getItem(position));
return convertView;
}
}
/**
* 返回
*
* @param view
*/
public void back(View view) {
finish();
}
}
| mit |
agersant/polaris-android | app/src/main/java/agersant/polaris/api/remote/APIVersion3.java | 6728 | package agersant.polaris.api.remote;
import android.net.Uri;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import agersant.polaris.CollectionItem;
import agersant.polaris.api.ItemsCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
public class APIVersion3 extends APIBase
implements IRemoteAPI {
private final Gson gson;
APIVersion3(DownloadQueue downloadQueue, RequestQueue requestQueue) {
super(downloadQueue, requestQueue);
this.gson = new GsonBuilder()
.registerTypeAdapter(CollectionItem.class, new CollectionItem.Deserializer())
.registerTypeAdapter(CollectionItem.Directory.class, new CollectionItem.Directory.Deserializer())
.registerTypeAdapter(CollectionItem.Song.class, new CollectionItem.Song.Deserializer())
.create();
}
String getAudioURL(String path) {
String serverAddress = ServerAPI.getAPIRootURL();
return serverAddress + "/serve/" + Uri.encode(path);
}
String getThumbnailURL(String path) {
String serverAddress = ServerAPI.getAPIRootURL();
return serverAddress + "/serve/" + Uri.encode(path);
}
public void browse(String path, final ItemsCallback handlers) {
String requestURL = ServerAPI.getAPIRootURL() + "/browse/" + Uri.encode(path);
HttpUrl parsedURL = HttpUrl.parse(requestURL);
if (parsedURL == null) {
handlers.onError();
return;
}
Request request = new Request.Builder().url(parsedURL).build();
Callback callback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
handlers.onError();
}
@Override
public void onResponse(Call call, Response response) {
if (response.body() == null) {
handlers.onError();
return;
}
Type collectionType = new TypeToken<ArrayList<CollectionItem>>() {
}.getType();
ArrayList<CollectionItem> items;
try {
items = gson.fromJson(response.body().charStream(), collectionType);
} catch (JsonSyntaxException e) {
handlers.onError();
return;
}
handlers.onSuccess(items);
}
};
requestQueue.requestAsync(request, callback);
}
void getAlbums(String url, final ItemsCallback handlers) {
HttpUrl parsedURL = HttpUrl.parse(url);
if (parsedURL == null) {
handlers.onError();
return;
}
Request request = new Request.Builder().url(parsedURL).build();
Callback callback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
handlers.onError();
}
@Override
public void onResponse(Call call, Response response) {
if (response.body() == null) {
handlers.onError();
return;
}
Type collectionType = new TypeToken<ArrayList<CollectionItem.Directory>>() {
}.getType();
ArrayList<? extends CollectionItem> items;
try {
items = gson.fromJson(response.body().charStream(), collectionType);
} catch (JsonSyntaxException e) {
handlers.onError();
return;
}
handlers.onSuccess(items);
}
};
requestQueue.requestAsync(request, callback);
}
public void flatten(String path, final ItemsCallback handlers) {
String requestURL = ServerAPI.getAPIRootURL() + "/flatten/" + Uri.encode(path);
Request request = new Request.Builder().url(requestURL).build();
Callback callback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
handlers.onError();
}
@Override
public void onResponse(Call call, Response response) {
if (response.body() == null) {
handlers.onError();
return;
}
Type collectionType = new TypeToken<ArrayList<CollectionItem.Song>>() {
}.getType();
ArrayList<? extends CollectionItem> items;
try {
items = gson.fromJson(response.body().charStream(), collectionType);
} catch (JsonSyntaxException e) {
handlers.onError();
return;
}
handlers.onSuccess(items);
}
};
requestQueue.requestAsync(request, callback);
}
public void setLastFMNowPlaying(String path) {
String requestURL = ServerAPI.getAPIRootURL() + "/lastfm/now_playing/" + Uri.encode(path);
Request request = new Request.Builder().url(requestURL).put(new RequestBody() {
@Override
public MediaType contentType() {
return null;
}
@Override
public void writeTo(BufferedSink sink) {
}
}).build();
requestQueue.requestAsync(request, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) {
}
});
}
public void scrobbleOnLastFM(String path) {
String requestURL = ServerAPI.getAPIRootURL() + "/lastfm/scrobble/" + Uri.encode(path);
Request request = new Request.Builder().url(requestURL).post(new RequestBody() {
@Override
public MediaType contentType() {
return null;
}
@Override
public void writeTo(BufferedSink sink) {
}
}).build();
requestQueue.requestAsync(request, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) {
}
});
}
}
| mit |
nille85/http-router | core/src/main/java/be/nille/http/router/netty/NettyRequest.java | 2552 | /*
* 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 be.nille.http.router.netty;
import be.nille.http.router.body.Body;
import be.nille.http.router.body.TextBody;
import be.nille.http.router.headers.Headers;
import be.nille.http.router.request.QueryParameters;
import be.nille.http.router.request.Request;
import be.nille.http.router.request.Method;
import be.nille.http.router.request.PathVariables;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author nholvoet
*/
public class NettyRequest implements Request {
private final HttpRequest httpRequest;
private final String httpContent;
public NettyRequest(final HttpRequest httpRequest, final String httpContent) {
this.httpRequest = httpRequest;
this.httpContent = httpContent;
}
@Override
public Headers getHeaders() {
HttpHeaders headers = httpRequest.headers();
Headers copiedHeaders = new Headers();
if (!headers.isEmpty()) {
for (Map.Entry<String, String> h : headers) {
copiedHeaders = copiedHeaders.add(h.getKey(), h.getValue());
}
}
return copiedHeaders;
}
@Override
public Body getBody() {
return new TextBody(httpContent);
}
@Override
public Method getMethod() {
return new Method(httpRequest.method().name());
}
@Override
public QueryParameters queryParameters() {
try {
return new QueryParameters(new URI(httpRequest.uri()));
} catch (URISyntaxException ex) {
throw new RuntimeException(
String.format("The value %s is not a valid URI ", httpRequest.uri()),
ex
);
}
}
@Override
public String getPath() {
return getURI().getPath();
}
@Override
public PathVariables variables() {
return new PathVariables(new HashMap<>());
}
@Override
public URI getURI() {
try {
return new URI(httpRequest.uri());
} catch (URISyntaxException ex) {
throw new RuntimeException(
String.format("The value %s is not a valid URI ", httpRequest.uri()),
ex
);
}
}
}
| mit |
TeamworkGuy2/JParserTools | src/twg2/parser/codeParser/analytics/PerformanceTrackers.java | 5241 | package twg2.parser.codeParser.analytics;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import twg2.collections.builder.ListBuilder;
import twg2.parser.codeParser.analytics.ParseTimes.TrackerAction;
import twg2.parser.output.JsonWritableSig;
import twg2.parser.output.WriteSettings;
import twg2.text.stringUtils.StringPad;
import twg2.text.stringUtils.StringSplit;
import twg2.text.tokenizer.analytics.ParserAction;
import twg2.tuple.Tuple3;
import twg2.tuple.Tuples;
/**
* @author TeamworkGuy2
* @since 2016-09-11
*/
public class PerformanceTrackers implements JsonWritableSig {
private final HashMap<String, Tuple3<ParseTimes, ParserActionLogger, Integer>> fileStats;
public PerformanceTrackers() {
this.fileStats = new HashMap<>();
}
public void log(TrackerAction action, String srcName, long timeNanos) {
var stat = getOrCreateParseStats(srcName, null);
stat.getValue0().setActionTime(action, timeNanos);
}
public void log(ParserAction action, String srcName, long detail) {
var stat = getOrCreateParseStats(srcName, null);
stat.getValue1().logCount(action, detail);
}
public ParseTimes getOrCreateParseTimes(String srcName) {
return getOrCreateParseStats(srcName, null).getValue0();
}
public ParserActionLogger getOrCreateStepDetails(String srcName) {
return getOrCreateParseStats(srcName, null).getValue1();
}
public void setSrcSize(String srcName, int fileSize) {
synchronized(fileStats) {
var stats = fileStats.get(srcName);
var inst = (stats == null
? Tuples.of(new ParseTimes(), new ParserActionLogger(), fileSize)
: Tuples.of(stats.getValue0(), stats.getValue1(), fileSize));
fileStats.put(srcName, inst);
}
}
public Map<String, Tuple3<ParseTimes, ParserActionLogger, Integer>> getParseStats() {
return this.fileStats;
}
public List<Entry<String, Tuple3<ParseTimes, ParserActionLogger, Integer>>> getTopParseTimes(boolean sortAscending, int size) {
var list = ListBuilder.mutable(
this.fileStats.entrySet().stream()
.sorted(PerformanceTrackers.createParseTimesSorter(sortAscending)).iterator()
);
return (size < 0 ? list.subList(list.size() + size, list.size()) : list.subList(0, size));
}
public List<Entry<String, Tuple3<ParseTimes, ParserActionLogger, Integer>>> getTopParseStepDetails(boolean sortAscending, int size) {
var list = ListBuilder.mutable(
this.fileStats.entrySet().stream()
.sorted(PerformanceTrackers.createParseStepDetailsSorter(sortAscending)).iterator()
);
return (size < 0 ? list.subList(list.size() + size, list.size()) : list.subList(0, size));
}
private Tuple3<ParseTimes, ParserActionLogger, Integer> getOrCreateParseStats(String srcName, Integer fileSize) {
synchronized(fileStats) {
var stats = fileStats.get(srcName);
if(stats == null) {
var inst = Tuples.of(new ParseTimes(), new ParserActionLogger(), fileSize);
fileStats.put(srcName, inst);
return inst;
}
return stats;
}
}
@Override
public void toJson(Appendable dst, WriteSettings st) throws IOException {
for(var stat : fileStats.entrySet()) {
dst.append("{ ");
dst.append("\"file\": \"");
dst.append(stat.getKey());
dst.append("\", ");
stat.getValue().getValue0().toJson(null, false, dst, st);
dst.append(", ");
stat.getValue().getValue1().toJson(null, false, dst, st);
dst.append(", \"fileSize\" :");
dst.append(stat.getValue().getValue2().toString());
dst.append(" },\n");
}
}
@Override
public String toString() {
return toString(fileStats.entrySet().iterator());
}
public static final String toString(Iterator<Entry<String, Tuple3<ParseTimes, ParserActionLogger, Integer>>> parseStatsIter) {
var sb = new StringBuilder();
while(parseStatsIter.hasNext()) {
var stat = parseStatsIter.next();
var key = stat.getKey();
var parseTimes = stat.getValue().getValue0();
var stepDetails = stat.getValue().getValue1();
var fileName = StringPad.padRight(StringSplit.lastMatch(key, '\\'), 40, ' ');
sb.append(fileName).append(" : ").append(parseTimes.toString(null, false));
sb.append(", ");
sb.append(stepDetails.toString(null, false));
sb.append('\n');
}
return sb.toString();
}
private static final Comparator<Entry<String, Tuple3<ParseTimes, ParserActionLogger, Integer>>> createParseTimesSorter(boolean sortAscending) {
if(sortAscending) {
return (a, b) -> (int)(a.getValue().getValue0().getTotalNs() - b.getValue().getValue0().getTotalNs());
}
else {
return (a, b) -> (int)(b.getValue().getValue0().getTotalNs() - a.getValue().getValue0().getTotalNs());
}
}
private static final Comparator<Entry<String, Tuple3<ParseTimes, ParserActionLogger, Integer>>> createParseStepDetailsSorter(boolean sortAscending) {
if(sortAscending) {
return (a, b) -> (int)(a.getValue().getValue1().getLogCount(ParserAction.CHAR_CHECKS) - b.getValue().getValue1().getLogCount(ParserAction.CHAR_CHECKS));
}
else {
return (a, b) -> (int)(b.getValue().getValue1().getLogCount(ParserAction.CHAR_CHECKS) - a.getValue().getValue1().getLogCount(ParserAction.CHAR_CHECKS));
}
}
}
| mit |
xeostream/Coursea | Index Technology/InvertedIndexQuery.java | 2449 | /*
* 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 IndexTechnology;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author Arthur
*/
public class InvertedIndexQuery {
public static void init(int[] result, int[] temp, int type) {
if (type == 0) return ;
Arrays.sort(result);
Arrays.sort(temp);
if (type == 1) {
for (int i = 0; i < result.length; i++) {
if (result[i] == -1) continue;
if (Arrays.binarySearch(temp, result[i]) < 0)
result[i] = -1;
}
} else {
for (int i = 0; i < result.length; i++) {
if (result[i] == -1) continue;
if (Arrays.binarySearch(temp, result[i]) >= 0)
result[i] = -1;
}
}
}
public static void main(String ...args) {
Scanner scan = new Scanner(System.in);
int len = scan.nextInt();
int[][] index = new int[len][];
for (int i = 0; i < len; i++) {
int l = scan.nextInt();
index[i] = new int[l];
for (int j = 0; j < l; j++)
index[i][j] = scan.nextInt();
}
int queryCnt = scan.nextInt();
int[] query = new int[len];
while (queryCnt-- > 0) {
System.out.println(query.length + " ");
int temp = 0;
int i = 0;
for (; i < len; i++) {
query[i] = scan.nextInt();
if (query[i] == 1) temp = i;
}
System.out.println(query.length);
for (int q : query)
System.out.print(q + " ");
System.out.println(query.length);
int[] result = index[temp];
query[temp] = 0;
for (int j = 0; j < len; j++) {
init(result, index[j], query[j]);
}
Arrays.sort(result);
len = result.length;
if (result[len-1] < 0)
System.out.println("NOT FOUND");
else {
for (int j = 0; j < len-1; j++) {
if (result[i] >= 0)
System.out.print(result[j] + " ");
}
System.out.println(result[len-1]);
}
}
}
}
| mit |
captianjroot/EquationBrackets | src/sedgewick/PlotFilter.java | 1153 | package sedgewick;
/*************************************************************************
* Compilation: javac PlotFilter.java
* Execution: java PlotFilter < input.txt
* Dependencies: StdDraw.java StdIn.java
*
* % java PlotFilter < USA.txt
*
* Datafiles: http://www.cs.princeton.edu/IntroProgramming/15inout/USA.txt
*
*************************************************************************/
public class PlotFilter {
public static void main(String[] args) {
// read in bounding box and rescale
double x0 = StdIn.readDouble();
double y0 = StdIn.readDouble();
double x1 = StdIn.readDouble();
double y1 = StdIn.readDouble();
StdDraw.setXscale(x0, x1);
StdDraw.setYscale(y0, y1);
// turn on animation mode to defer displaying all of the points
// StdDraw.show(0);
// plot points, one at a time
while (!StdIn.isEmpty()) {
double x = StdIn.readDouble();
double y = StdIn.readDouble();
StdDraw.point(x, y);
}
// display all of the points now
// StdDraw.show(0);
}
}
| mit |
dbunibas/BART | Bart_Engine/src/bart/model/dependency/operators/AssignAliasesInFormulas.java | 2175 | package bart.model.dependency.operators;
import bart.model.dependency.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AssignAliasesInFormulas {
public void assignAliases(Dependency dependency) {
AssignAliasesVisitor visitor = new AssignAliasesVisitor();
dependency.accept(visitor);
}
}
class AssignAliasesVisitor implements IFormulaVisitor {
private int differenceId = -1;
public void visitDependency(Dependency dependency) {
dependency.getPremise().accept(this);
this.differenceId = -1;
dependency.getConclusion().accept(this);
}
public void visitPositiveFormula(PositiveFormula formula) {
Map<String, List<RelationalAtom>> atomMap = new HashMap<String, List<RelationalAtom>>();
for (IFormulaAtom atom : formula.getAtoms()) {
if (atom instanceof RelationalAtom) {
RelationalAtom relationalAtom = (RelationalAtom) atom;
relationalAtom.addAlias((differenceId > 0 ? "D" + differenceId : ""));
String tableName = relationalAtom.getTableName();
List<RelationalAtom> atomsWithSameName = atomMap.get(tableName);
if (atomsWithSameName == null) {
atomsWithSameName = new ArrayList<RelationalAtom>();
atomMap.put(tableName, atomsWithSameName);
}
atomsWithSameName.add((RelationalAtom) atom);
}
}
for (List<RelationalAtom> atoms : atomMap.values()) {
if (atoms.size() > 1) {
int counter = 1;
for (RelationalAtom relationalAtom : atoms) {
relationalAtom.addAlias("" + counter++);
}
}
}
}
public void visitFormulaWithNegations(FormulaWithNegations formula) {
this.differenceId++;
formula.getPositiveFormula().accept(this);
for (IFormula negatedFormula : formula.getNegatedSubFormulas()) {
negatedFormula.accept(this);
}
}
public Object getResult() {
return null;
}
}
| mit |
vtrbtf/mini-bank | src/main/java/com/vtrbtf/minibank/application/command/client/http/payload/OpenAccountRequest.java | 714 | package com.vtrbtf.minibank.application.command.client.http.payload;
import com.vtrbtf.minibank.application.command.CommandConverter;
import com.vtrbtf.minibank.application.command.client.OpenAccount;
import lombok.AccessLevel;
import lombok.Data;
import lombok.experimental.FieldDefaults;
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class OpenAccountRequest implements CommandConverter<OpenAccount> {
String type;
String clientId;
public OpenAccountRequest withClientId(String clientId) {
this.clientId = clientId;
return this;
}
@Override
public OpenAccount toCommand(String accountId) {
return new OpenAccount(clientId, accountId, type);
}
}
| mit |
Technolords/microservice-mock | src/main/java/net/technolords/micro/camel/lifecycle/MainLifecycleStrategy.java | 1094 | package net.technolords.micro.camel.lifecycle;
import org.apache.camel.CamelContext;
import org.apache.camel.VetoCamelContextStartException;
import org.apache.camel.management.DefaultManagementLifecycleStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.technolords.micro.registry.MockRegistry;
public class MainLifecycleStrategy extends DefaultManagementLifecycleStrategy {
private final Logger LOGGER = LoggerFactory.getLogger(getClass());
public MainLifecycleStrategy(CamelContext camelContext) {
super(camelContext);
}
@Override
public void onContextStart(CamelContext camelContext) throws VetoCamelContextStartException {
LOGGER.debug("onContextStart called...");
MockRegistry.findRegistrationManager().registerService();
super.onContextStart(camelContext);
}
@Override
public void onContextStop(CamelContext context) {
LOGGER.debug("onContextStop called...");
MockRegistry.findRegistrationManager().deregisterService();
super.onContextStop(getCamelContext());
}
}
| mit |
SHOTbyGUN/ShotLogger | src/org/shotlogger/Log.java | 2942 | package org.shotlogger;
/**
*
* @author shotbygun
*/
public class Log {
// Severity constants
public static final short DEBUG = 0;
public static final short INFO = 1;
public static final short WARNING = 2;
public static final short ERROR = 3;
public static final short CRITICAL = 4;
public static final short FATAL = 5;
public static final String[] severityText = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL", "FATAL"};
public static void log(String category, short severity, String source, String message, Exception exception) {
/*
LogItem reusable = ShotLogger.trashLogItemQueue.poll();
if(reusable == null) {
reusable = new LogItem();
}
*/
LogItem logItem = new LogItem();
logItem.set(category, severity, source, message, exception, Thread.currentThread().getName());
ShotLogger.put(logItem);
}
// These are just "overloading" methods of the above
public static void debug(String category, String source, String message, Exception exception) {
log(category, DEBUG, source, message, exception);
}
public static void info(String category, String source, String message, Exception exception) {
log(category, INFO, source, message, exception);
}
public static void warning(String category, String source, String message, Exception exception) {
log(category, WARNING, source, message, exception);
}
public static void error(String category, String source, String message, Exception exception) {
log(category, ERROR, source, message, exception);
}
public static void critical(String category, String source, String message, Exception exception) {
log(category, CRITICAL, source, message, exception);
}
public static void fatal(String category, String source, String message, Exception exception) {
log(category, FATAL, source, message, exception);
}
// FailSafe will only work if FileLogWriter is initialized and running
private static final String FAILSAFEDELIMITER = ";";
protected static void failSafe(String category, short severity, String source, String message, Exception exception) {
// Create logitem out of the normal flow
LogItem logItem = new LogItem();
logItem.set(category, severity, source, message, exception, Thread.currentThread().getName());
// Generate string
String errorLine = LogPrinter.stringBuilder(logItem, FAILSAFEDELIMITER, true, true, true);
// Output the error
if(logItem.severity < Log.ERROR)
System.out.println(errorLine);
else
System.err.println(errorLine);
}
}
| mit |
kamegu/git-webapp | src/main/java/gw/core/auth/RepositoryControllRequestFilter.java | 1905 | package gw.core.auth;
import gw.core.RepositoryContext;
import gw.core.util.ResourceUtils;
import gw.model.pk.RepositoryPK;
import gw.service.RepositoryController;
import java.io.IOException;
import java.util.Optional;
import javax.annotation.Priority;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
@Provider
@Priority(Priorities.AUTHORIZATION)
public class RepositoryControllRequestFilter implements ContainerRequestFilter {
@Context private ResourceInfo resourceInfo;
@Context private HttpServletRequest servletRequest;
@Context private UriInfo uriInfo;
@Inject private RepositoryController repositoryController;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Repo repo = ResourceUtils.getAnnotation(resourceInfo, Repo.class).orElse(null);
if (repo != null) {
String owner = uriInfo.getPathParameters().getFirst(repo.ownerPath());
String repoName = uriInfo.getPathParameters().getFirst(repo.repositoryPath());
if (owner == null || repoName == null) {
throw new NotFoundException();
}
Optional<RepositoryContext> repoContext = repositoryController.getContext(new RepositoryPK(owner, repoName));
if (!repoContext.isPresent()) {
throw new NotFoundException();
}
servletRequest.setAttribute(RepositoryContext.ATTR_NAME, repoContext.get());
if (!repoContext.get().canAccess(repo.collaboratorOnly())) {
throw new ForbiddenException("collaborator-only");
}
}
}
}
| mit |
mkuokkanen/seda-proto | src/main/java/fi/iki/mkuokkanen/seda/timed/SchedulerModule.java | 380 | package fi.iki.mkuokkanen.seda.timed;
import javax.inject.Singleton;
import com.google.inject.AbstractModule;
/**
* Guice Module for Timed Operations
*
* @author mkuokkanen
*/
public class SchedulerModule extends AbstractModule {
@Override
protected void configure() {
bind(EventScheduler.class).to(EventSchedulerImpl.class).in(Singleton.class);
}
}
| mit |
jenkinsci/ghprb-plugin | src/main/java/org/jenkinsci/plugins/ghprb/jobdsl/GhprbExtensionContext.java | 2385 | package org.jenkinsci.plugins.ghprb.jobdsl;
import javaposse.jobdsl.dsl.Context;
import javaposse.jobdsl.plugin.ContextExtensionPoint;
import org.jenkinsci.plugins.ghprb.extensions.GhprbExtension;
import org.jenkinsci.plugins.ghprb.extensions.build.GhprbCancelBuildsOnUpdate;
import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbBuildStatus;
import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbCommentFile;
import org.jenkinsci.plugins.ghprb.extensions.status.GhprbSimpleStatus;
import java.util.ArrayList;
import java.util.List;
class GhprbExtensionContext implements Context {
private List<GhprbExtension> extensions = new ArrayList<GhprbExtension>();
/**
* Updates the commit status during the build.
*/
void commitStatus(Runnable closure) {
GhprbSimpleStatusContext context = new GhprbSimpleStatusContext();
ContextExtensionPoint.executeInContext(closure, context);
extensions.add(new GhprbSimpleStatus(
context.showMatrixStatus,
context.context,
context.statusUrl,
context.triggeredStatus,
context.startedStatus,
context.addTestResults,
context.completedStatus
));
}
/**
* Adds build result messages
*/
void buildStatus(Runnable closure) {
GhprbBuildStatusContext context = new GhprbBuildStatusContext();
ContextExtensionPoint.executeInContext(closure, context);
extensions.add(new GhprbBuildStatus(context.getCompletedStatus()));
}
/**
* Adds comment file path handling
*/
void commentFilePath(Runnable closure) {
GhprbCommentFilePathContext context = new GhprbCommentFilePathContext();
ContextExtensionPoint.executeInContext(closure, context);
extensions.add(new GhprbCommentFile(context.getCommentFilePath()));
}
/**
* Overrides global settings for cancelling builds when a PR was updated
*/
void cancelBuildsOnUpdate(Runnable closure) {
GhprbCancelBuildsOnUpdateContext context = new GhprbCancelBuildsOnUpdateContext();
ContextExtensionPoint.executeInContext(closure, context);
extensions.add(new GhprbCancelBuildsOnUpdate(context.getOverrideGlobal()));
}
public List<GhprbExtension> getExtensions() {
return extensions;
}
}
| mit |
abanoubmilad/dayra | dayra/app/src/main/java/abanoubm/dayra/contact/DisplayContact.java | 1014 | package abanoubm.dayra.contact;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import abanoubm.dayra.R;
public class DisplayContact extends AppCompatActivity {
private static final String ARG_ID = "id";
private static final String ARG_DUAL_MODE = "dual";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_display_contact);
if (savedInstanceState == null) {
Bundle arguments = new Bundle();
arguments.putString(ARG_ID, getIntent().getStringExtra(ARG_ID));
arguments.putBoolean(ARG_DUAL_MODE, false);
FragmentDisplayContact fragment = new FragmentDisplayContact();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.display_contact_fragment, fragment)
.commit();
}
}
}
| mit |
jasonh-n-austin/pbs-api-client | src/main/java/com/paperbackswap/data/BookRequestBuilder.java | 362 | package com.paperbackswap.data;
import com.paperbackswap.exceptions.*;
import org.json.JSONObject;
public interface BookRequestBuilder {
public BookRequest construct(JSONObject source) throws InvalidBookRequestException, InvalidBooksResponseException, ResponseHasErrorsException, InvalidBookException, BookListBuilderException, InvalidResponseException;
}
| mit |
mcxtzhang/TJ-notes | src/com/mcxtzhang/algorithm/offer/Test7.java | 2948 | package com.mcxtzhang.algorithm.offer;
import java.util.Stack;
/**
* Intro: 用两个栈实现队列
* Author: zhangxutong
* E-mail: mcxtzhang@163.com
* Home Page: http://blog.csdn.net/zxt0601
* Created: 2017/6/28.
* History:
*/
public class Test7 {
public static void main(String[] args) {
/* MyQueue<Integer> integerMyQueue = new MyQueue<>();
for (int i = 0; i < 10; i++) {
integerMyQueue.appendTail(i);
}
Integer i = null;
while ((i = integerMyQueue.deleteHead()) != null && i != 5) {
System.out.println(i);
}
for (int j = 10; j < 20; j++) {
integerMyQueue.appendTail(j);
}
i = null;
while ((i = integerMyQueue.deleteHead()) != null && i != 5) {
System.out.println(i);
}*/
MyQueue2<Integer> integerMyQueue = new MyQueue2<>();
for (int i = 0; i < 10; i++) {
integerMyQueue.appendTail(i);
}
Integer i = null;
while ((i = integerMyQueue.deleteHead()) != null && i != 5) {
System.out.println(i);
}
for (int j = 10; j < 20; j++) {
integerMyQueue.appendTail(j);
}
i = null;
while ((i = integerMyQueue.deleteHead()) != null && i != 5) {
System.out.println(i);
}
}
private static class MyQueue<T> {
private Stack<T> stack1;//专门存
private Stack<T> stack2;//专门取
public MyQueue() {
stack1 = new Stack<T>();
stack2 = new Stack<T>();
}
void appendTail(T t) {
if (stack2.isEmpty()) {
stack1.push(t);
} else {
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
stack1.push(t);
}
}
T deleteHead() {
if (stack2.isEmpty() && stack1.isEmpty())
return null;
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
} else {
return stack2.pop();
}
}
}
private static class MyQueue2<T> {
private Stack<T> stack1;//专门存
private Stack<T> stack2;//专门取
public MyQueue2() {
stack1 = new Stack<T>();
stack2 = new Stack<T>();
}
void appendTail(T t) {
stack1.push(t);
}
T deleteHead() {
if (!stack2.isEmpty()) {
return stack2.pop();
} else if (!stack1.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
} else {
return null;
}
}
}
}
| mit |
EpiCanard/GlobalMarketChest | src/main/java/fr/epicanard/globalmarketchest/gui/shops/baseinterfaces/DefaultFooter.java | 2765 | package fr.epicanard.globalmarketchest.gui.shops.baseinterfaces;
import com.google.common.collect.ImmutableMap;
import fr.epicanard.globalmarketchest.GlobalMarketChest;
import fr.epicanard.globalmarketchest.gui.InventoryGUI;
import fr.epicanard.globalmarketchest.gui.TransactionKey;
import fr.epicanard.globalmarketchest.gui.actions.NewAuction;
import fr.epicanard.globalmarketchest.gui.actions.NextInterface;
import fr.epicanard.globalmarketchest.shops.ShopInfo;
import fr.epicanard.globalmarketchest.utils.ItemStackUtils;
import fr.epicanard.globalmarketchest.utils.Utils;
import org.bukkit.inventory.ItemStack;
import static fr.epicanard.globalmarketchest.utils.EconomyUtils.format;
import static fr.epicanard.globalmarketchest.utils.EconomyUtils.getMoneyOfPlayer;
import static fr.epicanard.globalmarketchest.utils.LangUtils.format;
import static fr.epicanard.globalmarketchest.permissions.Permissions.*;
public class DefaultFooter extends ShopInterface {
protected ShopInfo shopInfo;
public DefaultFooter(InventoryGUI inv) {
super(inv);
this.shopInfo = this.inv.getTransactionValue(TransactionKey.SHOP_INFO);
if (GS_CREATEAUCTION.isSetOn(this.inv.getPlayer()) || GS_SHOP_CREATEAUCTION.isSetOnWithShop(this.inv.getPlayer(), this.shopInfo.getGroup())) {
this.actions.put(53, new NewAuction());
this.togglers.get(53).set();
}
this.actions.put(46, new NextInterface("AuctionGlobalView"));
}
private void updateBalance() {
ItemStack item = this.inv.getInv().getItem(45);
ItemStackUtils.setItemStackLore(item,
Utils.toList("&3" + format(getMoneyOfPlayer(this.inv.getPlayer().getUniqueId())))
);
this.inv.getInv().setItem(45, item);
}
protected void updateAuctionNumber() {
final ItemStack item = this.inv.getInv().getItem(53);
final Integer maxAuctionNumber = this.inv.getPlayerRankProperties().getMaxAuctionByPlayer();
final ShopInfo shop = this.inv.getTransactionValue(TransactionKey.SHOP_INFO);
GlobalMarketChest.plugin.auctionManager.getAuctionNumber(shop.getGroup(), this.inv.getPlayer(), auctionNumber -> {
this.inv.getTransaction().put(TransactionKey.PLAYER_AUCTIONS, auctionNumber);
ItemStackUtils.setItemStackLore(item,
Utils.toList(format("Buttons.NewAuction.Description", ImmutableMap.of(
"auctionNumber", auctionNumber,
"maxAuctionNumber", maxAuctionNumber
)))
);
this.inv.getInv().setItem(53, item);
});
}
@Override
public void load() {
super.load();
this.updateBalance();
if (GS_CREATEAUCTION.isSetOn(this.inv.getPlayer()) || GS_SHOP_CREATEAUCTION.isSetOnWithShop(this.inv.getPlayer(), this.shopInfo.getGroup())) {
this.updateAuctionNumber();
}
}
}
| mit |
bsimpson/halcyon | clients/java/src/org/apache/commons/codec/Encoder.java | 1689 | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec;
/**
* <p>Provides the highest level of abstraction for Encoders.
* This is the sister interface of {@link Decoder}. Every implementation of
* Encoder provides this common generic interface whic allows a user to pass a
* generic Object to any Encoder implementation in the codec package.</p>
*
* @author Apache Software Foundation
* @version $Id: Encoder.java,v 1.10 2004/02/29 04:08:31 tobrien Exp $
*/
public interface Encoder {
/**
* Encodes an "Object" and returns the encoded content
* as an Object. The Objects here may just be <code>byte[]</code>
* or <code>String</code>s depending on the implementation used.
*
* @param pObject An object ot encode
*
* @return An "encoded" Object
*
* @throws EncoderException an encoder exception is
* thrown if the encoder experiences a failure
* condition during the encoding process.
*/
Object encode(Object pObject) throws EncoderException;
}
| mit |
ivayloivanof/JavaBasics | 07.JavaOOP/Homework/src/firstLevelShop/products/electronicProducts/Computer.java | 716 | package firstLevelShop.products.electronicProducts;
import firstLevelShop.AgeRestriction;
public class Computer extends ElectronicProduct {
private final int GuaranteePeriodInMonths = 24;
private final int MinPromotionalQuantity = 1000;
public Computer(String name, double price, double quantity, AgeRestriction ageRestriction) {
super(name, price, quantity, ageRestriction);
super.setGuaranteePeriod(GuaranteePeriodInMonths);
this.checkGuaranteePeriod();
}
private void checkGuaranteePeriod() {
if (super.getQuantity() > MinPromotionalQuantity) {
double newPrice = super.getPrice() * 0.95;
super.setPrice(newPrice);
}
}
}
| cc0-1.0 |
paolokoelio/CVlab | ComputerVision/src/cleanNoise/Average.java | 1175 | package cleanNoise;
import filter.IFilter;
public class Average implements IFilter {
private int[][] matrix;
public Average(int[][] matrix) {
super();
this.matrix = matrix;
}
@Override
public int[][] addFilter(int[][] image) {
this.matrix = image;
filter();
return matrix;
}
public int get3by3Avg(int[][] threeByThree) {
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum += threeByThree[i][j];
}
}
return sum/9;
}
public void filter() {
int[][] tmp = new int[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
tmp[i][j] = matrix[i][j];
}
}
for (int i = 1; i < matrix.length-1; i++) {
for (int j = 1; j < matrix[0].length-1; j++) {
tmp[i][j] = get3by3Avg(get3by3Minor(i, j));
}
}
matrix = tmp;
}
public int[][] get3by3Minor(int xC, int yC) {
int[][] minor = new int[3][3];
for (int i = xC-1, k = 0; i < 2+xC; i++, k++) {
for (int j = yC-1, p = 0; j < 2+yC; j++, p++) {
minor[k][p] = matrix[i][j];
}
}
return minor;
}
public int[][] getMatrix() {
return matrix;
}
}
| cc0-1.0 |
tavalin/openhab2-addons | addons/binding/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiActorGatewayHandler.java | 9294 | /**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.mihome.internal.handler;
import static org.openhab.binding.mihome.internal.XiaomiGatewayBindingConstants.*;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.smarthome.core.library.types.DecimalType;
import org.eclipse.smarthome.core.library.types.HSBType;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.PercentType;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.State;
import org.openhab.binding.mihome.internal.ColorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonObject;
/**
* @author Patrick Boos - Initial contribution
* @author Dieter Schmidt - Refactor & sound
*/
public class XiaomiActorGatewayHandler extends XiaomiActorBaseHandler {
private static final int COLOR_TEMPERATURE_MAX = 6500;
private static final int COLOR_TEMPERATURE_MIN = 1700;
private static final int DEFAULT_BRIGTHNESS_PCENT = 100;
private static final int DEFAULT_VOLUME_PCENT = 50;
private static final int DEFAULT_COLOR = 0xffffff;
private static final String RGB = "rgb";
private static final String ILLUMINATION = "illumination";
private static final String MID = "mid";
private static final String VOL = "vol";
private static final String JOIN_PERMISSION = "join_permission";
private static final String YES = "yes";
private static final String NO = "no";
private Integer lastBrigthness;
private Integer lastVolume;
private Integer lastColor;
private static final int INCLUSION_MODE_TIMEOUT_MILLIS = 30000;
private Timer timer;
private boolean timerIsActive;
private final Logger logger = LoggerFactory.getLogger(XiaomiActorGatewayHandler.class);
public XiaomiActorGatewayHandler(Thing thing) {
super(thing);
lastBrigthness = DEFAULT_BRIGTHNESS_PCENT;
lastVolume = DEFAULT_VOLUME_PCENT;
lastColor = DEFAULT_COLOR;
timerIsActive = false;
}
private class TimerAction extends TimerTask {
@Override
public synchronized void run() {
updateState(CHANNEL_GATEWAY_JOIN_PERMISSION, OnOffType.OFF);
timerIsActive = false;
}
}
@Override
void execute(ChannelUID channelUID, Command command) {
switch (channelUID.getId()) {
case CHANNEL_GATEWAY_JOIN_PERMISSION:
if (command instanceof OnOffType) {
if (command == OnOffType.ON) {
timer = new Timer();
timer.schedule(new TimerAction(), INCLUSION_MODE_TIMEOUT_MILLIS);
timerIsActive = true;
} else {
if (timerIsActive) {
timer.cancel();
timerIsActive = false;
}
}
getXiaomiBridgeHandler().writeToBridge(new String[] { JOIN_PERMISSION },
new Object[] { command == OnOffType.ON ? YES : NO });
return;
}
break;
case CHANNEL_BRIGHTNESS:
if (command instanceof PercentType) {
int newBright = ((PercentType) command).intValue();
if (lastBrigthness != newBright) {
lastBrigthness = newBright;
logger.debug("Set brigthness to {}", lastBrigthness);
writeBridgeLightColor(lastColor, lastBrigthness);
} else {
logger.debug("Do not send this command, value {} already set", newBright);
}
return;
} else if (command instanceof OnOffType) {
writeBridgeLightColor(lastColor, command == OnOffType.ON ? lastBrigthness : 0);
return;
}
break;
case CHANNEL_COLOR:
if (command instanceof HSBType) {
lastColor = ((HSBType) command).getRGB() & 0xffffff;
writeBridgeLightColor(lastColor, lastBrigthness);
return;
}
break;
case CHANNEL_COLOR_TEMPERATURE:
if (command instanceof PercentType) {
PercentType colorTemperature = (PercentType) command;
int kelvin = (COLOR_TEMPERATURE_MAX - COLOR_TEMPERATURE_MIN) / 100 * colorTemperature.intValue()
+ COLOR_TEMPERATURE_MIN;
int color = ColorUtil.getRGBFromK(kelvin);
writeBridgeLightColor(color, lastBrigthness);
updateState(CHANNEL_COLOR,
HSBType.fromRGB((color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff));
return;
}
break;
case CHANNEL_GATEWAY_SOUND:
if (command instanceof DecimalType) {
writeBridgeRingtone(((DecimalType) command).intValue(), lastVolume);
updateState(CHANNEL_GATEWAY_SOUND_SWITCH, OnOffType.ON);
return;
}
break;
case CHANNEL_GATEWAY_SOUND_SWITCH:
if (command instanceof OnOffType) {
if (((OnOffType) command) == OnOffType.OFF) {
stopRingtone();
}
return;
}
break;
case CHANNEL_GATEWAY_VOLUME:
if (command instanceof DecimalType) {
updateLastVolume((DecimalType) command);
}
return;
}
// Only gets here, if no condition was met
logger.warn("Can't handle command {} on channel {}", command, channelUID);
}
private void updateLastVolume(DecimalType newVolume) {
lastVolume = newVolume.intValue();
logger.debug("Changed volume to {}", lastVolume);
}
@Override
public void handleUpdate(ChannelUID channelUID, State newState) {
logger.debug("Update {} for channel {} received", newState, channelUID);
switch (channelUID.getId()) {
case CHANNEL_BRIGHTNESS:
if (newState instanceof PercentType) {
lastBrigthness = ((PercentType) newState).intValue();
}
break;
case CHANNEL_COLOR:
if (newState instanceof HSBType) {
lastColor = ((HSBType) newState).getRGB();
}
break;
case CHANNEL_GATEWAY_VOLUME:
if (newState instanceof DecimalType) {
updateLastVolume((DecimalType) newState);
}
break;
}
}
@Override
void parseReport(JsonObject data) {
parseDefault(data);
}
@Override
void parseHeartbeat(JsonObject data) {
parseDefault(data);
}
@Override
void parseReadAck(JsonObject data) {
parseDefault(data);
}
@Override
void parseWriteAck(JsonObject data) {
parseDefault(data);
}
@Override
void parseDefault(JsonObject data) {
if (data.has(RGB)) {
long rgb = data.get(RGB).getAsLong();
updateState(CHANNEL_BRIGHTNESS, new PercentType((int) (((rgb >> 24) & 0xff))));
updateState(CHANNEL_COLOR,
HSBType.fromRGB((int) (rgb >> 16) & 0xff, (int) (rgb >> 8) & 0xff, (int) rgb & 0xff));
}
if (data.has(ILLUMINATION)) {
int illu = data.get(ILLUMINATION).getAsInt();
updateState(CHANNEL_ILLUMINATION, new DecimalType(illu));
}
}
private void writeBridgeLightColor(int color, int brightness) {
long brightnessInt = brightness << 24;
writeBridgeLightColor((color & 0xffffff) | brightnessInt & 0xff000000);
}
private void writeBridgeLightColor(long color) {
getXiaomiBridgeHandler().writeToBridge(new String[] { RGB }, new Object[] { color });
}
/**
* Play ringtone on Xiaomi Gateway
* 0 - 8, 10 - 13, 20 - 29 -- ringtones that come with the system)
* > 10001 -- user-defined ringtones
*
* @param ringtoneId
*/
private void writeBridgeRingtone(int ringtoneId, int volume) {
getXiaomiBridgeHandler().writeToBridge(new String[] { MID, VOL }, new Object[] { ringtoneId, volume });
}
/**
* Stop playing ringtone on Xiaomi Gateway
* by setting "mid" parameter to 10000
*/
private void stopRingtone() {
getXiaomiBridgeHandler().writeToBridge(new String[] { MID }, new Object[] { 10000 });
}
}
| epl-1.0 |
andre-santos-pt/pandionj | pt.iscte.pandionj.semanticmodel/src/model/program/semantics/java/VariableScope.java | 71 | package model.program.semantics.java;
public class VariableScope {
}
| epl-1.0 |
jesusc/bento | tests/test-outputs/bento.sirius.tests.metamodels.output/src/metamodel_bdsl/processOutputFlowDelayProcessOutputFlow73.java | 1442 | /**
*/
package metamodel_bdsl;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>process Output Flow Delay Process Output Flow73</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link metamodel_bdsl.processOutputFlowDelayProcessOutputFlow73#getName <em>Name</em>}</li>
* </ul>
*
* @see metamodel_bdsl.Metamodel_bdslPackage#getprocessOutputFlowDelayProcessOutputFlow73()
* @model
* @generated
*/
public interface processOutputFlowDelayProcessOutputFlow73 extends BindingAttribute {
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see metamodel_bdsl.Metamodel_bdslPackage#getprocessOutputFlowDelayProcessOutputFlow73_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link metamodel_bdsl.processOutputFlowDelayProcessOutputFlow73#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
} // processOutputFlowDelayProcessOutputFlow73
| epl-1.0 |
FTSRG/mondo-collab-framework | archive/workspaceTracker/VA/ikerlanEMF/src/eu/mondo/collaboration/operationtracemodel/example/WTSpec/CtrlUnit25.java | 8512 | /**
*/
package eu.mondo.collaboration.operationtracemodel.example.WTSpec;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Ctrl Unit25</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getInput__iStatus <em>Input iStatus</em>}</li>
* <li>{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getInput__iOverloadAlarm <em>Input iOverload Alarm</em>}</li>
* <li>{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getInput__iAlarmCounter <em>Input iAlarm Counter</em>}</li>
* <li>{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getOutput__oAlarmCounter <em>Output oAlarm Counter</em>}</li>
* <li>{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getFault__fOverload <em>Fault fOverload</em>}</li>
* <li>{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getTimer__tTimer <em>Timer tTimer</em>}</li>
* <li>{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getTimer__tSyncDelay <em>Timer tSync Delay</em>}</li>
* </ul>
* </p>
*
* @see eu.mondo.collaboration.operationtracemodel.example.WTSpec.WTSpecPackage#getCtrlUnit25()
* @model
* @generated
*/
public interface CtrlUnit25 extends wtc {
/**
* Returns the value of the '<em><b>Input iStatus</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Input iStatus</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Input iStatus</em>' reference.
* @see #setInput__iStatus(WTCInput)
* @see eu.mondo.collaboration.operationtracemodel.example.WTSpec.WTSpecPackage#getCtrlUnit25_Input__iStatus()
* @model
* @generated
*/
WTCInput getInput__iStatus();
/**
* Sets the value of the '{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getInput__iStatus <em>Input iStatus</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Input iStatus</em>' reference.
* @see #getInput__iStatus()
* @generated
*/
void setInput__iStatus(WTCInput value);
/**
* Returns the value of the '<em><b>Input iOverload Alarm</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Input iOverload Alarm</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Input iOverload Alarm</em>' reference.
* @see #setInput__iOverloadAlarm(WTCInput)
* @see eu.mondo.collaboration.operationtracemodel.example.WTSpec.WTSpecPackage#getCtrlUnit25_Input__iOverloadAlarm()
* @model
* @generated
*/
WTCInput getInput__iOverloadAlarm();
/**
* Sets the value of the '{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getInput__iOverloadAlarm <em>Input iOverload Alarm</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Input iOverload Alarm</em>' reference.
* @see #getInput__iOverloadAlarm()
* @generated
*/
void setInput__iOverloadAlarm(WTCInput value);
/**
* Returns the value of the '<em><b>Input iAlarm Counter</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Input iAlarm Counter</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Input iAlarm Counter</em>' reference.
* @see #setInput__iAlarmCounter(WTCInput)
* @see eu.mondo.collaboration.operationtracemodel.example.WTSpec.WTSpecPackage#getCtrlUnit25_Input__iAlarmCounter()
* @model
* @generated
*/
WTCInput getInput__iAlarmCounter();
/**
* Sets the value of the '{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getInput__iAlarmCounter <em>Input iAlarm Counter</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Input iAlarm Counter</em>' reference.
* @see #getInput__iAlarmCounter()
* @generated
*/
void setInput__iAlarmCounter(WTCInput value);
/**
* Returns the value of the '<em><b>Output oAlarm Counter</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Output oAlarm Counter</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Output oAlarm Counter</em>' reference.
* @see #setOutput__oAlarmCounter(WTCOutput)
* @see eu.mondo.collaboration.operationtracemodel.example.WTSpec.WTSpecPackage#getCtrlUnit25_Output__oAlarmCounter()
* @model
* @generated
*/
WTCOutput getOutput__oAlarmCounter();
/**
* Sets the value of the '{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getOutput__oAlarmCounter <em>Output oAlarm Counter</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Output oAlarm Counter</em>' reference.
* @see #getOutput__oAlarmCounter()
* @generated
*/
void setOutput__oAlarmCounter(WTCOutput value);
/**
* Returns the value of the '<em><b>Fault fOverload</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Fault fOverload</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Fault fOverload</em>' reference.
* @see #setFault__fOverload(WTCFault)
* @see eu.mondo.collaboration.operationtracemodel.example.WTSpec.WTSpecPackage#getCtrlUnit25_Fault__fOverload()
* @model
* @generated
*/
WTCFault getFault__fOverload();
/**
* Sets the value of the '{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getFault__fOverload <em>Fault fOverload</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Fault fOverload</em>' reference.
* @see #getFault__fOverload()
* @generated
*/
void setFault__fOverload(WTCFault value);
/**
* Returns the value of the '<em><b>Timer tTimer</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Timer tTimer</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Timer tTimer</em>' reference.
* @see #setTimer__tTimer(WTCTimer)
* @see eu.mondo.collaboration.operationtracemodel.example.WTSpec.WTSpecPackage#getCtrlUnit25_Timer__tTimer()
* @model
* @generated
*/
WTCTimer getTimer__tTimer();
/**
* Sets the value of the '{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getTimer__tTimer <em>Timer tTimer</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Timer tTimer</em>' reference.
* @see #getTimer__tTimer()
* @generated
*/
void setTimer__tTimer(WTCTimer value);
/**
* Returns the value of the '<em><b>Timer tSync Delay</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Timer tSync Delay</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Timer tSync Delay</em>' reference.
* @see #setTimer__tSyncDelay(WTCTimer)
* @see eu.mondo.collaboration.operationtracemodel.example.WTSpec.WTSpecPackage#getCtrlUnit25_Timer__tSyncDelay()
* @model
* @generated
*/
WTCTimer getTimer__tSyncDelay();
/**
* Sets the value of the '{@link eu.mondo.collaboration.operationtracemodel.example.WTSpec.CtrlUnit25#getTimer__tSyncDelay <em>Timer tSync Delay</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Timer tSync Delay</em>' reference.
* @see #getTimer__tSyncDelay()
* @generated
*/
void setTimer__tSyncDelay(WTCTimer value);
} // CtrlUnit25
| epl-1.0 |
RodriguesJ/Atem | oldclient/Model.java | 9932 | package com.runescape.revised.client;
import com.runescape.client.revised.config.definitions.ObjectDef;
import com.runescape.client.revised.graphics.cache.FloorDecoration;
import com.runescape.client.revised.graphics.cache.InteractiveObject;
import com.runescape.client.revised.graphics.cache.WallDecoration;
import com.runescape.client.revised.packets.server.StillGraphic;
public class Model {
private void manageModelCreations(RSBuffer stream, int j)
{
if(j == 84)
{
int k = stream.readUnsignedByte();
int j3 = anInt1268 + (k >> 4 & 7);
int i6 = anInt1269 + (k & 7);
int l8 = stream.readUnsignedWord();
int k11 = stream.readUnsignedWord();
int l13 = stream.readUnsignedWord();
if(j3 >= 0 && i6 >= 0 && j3 < 104 && i6 < 104)
{
Deque class19_1 = groundArray[plane][j3][i6];
if(class19_1 != null)
{
for(Item class30_sub2_sub4_sub2_3 = (Item)class19_1.reverseGetFirst(); class30_sub2_sub4_sub2_3 != null; class30_sub2_sub4_sub2_3 = (Item)class19_1.reverseGetNext())
{
if(class30_sub2_sub4_sub2_3.ID != (l8 & 0x7fff) || class30_sub2_sub4_sub2_3.anInt1559 != k11)
continue;
class30_sub2_sub4_sub2_3.anInt1559 = l13;
break;
}
spawnGroundItem(j3, i6);
}
}
return;
}
if(j == 105)
{
int l = stream.readUnsignedByte();
int k3 = anInt1268 + (l >> 4 & 7);
int j6 = anInt1269 + (l & 7);
int i9 = stream.readUnsignedWord();
int l11 = stream.readUnsignedByte();
int i14 = l11 >> 4 & 0xf;
int i16 = l11 & 7;
if(myPlayer.smallX[0] >= k3 - i14 && myPlayer.smallX[0] <= k3 + i14 && myPlayer.smallY[0] >= j6 - i14 && myPlayer.smallY[0] <= j6 + i14 && wave_on && !lowMem && anInt1062 < 50)
{
anIntArray1207[anInt1062] = i9;
anIntArray1241[anInt1062] = i16;
anIntArray1250[anInt1062] = Sounds.anIntArray326[i9];
anInt1062++;
}
}
if(j == 215)
{
int i1 = stream.method435();
int l3 = stream.method428();
int k6 = anInt1268 + (l3 >> 4 & 7);
int j9 = anInt1269 + (l3 & 7);
int i12 = stream.method435();
int j14 = stream.readUnsignedWord();
if(k6 >= 0 && j9 >= 0 && k6 < 104 && j9 < 104 && i12 != unknownInt10)
{
Item class30_sub2_sub4_sub2_2 = new Item();
class30_sub2_sub4_sub2_2.ID = i1;
class30_sub2_sub4_sub2_2.anInt1559 = j14;
if(groundArray[plane][k6][j9] == null)
groundArray[plane][k6][j9] = new Deque();
groundArray[plane][k6][j9].insertHead(class30_sub2_sub4_sub2_2);
spawnGroundItem(k6, j9);
}
return;
}
if(j == 156)
{
int j1 = stream.method426();
int i4 = anInt1268 + (j1 >> 4 & 7);
int l6 = anInt1269 + (j1 & 7);
int k9 = stream.readUnsignedWord();
if(i4 >= 0 && l6 >= 0 && i4 < 104 && l6 < 104)
{
Deque class19 = groundArray[plane][i4][l6];
if(class19 != null)
{
for(Item item = (Item)class19.reverseGetFirst(); item != null; item = (Item)class19.reverseGetNext())
{
if(item.ID != (k9 & 0x7fff))
continue;
item.unlink();
break;
}
if(class19.reverseGetFirst() == null)
groundArray[plane][i4][l6] = null;
spawnGroundItem(i4, l6);
}
}
return;
}
if(j == 160)
{
int k1 = stream.method428();
int j4 = anInt1268 + (k1 >> 4 & 7);
int i7 = anInt1269 + (k1 & 7);
int l9 = stream.method428();
int j12 = l9 >> 2;
int k14 = l9 & 3;
int j16 = anIntArray1177[j12];
int j17 = stream.method435();
if(j4 >= 0 && i7 >= 0 && j4 < 103 && i7 < 103)
{
int j18 = intGroundArray[plane][j4][i7];
int i19 = intGroundArray[plane][j4 + 1][i7];
int l19 = intGroundArray[plane][j4 + 1][i7 + 1];
int k20 = intGroundArray[plane][j4][i7 + 1];
if(j16 == 0)
{
Wall class10 = worldController.method296(plane, j4, i7);
if(class10 != null)
{
int k21 = class10.uid >> 14 & 0x7fff;
if(j12 == 2)
{
class10.aClass30_Sub2_Sub4_278 = new GameObject(k21, 4 + k14, 2, i19, l19, j18, k20, j17, false);
class10.aClass30_Sub2_Sub4_279 = new GameObject(k21, k14 + 1 & 3, 2, i19, l19, j18, k20, j17, false);
} else
{
class10.aClass30_Sub2_Sub4_278 = new GameObject(k21, k14, j12, i19, l19, j18, k20, j17, false);
}
}
}
if(j16 == 1)
{
WallDecoration class26 = worldController.method297(j4, i7, plane);
if(class26 != null)
class26.aClass30_Sub2_Sub4_504 = new GameObject(class26.uid >> 14 & 0x7fff, 0, 4, i19, l19, j18, k20, j17, false);
}
if(j16 == 2)
{
InteractiveObject class28 = worldController.method298(j4, i7, plane);
if(j12 == 11)
j12 = 10;
if(class28 != null)
class28.aClass30_Sub2_Sub4_521 = new GameObject(class28.uid >> 14 & 0x7fff, k14, j12, i19, l19, j18, k20, j17, false);
}
if(j16 == 3)
{
FloorDecoration class49 = worldController.method299(i7, j4, plane);
if(class49 != null)
class49.aClass30_Sub2_Sub4_814 = new GameObject(class49.uid >> 14 & 0x7fff, k14, 22, i19, l19, j18, k20, j17, false);
}
}
return;
}
if(j == 147)
{
int l1 = stream.method428();
int k4 = anInt1268 + (l1 >> 4 & 7);
int j7 = anInt1269 + (l1 & 7);
int i10 = stream.readUnsignedWord();
byte byte0 = stream.method430();
int l14 = stream.method434();
byte byte1 = stream.method429();
int k17 = stream.readUnsignedWord();
int k18 = stream.method428();
int j19 = k18 >> 2;
int i20 = k18 & 3;
int l20 = anIntArray1177[j19];
byte byte2 = stream.readSignedByte();
int l21 = stream.readUnsignedWord();
byte byte3 = stream.method429();
Player player;
if(i10 == unknownInt10)
player = myPlayer;
else
player = playerArray[i10];
if(player != null)
{
ObjectDef class46 = ObjectDef.forID(l21);
int i22 = intGroundArray[plane][k4][j7];
int j22 = intGroundArray[plane][k4 + 1][j7];
int k22 = intGroundArray[plane][k4 + 1][j7 + 1];
int l22 = intGroundArray[plane][k4][j7 + 1];
Model model = class46.method578(j19, i20, i22, j22, k22, l22, -1);
if(model != null)
{
createObject(k17 + 1, -1, 0, l20, j7, 0, plane, k4, l14 + 1);
player.anInt1707 = l14 + loopCycle;
player.anInt1708 = k17 + loopCycle;
player.aModel_1714 = model;
int i23 = class46.width;
int j23 = class46.height;
if(i20 == 1 || i20 == 3)
{
i23 = class46.height;
j23 = class46.width;
}
player.anInt1711 = k4 * 128 + i23 * 64;
player.anInt1713 = j7 * 128 + j23 * 64;
player.anInt1712 = method42(plane, player.anInt1713, player.anInt1711);
if(byte2 > byte0)
{
byte byte4 = byte2;
byte2 = byte0;
byte0 = byte4;
}
if(byte3 > byte1)
{
byte byte5 = byte3;
byte3 = byte1;
byte1 = byte5;
}
player.anInt1719 = k4 + byte2;
player.anInt1721 = k4 + byte0;
player.anInt1720 = j7 + byte3;
player.anInt1722 = j7 + byte1;
}
}
}
if(j == 151)
{
int i2 = stream.method426();
int l4 = anInt1268 + (i2 >> 4 & 7);
int k7 = anInt1269 + (i2 & 7);
int j10 = stream.method434();
int k12 = stream.method428();
int i15 = k12 >> 2;
int k16 = k12 & 3;
int l17 = anIntArray1177[i15];
if(l4 >= 0 && k7 >= 0 && l4 < 104 && k7 < 104)
createObject(-1, j10, k16, l17, k7, i15, plane, l4, 0);
return;
}
if(j == 4)
{
int j2 = stream.readUnsignedByte();
int i5 = anInt1268 + (j2 >> 4 & 7);
int l7 = anInt1269 + (j2 & 7);
int k10 = stream.readUnsignedWord();
int l12 = stream.readUnsignedByte();
int j15 = stream.readUnsignedWord();
if(i5 >= 0 && l7 >= 0 && i5 < 104 && l7 < 104)
{
i5 = i5 * 128 + 64;
l7 = l7 * 128 + 64;
StillGraphic class30_sub2_sub4_sub3 = new StillGraphic(plane, loopCycle, j15, k10, method42(plane, l7, i5) - l12, l7, i5);
aClass19_1056.insertHead(class30_sub2_sub4_sub3);
}
return;
}
if(j == 44)
{
int k2 = stream.method436();
int j5 = stream.readUnsignedWord();
int i8 = stream.readUnsignedByte();
int l10 = anInt1268 + (i8 >> 4 & 7);
int i13 = anInt1269 + (i8 & 7);
if(l10 >= 0 && i13 >= 0 && l10 < 104 && i13 < 104)
{
Item class30_sub2_sub4_sub2_1 = new Item();
class30_sub2_sub4_sub2_1.ID = k2;
class30_sub2_sub4_sub2_1.anInt1559 = j5;
if(groundArray[plane][l10][i13] == null)
groundArray[plane][l10][i13] = new Deque();
groundArray[plane][l10][i13].insertHead(class30_sub2_sub4_sub2_1);
spawnGroundItem(l10, i13);
}
return;
}
if(j == 101)
{
int l2 = stream.method427();
int k5 = l2 >> 2;
int j8 = l2 & 3;
int i11 = anIntArray1177[k5];
int j13 = stream.readUnsignedByte();
int k15 = anInt1268 + (j13 >> 4 & 7);
int l16 = anInt1269 + (j13 & 7);
if(k15 >= 0 && l16 >= 0 && k15 < 104 && l16 < 104)
createObject(-1, -1, j8, i11, l16, k5, plane, k15, 0);
return;
}
if(j == 117)
{
int i3 = stream.readUnsignedByte();
int l5 = anInt1268 + (i3 >> 4 & 7);
int k8 = anInt1269 + (i3 & 7);
int j11 = l5 + stream.readSignedByte();
int k13 = k8 + stream.readSignedByte();
int l15 = stream.readSignedWord();
int i17 = stream.readUnsignedWord();
int i18 = stream.readUnsignedByte() * 4;
int l18 = stream.readUnsignedByte() * 4;
int k19 = stream.readUnsignedWord();
int j20 = stream.readUnsignedWord();
int i21 = stream.readUnsignedByte();
int j21 = stream.readUnsignedByte();
if(l5 >= 0 && k8 >= 0 && l5 < 104 && k8 < 104 && j11 >= 0 && k13 >= 0 && j11 < 104 && k13 < 104 && i17 != 65535)
{
l5 = l5 * 128 + 64;
k8 = k8 * 128 + 64;
j11 = j11 * 128 + 64;
k13 = k13 * 128 + 64;
Projectile class30_sub2_sub4_sub4 = new Projectile(i21, l18, k19 + loopCycle, j20 + loopCycle, j21, plane, method42(plane, k8, l5) - i18, k8, l5, l15, i17);
class30_sub2_sub4_sub4.method455(k19 + loopCycle, k13, method42(plane, k13, j11) - l18, j11);
aClass19_1013.insertHead(class30_sub2_sub4_sub4);
}
}
}
} | epl-1.0 |
sidlors/digital-booking | digital-booking-services/src/main/java/mx/com/cinepolis/digital/booking/service/util/RegionTOToCatalogTOTransformer.java | 910 | package mx.com.cinepolis.digital.booking.service.util;
import mx.com.cinepolis.digital.booking.commons.to.CatalogTO;
import mx.com.cinepolis.digital.booking.commons.to.RegionTO;
import org.apache.commons.collections.Transformer;
/**
* Transforms a {@link mx.com.cinepolis.digital.booking.commons.to.RegionTO} to a
* {@link mx.com.cinepolis.digital.booking.commons.to.CatalogTO}
*
* @author afuentes
*/
public class RegionTOToCatalogTOTransformer implements Transformer
{
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public Object transform( Object obj )
{
CatalogTO catalogTO = null;
if( obj instanceof RegionTO<?, ?> )
{
RegionTO<CatalogTO, CatalogTO> regionTO = (RegionTO<CatalogTO, CatalogTO>) obj;
catalogTO = new CatalogTO( regionTO.getCatalogRegion().getId(), regionTO.getCatalogRegion().getName() );
}
return catalogTO;
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/models/events/EmailAccount.java | 6570 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.events;
import org.eclipse.persistence.descriptors.RelationalDescriptor;
import org.eclipse.persistence.descriptors.DescriptorEvent;
import org.eclipse.persistence.tools.schemaframework.TableDefinition;
public class EmailAccount {
public String owner;
public String emailAddress;
public String hostName;
public Number id;
public boolean preInsertExecuted;
public boolean postInsertExecuted;
public boolean preUpdateExecuted;
public boolean postUpdateExecuted;
public boolean preDeleteExecuted;
public boolean postDeleteExecuted;
public boolean preWriteExecuted;
public boolean postWriteExecuted;
public boolean postBuildExecuted;
public boolean postRefreshExecuted;
public boolean postMergeExecuted;
public boolean postCloneExecuted;
public boolean aboutToInsertExecuted;
public boolean aboutToUpdateExecuted;
public boolean aboutToDeleteExecuted;
public EmailAccount() {
resetFlags();
}
public EmailAccount(String newEmailAddress, String newOwner, String newHostName) {
setEmailAddress(newEmailAddress);
setOwner(newOwner);
setHostName(newHostName);
resetFlags();
}
public void aboutToInsertMethod(DescriptorEvent event) {
aboutToInsertExecuted = true;
}
public void aboutToUpdateMethod(DescriptorEvent event) {
aboutToUpdateExecuted = true;
}
public void aboutToDeleteMethod(DescriptorEvent event) {
aboutToDeleteExecuted = true;
}
public static RelationalDescriptor descriptor() {
RelationalDescriptor descriptor = new RelationalDescriptor();
/* First define the class, table and descriptor properties. */
descriptor.setJavaClass(EmailAccount.class);
descriptor.setTableName("EMAILACC");
descriptor.setPrimaryKeyFieldName("ID");
descriptor.setSequenceNumberName("SEQ");
descriptor.setSequenceNumberFieldName("ID");
/* Next define the attribute mappings. */
descriptor.addDirectMapping("id", "ID");
descriptor.addDirectMapping("emailAddress", "EMAILADD");
descriptor.addDirectMapping("owner", "ACC_OWNER");
descriptor.addDirectMapping("hostName", "HOSTNAME");
return descriptor;
}
public static EmailAccount example1() {
return new EmailAccount("tedt@geocities.com", "Ted Turner", "mail.geocities.com");
}
public static EmailAccount example2() {
return new EmailAccount("billd@freemail.com", "Bill Dullmar", "mail.freemail.com");
}
public static EmailAccount example3() {
return new EmailAccount("taniad@freemail.com", "Tania Davidson", "mail.freemail.com");
}
private String getEmailAddress() {
return emailAddress;
}
private String getHostName() {
return hostName;
}
private String getOwner() {
return owner;
}
public void postBuildMethod(DescriptorEvent event) {
postBuildExecuted = true;
}
public void postCloneMethod(DescriptorEvent event) {
postCloneExecuted = true;
}
public void postDeleteMethod(DescriptorEvent event) {
postDeleteExecuted = true;
}
public void postInsertMethod(DescriptorEvent event) {
postInsertExecuted = true;
}
public void postMergeMethod(DescriptorEvent event) {
postMergeExecuted = true;
}
public void postRefreshMethod(DescriptorEvent event) {
postRefreshExecuted = true;
}
public void postUpdateMethod(DescriptorEvent event) {
postUpdateExecuted = true;
}
public void postWriteMethod(DescriptorEvent event) {
postWriteExecuted = true;
}
public void preDeleteMethod(DescriptorEvent event) {
preDeleteExecuted = true;
}
public void preInsertMethod(DescriptorEvent event) {
preInsertExecuted = true;
}
public void preUpdateMethod(DescriptorEvent event) {
preUpdateExecuted = true;
}
public void preWriteMethod(DescriptorEvent event) {
preWriteExecuted = true;
}
public void resetFlags() {
preInsertExecuted = false;
postInsertExecuted = false;
preUpdateExecuted = false;
postUpdateExecuted = false;
preDeleteExecuted = false;
postDeleteExecuted = false;
preWriteExecuted = false;
postWriteExecuted = false;
postBuildExecuted = false;
aboutToInsertExecuted = false;
aboutToUpdateExecuted = false;
aboutToDeleteExecuted = false;
postCloneExecuted = false;
postMergeExecuted = false;
postRefreshExecuted = false;
}
private void setEmailAddress(String newEmailAddress) {
emailAddress = newEmailAddress;
}
public void setHostName(String newHostName) {
hostName = newHostName;
}
private void setOwner(String newOwner) {
owner = newOwner;
}
/**
* Return a platform independant definition of the database table.
*/
public static TableDefinition tableDefinition() {
TableDefinition definition = new TableDefinition();
definition.setName("EMAILACC");
definition.addIdentityField("ID", java.math.BigDecimal.class, 15);
definition.addField("EMAILADD", String.class, 40);
definition.addField("ACC_OWNER", String.class, 20);
definition.addField("HOSTNAME", String.class, 20);
return definition;
}
public String toString() {
return "EmailAccount(" + getEmailAddress() + ")";
}
}
| epl-1.0 |
JonahSloan/3D-Game | src/rendering/shapes/Cylinder.java | 430 | package rendering.shapes;
public class Cylinder extends javafx.scene.shape.Cylinder
{
public Cylinder()
{
// TODO Auto-generated constructor stub
}
public Cylinder(double radius, double height)
{
super(radius, height);
// TODO Auto-generated constructor stub
}
public Cylinder(double radius, double height, int divisions)
{
super(radius, height, divisions);
// TODO Auto-generated constructor stub
}
}
| epl-1.0 |
eroslevi/titan.EclipsePlug-ins | org.eclipse.titanium/src/org/eclipse/titanium/metrics/implementation/BaseTestcaseMetric.java | 799 | /******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.eclipse.titanium.metrics.implementation;
import org.eclipse.titan.designer.AST.TTCN3.definitions.Def_Testcase;
import org.eclipse.titanium.metrics.TestcaseMetric;
abstract class BaseTestcaseMetric extends BaseMetric<Def_Testcase, TestcaseMetric> {
BaseTestcaseMetric(final TestcaseMetric metric) {
super(metric);
}
}
| epl-1.0 |
theanuradha/debrief | org.mwc.debrief.multipath2/src/org/mwc/debrief/multipath2/MultiPathPresenter.java | 13010 | /*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* 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.
*/
package org.mwc.debrief.multipath2;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.ui.IMemento;
import org.jfree.data.time.TimeSeries;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.debrief.multipath2.MultiPathPresenter.Display.FileHandler;
import org.mwc.debrief.multipath2.MultiPathPresenter.Display.ValueHandler;
import org.mwc.debrief.multipath2.model.MultiPathModel;
import org.mwc.debrief.multipath2.model.MultiPathModel.CalculationException;
import org.mwc.debrief.multipath2.model.MultiPathModel.DataFormatException;
import org.mwc.debrief.multipath2.model.SVP;
import org.mwc.debrief.multipath2.model.TimeDeltas;
import MWC.GenericData.WatchableList;
import MWC.TacticalData.TrackDataProvider;
import flanagan.math.Minimisation;
import flanagan.math.MinimisationFunction;
public class MultiPathPresenter
{
private static final String INTERVAL_FILE = "INTERVAL_FILE";
private static final String SVP_FILE = "SVP_FILE";
public static final int DEFAULT_DEPTH = 50;
private static final String DEPTH_VAL = "DEPTH_VAL";
/**
* UI component of multipath analysis
*
* @author ianmayo
*
*/
public static interface Display
{
/**
* interface for anybody that wants to know about files being dropped
*
* @author ianmayo
*
*/
public static interface FileHandler
{
/**
* the specified file has been dropped
*
* @param path
*/
void newFile(String path);
}
/**
* interface for anybody that wants to know about a slider being dragged
*
* @author ianmayo
*
*/
public static interface ValueHandler
{
/**
* the new value on the slider
*
* @param val
*/
void newValue(int val);
}
/**
* let someone know about a new SVP file being dropped
*
* @param handler
*/
public void addSVPListener(FileHandler handler);
/**
* let someone know about a ranges file being dropped
*
* @param handler
*/
public void addRangesListener(FileHandler handler);
/**
* let someone know about a new time-delta file being dropped
*
* @param handler
*/
public void addTimeDeltaListener(FileHandler handler);
/**
* let someone know about the drag-handle being dragged
*
* @param handler
*/
public void addDragHandler(ValueHandler handler);
/**
* see if anybody can provide tracks
*
* @return
*/
public TrackDataProvider getDataProvider();
/**
* there's a problem, show it to the user
*
* @param string
*/
public void showError(String string);
/**
* show these data series
*
* @param _measuredSeries
* @param calculated
*/
public void display(TimeSeries _measuredSeries, TimeSeries calculated);
/**
* indicate whether the slider should be enabled
*
* @param b
* yes/no
*/
public void setEnabled(boolean b);
/**
* show the SVP filename
*
* @param fName
*/
public void setSVPName(String fName);
/**
* show the interval filename
*
* @param fName
*/
public void setIntervalName(String fName);
/**
* feedback on the current slider value
*
* @param val
*/
public void setSliderText(String text);
/**
* set the value on the slider
*
* @param _curDepth
*/
public void setSliderVal(int _curDepth);
/**
* let someone listen out for the magic button being pressed
*
* @param listener
*/
public void addMagicListener(SelectionListener listener);
/** specify the upper limit for the slider
*
* @param maxDepth
*/
public void setSliderMax(int maxDepth);
};
protected final Display _display;
protected final MultiPathModel _model;
private TimeSeries _measuredSeries = null;
protected SVP _svp = null;
protected TimeDeltas _times = null;
protected String _intervalPath;
protected int _curDepth = DEFAULT_DEPTH;
protected String _svpPath;
protected ValueHandler _dragHandler;
/**
* initialise presenter
*
* @param display
* @param model
*/
public MultiPathPresenter(final Display display)
{
_display = display;
_model = new MultiPathModel();
}
protected void loadSVP(final String path)
{
try
{
// clear the path = we'll overwrite it if we're successful
_svpPath = null;
_display.setSVPName("[pending]");
_svp = new SVP();
_svp.load(path);
_svpPath = path;
// display the filename
final File file = new File(path);
final String fName = file.getName();
_display.setSVPName(fName);
// and set the depth slider max value
final double maxDepth = _svp.getMaxDepth();
_display.setSliderMax((int)maxDepth);
}
catch (final ParseException e)
{
CorePlugin.logError(Status.ERROR, "time-delta formatting problem", e);
_svp = null;
}
catch (final IOException e)
{
CorePlugin.logError(Status.ERROR, "time-delta file-read problem", e);
_svp = null;
}
catch (final DataFormatException e)
{
_display.showError("Does not look like SVP data");
}
// check if UI should be enabled
checkEnablement();
}
/**
* see if we have sufficient data to enable the display
*
*/
protected void checkEnablement()
{
if (_svpPath == null)
{
// disable it
_display.setEnabled(false);
// show error
_display.setSliderText("Waiting for SVP");
}
else if (_intervalPath == null)
{
// disable it
_display.setEnabled(false);
// show error
_display.setSliderText("Waiting for interval data");
}
else
{
// just check the init is complete
if ((_svp != null) && (_times != null))
{
// enable it
_display.setEnabled(true);
// initialise the slider
_display.setSliderVal(_curDepth);
// and give it a sensible start value
_dragHandler.newValue(_curDepth);
}
}
}
protected void disableUI()
{
}
protected TimeSeries getCalculatedProfile(final int val)
{
TimeSeries res = null;
final TrackDataProvider tv = getTracks();
// check we've actually got some tracks
if (tv != null)
{
final WatchableList primary = tv.getPrimaryTrack();
final WatchableList secondary = tv.getSecondaryTracks()[0];
if ((primary != null) && (secondary != null))
{
res = _model.getCalculatedProfileFor(primary, secondary, _svp, _times,
val);
}
}
return res;
}
protected void updateCalc(final int val)
{
// do we have our measured series?
if (_measuredSeries == null)
{
_measuredSeries = _model.getMeasuredProfileFor(_times);
}
// remember the depth
_curDepth = (int) val;
// cool, valid data
_display.setSliderText("Depth:" + val + "m");
TimeSeries calculated = null;
try
{
calculated = getCalculatedProfile(val);
}
catch (final CalculationException e)
{
final String trouble = e.getMessage();
_display.setSliderText(trouble);
}
if (calculated != null)
{
// ok, ready to plot
_display.display(_measuredSeries, calculated);
}
}
private TrackDataProvider getTracks()
{
// do we have a tote?
TrackDataProvider tv = _display.getDataProvider();
// do we only have one seconary?
if (tv == null)
{
_display
.showError("Must have a primary and a secondary track on the tote");
}
else if (tv.getPrimaryTrack() == null)
{
tv = null;
_display.showError("Needs a primary track (or location)");
}
else if (tv.getSecondaryTracks() == null)
{
tv = null;
_display.showError("Secondary track missing");
}
else if (tv.getSecondaryTracks().length == 0)
{
tv = null;
_display.showError("Secondary track missing");
}
else if (tv.getSecondaryTracks().length > 1)
{
tv = null;
_display.showError("Too many secondary tracks");
}
else if (_times == null)
{
tv = null;
_display.showError("Waiting for interval data");
}
return tv;
}
public void saveState(final IMemento memento)
{
// store the filenames
if (_svpPath != null)
memento.putString(SVP_FILE, _svpPath);
if (_intervalPath != null)
memento.putString(INTERVAL_FILE, _intervalPath);
memento.putInteger(DEPTH_VAL, _curDepth);
}
/**
* initialise ourselves from the memento
*
*/
public void init(final IMemento memento)
{
if (memento != null)
{
_svpPath = memento.getString(SVP_FILE);
_intervalPath = memento.getString(INTERVAL_FILE);
final Integer depth = memento.getInteger(DEPTH_VAL);
if (depth != null)
_curDepth = depth;
}
}
/**
* load the intervals from the supplied file
*
* @param path
*/
protected void loadIntervals(final String path)
{
try
{
// clear the path = we'll overwrite it if we're successful
_intervalPath = null;
_display.setIntervalName("[pending]");
_times = new TimeDeltas();
_times.load(path);
_intervalPath = path;
// reset the measured series
_measuredSeries = null;
// get the filename
final File file = new File(path);
final String fName = file.getName();
_display.setIntervalName(fName);
}
catch (final ParseException e)
{
CorePlugin.logError(Status.ERROR, "time-delta formatting problem", e);
_times = null;
}
catch (final IOException e)
{
CorePlugin.logError(Status.ERROR, "time-delta file-read problem", e);
_times = null;
}
catch (final DataFormatException e)
{
_display.showError("Does not look like interval data");
}
// check if UI should be enabled
checkEnablement();
}
/**
* connect the presenter to the UI component, now that it's initialised
*
*/
public void bind()
{
// setup assorted listeners
_dragHandler = new ValueHandler()
{
@Override
public void newValue(final int val)
{
updateCalc(val);
}
};
_display.addDragHandler(_dragHandler);
_display.addSVPListener(new FileHandler()
{
public void newFile(final String path)
{
loadSVP(path);
}
});
_display.addTimeDeltaListener(new FileHandler()
{
public void newFile(final String path)
{
loadIntervals(path);
}
});
_display.addMagicListener(new SelectionListener()
{
public void widgetSelected(final SelectionEvent e)
{
doMagic();
}
public void widgetDefaultSelected(final SelectionEvent e)
{
}
});
// aah, do we have any pending files?
if (_svpPath != null)
loadSVP(_svpPath);
if (_intervalPath != null)
loadIntervals(_intervalPath);
// lastly, check if we're enabled.
checkEnablement();
}
/**
* do an optimisation on the current datasets
*
*/
protected void doMagic()
{
// Create instace of class holding function to be minimised
final MinimisationFunction funct = createMiracle();
// Create instance of Minimisation
final Minimisation min = new Minimisation();
// initial estimates
final double[] start =
{ 100 };
// initial step sizes
final double[] step =
{ 60 };
// convergence tolerance
final double ftol = 1e-8;
// set the minimum depth
min.addConstraint(0, -1, 0d);
// and the maximum depth
final double maxDepth = _svp.getMaxDepth();
min.addConstraint(0, 1, maxDepth);
// Nelder and Mead minimisation procedure
min.nelderMead(funct, start, step, ftol, 500);
// get the results out
final double[] param = min.getParamValues();
final double depth = param[0];
CorePlugin.logError(Status.INFO, "Optimised multipath depth is " + depth,
null);
// fire in the minimum
updateCalc((int) depth);
_display.setSliderVal((int) depth);
}
protected MinimisationFunction createMiracle()
{
// get the tracks
final TrackDataProvider tv = getTracks();
final WatchableList primary = tv.getPrimaryTrack();
final WatchableList secondary = tv.getSecondaryTracks()[0];
return new MultiPathModel.MiracleFunction(primary, secondary, _svp, _times);
}
}
| epl-1.0 |
lttng/lttng-scope | ctfreader/src/main/java/org/eclipse/tracecompass/ctf/core/trace/CTFTrace.java | 25770 | /*******************************************************************************
* Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
*
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Khouzam - Initial API and implementation
* Alexandre Montplaisir - Initial API and implementation
* Simon Delisle - Replace LinkedList by TreeSet in callsitesByName attribute
*******************************************************************************/
package org.eclipse.tracecompass.ctf.core.trace;
import com.google.common.collect.ImmutableMap;
import org.eclipse.tracecompass.ctf.core.CTFException;
import org.eclipse.tracecompass.ctf.core.CTFStrings;
import org.eclipse.tracecompass.ctf.core.event.CTFClock;
import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
import org.eclipse.tracecompass.ctf.core.event.io.BitBuffer;
import org.eclipse.tracecompass.ctf.core.event.metadata.DeclarationScope;
import org.eclipse.tracecompass.ctf.core.event.metadata.ParseException;
import org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope;
import org.eclipse.tracecompass.ctf.core.event.scope.ILexicalScope;
import org.eclipse.tracecompass.ctf.core.event.types.*;
import org.eclipse.tracecompass.internal.ctf.core.SafeMappedByteBuffer;
import org.eclipse.tracecompass.internal.ctf.core.event.metadata.MetadataStrings;
import org.eclipse.tracecompass.internal.ctf.core.trace.CTFStream;
import org.eclipse.tracecompass.internal.ctf.core.trace.Utils;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.StandardOpenOption;
import java.util.*;
/**
* A CTF trace on the file system.
*
* Represents a trace on the filesystem. It is responsible of parsing the
* metadata, creating declarations data structures, indexing the event packets
* (in other words, all the work that can be shared between readers), but the
* actual reading of events is left to TraceReader.
*
* TODO: internalize CTFTrace and DeclarationScope
*
* @author Matthew Khouzam
* @version $Revision: 1.0 $
*/
public class CTFTrace implements IDefinitionScope {
@Override
public String toString() {
/* Only for debugging, shouldn't be externalized */
return "CTFTrace [path=" + fPath + ", major=" + fMajor + ", minor=" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ fMinor + ", uuid=" + fUuid + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* The trace directory on the filesystem.
*/
private final File fPath;
/**
* Major CTF version number
*/
private Long fMajor;
/**
* Minor CTF version number
*/
private Long fMinor;
/**
* Trace UUID
*/
private UUID fUuid;
/**
* Trace byte order
*/
private ByteOrder fByteOrder;
/**
* Packet header structure declaration
*/
private StructDeclaration fPacketHeaderDecl = null;
/**
* The clock of the trace
*/
private CTFClock fSingleClock = null;
/**
* Packet header structure definition
*
* This is only used when opening the trace files, to read the first packet
* header and see if they are valid trace files.
*/
private StructDefinition fPacketHeaderDef;
/**
* Collection of streams contained in the trace.
*/
private final Map<Long, ICTFStream> fStreams = new HashMap<>();
/**
* Collection of environment variables set by the tracer
*/
private Map<String, String> fEnvironment = new HashMap<>();
/**
* Collection of all the clocks in a system.
*/
private final Map<String, CTFClock> fClocks = new HashMap<>();
/** Handlers for the metadata files */
private static final FileFilter METADATA_FILE_FILTER = new MetadataFileFilter();
private static final Comparator<File> METADATA_COMPARATOR = new MetadataComparator();
private final DeclarationScope fScope = new DeclarationScope(null, MetadataStrings.TRACE);
// ------------------------------------------------------------------------
// Constructors
// ------------------------------------------------------------------------
/**
* Trace constructor.
*
* @param path
* Filesystem path of the trace directory
* @throws CTFException
* If no CTF trace was found at the path
*/
public CTFTrace(String path) throws CTFException {
this(new File(path));
}
/**
* Trace constructor.
*
* @param path
* Filesystem path of the trace directory.
* @throws CTFException
* If no CTF trace was found at the path
*/
public CTFTrace(File path) throws CTFException {
fPath = path;
final Metadata metadata = new Metadata(this);
/* Set up the internal containers for this trace */
if (!fPath.exists()) {
throw new CTFException("Trace (" + path.getPath() + ") doesn't exist. Deleted or moved?"); //$NON-NLS-1$ //$NON-NLS-2$
}
if (!fPath.isDirectory()) {
throw new CTFException("Path must be a valid directory"); //$NON-NLS-1$
}
/* Open and parse the metadata file */
metadata.parseFile();
init(path);
}
/**
* Streamed constructor
*/
public CTFTrace() {
fPath = null;
}
private void init(File path) throws CTFException {
/* Open all the trace files */
/* List files not called metadata and not hidden. */
File[] files = path.listFiles(METADATA_FILE_FILTER);
Arrays.sort(files, METADATA_COMPARATOR);
/* Try to open each file */
for (File streamFile : files) {
openStreamInput(streamFile);
}
/* Create their index */
for (ICTFStream stream : getStreams()) {
Set<CTFStreamInput> inputs = stream.getStreamInputs();
for (CTFStreamInput s : inputs) {
addStream(s);
}
}
}
// ------------------------------------------------------------------------
// Getters/Setters/Predicates
// ------------------------------------------------------------------------
/**
* Gets an event declaration list for a given streamID
*
* @param streamId
* The ID of the stream from which to read
* @return The list of event declarations
*/
public Collection<IEventDeclaration> getEventDeclarations(Long streamId) {
ICTFStream stream = fStreams.get(streamId);
if (stream == null) {
return null;
}
return stream.getEventDeclarations();
}
/**
* Method getStream gets the stream for a given id
*
* @param id
* Long the id of the stream
* @return Stream the stream that we need
* @since 2.0
*/
public ICTFStream getStream(Long id) {
if (id == null) {
return fStreams.get(0L);
}
return fStreams.get(id);
}
/**
* Method nbStreams gets the number of available streams
*
* @return int the number of streams
*/
public int nbStreams() {
return fStreams.size();
}
/**
* Method setMajor sets the major version of the trace (DO NOT USE)
*
* @param major
* long the major version
*/
public void setMajor(long major) {
fMajor = major;
}
/**
* Method setMinor sets the minor version of the trace (DO NOT USE)
*
* @param minor
* long the minor version
*/
public void setMinor(long minor) {
fMinor = minor;
}
/**
* Method setUUID sets the UUID of a trace
*
* @param uuid
* UUID
*/
public void setUUID(UUID uuid) {
fUuid = uuid;
}
/**
* Method setByteOrder sets the byte order
*
* @param byteOrder
* ByteOrder of the trace, can be little-endian or big-endian
*/
public void setByteOrder(ByteOrder byteOrder) {
fByteOrder = byteOrder;
}
/**
* Method setPacketHeader sets the packet header of a trace (DO NOT USE)
*
* @param packetHeader
* StructDeclaration the header in structdeclaration form
*/
public void setPacketHeader(StructDeclaration packetHeader) {
fPacketHeaderDecl = packetHeader;
}
/**
* Method majorIsSet is the major version number set?
*
* @return boolean is the major set?
*/
public boolean majorIsSet() {
return fMajor != null;
}
/**
* Method minorIsSet. is the minor version number set?
*
* @return boolean is the minor set?
*/
public boolean minorIsSet() {
return fMinor != null;
}
/**
* Method UUIDIsSet is the UUID set?
*
* @return boolean is the UUID set?
*/
public boolean uuidIsSet() {
return fUuid != null;
}
/**
* Method byteOrderIsSet is the byteorder set?
*
* @return boolean is the byteorder set?
*/
public boolean byteOrderIsSet() {
return fByteOrder != null;
}
/**
* Method packetHeaderIsSet is the packet header set?
*
* @return boolean is the packet header set?
*/
public boolean packetHeaderIsSet() {
return fPacketHeaderDecl != null;
}
/**
* Method getUUID gets the trace UUID
*
* @return UUID gets the trace UUID
*/
public UUID getUUID() {
return fUuid;
}
/**
* Method getMajor gets the trace major version
*
* @return long gets the trace major version
*/
public long getMajor() {
return fMajor;
}
/**
* Method getMinor gets the trace minor version
*
* @return long gets the trace minor version
*/
public long getMinor() {
return fMinor;
}
/**
* Method getByteOrder gets the trace byte order
*
* @return ByteOrder gets the trace byte order
*/
public final ByteOrder getByteOrder() {
return fByteOrder;
}
/**
* Method getPacketHeader gets the trace packet header
*
* @return StructDeclaration gets the trace packet header
*/
public StructDeclaration getPacketHeader() {
return fPacketHeaderDecl;
}
/**
* Method getTraceDirectory gets the trace directory
*
* @return File the path in "File" format.
*/
public File getTraceDirectory() {
return fPath;
}
/**
* Get all the streams as an iterable.
*
* @return Iterable<Stream> an iterable over streams.
*/
public Iterable<ICTFStream> getStreams() {
return fStreams.values();
}
/**
* Method getPath gets the path of the trace directory
*
* @return String the path of the trace directory, in string format.
* @see java.io.File#getPath()
*/
public String getPath() {
return (fPath != null) ? fPath.getPath() : ""; //$NON-NLS-1$
}
// ------------------------------------------------------------------------
// Operations
// ------------------------------------------------------------------------
private void addStream(CTFStreamInput s) {
/*
* add the stream
*/
ICTFStream stream = s.getStream();
fStreams.put(stream.getId(), stream);
/*
* index the trace
*/
s.setupIndex();
}
/**
* Tries to open the given file, reads the first packet header of the file
* and check its validity. This will add a file to a stream as a streaminput
*
* @param streamFile
* A trace file in the trace directory.
* must use
* @throws CTFException
* if there is a file error
*/
private ICTFStream openStreamInput(File streamFile) throws CTFException {
ByteBuffer byteBuffer;
BitBuffer streamBitBuffer;
ICTFStream stream;
if (!streamFile.canRead()) {
throw new CTFException("Unreadable file : " //$NON-NLS-1$
+ streamFile.getPath());
}
if (streamFile.length() == 0) {
return null;
}
try (FileChannel fc = FileChannel.open(streamFile.toPath(), StandardOpenOption.READ)) {
/* Map one memory page of 4 kiB */
byteBuffer = SafeMappedByteBuffer.map(fc, MapMode.READ_ONLY, 0, (int) Math.min(fc.size(), 4096L));
if (byteBuffer == null) {
throw new IllegalStateException("Failed to allocate memory"); //$NON-NLS-1$
}
/* Create a BitBuffer with this mapping and the trace byte order */
streamBitBuffer = new BitBuffer(byteBuffer, this.getByteOrder());
if (fPacketHeaderDecl != null) {
/* Read the packet header */
fPacketHeaderDef = fPacketHeaderDecl.createDefinition(this, ILexicalScope.PACKET_HEADER, streamBitBuffer);
}
} catch (IOException e) {
/* Shouldn't happen at this stage if every other check passed */
throw new CTFException(e);
}
final StructDefinition packetHeaderDef = getPacketHeaderDef();
if (packetHeaderDef != null) {
validateMagicNumber(packetHeaderDef);
validateUUID(packetHeaderDef);
/* Read the stream ID */
IDefinition streamIDDef = packetHeaderDef.lookupDefinition(MetadataStrings.STREAM_ID);
if (streamIDDef instanceof IntegerDefinition) {
/* This doubles as a null check */
long streamID = ((IntegerDefinition) streamIDDef).getValue();
stream = fStreams.get(streamID);
} else {
/* No stream_id in the packet header */
stream = getStream(null);
}
} else {
/* No packet header, we suppose there is only one stream */
stream = getStream(null);
}
if (stream == null) {
throw new CTFException("Unexpected end of stream"); //$NON-NLS-1$
}
if (!(stream instanceof CTFStream)) {
throw new CTFException("Stream is not a CTFStream, but rather a " + stream.getClass().getCanonicalName()); //$NON-NLS-1$
}
CTFStream ctfStream = (CTFStream) stream;
/*
* Create the stream input and add a reference to the streamInput in the
* stream.
*/
ctfStream.addInput(new CTFStreamInput(ctfStream, streamFile));
return ctfStream;
}
private void validateUUID(StructDefinition packetHeaderDef) throws CTFException {
IDefinition lookupDefinition = packetHeaderDef.lookupDefinition("uuid"); //$NON-NLS-1$
AbstractArrayDefinition uuidDef = (AbstractArrayDefinition) lookupDefinition;
if (uuidDef != null) {
UUID otheruuid = Utils.getUUIDfromDefinition(uuidDef);
if (!fUuid.equals(otheruuid)) {
throw new CTFException("UUID mismatch"); //$NON-NLS-1$
}
}
}
private static void validateMagicNumber(StructDefinition packetHeaderDef) throws CTFException {
IntegerDefinition magicDef = (IntegerDefinition) packetHeaderDef.lookupDefinition(CTFStrings.MAGIC);
if (magicDef != null) {
int magic = (int) magicDef.getValue();
if (magic != Utils.CTF_MAGIC) {
throw new CTFException("CTF magic mismatch"); //$NON-NLS-1$
}
}
}
// ------------------------------------------------------------------------
// IDefinitionScope
// ------------------------------------------------------------------------
/**
* @since 1.0
*/
@Override
public ILexicalScope getScopePath() {
return ILexicalScope.TRACE;
}
/**
* Looks up a definition from packet
*
* @param lookupPath
* String
* @return Definition
* @see org.eclipse.tracecompass.ctf.core.event.scope.IDefinitionScope#lookupDefinition(String)
*/
@Override
public Definition lookupDefinition(String lookupPath) {
if (lookupPath.equals(ILexicalScope.TRACE_PACKET_HEADER.getPath())) {
return getPacketHeaderDef();
}
return null;
}
// ------------------------------------------------------------------------
// Live trace reading
// ------------------------------------------------------------------------
/**
* Add a new stream file to support new streams while the trace is being
* read.
*
* @param streamFile
* the file of the stream
* @throws CTFException
* A stream had an issue being read
*/
public void addStreamFile(File streamFile) throws CTFException {
openStreamInput(streamFile);
}
/**
* Registers a new stream to the trace.
*
* @param stream
* A stream object.
* @throws ParseException
* If there was some problem reading the metadata
* @since 2.0
*/
public void addStream(ICTFStream stream) throws ParseException {
/*
* If there is already a stream without id (the null key), it must be
* the only one
*/
if (fStreams.get(null) != null) {
throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
}
/*
* If the stream we try to add has no key set, it must be the only one.
* Thus, if the streams container is not empty, it is not valid.
*/
if ((!stream.isIdSet()) && (!fStreams.isEmpty())) {
throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
}
/*
* If a stream with the same ID already exists, it is not valid.
*/
ICTFStream existingStream = fStreams.get(stream.getId());
if (existingStream != null) {
throw new ParseException("Stream id already exists"); //$NON-NLS-1$
}
/* This stream is valid and has a unique id. */
fStreams.put(stream.getId(), stream);
}
/**
* Gets the Environment variables from the trace metadata (See CTF spec)
*
* @return The environment variables in the form of an unmodifiable map
* (key, value)
*/
public Map<String, String> getEnvironment() {
return Collections.unmodifiableMap(fEnvironment);
}
/**
* Add a clock to the clock list
*
* @param nameValue
* the name of the clock (full name with scope)
* @param ctfClock
* the clock
*/
public void addClock(String nameValue, CTFClock ctfClock) {
fClocks.put(nameValue, ctfClock);
}
/**
* gets the clock with a specific name
*
* @param name
* the name of the clock.
* @return the clock
*/
public CTFClock getClock(String name) {
return fClocks.get(name);
}
/**
* gets the clock if there is only one. (this is 100% of the use cases as of
* June 2012)
*
* @return the clock
*/
public final CTFClock getClock() {
if (fSingleClock != null && fClocks.size() == 1) {
return fSingleClock;
}
if (fClocks.size() == 1) {
fSingleClock = fClocks.get(fClocks.keySet().iterator().next());
return fSingleClock;
}
return null;
}
/**
* Gets the clock offset with respect to POSIX.1 Epoch in cycles
*
* @return the clock offset with respect to POSIX.1 Epoch in cycles
*/
public final long getOffset() {
if (getClock() == null) {
return 0;
}
return fSingleClock.getClockOffset();
}
/**
* Gets the time scale in nanoseconds/cycle
*
* @return the time scale in nanoseconds/cycle
*/
private double getTimeScale() {
if (getClock() == null) {
return 1.0;
}
return fSingleClock.getClockScale();
}
/**
* Gets the current first packet start time
*
* @return the current start time
*/
public long getCurrentStartTime() {
long currentStart = Long.MAX_VALUE;
for (ICTFStream stream : fStreams.values()) {
for (CTFStreamInput si : stream.getStreamInputs()) {
currentStart = Math.min(currentStart, si.getIndex().getElement(0).getTimestampBegin());
}
}
return timestampCyclesToNanos(currentStart);
}
/**
* Gets the current last packet end time
*
* @return the current end time
*/
public long getCurrentEndTime() {
long currentEnd = Long.MIN_VALUE;
for (ICTFStream stream : fStreams.values()) {
for (CTFStreamInput si : stream.getStreamInputs()) {
currentEnd = Math.max(currentEnd, si.getTimestampEnd());
}
}
return timestampCyclesToNanos(currentEnd);
}
/**
* Does the trace need to time scale?
*
* @return if the trace is in ns or cycles.
*/
private boolean clockNeedsScale() {
if (getClock() == null) {
return false;
}
return fSingleClock.isClockScaled();
}
/**
* Gets the inverse time scale in cycles/nanosecond
*
* @return the inverse time scale in cycles/nanosecond
*/
private double getInverseTimeScale() {
if (getClock() == null) {
return 1.0;
}
return fSingleClock.getClockAntiScale();
}
/**
* Gets the clock cycles count for a specified time
*
* @param cycles
* clock cycles relative to clock offset
* @return time in nanoseconds relative to POSIX.1 Epoch
*/
public long timestampCyclesToNanos(long cycles) {
long retVal = cycles + getOffset();
/*
* this fix is since quite often the offset will be > than 53 bits and
* therefore the conversion will be lossy
*/
if (clockNeedsScale()) {
retVal = (long) (retVal * getTimeScale());
}
return retVal;
}
/**
* Gets the time for a specified clock cycle count
*
* @param nanos
* time in nanoseconds relative to POSIX.1 Epoch
* @return clock cycles relative to clock offset
*/
public long timestampNanoToCycles(long nanos) {
long retVal;
/*
* this fix is since quite often the offset will be > than 53 bits and
* therefore the conversion will be lossy
*/
if (clockNeedsScale()) {
retVal = (long) (nanos * getInverseTimeScale());
} else {
retVal = nanos;
}
return retVal - getOffset();
}
/**
* Add a new stream
*
* @param id
* the ID of the stream
* @param streamFile
* new file in the stream
* @throws CTFException
* The file must exist
*/
public void addStream(long id, File streamFile) throws CTFException {
final File file = streamFile;
if (file == null) {
throw new CTFException("cannot create a stream with no file"); //$NON-NLS-1$
}
ICTFStream stream = fStreams.get(id);
if (stream == null) {
stream = new CTFStream(this);
fStreams.put(id, stream);
}
if (stream instanceof CTFStream) {
CTFStream ctfStream = (CTFStream) stream;
ctfStream.addInput(new CTFStreamInput(stream, file));
} else {
throw new CTFException("Stream does not support adding input"); //$NON-NLS-1$
}
}
/**
* Gets the current trace scope
*
* @return the current declaration scope
*
* @since 1.1
*/
public DeclarationScope getScope() {
return fScope;
}
/**
* Gets the packet header definition (UUID, magic number and such)
*
* @return the packet header definition
*
* @since 2.0
*/
public StructDefinition getPacketHeaderDef() {
return fPacketHeaderDef;
}
/**
* Sets the environment map
*
* @param parseEnvironment
* The environment map
* @since 2.0
*/
public void setEnvironment(@NotNull Map<String, String> parseEnvironment) {
fEnvironment = ImmutableMap.copyOf(parseEnvironment);
}
}
class MetadataFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return false;
}
if (pathname.isHidden()) {
return false;
}
if (pathname.getName().equals("metadata")) { //$NON-NLS-1$
return false;
}
return true;
}
}
class MetadataComparator implements Comparator<File>, Serializable {
private static final long serialVersionUID = 1L;
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
}
| epl-1.0 |
sonatype/nexus-public | plugins/nexus-ssl-plugin/src/main/java/com/sonatype/nexus/ssl/plugin/validator/HostnameOrIpAddressValidator.java | 1409 | /*
* Sonatype Nexus (TM) Open Source Version
* Copyright (c) 2008-present Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the
* Eclipse Foundation. All other trademarks are the property of their respective owners.
*/
package com.sonatype.nexus.ssl.plugin.validator;
import javax.validation.ConstraintValidatorContext;
import org.sonatype.nexus.validation.ConstraintValidatorSupport;
import com.google.common.net.InetAddresses;
import com.google.common.net.InternetDomainName;
/**
* Hostname or IP address validator.
*
* @since 3.36
*/
public class HostnameOrIpAddressValidator
extends ConstraintValidatorSupport<HostnameOrIpAddress, String>
{
@Override
public boolean isValid(final String value, final ConstraintValidatorContext context) {
return InternetDomainName.isValid(value) || InetAddresses.isInetAddress(value);
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/page/core/com.odcgroup.page.model/src/main/java/com/odcgroup/page/model/validator/PositivePropertyBlankValidator.java | 1188 | package com.odcgroup.page.model.validator;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.runtime.Assert;
/**
* Validator for the positive integer, accept only well formed
* number greater than zero.
*
* @author can
*
*/
public class PositivePropertyBlankValidator extends AbstractPropertyValidator implements PropertyValidator {
private static String ERROR = "Number must be greater than zero!";
/**
* Returns a String if the value is not valid. Returns null if the value is
* valid or no value has been entered.
*
* @param value
* the value to be validated
* @param acceptBlank
* determines if should check value if it contains nothing
* @return the error message, or <code>null</code> indicating that the
* value is valid
*/
public String isValid(Object value) {
String result = null;
Assert.isTrue(value instanceof String);
if (StringUtils.isBlank((String) value)) {
return result;
} else {
try {
int val = Integer.parseInt((String) value);
if (val <= 0) {
result = ERROR;
}
} catch (NumberFormatException e) {
result = ERROR;
}
}
return result;
}
}
| epl-1.0 |
lbeurerkellner/n4js | plugins/org.eclipse.n4js.generator.headless/src/org/eclipse/n4js/generator/headless/logging/IHeadlessLogger.java | 1210 | /**
* Copyright (c) 2017 NumberFour AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* NumberFour AG - Initial API and implementation
*/
package org.eclipse.n4js.generator.headless.logging;
import org.eclipse.xtext.validation.Issue;
import com.google.inject.ImplementedBy;
/**
* Interface for the logger used in the headless case.
*/
@ImplementedBy(SuppressedHeadlessLogger.class)
public interface IHeadlessLogger {
/** Prints the given debug message. */
public void debug(String message);
/** Prints the given info message. */
public void info(String message);
/** Prints the given issue. */
public void issue(Issue issue);
/** Prints the given warning. */
public void warn(String message);
/** Prints the given error message. */
public void error(String message);
/**
* Indicates whether or not debug logging is enabled.
*/
public boolean isCreateDebugOutput();
/**
* Indicates whether verbose logging is enabled.
*/
public boolean isVerbose();
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.webthing/src/main/java/org/openhab/binding/webthing/internal/client/DescriptionLoader.java | 4274 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.webthing.internal.client;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jetty.client.HttpClient;
import org.openhab.binding.webthing.internal.client.dto.WebThingDescription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
/**
* Utility class to load the WebThing description (meta data). Refer https://iot.mozilla.org/wot/#web-thing-description
*
* @author Gregor Roth - Initial contribution
*/
@NonNullByDefault
public class DescriptionLoader {
private final Logger logger = LoggerFactory.getLogger(DescriptionLoader.class);
private final Gson gson = new Gson();
private final HttpClient httpClient;
/**
* constructor
*
* @param httpClient the http client to use
*/
public DescriptionLoader(HttpClient httpClient) {
this.httpClient = httpClient;
}
/**
* loads the WebThing meta data
*
* @param webthingURI the WebThing URI
* @param timeout the timeout
* @return the Webthing description
* @throws IOException if the WebThing can not be connected
*/
public WebThingDescription loadWebthingDescription(URI webthingURI, Duration timeout) throws IOException {
try {
var response = httpClient.newRequest(webthingURI).timeout(30, TimeUnit.SECONDS).accept("application/json")
.send();
if (response.getStatus() < 200 || response.getStatus() >= 300) {
throw new IOException(
"could not read resource description " + webthingURI + ". Got " + response.getStatus());
}
var body = response.getContentAsString();
var description = gson.fromJson(body, WebThingDescription.class);
if ((description != null) && (description.properties != null) && (description.properties.size() > 0)) {
if ((description.contextKeyword == null) || description.contextKeyword.trim().length() == 0) {
description.contextKeyword = "https://webthings.io/schemas";
}
var schema = description.contextKeyword.replaceFirst("/$", "").toLowerCase(Locale.US).trim();
// currently, the old and new location of the WebThings schema are supported only.
// In the future, other schemas such as http://iotschema.org/docs/full.html may be supported
if (schema.equals("https://webthings.io/schemas") || schema.equals("https://iot.mozilla.org/schemas")) {
return description;
}
logger.debug(
"WebThing {} detected with unsupported schema {} (Supported schemas are https://webthings.io/schemas and https://iot.mozilla.org/schemas)",
webthingURI, description.contextKeyword);
throw new IOException("unsupported schema (@context parameter) " + description.contextKeyword
+ " (Supported schemas are https://webthings.io/schemas and https://iot.mozilla.org/schemas)");
} else {
throw new IOException("description does not include properties");
}
} catch (ExecutionException | TimeoutException e) {
throw new IOException("error occurred by calling WebThing", e);
} catch (JsonSyntaxException se) {
throw new IOException("resource seems not to be a WebThing. Typo?");
} catch (InterruptedException ie) {
throw new IOException("resource seems not to be reachable");
}
}
}
| epl-1.0 |
lunifera/lunifera-doc | org.lunifera.doc.dsl.semantic/src/org/lunifera/doc/dsl/doccompiler/validation/ForLoopEndValidator.java | 629 | /**
*
* $Id$
*/
package org.lunifera.doc.dsl.doccompiler.validation;
import org.lunifera.doc.dsl.doccompiler.ForLoopStart;
/**
* A sample validator interface for {@link org.lunifera.doc.dsl.doccompiler.ForLoopEnd}.
* This doesn't really do anything, and it's not a real EMF artifact.
* It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code generator can be extended.
* This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false.
*/
public interface ForLoopEndValidator {
boolean validate();
boolean validateStart(ForLoopStart value);
}
| epl-1.0 |
NABUCCO/org.nabucco.framework.generator | org.nabucco.framework.generator.compiler/src/main/org/nabucco/framework/generator/compiler/transformation/java/view/common/combobox/NabuccoToJavaRcpViewComboBoxContentProviderVisitor.java | 14847 | /*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nabucco.framework.generator.compiler.transformation.java.view.common.combobox;
import org.eclipse.jdt.internal.compiler.ast.AllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.ForeachStatement;
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference;
import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.nabucco.framework.generator.compiler.constants.NabuccoJavaTemplateConstants;
import org.nabucco.framework.generator.compiler.transformation.common.annotation.NabuccoAnnotation;
import org.nabucco.framework.generator.compiler.transformation.common.annotation.NabuccoAnnotationMapper;
import org.nabucco.framework.generator.compiler.transformation.common.annotation.NabuccoAnnotationType;
import org.nabucco.framework.generator.compiler.transformation.java.common.ast.JavaAstSupport;
import org.nabucco.framework.generator.compiler.transformation.java.constants.ViewConstants;
import org.nabucco.framework.generator.compiler.transformation.java.view.NabuccoToJavaRcpViewVisitorSupport;
import org.nabucco.framework.generator.compiler.transformation.java.view.util.MappedFieldVisitor;
import org.nabucco.framework.generator.compiler.transformation.java.visitor.NabuccoToJavaVisitorContext;
import org.nabucco.framework.generator.compiler.transformation.java.visitor.NabuccoToJavaVisitorSupport;
import org.nabucco.framework.generator.compiler.transformation.util.NabuccoTransformationUtility;
import org.nabucco.framework.generator.compiler.visitor.NabuccoVisitorException;
import org.nabucco.framework.generator.parser.model.client.NabuccoClientType;
import org.nabucco.framework.generator.parser.syntaxtree.AnnotationDeclaration;
import org.nabucco.framework.generator.parser.syntaxtree.ComboBoxDeclaration;
import org.nabucco.framework.generator.parser.syntaxtree.DatatypeDeclaration;
import org.nabucco.framework.generator.parser.syntaxtree.EditViewStatement;
import org.nabucco.framework.generator.parser.syntaxtree.LabeledComboBoxDeclaration;
import org.nabucco.framework.generator.parser.syntaxtree.SearchViewStatement;
import org.nabucco.framework.mda.model.MdaModel;
import org.nabucco.framework.mda.model.java.JavaCompilationUnit;
import org.nabucco.framework.mda.model.java.JavaModel;
import org.nabucco.framework.mda.model.java.JavaModelException;
import org.nabucco.framework.mda.model.java.ast.element.JavaAstElementFactory;
import org.nabucco.framework.mda.model.java.ast.element.method.JavaAstMethodSignature;
import org.nabucco.framework.mda.model.java.ast.produce.JavaAstModelProducer;
import org.nabucco.framework.mda.template.java.JavaTemplateException;
/**
* NabuccoToJavaRcpViewComboBoxContentProviderVisitor
*
* @author Stefanie Feld, PRODYNA AG
*/
public class NabuccoToJavaRcpViewComboBoxContentProviderVisitor extends NabuccoToJavaVisitorSupport implements
NabuccoJavaTemplateConstants, ViewConstants {
/**
* the annotation declaration of the view.
*/
private AnnotationDeclaration viewAnnotationDeclaration;
/**
* the name of the view.
*/
private String viewName;
/**
* The reference of the NabuccoToJavaRcpViewVisitorSupport.
*/
private NabuccoToJavaRcpViewVisitorSupport util;
/**
* The key for the referenced field of the combo box.
*/
private String referencedFieldTypeKey;
/**
* The method signature for "getElements".
*/
private final JavaAstMethodSignature signature = new JavaAstMethodSignature(ViewConstants.GET_ELEMENTS,
ViewConstants.OBJECT);
/**
* Creates a new {@link NabuccoToJavaRcpViewComboBoxContentProviderVisitor} instance.
*
* @param visitorContext
* the context of the visitor.
* @param viewName
* the name of the view from which the constructor is called.
* @param annotationDeclaration
* the annotationDeclaration of the view from which the constructor is called.
* @param nabuccoEditView
* the edit view from which the constructor is called.
*/
public NabuccoToJavaRcpViewComboBoxContentProviderVisitor(NabuccoToJavaVisitorContext visitorContext,
String viewName, AnnotationDeclaration annotationDeclaration, EditViewStatement nabuccoEditView) {
super(visitorContext);
this.viewName = viewName;
this.viewAnnotationDeclaration = annotationDeclaration;
this.util = new NabuccoToJavaRcpViewVisitorSupport(this.getVisitorContext());
MappedFieldVisitor mappedFieldVisitor = new MappedFieldVisitor();
nabuccoEditView.accept(mappedFieldVisitor);
this.util.setMappedFieldsInUse((mappedFieldVisitor.getMappedFields()));
}
/**
* Constructor to create a new instance of NabuccoToJavaRcpViewComboBoxContentProviderVisitor.
*
* @param visitorContext
* the context of the visitor.
* @param viewName
* the name of the view from which the constructor is called.
* @param annotationDeclaration
* the annotationDeclaration of the view from which the constructor is called.
* @param nabuccoSearchView
* the search view from which the constructor is called.
*/
public NabuccoToJavaRcpViewComboBoxContentProviderVisitor(NabuccoToJavaVisitorContext visitorContext,
String viewName, AnnotationDeclaration annotationDeclaration, SearchViewStatement nabuccoSearchView) {
super(visitorContext);
this.viewName = viewName;
this.viewAnnotationDeclaration = annotationDeclaration;
this.util = new NabuccoToJavaRcpViewVisitorSupport(this.getVisitorContext());
MappedFieldVisitor mappedFieldVisitor = new MappedFieldVisitor();
nabuccoSearchView.accept(mappedFieldVisitor);
this.util.setMappedFieldsInUse((mappedFieldVisitor.getMappedFields()));
}
@Override
public void visit(DatatypeDeclaration datatypeDeclaration, MdaModel<JavaModel> target) {
util.createMappingInformation(datatypeDeclaration, getVisitorContext());
}
@Override
public void visit(LabeledComboBoxDeclaration labeledComboBox, MdaModel<JavaModel> target) {
AnnotationDeclaration annotationDeclaration = labeledComboBox.annotationDeclaration;
String comboBoxName = labeledComboBox.nodeToken2.tokenImage;
this.createComboBoxContentProvider(target, annotationDeclaration, comboBoxName);
}
@Override
public void visit(ComboBoxDeclaration comboBox, MdaModel<JavaModel> target) {
AnnotationDeclaration annotationDeclaration = comboBox.annotationDeclaration;
String comboBoxName = comboBox.nodeToken2.tokenImage;
this.createComboBoxContentProvider(target, annotationDeclaration, comboBoxName);
}
/**
* Creates a content provider for a combo box.
*
* @param target
* the target mda model.
* @param annotationDeclaration
* the annotation declaration of the combo box.
* @param comboBoxName
* the name of the combo box.
*/
private void createComboBoxContentProvider(MdaModel<JavaModel> target, AnnotationDeclaration annotationDeclaration,
String comboBoxName) {
JavaAstElementFactory javaFactory = JavaAstElementFactory.getInstance();
String name = viewName
+ NabuccoTransformationUtility.firstToUpper(comboBoxName) + ViewConstants.CONTENT_PROVIDER;
String pkg = super.getVisitorContext().getPackage().replace(ViewConstants.UI, ViewConstants.UI_RCP)
+ ViewConstants.PKG_SEPARATOR + ViewConstants.VIEW_PACKAGE;
String projectName = super.getComponentName(NabuccoClientType.RCP);
try {
JavaCompilationUnit unit = super.extractAst(COMMON_VIEW_COMBO_BOX_CONTENT_PROVIDER_TEMPLATE);
TypeDeclaration type = unit.getType(COMMON_VIEW_COMBO_BOX_CONTENT_PROVIDER_TEMPLATE);
javaFactory.getJavaAstType().setTypeName(type, name);
javaFactory.getJavaAstUnit().setPackage(unit.getUnitDeclaration(), pkg);
// change method getElements(Object arg0)
this.changeGetElements(annotationDeclaration, type);
// JavaDocAnnotations
JavaAstSupport.convertJavadocAnnotations(annotationDeclaration, type);
// addImport
this.addImports(unit);
JavaAstSupport.convertAstNodes(unit, getVisitorContext().getContainerList(), getVisitorContext()
.getImportList());
// Annotations
JavaAstSupport.convertJavadocAnnotations(viewAnnotationDeclaration, type);
unit.setProjectName(projectName);
unit.setSourceFolder(super.getSourceFolder());
target.getModel().getUnitList().add(unit);
} catch (JavaModelException jme) {
throw new NabuccoVisitorException(
"Error during Java AST editview combo box content provider modification.", jme);
} catch (JavaTemplateException te) {
throw new NabuccoVisitorException(
"Error during Java template editview combo box content provider processing.", te);
}
}
/**
* Adds all imports to the unit.
*
* @param unit
* the java compilation unit where all imports are added to.
* @throws JavaModelException
* if an error occurred transforming the model.
*/
private void addImports(JavaCompilationUnit unit) throws JavaModelException {
JavaAstElementFactory javaFactory = JavaAstElementFactory.getInstance();
if (this.util.getFieldNameToTypeReference().get(BASETYPE) != null
&& this.util.getFieldNameToTypeReference().get(BASETYPE).containsKey(referencedFieldTypeKey)) {
for (String importReferenceString : this.util.getFieldNameToTypeReference().get(BASETYPE)
.get(referencedFieldTypeKey).getImports()) {
ImportReference importReference = JavaAstModelProducer.getInstance().createImportReference(
importReferenceString);
javaFactory.getJavaAstUnit().addImport(unit.getUnitDeclaration(), importReference);
}
} else if (this.util.getFieldNameToTypeReference().get(ENUMERATION) != null
&& this.util.getFieldNameToTypeReference().get(ENUMERATION).containsKey(referencedFieldTypeKey)) {
for (String importReferenceString : this.util.getFieldNameToTypeReference().get(ENUMERATION)
.get(referencedFieldTypeKey).getImports()) {
ImportReference importReference = JavaAstModelProducer.getInstance().createImportReference(
importReferenceString);
javaFactory.getJavaAstUnit().addImport(unit.getUnitDeclaration(), importReference);
}
}
}
/**
* Changes the method getElements().
*
* @param annotationDeclaration
* the annotation declaration of the combo box.
* @param type
* the type declaration.
* @throws JavaModelException
* if an error occurred transforming the model.
*/
private void changeGetElements(AnnotationDeclaration annotationDeclaration, TypeDeclaration type)
throws JavaModelException {
JavaAstElementFactory javaFactory = JavaAstElementFactory.getInstance();
// mappedField
NabuccoAnnotation mappedFieldAnn = NabuccoAnnotationMapper.getInstance().mapToAnnotation(annotationDeclaration,
NabuccoAnnotationType.MAPPED_FIELD);
String mappedField = mappedFieldAnn == null ? null : mappedFieldAnn.getValue();
String[] accessPath = mappedField.split(ViewConstants.FIELD_SEPARATOR);
String localField = accessPath[0];
this.referencedFieldTypeKey = accessPath[1];
SingleTypeReference typeReference;
if (this.util.getFieldNameToFieldTypeProperties().get(localField).get(BASETYPE) != null
&& this.util.getFieldNameToFieldTypeProperties().get(localField).get(BASETYPE)
.containsKey(this.referencedFieldTypeKey)) {
typeReference = (SingleTypeReference) this.util.getFieldNameToFieldTypeProperties().get(localField)
.get(BASETYPE).get(this.referencedFieldTypeKey).getAstNode();
} else if (this.util.getFieldNameToFieldTypeProperties().get(localField).get(ENUMERATION) != null
&& this.util.getFieldNameToFieldTypeProperties().get(localField).get(ENUMERATION)
.containsKey(this.referencedFieldTypeKey)) {
typeReference = (SingleTypeReference) this.util.getFieldNameToFieldTypeProperties().get(localField)
.get(ENUMERATION).get(this.referencedFieldTypeKey).getAstNode();
} else {
throw new NabuccoVisitorException("Used MappedField \""
+ referencedFieldTypeKey + "\" is no Basetype or Enumeration.");
}
// select the method getElements(Object arg0)
MethodDeclaration methodGetElements = (MethodDeclaration) javaFactory.getJavaAstType().getMethod(type,
this.signature);
((ParameterizedSingleTypeReference) ((LocalDeclaration) methodGetElements.statements[0]).type).typeArguments[0] = typeReference;
((ParameterizedSingleTypeReference) ((AllocationExpression) ((LocalDeclaration) methodGetElements.statements[0]).initialization).type).typeArguments[0] = typeReference;
((ForeachStatement) methodGetElements.statements[1]).elementVariable.type = typeReference;
((ForeachStatement) methodGetElements.statements[1]).collection = JavaAstModelProducer.getInstance()
.createMessageSend(ViewConstants.VALUES, typeReference, null);
}
}
| epl-1.0 |
scmod/nexus-public | components/nexus-core/src/main/java/org/sonatype/nexus/proxy/maven/metadata/operations/PluginOperand.java | 1403 | /*
* Sonatype Nexus (TM) Open Source Version
* Copyright (c) 2008-present Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the
* Eclipse Foundation. All other trademarks are the property of their respective owners.
*/
package org.sonatype.nexus.proxy.maven.metadata.operations;
import org.sonatype.nexus.proxy.maven.metadata.operations.ModelVersionUtility.Version;
import org.apache.maven.artifact.repository.metadata.Plugin;
/**
* Plugin storage
*
* @author Oleg Gusakov
* @version $Id: PluginOperand.java 726701 2008-12-15 14:31:34Z hboutemy $
*/
public class PluginOperand
extends AbstractOperand
{
private final Plugin plugin;
public PluginOperand(final Version originModelVersion, final Plugin data) {
super(originModelVersion);
this.plugin = data;
}
public Plugin getOperand() {
return plugin;
}
}
| epl-1.0 |
jesusc/bento | tests/test-outputs/bento.sirius.tests.metamodels.output/src/metamodel_bdsl/processOutputFlowStorage23.java | 1334 | /**
*/
package metamodel_bdsl;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>process Output Flow Storage23</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link metamodel_bdsl.processOutputFlowStorage23#getName <em>Name</em>}</li>
* </ul>
*
* @see metamodel_bdsl.Metamodel_bdslPackage#getprocessOutputFlowStorage23()
* @model
* @generated
*/
public interface processOutputFlowStorage23 extends BindingAttribute {
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see metamodel_bdsl.Metamodel_bdslPackage#getprocessOutputFlowStorage23_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link metamodel_bdsl.processOutputFlowStorage23#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
} // processOutputFlowStorage23
| epl-1.0 |
jesusc/bento | webrepo/bento.repository.rest/src/bento/repository/actions/ComponentGET.java | 1080 | package bento.repository.actions;
import javax.servlet.ServletOutputStream;
import spark.Request;
import spark.Response;
import spark.utils.IOUtils;
/**
* Look up a component in the database, returning it...
*
* @author jesus
*/
public class ComponentGET extends AbstractAction {
@Override
public Object handle(Request request, Response response) throws Exception {
String name = request.params("name");
if ( ! db().existsComponent(name) ) {
return requestInvalid(response, "Component not exists");
}
db().retrieveComponent(name, (is) -> {
response.type("application/binary");
ServletOutputStream os;
try {
os = response.raw().getOutputStream();
org.apache.commons.io.IOUtils.copy(is, os);
os.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
/*
try {
byte array[] = IOUtils.toByteArray(is);
response.body(String.valueOf(array));
} catch (Exception e) {
e.printStackTrace();
return false;
}
*/
return true;
});
return requestOk(response, null);
}
}
| epl-1.0 |
bradsdavis/cxml-api | src/main/java/org/cxml/v12028/XadesCommitmentTypeQualifiers.java | 2016 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.09.23 at 10:57:51 AM CEST
//
package org.cxml.v12028;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"xadesCommitmentTypeQualifier"
})
@XmlRootElement(name = "xades:CommitmentTypeQualifiers")
public class XadesCommitmentTypeQualifiers {
@XmlElement(name = "xades:CommitmentTypeQualifier")
protected List<XadesCommitmentTypeQualifier> xadesCommitmentTypeQualifier;
/**
* Gets the value of the xadesCommitmentTypeQualifier property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the xadesCommitmentTypeQualifier property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getXadesCommitmentTypeQualifier().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link XadesCommitmentTypeQualifier }
*
*
*/
public List<XadesCommitmentTypeQualifier> getXadesCommitmentTypeQualifier() {
if (xadesCommitmentTypeQualifier == null) {
xadesCommitmentTypeQualifier = new ArrayList<XadesCommitmentTypeQualifier>();
}
return this.xadesCommitmentTypeQualifier;
}
}
| epl-1.0 |
ibm-messaging/mq-mft | mft.azconnect/src/mft/azconnect/AzConnectStorage.java | 1780 | /**
* Copyright (c) IBM Corporation 2018
* 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
* Contributors:
* Shashikanth Rao T - Initial Contribution
*
***************************************************************************
*/
package mft.azconnect;
import com.microsoft.azure.storage.StorageException;
import com.microsoft.azure.storage.blob.BlobInputStream;
import com.microsoft.azure.storage.blob.BlobOutputStream;
import com.microsoft.azure.storage.blob.CloudBlobDirectory;
/**
* @author shashikanth
*
*/
public abstract class AzConnectStorage {
private int azStorageType = 0;
public AzConnectStorage(final int type) {
this.azStorageType = type;
}
protected int getType() {
return azStorageType;
}
protected CloudBlobDirectory getParent(){return null;}
protected void delete() throws StorageException {}
protected boolean exists() throws StorageException {return false;}
protected long getLastModifiedTime() {
return 0;
}
protected BlobOutputStream openOutputStream() throws StorageException {
return null;
}
protected BlobInputStream openInputStream() throws StorageException {
return null;
}
protected long getSize() {
return 0;
}
protected String getName() {
return null;
}
protected void renameTo(final String newPath){}
protected String getBlobName() {return null;}
}
| epl-1.0 |
RodriguesJ/Atem | src/com/runescape/client/revised/packets/server/OneFourtySeven.java | 86 | package com.runescape.client.revised.packets.server;
public class OneFourtySeven {
} | epl-1.0 |
boniatillo-com/PhaserEditor | source/phasereditor/phasereditor.canvas.ui/src/phasereditor/canvas/ui/search/SearchPrefabResult.java | 2968 | // The MIT License (MIT)
//
// Copyright (c) 2015, 2017 Arian Fornaris
//
// 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 phasereditor.canvas.ui.search;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.search.ui.ISearchQuery;
import org.eclipse.search.ui.ISearchResult;
import org.eclipse.search.ui.ISearchResultListener;
import phasereditor.canvas.ui.CanvasUI.FindPrefabReferencesResult;
import phasereditor.ui.EditorSharedImages;
import phasereditor.ui.IEditorSharedImages;
/**
* @author arian
*
*/
public class SearchPrefabResult implements ISearchResult {
private ListenerList<ISearchResultListener> _listeners;
private SearchPrefabQuery _query;
private FindPrefabReferencesResult _references;
public SearchPrefabResult(SearchPrefabQuery query) {
_listeners = new ListenerList<>();
_query = query;
_references = new FindPrefabReferencesResult();
}
public FindPrefabReferencesResult getReferences() {
return _references;
}
public void setReferences(FindPrefabReferencesResult references) {
_references = references;
SearchPrefabResultEvent e = new SearchPrefabResultEvent(this);
for (ISearchResultListener l : _listeners) {
l.searchResultChanged(e);
}
}
@Override
public void addListener(ISearchResultListener l) {
_listeners.add(l);
}
@Override
public void removeListener(ISearchResultListener l) {
_listeners.remove(l);
}
@Override
public String getLabel() {
return "'" + _query.getPrefab().getFile().getName() + "' - found " + _references.getTotalReferences() + " instances in "
+ _references.getTotalFiles() + " files.";
}
@Override
public String getTooltip() {
return getLabel();
}
@Override
public ImageDescriptor getImageDescriptor() {
return EditorSharedImages.getImageDescriptor(IEditorSharedImages.IMG_CANVAS);
}
@Override
public ISearchQuery getQuery() {
return _query;
}
}
| epl-1.0 |
sifeier/One | app/src/main/java/com/one/util/SerializeCallback.java | 198 | package com.one.util;
/**
* 序列化回调,这里的回调不一定是在UI线程
*/
public interface SerializeCallback {
public void onComplete(Object data);
public void onFailed();
} | epl-1.0 |
debabratahazra/DS | designstudio/components/edge/ui/com.odcgroup.edge.t24ui.model.ui/src/main/java/com/odcgroup/edge/t24ui/model/ui/action/NewCOSUtil.java | 5186 | package com.odcgroup.edge.t24ui.model.ui.action;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.ContainerGenerator;
import org.eclipse.ui.part.FileEditorInput;
import com.odcgroup.edge.t24ui.CompositeScreen;
import com.odcgroup.edge.t24ui.T24UIFactory;
public class NewCOSUtil {
/**
* @param fileName
* @param containerpath
* @return
*/
public static IFile createNewFile(String fileName, IPath containerpath) {
// create the new file and cache it if successful
final IPath containerPath = containerpath;
IPath newFilePath = containerPath.append(fileName);
final IFile newFileHandle = createFileHandle(newFilePath);
final InputStream initialContents = null;
IWorkbenchWindow container = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
protected void execute(IProgressMonitor monitor)
throws CoreException {
try {
monitor.beginTask("Creating New Item", 2000);
ContainerGenerator generator = new ContainerGenerator(containerPath);
generator.generateContainer(new SubProgressMonitor(monitor, 1000));
createFile(newFileHandle, initialContents, new SubProgressMonitor(monitor, 1000));
} finally {
monitor.done();
}
}
};
try {
container.run(true, true, op);
} catch (InterruptedException e) {
return null;
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof CoreException) {
ErrorDialog.openError(container.getShell(),
"New Item Error", null,
((CoreException) e.getTargetException()).getStatus());
} else {
// CoreExceptions are handled above, but unexpected runtime
// exceptions and errors may still occur.
MessageDialog.openError(container.getShell(),
"New Item Error", "Error creating / opening the file: "
+ e.getTargetException().getMessage());
}
return null;
}
return newFileHandle;
}
/**
* @return
*/
public static CompositeScreen createInitialModel() {
CompositeScreen root = T24UIFactory.eINSTANCE.createCompositeScreen();
root.setName("CompositeScreen");
return root;
}
/**
* @param filePath
* @return
*/
private static IFile createFileHandle(IPath filePath) {
return ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
}
/**
* @param fileHandle
* @param contents
* @param monitor
* @throws CoreException
*/
public static void createFile(IFile fileHandle, InputStream contents,
IProgressMonitor monitor) throws CoreException {
if (contents == null) {
contents = new ByteArrayInputStream(new byte[0]);
}
try {
IPath path = fileHandle.getFullPath();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
int numSegments = path.segmentCount();
if (numSegments > 2
&& !root.getFolder(path.removeLastSegments(1)).exists()) {
// If the direct parent of the path doesn't exist, try to create
// the
// necessary directories.
for (int i = numSegments - 2; i > 0; i--) {
IFolder folder = root.getFolder(path.removeLastSegments(i));
if (!folder.exists()) {
folder.create(false, true, monitor);
}
}
}
fileHandle.create(contents, false, monitor);
} catch (CoreException e) {
// If the file already existed locally, just refresh to get contents
if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED) {
fileHandle.refreshLocal(IResource.DEPTH_ZERO, null);
} else {
throw e;
}
}
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
}
/**
* @param file
* @throws PartInitException
*/
public static void openEditor(IFile file) throws PartInitException {
if (PlatformUI.getWorkbench()!=null && PlatformUI.getWorkbench().getActiveWorkbenchWindow()!=null
&& PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()!=null) {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(file.getName());
page.openEditor(new FileEditorInput(file), desc.getId());
}
}
}
| epl-1.0 |
tavalin/openhab2-addons | addons/binding/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/handler/SomfyTahomaHeatingSystemHandler.java | 2083 | /**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.somfytahoma.handler;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.RefreshType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import static org.openhab.binding.somfytahoma.SomfyTahomaBindingConstants.*;
/**
* The {@link SomfyTahomaHeatingSystemHandler} is responsible for handling commands,
* which are sent to one of the channels of the heating system thing.
*
* @author Ondrej Pecta - Initial contribution
*/
public class SomfyTahomaHeatingSystemHandler extends SomfyTahomaBaseThingHandler {
private final Logger logger = LoggerFactory.getLogger(SomfyTahomaHeatingSystemHandler.class);
public SomfyTahomaHeatingSystemHandler(Thing thing) {
super(thing);
stateNames = new HashMap<String, String>() {
{
put(TARGET_TEMPERATURE, "core:TargetTemperatureState");
put(CURRENT_TEMPERATURE, "zwave:SetPointHeatingValueState");
put(BATTERY_LEVEL, "core:BatteryLevelState");
put(CURRENT_STATE, "zwave:SetPointTypeState");
}
};
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
logger.debug("Received command {} for channel {}", command, channelUID);
if (RefreshType.REFRESH.equals(command)) {
updateChannelState(channelUID);
} else {
if (TARGET_TEMPERATURE.equals(channelUID.getId())) {
String param = "[" + command.toString() + "]";
sendCommand("setTargetTemperature", param);
}
}
}
}
| epl-1.0 |
zsmartsystems/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee/src/test/java/com/zsmartsystems/zigbee/zcl/clusters/iaszone/ZoneStatusChangeNotificationCommandTest.java | 1504 | /**
* Copyright (c) 2016-2022 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.zsmartsystems.zigbee.zcl.clusters.iaszone;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.zsmartsystems.zigbee.CommandTest;
import com.zsmartsystems.zigbee.serialization.DefaultDeserializer;
import com.zsmartsystems.zigbee.zcl.ZclFieldDeserializer;
import com.zsmartsystems.zigbee.zcl.ZclHeader;
/**
*
* @author Chris Jackson
*
*/
public class ZoneStatusChangeNotificationCommandTest extends CommandTest {
@Test
public void test() {
int[] packet = getPacketData("09 7B 00 24 00 00 00 00 00");
ZoneStatusChangeNotificationCommand command = new ZoneStatusChangeNotificationCommand(null, null, null, null);
DefaultDeserializer deserializer = new DefaultDeserializer(packet);
ZclFieldDeserializer fieldDeserializer = new ZclFieldDeserializer(deserializer);
ZclHeader zclHeader = new ZclHeader(fieldDeserializer);
System.out.println(zclHeader);
command.deserialize(fieldDeserializer);
System.out.println(command);
assertEquals(Integer.valueOf(0x500), command.getClusterId());
assertEquals(Integer.valueOf(36), command.getZoneStatus());
}
}
| epl-1.0 |
aryantaheri/controller | opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/CodecRegistryProvider.java | 1992 | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.config.manager.impl.osgi.mapping;
import javassist.ClassPool;
import org.opendaylight.controller.config.manager.impl.util.OsgiRegistrationUtil;
import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.osgi.framework.BundleContext;
/**
* Creates and initializes {@link RuntimeGeneratedMappingServiceImpl}, which is used to get {@link CodecRegistry}.
* Also maintains service registrations of {@link RuntimeGeneratedMappingServiceImpl}.
*/
// TODO move to yang runtime
public class CodecRegistryProvider implements AutoCloseable {
private static final ClassPool CLASS_POOL = ClassPool.getDefault();
private final RuntimeGeneratedMappingServiceImpl service;
private final AutoCloseable registration;
public CodecRegistryProvider(final ClassLoadingStrategy classLoadingStrategy, final BundleContext context) {
service = new RuntimeGeneratedMappingServiceImpl(CLASS_POOL, classLoadingStrategy);
registration = OsgiRegistrationUtil.registerService(context, service,
SchemaContextListener.class, BindingIndependentMappingService.class);
}
public CodecRegistry getCodecRegistry() {
return service.getCodecRegistry();
}
@Override
public void close() throws Exception {
registration.close();
}
}
| epl-1.0 |
niksavis/mm-dsl | org.xtext.nv.dsl/src-gen/org/xtext/nv/dsl/mMDSL/impl/RelationImpl.java | 15427 | /**
*/
package org.xtext.nv.dsl.mMDSL.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.xtext.nv.dsl.mMDSL.Attribute;
import org.xtext.nv.dsl.mMDSL.InsertEmbedCode;
import org.xtext.nv.dsl.mMDSL.MMDSLPackage;
import org.xtext.nv.dsl.mMDSL.Relation;
import org.xtext.nv.dsl.mMDSL.SymbolRelation;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Relation</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.xtext.nv.dsl.mMDSL.impl.RelationImpl#getName <em>Name</em>}</li>
* <li>{@link org.xtext.nv.dsl.mMDSL.impl.RelationImpl#getParentrelationname <em>Parentrelationname</em>}</li>
* <li>{@link org.xtext.nv.dsl.mMDSL.impl.RelationImpl#getSymbolrelation <em>Symbolrelation</em>}</li>
* <li>{@link org.xtext.nv.dsl.mMDSL.impl.RelationImpl#getFromclassname <em>Fromclassname</em>}</li>
* <li>{@link org.xtext.nv.dsl.mMDSL.impl.RelationImpl#getToclassname <em>Toclassname</em>}</li>
* <li>{@link org.xtext.nv.dsl.mMDSL.impl.RelationImpl#getAttribute <em>Attribute</em>}</li>
* <li>{@link org.xtext.nv.dsl.mMDSL.impl.RelationImpl#getInsertembedcode <em>Insertembedcode</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class RelationImpl extends MinimalEObjectImpl.Container implements Relation
{
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getParentrelationname() <em>Parentrelationname</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParentrelationname()
* @generated
* @ordered
*/
protected Relation parentrelationname;
/**
* The cached value of the '{@link #getSymbolrelation() <em>Symbolrelation</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSymbolrelation()
* @generated
* @ordered
*/
protected SymbolRelation symbolrelation;
/**
* The cached value of the '{@link #getFromclassname() <em>Fromclassname</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFromclassname()
* @generated
* @ordered
*/
protected org.xtext.nv.dsl.mMDSL.Class fromclassname;
/**
* The cached value of the '{@link #getToclassname() <em>Toclassname</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getToclassname()
* @generated
* @ordered
*/
protected org.xtext.nv.dsl.mMDSL.Class toclassname;
/**
* The cached value of the '{@link #getAttribute() <em>Attribute</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAttribute()
* @generated
* @ordered
*/
protected EList<Attribute> attribute;
/**
* The cached value of the '{@link #getInsertembedcode() <em>Insertembedcode</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getInsertembedcode()
* @generated
* @ordered
*/
protected EList<InsertEmbedCode> insertembedcode;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected RelationImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return MMDSLPackage.eINSTANCE.getRelation();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName()
{
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName)
{
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MMDSLPackage.RELATION__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Relation getParentrelationname()
{
if (parentrelationname != null && parentrelationname.eIsProxy())
{
InternalEObject oldParentrelationname = (InternalEObject)parentrelationname;
parentrelationname = (Relation)eResolveProxy(oldParentrelationname);
if (parentrelationname != oldParentrelationname)
{
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MMDSLPackage.RELATION__PARENTRELATIONNAME, oldParentrelationname, parentrelationname));
}
}
return parentrelationname;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Relation basicGetParentrelationname()
{
return parentrelationname;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParentrelationname(Relation newParentrelationname)
{
Relation oldParentrelationname = parentrelationname;
parentrelationname = newParentrelationname;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MMDSLPackage.RELATION__PARENTRELATIONNAME, oldParentrelationname, parentrelationname));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SymbolRelation getSymbolrelation()
{
if (symbolrelation != null && symbolrelation.eIsProxy())
{
InternalEObject oldSymbolrelation = (InternalEObject)symbolrelation;
symbolrelation = (SymbolRelation)eResolveProxy(oldSymbolrelation);
if (symbolrelation != oldSymbolrelation)
{
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MMDSLPackage.RELATION__SYMBOLRELATION, oldSymbolrelation, symbolrelation));
}
}
return symbolrelation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SymbolRelation basicGetSymbolrelation()
{
return symbolrelation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSymbolrelation(SymbolRelation newSymbolrelation)
{
SymbolRelation oldSymbolrelation = symbolrelation;
symbolrelation = newSymbolrelation;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MMDSLPackage.RELATION__SYMBOLRELATION, oldSymbolrelation, symbolrelation));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public org.xtext.nv.dsl.mMDSL.Class getFromclassname()
{
if (fromclassname != null && fromclassname.eIsProxy())
{
InternalEObject oldFromclassname = (InternalEObject)fromclassname;
fromclassname = (org.xtext.nv.dsl.mMDSL.Class)eResolveProxy(oldFromclassname);
if (fromclassname != oldFromclassname)
{
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MMDSLPackage.RELATION__FROMCLASSNAME, oldFromclassname, fromclassname));
}
}
return fromclassname;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public org.xtext.nv.dsl.mMDSL.Class basicGetFromclassname()
{
return fromclassname;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFromclassname(org.xtext.nv.dsl.mMDSL.Class newFromclassname)
{
org.xtext.nv.dsl.mMDSL.Class oldFromclassname = fromclassname;
fromclassname = newFromclassname;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MMDSLPackage.RELATION__FROMCLASSNAME, oldFromclassname, fromclassname));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public org.xtext.nv.dsl.mMDSL.Class getToclassname()
{
if (toclassname != null && toclassname.eIsProxy())
{
InternalEObject oldToclassname = (InternalEObject)toclassname;
toclassname = (org.xtext.nv.dsl.mMDSL.Class)eResolveProxy(oldToclassname);
if (toclassname != oldToclassname)
{
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MMDSLPackage.RELATION__TOCLASSNAME, oldToclassname, toclassname));
}
}
return toclassname;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public org.xtext.nv.dsl.mMDSL.Class basicGetToclassname()
{
return toclassname;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setToclassname(org.xtext.nv.dsl.mMDSL.Class newToclassname)
{
org.xtext.nv.dsl.mMDSL.Class oldToclassname = toclassname;
toclassname = newToclassname;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MMDSLPackage.RELATION__TOCLASSNAME, oldToclassname, toclassname));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Attribute> getAttribute()
{
if (attribute == null)
{
attribute = new EObjectContainmentEList<Attribute>(Attribute.class, this, MMDSLPackage.RELATION__ATTRIBUTE);
}
return attribute;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<InsertEmbedCode> getInsertembedcode()
{
if (insertembedcode == null)
{
insertembedcode = new EObjectContainmentEList<InsertEmbedCode>(InsertEmbedCode.class, this, MMDSLPackage.RELATION__INSERTEMBEDCODE);
}
return insertembedcode;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case MMDSLPackage.RELATION__ATTRIBUTE:
return ((InternalEList<?>)getAttribute()).basicRemove(otherEnd, msgs);
case MMDSLPackage.RELATION__INSERTEMBEDCODE:
return ((InternalEList<?>)getInsertembedcode()).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 MMDSLPackage.RELATION__NAME:
return getName();
case MMDSLPackage.RELATION__PARENTRELATIONNAME:
if (resolve) return getParentrelationname();
return basicGetParentrelationname();
case MMDSLPackage.RELATION__SYMBOLRELATION:
if (resolve) return getSymbolrelation();
return basicGetSymbolrelation();
case MMDSLPackage.RELATION__FROMCLASSNAME:
if (resolve) return getFromclassname();
return basicGetFromclassname();
case MMDSLPackage.RELATION__TOCLASSNAME:
if (resolve) return getToclassname();
return basicGetToclassname();
case MMDSLPackage.RELATION__ATTRIBUTE:
return getAttribute();
case MMDSLPackage.RELATION__INSERTEMBEDCODE:
return getInsertembedcode();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case MMDSLPackage.RELATION__NAME:
setName((String)newValue);
return;
case MMDSLPackage.RELATION__PARENTRELATIONNAME:
setParentrelationname((Relation)newValue);
return;
case MMDSLPackage.RELATION__SYMBOLRELATION:
setSymbolrelation((SymbolRelation)newValue);
return;
case MMDSLPackage.RELATION__FROMCLASSNAME:
setFromclassname((org.xtext.nv.dsl.mMDSL.Class)newValue);
return;
case MMDSLPackage.RELATION__TOCLASSNAME:
setToclassname((org.xtext.nv.dsl.mMDSL.Class)newValue);
return;
case MMDSLPackage.RELATION__ATTRIBUTE:
getAttribute().clear();
getAttribute().addAll((Collection<? extends Attribute>)newValue);
return;
case MMDSLPackage.RELATION__INSERTEMBEDCODE:
getInsertembedcode().clear();
getInsertembedcode().addAll((Collection<? extends InsertEmbedCode>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case MMDSLPackage.RELATION__NAME:
setName(NAME_EDEFAULT);
return;
case MMDSLPackage.RELATION__PARENTRELATIONNAME:
setParentrelationname((Relation)null);
return;
case MMDSLPackage.RELATION__SYMBOLRELATION:
setSymbolrelation((SymbolRelation)null);
return;
case MMDSLPackage.RELATION__FROMCLASSNAME:
setFromclassname((org.xtext.nv.dsl.mMDSL.Class)null);
return;
case MMDSLPackage.RELATION__TOCLASSNAME:
setToclassname((org.xtext.nv.dsl.mMDSL.Class)null);
return;
case MMDSLPackage.RELATION__ATTRIBUTE:
getAttribute().clear();
return;
case MMDSLPackage.RELATION__INSERTEMBEDCODE:
getInsertembedcode().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case MMDSLPackage.RELATION__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case MMDSLPackage.RELATION__PARENTRELATIONNAME:
return parentrelationname != null;
case MMDSLPackage.RELATION__SYMBOLRELATION:
return symbolrelation != null;
case MMDSLPackage.RELATION__FROMCLASSNAME:
return fromclassname != null;
case MMDSLPackage.RELATION__TOCLASSNAME:
return toclassname != null;
case MMDSLPackage.RELATION__ATTRIBUTE:
return attribute != null && !attribute.isEmpty();
case MMDSLPackage.RELATION__INSERTEMBEDCODE:
return insertembedcode != null && !insertembedcode.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(" (name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //RelationImpl
| epl-1.0 |
argocasegeo/argocasegeo | src/org/argouml/uml/cognitive/critics/CrWrongLinkEnds.java | 4955 | // Copyright (c) 1996-99 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
// File: CrClassWithoutComponent.java
// Classes: CrClassWithoutComponent
// Original Author: 5eichler@informatik.uni-hamburg.de
// $Id: CrWrongLinkEnds.java,v 1.3 2002/08/19 08:41:39 kataka Exp $
package org.argouml.uml.cognitive.critics;
import java.util.*;
import ru.novosoft.uml.foundation.core.*;
import ru.novosoft.uml.behavior.common_behavior.*;
import org.tigris.gef.util.*;
import org.argouml.cognitive.*;
import org.argouml.uml.diagram.static_structure.ui.*;
import org.argouml.uml.diagram.deployment.ui.*;
/**
* A critic to detect when in a deployment-diagram
* the FigObject of the first MLinkEnd is inside a FigComponent
* and the FigObject of the other MLinkEnd is inside a FigComponentInstance
**/
public class CrWrongLinkEnds extends CrUML {
public CrWrongLinkEnds() {
setHeadline("LinkEnds have not the same locations");
addSupportedDecision(CrUML.decPATTERNS);
}
public boolean predicate2(Object dm, Designer dsgr) {
if (!(dm instanceof UMLDeploymentDiagram)) return NO_PROBLEM;
UMLDeploymentDiagram dd = (UMLDeploymentDiagram) dm;
VectorSet offs = computeOffenders(dd);
if (offs == null) return NO_PROBLEM;
return PROBLEM_FOUND;
}
public ToDoItem toDoItem(Object dm, Designer dsgr) {
UMLDeploymentDiagram dd = (UMLDeploymentDiagram) dm;
VectorSet offs = computeOffenders(dd);
return new ToDoItem(this, offs, dsgr);
}
public boolean stillValid(ToDoItem i, Designer dsgr) {
if (!isActive()) return false;
VectorSet offs = i.getOffenders();
UMLDeploymentDiagram dd = (UMLDeploymentDiagram) offs.firstElement();
//if (!predicate(dm, dsgr)) return false;
VectorSet newOffs = computeOffenders(dd);
boolean res = offs.equals(newOffs);
return res;
}
/**
* If there are links that are going from inside a FigComponent
* to inside a FigComponentInstance the returned vector-set is not null.
* Then in the vector-set are the UMLDeploymentDiagram and all FigLinks
* with this characteristic and their FigObjects described over the links MLinkEnds
**/
public VectorSet computeOffenders(UMLDeploymentDiagram dd) {
Vector figs = dd.getLayer().getContents();
VectorSet offs = null;
int size = figs.size();
for (int i=0; i<size; i++) {
Object obj = figs.elementAt(i);
if (!(obj instanceof FigLink)) continue;
FigLink fl = (FigLink) obj;
if (!(fl.getOwner() instanceof MLink)) continue;
MLink link = (MLink) fl.getOwner();
Collection ends = link.getConnections();
if (ends != null && (ends.size() > 0)) {
int count = 0;
Iterator it = ends.iterator();
while (it.hasNext()) {
MLinkEnd le = (MLinkEnd) it.next();
if (le.getInstance().getElementResidences() != null && (le.getInstance().getElementResidences().size() > 0)) count = count+2;
if (le.getInstance().getComponentInstance() != null) count = count+1;
}
if (count == 3) {
if (offs == null) {
offs = new VectorSet();
offs.addElement(dd);
}
offs.addElement(fl);
offs.addElement(fl.getSourcePortFig());
offs.addElement(fl.getDestPortFig());
}
}
}
return offs;
}
} /* end class CrWrongLinkEnds.java */
| epl-1.0 |
sehrgut/minecraft-smp-mocreatures | moCreatures/client/core/sources/net/minecraft/src/TileEntityChest.java | 3472 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
package net.minecraft.src;
// Referenced classes of package net.minecraft.src:
// TileEntity, IInventory, ItemStack, NBTTagCompound,
// NBTTagList, World, EntityPlayer
public class TileEntityChest extends TileEntity
implements IInventory
{
public TileEntityChest()
{
chestContents = new ItemStack[36];
}
public int getSizeInventory()
{
return 27;
}
public ItemStack getStackInSlot(int i)
{
return chestContents[i];
}
public ItemStack decrStackSize(int i, int j)
{
if(chestContents[i] != null)
{
if(chestContents[i].stackSize <= j)
{
ItemStack itemstack = chestContents[i];
chestContents[i] = null;
onInventoryChanged();
return itemstack;
}
ItemStack itemstack1 = chestContents[i].splitStack(j);
if(chestContents[i].stackSize == 0)
{
chestContents[i] = null;
}
onInventoryChanged();
return itemstack1;
} else
{
return null;
}
}
public void setInventorySlotContents(int i, ItemStack itemstack)
{
chestContents[i] = itemstack;
if(itemstack != null && itemstack.stackSize > getInventoryStackLimit())
{
itemstack.stackSize = getInventoryStackLimit();
}
onInventoryChanged();
}
public String getInvName()
{
return "Chest";
}
public void readFromNBT(NBTTagCompound nbttagcompound)
{
super.readFromNBT(nbttagcompound);
NBTTagList nbttaglist = nbttagcompound.getTagList("Items");
chestContents = new ItemStack[getSizeInventory()];
for(int i = 0; i < nbttaglist.tagCount(); i++)
{
NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.tagAt(i);
int j = nbttagcompound1.getByte("Slot") & 0xff;
if(j >= 0 && j < chestContents.length)
{
chestContents[j] = new ItemStack(nbttagcompound1);
}
}
}
public void writeToNBT(NBTTagCompound nbttagcompound)
{
super.writeToNBT(nbttagcompound);
NBTTagList nbttaglist = new NBTTagList();
for(int i = 0; i < chestContents.length; i++)
{
if(chestContents[i] != null)
{
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte)i);
chestContents[i].writeToNBT(nbttagcompound1);
nbttaglist.setTag(nbttagcompound1);
}
}
nbttagcompound.setTag("Items", nbttaglist);
}
public int getInventoryStackLimit()
{
return 64;
}
public boolean canInteractWith(EntityPlayer entityplayer)
{
if(worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) != this)
{
return false;
}
return entityplayer.getDistanceSq((double)xCoord + 0.5D, (double)yCoord + 0.5D, (double)zCoord + 0.5D) <= 64D;
}
private ItemStack chestContents[];
}
| epl-1.0 |
eroslevi/titan.EclipsePlug-ins | org.eclipse.titanium/src/org/eclipse/titanium/metrics/implementation/MMNofImports.java | 915 | /******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.eclipse.titanium.metrics.implementation;
import org.eclipse.titan.designer.AST.Module;
import org.eclipse.titanium.metrics.MetricData;
import org.eclipse.titanium.metrics.ModuleMetric;
public class MMNofImports extends BaseModuleMetric {
public MMNofImports() {
super(ModuleMetric.NOF_IMPORTS);
}
@Override
public Number measure(final MetricData data, final Module module) {
return module.getImportedModules().size();
}
}
| epl-1.0 |
rherrmann/eclipse-extras | com.codeaffine.extras.ide.test/src/com/codeaffine/extras/ide/internal/delete/DeleteEditorFileKeyBindingPDETest.java | 913 | package com.codeaffine.extras.ide.internal.delete;
import static com.codeaffine.extras.test.util.KeyBindingInspector.DEFAULT_SCHEME_ID;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import com.codeaffine.extras.test.util.KeyBindingInfo;
import com.codeaffine.extras.test.util.KeyBindingInspector;
public class DeleteEditorFileKeyBindingPDETest {
private static final String KEY_SEQUENCE = "M3+Del";
@Test
public void testGeneralKeyBinding() {
KeyBindingInfo keyBinding = KeyBindingInspector.keyBindingFor( KEY_SEQUENCE );
assertThat( keyBinding.getSchemeId() ).isEqualTo( DEFAULT_SCHEME_ID );
assertThat( keyBinding.getCommandId() ).isEqualTo( DeleteEditorFileHandler.COMMAND_ID );
assertThat( keyBinding.getContextId() ).isNull();
assertThat( keyBinding.getPlatform() ).isNull();
assertThat( keyBinding.getParameters() ).isEmpty();
}
}
| epl-1.0 |
parraman/micobs | mclev/domains/edroom/es.uah.aut.srg.micobs.mclev.domain.edroom.editor.dclass.ui/src/es/uah/aut/srg/micobs/mclev/domain/edroom/lang/ui/contentassist/DCLASSProposalProvider.java | 923 | /*******************************************************************************
* Copyright (c) 2013-2015 UAH Space Research Group.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* MICOBS SRG Team - Initial API and implementation
******************************************************************************/
package es.uah.aut.srg.micobs.mclev.domain.edroom.lang.ui.contentassist;
import es.uah.aut.srg.micobs.mclev.domain.edroom.lang.ui.contentassist.AbstractDCLASSProposalProvider;
/**
* see http://www.eclipse.org/Xtext/documentation/latest/xtext.html#contentAssist on how to customize content assistant
*/
public class DCLASSProposalProvider extends AbstractDCLASSProposalProvider {
}
| epl-1.0 |
rohitmohan96/ceylon-ide-eclipse | plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/util/Highlights.java | 21278 | package com.redhat.ceylon.eclipse.util;
import static com.redhat.ceylon.eclipse.code.preferences.CeylonPreferenceInitializer.MATCH_HIGHLIGHTING;
import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID;
import static com.redhat.ceylon.eclipse.util.EditorUtil.getCurrentTheme;
import static java.lang.Character.isDigit;
import static java.lang.Character.isJavaIdentifierStart;
import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;
import static org.eclipse.ui.PlatformUI.getWorkbench;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.antlr.runtime.CommonToken;
import org.eclipse.jface.resource.ColorRegistry;
import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.StyledString.Styler;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.TextStyle;
import org.eclipse.ui.themes.IThemeManager;
import com.redhat.ceylon.compiler.typechecker.parser.CeylonParser;
import com.redhat.ceylon.eclipse.code.editor.CeylonTaskUtil;
import com.redhat.ceylon.eclipse.code.editor.CeylonTaskUtil.Task;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
import com.redhat.ceylon.ide.common.util.Escaping;
public class Highlights {
public static String IDENTIFIERS = "identifiers";
public static String TYPES = "types";
public static String TYPE_LITERALS = "typeLiterals";
public static String KEYWORDS = "keywords";
public static String NUMBERS = "numbers";
public static String STRINGS = "strings";
public static String CHARS = "characters";
public static String INTERP = "interpolation";
public static String COMMENTS = "comments";
public static String TODOS = "todos";
public static String ANNOTATIONS = "annotations";
public static String ANNOTATION_STRINGS = "annotationstrings";
public static String SEMIS = "semis";
public static String BRACES = "braces";
public static String PACKAGES = "packages";
public static String MEMBERS = "members";
public static String OUTLINE_TYPES = "outlineTypes";
public static String MATCHES = "matches";
public static final String DOC_BACKGROUND = "documentationBackground";
private static TextAttribute identifierAttribute,
typeAttribute, typeLiteralAttribute,
keywordAttribute, numberAttribute,
annotationAttribute, annotationStringAttribute,
commentAttribute, stringAttribute, todoAttribute,
semiAttribute, braceAttribute, packageAttribute,
interpAttribute, charAttribute, memberAttribute;
private static TextAttribute text(ColorRegistry colorRegistry,
String key, int style) {
return new TextAttribute(color(colorRegistry, key),
null, style);
}
public static Color color(ColorRegistry colorRegistry, String key) {
return colorRegistry.get(PLUGIN_ID + ".theme.color." + key);
}
static {
initColors(getCurrentTheme().getColorRegistry());
IThemeManager themeManager =
getWorkbench().getThemeManager();
themeManager.addPropertyChangeListener(new IPropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
if (isColorChange(event)) {
refreshColors();
}
}
});
}
public static boolean isColorChange(PropertyChangeEvent event) {
String property = event.getProperty();
return property.startsWith(PLUGIN_ID + ".theme.color.") ||
property.equals(IThemeManager.CHANGE_CURRENT_THEME);
}
public static Color getCurrentThemeColor(String key) {
return color(getCurrentTheme().getColorRegistry(), key);
}
public static void refreshColors() {
initColors(getCurrentTheme().getColorRegistry());
}
private static void initColors(ColorRegistry colorRegistry) {
identifierAttribute = text(colorRegistry, IDENTIFIERS, SWT.NORMAL);
typeAttribute = text(colorRegistry, TYPES, SWT.NORMAL);
typeLiteralAttribute = text(colorRegistry, TYPE_LITERALS, SWT.NORMAL);
keywordAttribute = text(colorRegistry, KEYWORDS, SWT.BOLD);
numberAttribute = text(colorRegistry, NUMBERS, SWT.NORMAL);
commentAttribute = text(colorRegistry, COMMENTS, SWT.NORMAL);
stringAttribute = text(colorRegistry, STRINGS, SWT.NORMAL);
charAttribute = text(colorRegistry, CHARS, SWT.NORMAL);
interpAttribute = text(colorRegistry, INTERP, SWT.NORMAL);
annotationStringAttribute = text(colorRegistry, ANNOTATION_STRINGS, SWT.NORMAL);
annotationAttribute = text(colorRegistry, ANNOTATIONS, SWT.NORMAL);
todoAttribute = text(colorRegistry, TODOS, SWT.NORMAL);
semiAttribute = text(colorRegistry, SEMIS, SWT.NORMAL);
braceAttribute = text(colorRegistry, BRACES, SWT.NORMAL);
packageAttribute = text(colorRegistry, PACKAGES, SWT.NORMAL);
memberAttribute = text(colorRegistry, MEMBERS, SWT.NORMAL);
}
public static TextAttribute getInterpolationColoring() {
return interpAttribute;
}
public static TextAttribute getMetaLiteralColoring() {
return typeLiteralAttribute;
}
public static TextAttribute getMemberColoring() {
return memberAttribute;
}
public static TextAttribute getColoring(CommonToken token) {
switch (token.getType()) {
case CeylonParser.PIDENTIFIER:
return packageAttribute;
case CeylonParser.AIDENTIFIER:
return annotationAttribute;
case CeylonParser.UIDENTIFIER:
return typeAttribute;
case CeylonParser.LIDENTIFIER:
return identifierAttribute;
case CeylonParser.FLOAT_LITERAL:
case CeylonParser.NATURAL_LITERAL:
return numberAttribute;
case CeylonParser.ASTRING_LITERAL:
case CeylonParser.AVERBATIM_STRING:
return annotationStringAttribute;
case CeylonParser.CHAR_LITERAL:
return charAttribute;
case CeylonParser.STRING_LITERAL:
case CeylonParser.STRING_END:
case CeylonParser.STRING_START:
case CeylonParser.STRING_MID:
case CeylonParser.VERBATIM_STRING:
return stringAttribute;
case CeylonParser.MULTI_COMMENT:
case CeylonParser.LINE_COMMENT:
List<Task> tasks = CeylonTaskUtil.getTasks(token);
if (tasks != null && tasks.size() > 0) {
return todoAttribute;
}
else {
return commentAttribute;
}
case CeylonParser.BACKTICK:
return typeLiteralAttribute;
case CeylonParser.SEMICOLON:
return semiAttribute;
case CeylonParser.LBRACE:
case CeylonParser.RBRACE:
return braceAttribute;
case CeylonParser.EOF:
case CeylonParser.WS:
return null;
default:
if (Escaping.KEYWORDS.contains(token.getText())) {
return keywordAttribute;
}
else {
return null;
}
}
}
private static final Pattern path =
Pattern.compile("\\b\\p{Ll}+(\\.\\p{Ll}+)+\\b");
public static class FontStyler extends Styler {
private final Font font;
private Styler styler;
public FontStyler(Font font) {
this.font = font;
}
public FontStyler(Font font, Styler styler) {
this(font);
this.styler = styler;
}
@Override
public void applyStyles(TextStyle textStyle) {
if (font!=null) {
textStyle.font = font;
}
if (styler!=null) {
styler.applyStyles(textStyle);
}
}
}
public static void styleFragment(
StyledString result,
String codeFragment,
boolean qualifiedNameIsPath,
String prefix, Font font) {
qualifiedNameIsPath &=
path.matcher(codeFragment).find();
StringTokenizer tokens =
new StringTokenizer(codeFragment,
qualifiedNameIsPath ?
" |&()<>*+?,:{}[]@\"'!^/%~-=;" :
" |&()<>*+?,:{}[]@\"'!^/%~-=;.",
true);
boolean version = false;
boolean qualified = false;
boolean matchHighlighting = prefix!=null;
while (tokens.hasMoreTokens()) {
final String token = tokens.nextToken();
if (token.equals("\"") || token.equals("'")) {
version = !version;
append(result, token, font, STRING_STYLER);
}
else if (version) {
append(result, token, font, STRING_STYLER);
}
else if (token.equals(".")) {
qualified = true;
append(result, token, font, null);
continue;
}
else {
int initial = token.codePointAt(0);
if (initial=='\\' && token.length()>1) {
initial = token.codePointAt(1);
}
if (isDigit(initial)) {
append(result, token, font, NUM_STYLER);
}
else if (isUpperCase(initial)) {
if (matchHighlighting) {
styleIdentifier(
result, prefix, token,
new FontStyler(font,
TYPE_ID_STYLER),
font);
matchHighlighting = false;
}
else {
append(result, token, font,
TYPE_ID_STYLER);
}
}
else if (isLowerCase(initial)) {
if (Escaping.KEYWORDS.contains(token)) {
append(result, token, font,
KW_STYLER);
}
else if (token.contains(".")) {
append(result, token, font,
PACKAGE_STYLER);
}
else if (qualified) {
if (matchHighlighting) {
styleIdentifier(
result, prefix, token,
new FontStyler(font,
MEMBER_STYLER),
font);
matchHighlighting = false;
}
else {
append(result, token, font,
MEMBER_STYLER);
}
}
else {
if (matchHighlighting) {
styleIdentifier(
result, prefix, token,
new FontStyler(font,
ID_STYLER),
font);
matchHighlighting = false;
}
else {
append(result, token, font,
ID_STYLER);
}
}
}
else {
append(result, token, font, null);
}
}
qualified = false;
}
}
private static void append(StyledString result,
String token, Font font, Styler styler) {
result.append(token, new FontStyler(font, styler));
}
private static Font getBoldFont(Font font) {
FontData[] data = font.getFontData();
for (int i= 0; i<data.length; i++) {
data[i].setStyle(SWT.BOLD);
}
return new Font(font.getDevice(), data);
}
private static final Pattern HUMP =
Pattern.compile("(\\w|\\\\[iI])\\p{Ll}*");
public static void styleIdentifier(StyledString result,
String prefix, String token,
Styler colorStyler, final Font font) {
final Styler fontAndColorStyler =
new FontStyler(font, colorStyler);
final String type =
CeylonPlugin.getPreferences()
.getString(MATCH_HIGHLIGHTING);
if ("none".equals(type) || prefix.isEmpty()) {
result.append(token, fontAndColorStyler);
return;
}
Matcher m = HUMP.matcher(prefix);
int i = 0;
while (i<token.length() && m.find()) {
String bit = m.group();
//look for an exact-case match
int loc = token.indexOf(bit, i);
if (loc<0) {
//look for an inexact-case match
loc = token.toLowerCase()
.indexOf(bit.toLowerCase(), i);
}
if (i==0 && loc>0 && !prefix.startsWith("*")) {
//first match must be at start of identifier
break;
}
if (loc<0) {
//roll back the highlighting already done
result.setStyle(result.length()-i, i,
fontAndColorStyler);
break;
}
result.append(token.substring(i, loc),
fontAndColorStyler);
Styler matchStyler = new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
fontAndColorStyler.applyStyles(textStyle);
switch (type) {
case "underline":
textStyle.underline = true;
break;
case "bold":
textStyle.font = getBoldFont(font);
break;
case "color":
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
MATCHES);
break;
case "background":
textStyle.background =
color(getCurrentTheme()
.getColorRegistry(),
MATCHES);
break;
}
}
};
result.append(token.substring(loc, loc+bit.length()),
matchStyler);
i = loc + bit.length();
}
result.append(token.substring(i), fontAndColorStyler);
}
public static void styleJavaType(StyledString result,
String string) {
styleJavaType(result, string, TYPE_ID_STYLER);
}
public static void styleJavaType(StyledString result,
String string, Styler styler) {
StringTokenizer tokens =
new StringTokenizer(string,
" <>,[]?.", true);
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
if (token.equals("int") ||
token.equals("short") ||
token.equals("byte") ||
token.equals("long") ||
token.equals("double") ||
token.equals("float") ||
token.equals("boolean") ||
token.equals("char") ||
token.equals("extends") ||
token.equals("super")) {
result.append(token, KW_STYLER);
}
else if (isJavaIdentifierStart(token.charAt(0))) {
result.append(token, styler);
}
else {
result.append(token);
}
}
}
public static StyledString styleProposal(
String description,
boolean qualifiedNameIsPath,
boolean eliminateQuotes) {
StyledString result = new StyledString();
StringTokenizer tokens =
new StringTokenizer(description,
"'\"", true);
result.append(tokens.nextToken());
while (tokens.hasMoreTokens()) {
String tok = tokens.nextToken();
if (tok.equals("\'")) {
if (!eliminateQuotes) {
result.append(tok);
}
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
if (token.equals("\'")) {
if (!eliminateQuotes) {
result.append(token);
}
break;
}
else if (token.equals("\"")) {
result.append(token, STRING_STYLER);
while (tokens.hasMoreTokens()) {
String quoted = tokens.nextToken();
result.append(quoted, STRING_STYLER);
if (quoted.equals("\"")) {
break;
}
}
}
else {
styleFragment(result, token,
qualifiedNameIsPath, null,
CeylonPlugin.getCompletionFont());
}
}
}
else {
result.append(tok);
}
}
return result;
}
public static StyledString styleProposal(
String description,
boolean qualifiedNameIsPath) {
return styleProposal(description,
qualifiedNameIsPath, true);
}
public static final Styler TYPE_STYLER =
new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
TYPES);
}
};
public static final Styler MEMBER_STYLER =
new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
MEMBERS);
}
};
public static final Styler TYPE_ID_STYLER =
new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
TYPES);
}
};
public static final Styler KW_STYLER =
new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
KEYWORDS);
}
};
public static final Styler STRING_STYLER =
new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
STRINGS);
}
};
public static final Styler NUM_STYLER =
new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
NUMBERS);
}
};
public static final Styler PACKAGE_STYLER =
new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
PACKAGES);
}
};
public static final Styler ARROW_STYLER =
new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
OUTLINE_TYPES);
}
};
public static final Styler ANN_STYLER =
new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
ANNOTATIONS);
}
};
public static final Styler ID_STYLER =
new Styler() {
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.foreground =
color(getCurrentTheme()
.getColorRegistry(),
IDENTIFIERS);
}
};
} | epl-1.0 |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/ui/providers/MainLabelProvider.java | 2542 | package eme.ui.providers;
import org.eclipse.jdt.ui.ISharedImages;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.swt.graphics.Image;
import eme.model.ExtractedClass;
import eme.model.ExtractedElement;
import eme.model.ExtractedEnum;
import eme.model.ExtractedInterface;
import eme.model.ExtractedPackage;
import eme.model.ExtractedType;
/**
* Label provider that uses the information given by the intermediate model to show specific text for intermediate model
* elements. It shows the simple name of the element as column text and a correlating icon.
* @author Timur Saglam
*/
public class MainLabelProvider extends GenericColumnLabelProvider<ExtractedElement> {
/**
* Basic constructor, creates a column label provider for intermediate model elements.
*/
public MainLabelProvider() {
super(ExtractedElement.class);
}
@Override
public Image getColumnImage(ExtractedElement element) {
if (element instanceof ExtractedPackage) { // TODO (HIGH) make this a lot cleaner.
return getEclipseImage(ISharedImages.IMG_OBJS_PACKAGE);
} else if (element instanceof ExtractedClass) {
return ((ExtractedType) element).isInnerType() ? getEclipseImage(ISharedImages.IMG_OBJS_INNER_CLASS_PRIVATE)
: getEclipseImage(ISharedImages.IMG_OBJS_CLASS);
} else if (element instanceof ExtractedInterface) {
return ((ExtractedType) element).isInnerType() ? getEclipseImage(ISharedImages.IMG_OBJS_INNER_INTERFACE_PRIVATE)
: getEclipseImage(ISharedImages.IMG_OBJS_INTERFACE);
} else if (element instanceof ExtractedEnum) {
return ((ExtractedType) element).isInnerType() ? getEclipseImage(ISharedImages.IMG_OBJS_ENUM_PRIVATE)
: getEclipseImage(ISharedImages.IMG_OBJS_ENUM);
}
return super.getImage(element);
}
@Override
public String getColumnText(ExtractedElement element) {
if (element.getName().isEmpty() && element instanceof ExtractedPackage) {
return "(default package)";
}
return element.getName();
}
@Override
public String getColumnToolTip(ExtractedElement element) {
return "full name: " + element.getFullName();
}
/**
* Grants access to the Eclipse {@link JavaUI} shared images with the String contained in {@link ISharedImages}.
*/
private Image getEclipseImage(String symbolicName) {
return JavaUI.getSharedImages().getImage(symbolicName);
}
} | epl-1.0 |
RodriguesJ/Atem | src/com/runescape/server/revised/content/minigame/impl/FishingTrawlerMiniGame.java | 11730 | /**
* Eclipse Public License - v 1.0
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION
* OF THE
* PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* 1. DEFINITIONS
*
* "Contribution" means:
*
* a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
* b) in the case of each subsequent Contributor:
* i) changes to the Program, and
* ii) additions to the Program;
* where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution
* 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf.
* Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program
* under their own license agreement, and (ii) are not derivative works of the Program.
* "Contributor" means any person or entity that distributes the Program.
*
* "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone
* or when combined with the Program.
*
* "Program" means the Contributions distributed in accordance with this Agreement.
*
* "Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
*
* 2. GRANT OF RIGHTS
*
* a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license
* to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor,
* if any, and such derivative works, in source code and object code form.
* b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license
* under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source
* code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the
* Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The
* patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
* c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided
* by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor
* disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise.
* As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other
* intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the
* Program, it is Recipient's responsibility to acquire that license before distributing the Program.
* d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright
* license set forth in this Agreement.
* 3. REQUIREMENTS
*
* A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
*
* a) it complies with the terms and conditions of this Agreement; and
* b) its license agreement:
* i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions
* of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
* ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and
* consequential damages, such as lost profits;
* iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
* iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner
* on or through a medium customarily used for software exchange.
* When the Program is made available in source code form:
*
* a) it must be made available under this Agreement; and
* b) a copy of this Agreement must be included with each copy of the Program.
* Contributors may not remove or alter any copyright notices contained within the Program.
*
* Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients
* to identify the originator of the Contribution.
*
* 4. COMMERCIAL DISTRIBUTION
*
* Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this
* license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering
* should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in
* a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor
* ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions
* brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in
* connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or
* Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly
* notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the
* Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim
* at its own expense.
*
* For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial
* Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims
* and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend
* claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay
* any damages as a result, the Commercial Contributor must pay those damages.
*
* 5. NO WARRANTY
*
* EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS
* FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and
* assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program
* errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
*
* 6. DISCLAIMER OF LIABILITY
*
* EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION
* OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* 7. GENERAL
*
* If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the
* remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum
* extent necessary to make such provision valid and enforceable.
*
* If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program
* itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's
* rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
*
* All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this
* Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights
* under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However,
* Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
*
* Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may
* only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this
* Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the
* initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate
* entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be
* distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is
* published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in
* Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement,
* whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
*
* This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to
* this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights
* to a jury trial in any resulting litigation.
*/
package com.runescape.server.revised.content.minigame.impl;
public class FishingTrawlerMiniGame {
} | epl-1.0 |
niuqg/controller | opendaylight/statusmanager0.3/statusmanager/src/test/java/edu/ustc/qos/statusmanager/AppTest.java | 620 | package edu.ustc.qos.statusmanager;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{}
}
| epl-1.0 |
eroslevi/titan.EclipsePlug-ins | org.eclipse.titan.executor/src/org/eclipse/titan/executor/executors/jni/LaunchConfigurationTabGroup.java | 2448 | /******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.eclipse.titan.executor.executors.jni;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.CommonTab;
import org.eclipse.debug.ui.EnvironmentTab;
import org.eclipse.debug.ui.ILaunchConfigurationDialog;
import org.eclipse.debug.ui.ILaunchConfigurationTab;
import org.eclipse.debug.ui.ILaunchConfigurationTabGroup;
import org.eclipse.titan.executor.tabpages.hostcontrollers.HostControllersTab;
import org.eclipse.titan.executor.tabpages.maincontroller.JNIMainControllerTab;
import org.eclipse.titan.executor.tabpages.performance.JniPerformanceSettingsTab;
import org.eclipse.titan.executor.tabpages.testset.TestSetTab;
/**
* @author Kristof Szabados
* */
public final class LaunchConfigurationTabGroup implements ILaunchConfigurationTabGroup {
private ILaunchConfigurationTab[] tabs;
@Override
public void createTabs(final ILaunchConfigurationDialog arg0, final String arg1) {
tabs = new ILaunchConfigurationTab[] {new JNIMainControllerTab(this), new HostControllersTab(this), new TestSetTab(),
new JniPerformanceSettingsTab(), new EnvironmentTab(), new CommonTab()};
}
@Override
public void dispose() {
if (null != tabs) {
for (ILaunchConfigurationTab tab : tabs) {
tab.dispose();
}
}
}
@Override
public ILaunchConfigurationTab[] getTabs() {
return tabs;
}
@Override
public void initializeFrom(final ILaunchConfiguration arg0) {
for (ILaunchConfigurationTab tab : tabs) {
tab.initializeFrom(arg0);
}
}
@Override
public void launched(final ILaunch arg0) {
// Do nothing
}
@Override
public void performApply(final ILaunchConfigurationWorkingCopy arg0) {
for (ILaunchConfigurationTab tab : tabs) {
tab.performApply(arg0);
}
}
@Override
public void setDefaults(final ILaunchConfigurationWorkingCopy arg0) {
for (ILaunchConfigurationTab tab : tabs) {
tab.setDefaults(arg0);
}
}
}
| epl-1.0 |
mcarlson/openlaszlo | WEB-INF/lps/server/src/org/openlaszlo/servlets/responders/ResponderAGENTLIST.java | 1798 | /******************************************************************************
* ResponderAGENTLIST.java
* ****************************************************************************/
/* J_LZ_COPYRIGHT_BEGIN *******************************************************
* Copyright 2001-2004 Laszlo Systems, Inc. All Rights Reserved. *
* Use is subject to license terms. *
* J_LZ_COPYRIGHT_END *********************************************************/
package org.openlaszlo.servlets.responders;
import java.io.*;
import java.util.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.openlaszlo.compiler.*;
import org.openlaszlo.connection.*;
import org.openlaszlo.utils.*;
import org.apache.log4j.*;
public class ResponderAGENTLIST extends ResponderConnectionAgent
{
private static boolean mIsInitialized = false;
private static Logger mLogger = Logger.getLogger(ResponderAGENTLIST.class);
protected void respondAgent(HttpServletRequest req, HttpServletResponse res,
ConnectionGroup group) throws IOException
{
String users = req.getParameter("users");
if ( users == null || users.equals("") ) {
replyWithXMLStatus(res, "missing 'users' parameter", SC_MISSING_PARAMETER);
return;
}
StringBuffer buf = new StringBuffer("<list>");
Set set = group.list(users);
Iterator iter = set.iterator();
while (iter.hasNext()) {
buf.append("<user name=\"")
.append((String)iter.next())
.append("\" />");
}
buf.append("</list>");
mLogger.debug(buf.toString());
replyWithXML(res, "ok", buf.toString());
}
}
| epl-1.0 |
danielUni/eeSample | src/ejb/eeSample/jar/entities/ManufacturerEntity.java | 968 | package ejb.eeSample.jar.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
import java.io.Serializable;
/**
* Created by Cedric Roeck (cedric.roeck@gmail.com) on 12.11.14.
*/
@Entity
@Table(name = "MANUFACTURER")
public class ManufacturerEntity implements Serializable {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = "id", columnDefinition = "serial")
private Long id;
@Version
private Long version;
@Column(name="MANUFACTURER_NAME")
private String name;
public Long getId() {
return id;
}
public Long getVersion() {
return version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| epl-1.0 |
wselwood/jgrapht | jgrapht-core/src/main/java/org/jgrapht/alg/CliqueMinimalSeparatorDecomposition.java | 14880 | /* ==========================================
* JGraphT : a free Java graph-theory library
* ==========================================
*
* Project Info: http://jgrapht.sourceforge.net/
* Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh)
*
* (C) Copyright 2003-2015, by Barak Naveh and Contributors.
*
* This program and the accompanying materials are dual-licensed under
* either
*
* (a) the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation, or (at your option) any
* later version.
*
* or (per the licensee's choosing)
*
* (b) the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation.
*/
/* -----------------
* CliqueMinimalSeparatorDecomposition.java
* -----------------
* (C) Copyright 2015, by Florian Buenzli and Contributors.
*
* Original Author: Florian Buenzli
* Contributor(s): Thomas Tschager
* Tomas Hruz
* Philipp Hoppen
*
* $Id$
*
* Changes
* -------
* 06-Feb-2015 : Initial revision (FB);
*
*/
package org.jgrapht.alg;
import java.util.*;
import java.util.Map.*;
import org.jgrapht.*;
import org.jgrapht.graph.*;
/**
* Clique Minimal Separator Decomposition using MCS-M+ and Atoms algorithm as
* described in Berry et al. An Introduction to Clique Minimal Separator
* Decomposition (2010), DOI:10.3390/a3020197, <a
* href="http://www.mdpi.com/1999-4893/3/2/197">
* http://www.mdpi.com/1999-4893/3/2/197</a>
*
* <p>The Clique Minimal Separator (CMS) Decomposition is a procedure that
* splits a graph into a set of subgraphs separated by minimal clique
* separators, adding the separating clique to each component produced by the
* separation. At the end we have a set of atoms. The CMS decomposition is
* unique and yields the set of the atoms independent of the order of the
* decomposition.
*
* @author Florian Buenzli (fbuenzli@student.ethz.ch)
* @author Thomas Tschager (thomas.tschager@inf.ethz.ch)
* @author Tomas Hruz (tomas.hruz@inf.ethz.ch)
* @author Philipp Hoppen
*/
public class CliqueMinimalSeparatorDecomposition<V, E>
{
/**
* Source graph to operate on
*/
private UndirectedGraph<V, E> graph;
/**
* Minimal triangulation of graph
*/
private UndirectedGraph<V, E> chordalGraph;
/**
* Fill edges
*/
private Set<E> fillEdges;
/**
* Minimal elimination ordering on the vertices of graph
*/
private LinkedList<V> meo;
/**
* List of all vertices that generate a minimal separator of <code>
* chordGraph</code>
*/
private List<V> generators;
/**
* Set of clique minimal separators
*/
private Set<Set<V>> separators;
/**
* The atoms generated by the decomposition
*/
private Set<Set<V>> atoms;
/**
* Map for each separator how many components it produces.
*/
private Map<Set<V>, Integer> fullComponentCount =
new HashMap<Set<V>, Integer>();
/**
* Setup a clique minimal separator decomposition on undirected graph <code>
* g</code>. Loops and multiple edges are removed, i.e. the graph is
* transformed to a simple graph.
*
* @param g The graph to decompose.
*/
public CliqueMinimalSeparatorDecomposition(UndirectedGraph<V, E> g)
{
this.graph = g;
this.fillEdges = new HashSet<E>();
}
/**
* Compute the minimal triangulation of the graph. Implementation of
* Algorithm MCS-M+ as described in Berry et al. (2010),
* DOI:10.3390/a3020197 <a href="http://www.mdpi.com/1999-4893/3/2/197">
* http://www.mdpi.com/1999-4893/3/2/197</a>
*/
private void computeMinimalTriangulation()
{
// initialize chordGraph with same vertices as graph
chordalGraph = new SimpleGraph<V, E>(graph.getEdgeFactory());
for (V v : graph.vertexSet()) {
chordalGraph.addVertex(v);
}
// initialize g' as subgraph of graph (same vertices and edges)
final UndirectedGraph<V, E> gprime = copyAsSimpleGraph(graph);
int s = -1;
generators = new ArrayList<V>();
meo = new LinkedList<V>();
final Map<V, Integer> vertexLabels = new HashMap<V, Integer>();
for (V v : gprime.vertexSet()) {
vertexLabels.put(v, 0);
}
for (int i = 1, n = graph.vertexSet().size(); i <= n; i++) {
V v = getMaxLabelVertex(vertexLabels);
LinkedList<V> Y =
new LinkedList<V>(
Graphs.neighborListOf(gprime, v));
if (vertexLabels.get(v) <= s) {
generators.add(v);
}
s = vertexLabels.get(v);
// Mark x reached and all other vertices of gprime unreached
HashSet<V> reached = new HashSet<V>();
reached.add(v);
// mark neighborhood of x reached and add to reach(label(y))
HashMap<Integer, HashSet<V>> reach =
new HashMap<Integer, HashSet<V>>();
// mark y reached and add y to reach
for (V y : Y) {
reached.add(y);
addToReach(vertexLabels.get(y), y, reach);
}
for (int j = 0; j < graph.vertexSet().size(); j++) {
if (!reach.containsKey(j)) {
continue;
}
while (reach.get(j).size() > 0) {
// remove a vertex y from reach(j)
V y = reach.get(j).iterator().next();
reach.get(j).remove(y);
for (V z : Graphs.neighborListOf(gprime, y)) {
if (!reached.contains(z)) {
reached.add(z);
if (vertexLabels.get(z) > j) {
Y.add(z);
E fillEdge =
graph.getEdgeFactory().createEdge(
v,
z);
fillEdges.add(fillEdge);
addToReach(vertexLabels.get(z), z, reach);
} else {
addToReach(j, z, reach);
}
}
}
}
}
for (V y : Y) {
chordalGraph.addEdge(v, y);
vertexLabels.put(y, vertexLabels.get(y) + 1);
}
meo.addLast(v);
gprime.removeVertex(v);
vertexLabels.remove(v);
}
}
/**
* Get the vertex with the maximal label.
*
* @param vertexLabels Map that gives a label for each vertex.
*
* @return Vertex with the maximal label.
*/
private V getMaxLabelVertex(Map<V, Integer> vertexLabels)
{
Iterator<Entry<V, Integer>> iterator =
vertexLabels.entrySet().iterator();
Entry<V, Integer> max = iterator.next();
while (iterator.hasNext()) {
Entry<V, Integer> e = iterator.next();
if (e.getValue() > max.getValue()) {
max = e;
}
}
return max.getKey();
}
/**
* Add a vertex to reach.
*
* @param k vertex' label
* @param v the vertex
* @param r the reach structure.
*/
private void addToReach(Integer k, V v, HashMap<Integer, HashSet<V>> r)
{
if (r.containsKey(k)) {
r.get(k).add(v);
} else {
HashSet<V> set = new HashSet<V>();
set.add(v);
r.put(k, set);
}
}
/**
* Compute the unique decomposition of the input graph G (atoms of G).
* Implementation of algorithm Atoms as described in Berry et al. (2010),
* DOI:10.3390/a3020197, <a href="http://www.mdpi.com/1999-4893/3/2/197">
* http://www.mdpi.com/1999-4893/3/2/197</a>
*/
private void computeAtoms()
{
if (chordalGraph == null) {
computeMinimalTriangulation();
}
separators = new HashSet<Set<V>>();
// initialize g' as subgraph of graph (same vertices and edges)
UndirectedGraph<V, E> gprime = copyAsSimpleGraph(graph);
// initialize h' as subgraph of chordalGraph (same vertices and edges)
UndirectedGraph<V, E> hprime = copyAsSimpleGraph(chordalGraph);
atoms = new HashSet<Set<V>>();
Iterator<V> iterator = meo.descendingIterator();
while (iterator.hasNext()) {
V v = iterator.next();
if (generators.contains(v)) {
Set<V> separator =
new HashSet<V>(Graphs.neighborListOf(
hprime,
v));
if (isClique(graph, separator)) {
if (separator.size() > 0) {
if (separators.contains(separator)) {
fullComponentCount.put(
separator,
fullComponentCount.get(separator) + 1);
} else {
fullComponentCount.put(separator, 2);
separators.add(separator);
}
}
UndirectedGraph<V, E> tmpGraph = copyAsSimpleGraph(gprime);
tmpGraph.removeAllVertices(separator);
ConnectivityInspector<V, E> con =
new ConnectivityInspector<V, E>(tmpGraph);
if (con.isGraphConnected()) {
throw new RuntimeException(
"separator did not separate the graph");
}
for (Set<V> component : con.connectedSets()) {
if (component.contains(v)) {
gprime.removeAllVertices(component);
component.addAll(separator);
atoms.add(new HashSet<V>(component));
assert (component.size() > 0);
break;
}
}
}
}
hprime.removeVertex(v);
}
if (gprime.vertexSet().size() > 0) {
atoms.add(new HashSet<V>(gprime.vertexSet()));
}
}
/**
* Check whether the subgraph of <code>graph</code> induced by the given
* <code>vertices</code> is complete, i.e. a clique.
*
* @param graph the graph.
* @param vertices the vertices to induce the subgraph from.
*
* @return true if the induced subgraph is a clique.
*/
private static <V, E> boolean isClique(
UndirectedGraph<V, E> graph,
Set<V> vertices)
{
for (V v1 : vertices) {
for (V v2 : vertices) {
if ((v1 != v2) && (graph.getEdge(v1, v2) == null)) {
return false;
}
}
}
return true;
}
/**
* Create a copy of a graph for internal use.
*
* @param graph the graph to copy.
*
* @return A copy of the graph projected to a SimpleGraph.
*/
private static <V, E> UndirectedGraph<V, E> copyAsSimpleGraph(
UndirectedGraph<V, E> graph)
{
UndirectedGraph<V, E> copy =
new SimpleGraph<V, E>(
graph.getEdgeFactory());
if (graph instanceof SimpleGraph) {
Graphs.addGraph(copy, graph);
} else {
// project graph to SimpleGraph
Graphs.addAllVertices(copy, graph.vertexSet());
for (E e : graph.edgeSet()) {
V v1 = graph.getEdgeSource(e);
V v2 = graph.getEdgeTarget(e);
if ((v1 != v2) && !copy.containsEdge(e)) {
copy.addEdge(v1, v2);
}
}
}
return copy;
}
/**
* Check if the graph is chordal.
*
* @return true if the graph is chordal, false otherwise.
*/
public boolean isChordal()
{
if (chordalGraph == null) {
computeMinimalTriangulation();
}
return (chordalGraph.edgeSet().size() == graph.edgeSet().size());
}
/**
* Get the fill edges generated by the triangulation.
*
* @return Set of fill edges.
*/
public Set<E> getFillEdges()
{
if (fillEdges == null) {
computeMinimalTriangulation();
}
return fillEdges;
}
/**
* Get the minimal triangulation of the graph.
*
* @return Triangulated graph.
*/
public UndirectedGraph<V, E> getMinimalTriangulation()
{
if (chordalGraph == null) {
computeMinimalTriangulation();
}
return chordalGraph;
}
/**
* Get the generators of the separators of the triangulated graph, i.e. all
* vertices that generate a minimal separator of triangulated graph.
*
* @return List of generators.
*/
public List<V> getGenerators()
{
if (generators == null) {
computeMinimalTriangulation();
}
return generators;
}
/**
* Get the minimal elimination ordering produced by the triangulation.
*
* @return The minimal elimination ordering.
*/
public LinkedList<V> getMeo()
{
if (meo == null) {
computeMinimalTriangulation();
}
return meo;
}
/**
* Get a map to know for each separator how many components it produces.
*
* @return A map from separators to integers (component count).
*/
public Map<Set<V>, Integer> getFullComponentCount()
{
if (fullComponentCount == null) {
computeAtoms();
}
return fullComponentCount;
}
/**
* Get the atoms generated by the decomposition.
*
* @return Set of atoms, where each atom is described as the set of its
* vertices.
*/
public Set<Set<V>> getAtoms()
{
if (atoms == null) {
computeAtoms();
}
return atoms;
}
/**
* Get the clique minimal separators.
*
* @return Set of separators, where each separator is described as the set
* of its vertices.
*/
public Set<Set<V>> getSeparators()
{
if (separators == null) {
computeAtoms();
}
return separators;
}
/**
* Get the original graph.
*
* @return Original graph.
*/
public UndirectedGraph<V, E> getGraph()
{
return graph;
}
}
// End CliqueMinimalSeparatorDecomposition.java
| epl-1.0 |
DeznekCZ/zswi_eeg_explorer_2015 | ZSWI_EEG_EXPLORER/src/cz/eeg/ui/dialog/savedialog/Segment.java | 529 | package cz.eeg.ui.dialog.savedialog;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class Segment {
public static JPanel panel(String title, JComponent... components) {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(title));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (int i = 0; i < components.length; i++) {
panel.add(components[i]);
}
return panel;
}
}
| epl-1.0 |
Obeo/Game-Designer | plugins/fr.obeo.dsl.game/src-gen/fr/obeo/dsl/game/impl/MoveRightImpl.java | 698 | /**
*/
package fr.obeo.dsl.game.impl;
import fr.obeo.dsl.game.GamePackage;
import fr.obeo.dsl.game.MoveRight;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Move Right</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class MoveRightImpl extends MoveEventImpl implements MoveRight {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected MoveRightImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return GamePackage.Literals.MOVE_RIGHT;
}
} //MoveRightImpl
| epl-1.0 |
FTSRG/massif | plugins/hu.bme.mit.massif.simulink.edit/src/hu/bme/mit/massif/simulink/provider/EnableBlockItemProvider.java | 3373 | /*******************************************************************************
* Copyright (c) 2010-2013, Embraer S.A., Budapest University of Technology and Economics
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Abel Hegedus, Akos Horvath - initial API and implementation
*******************************************************************************/
package hu.bme.mit.massif.simulink.provider;
import hu.bme.mit.massif.simulink.EnableBlock;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
/**
* This is the item provider adapter for a {@link hu.bme.mit.massif.simulink.EnableBlock} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class EnableBlockItemProvider extends InPortBlockItemProvider {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EnableBlockItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
}
return itemPropertyDescriptors;
}
/**
* This returns EnableBlock.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/EnableBlock"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((EnableBlock)object).getName();
return label == null || label.length() == 0 ?
getString("_UI_EnableBlock_type") :
getString("_UI_EnableBlock_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| epl-1.0 |
sdirix/emf2web | org.eclipse.emf.ecp.emf2web/src/org/eclipse/emf/ecp/emf2web/wizard/ViewModelExportWizard.java | 10542 | /*******************************************************************************
* Copyright (c) 2014-2015 EclipseSource Muenchen GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Stefan Dirix - initial API and implementation
*
*******************************************************************************/
package org.eclipse.emf.ecp.emf2web.wizard;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecp.emf2web.export.Emf2QbExporter;
import org.eclipse.emf.ecp.emf2web.wizard.pages.EClassPage;
import org.eclipse.emf.ecp.emf2web.wizard.pages.ModelPathsPage;
import org.eclipse.emf.ecp.emf2web.wizard.pages.ViewModelsPage;
import org.eclipse.jface.dialogs.IPageChangingListener;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.PageChangingEvent;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;
/**
* Wizard for converting an Ecore model file into a format for the qb Play Application. It supports optional view model
* files and can create the qb Play Application via a template file.
*
*/
public class ViewModelExportWizard extends Wizard implements IWorkbenchWizard, IPageChangingListener {
private IFile ecoreModel;
private IFile genModel;
private final ResourceSet resourceSet;
private Resource ecoreResource;
private ModelPathsPage modelsPage;
private EClassPage eClassPage;
private ViewModelsPage viewModelPage;
/**
* Sets the Ecore model file for the wizard and its pages. Can be used before the wizard is actually opened to
* display the given model as default option.
*
* @param ecoreModel
* the {@link IFile} containing the Ecore model.
*/
public void setEcoreModel(IFile ecoreModel) {
if (this.ecoreModel != null) {
if (this.ecoreModel.getLocation().toString()
.equals(ecoreModel.getLocation().toString())) {
return;
}
}
this.ecoreModel = ecoreModel;
resolveReferences(ecoreModel);
if (eClassPage != null && viewModelPage != null) {
eClassPage.setNewResource(ecoreResource);
viewModelPage.clear();
}
}
/**
* Resolves References for the given Ecore Model. This is needed to properly access the ViewModel.
*
* @param ecoreModel
* the model for which the references shall be resolved.
*/
private void resolveReferences(IFile ecoreModel) {
final URI fileURI = URI.createFileURI(ecoreModel.getLocation().toString());
ecoreResource = resourceSet.getResource(fileURI, true);
// needed to resolve viewmodel references
for (final Iterator<EObject> it = ecoreResource.getAllContents(); it
.hasNext();) {
final EObject object = it.next();
if (object instanceof EPackage) {
final EPackage ePackage = (EPackage) object;
resourceSet.getPackageRegistry().put(ePackage.getNsURI(),
ePackage);
}
}
}
/**
* Returns the .genmodel file if the user entered one.
*
* @return
* the {@link IFile} containing the .genmodel or {@code null} if the user did not select one.
*/
public IFile getGenModel() {
return genModel;
}
/**
* Sets the .genmodel file for the wizard and its pages. Can be used before the wizard is actually opened to
* display the given model as default option.
*
* @param genModel
* the {@link IFile} containing the genmodel.
*/
public void setGenModel(IFile genModel) {
this.genModel = genModel;
}
/**
* Default constructor.
*/
public ViewModelExportWizard() {
setWindowTitle("Export View Model to Web");
resourceSet = new ResourceSetImpl();
}
@Override
public void addPages() {
modelsPage = new ModelPathsPage(ecoreModel, genModel);
eClassPage = new EClassPage();
viewModelPage = new ViewModelsPage();
addPage(modelsPage);
addPage(eClassPage);
addPage(viewModelPage);
}
/**
* Creates or updates a qb Play Application within the workspace or file system.
*
* @see org.eclipse.jface.wizard.Wizard#performFinish()
*/
@Override
public boolean performFinish() {
final File exportDirectory;
IProject project = null;
final IWorkspace workspace = ResourcesPlugin.getWorkspace();
final File workspaceDirectory = workspace.getRoot().getLocation().toFile();
if (modelsPage.isCreateNewApplication()) {
// determine destination
final String newProjectName = modelsPage.getProjectPath();
if (modelsPage.isInWorkspace()) {
exportDirectory = new File(workspaceDirectory, newProjectName);
} else {
exportDirectory = new File(modelsPage.getProjectPath());
}
final String templatePath = modelsPage.getTemplatePath();
if (templatePath != null && !templatePath.trim().equals("")) { //$NON-NLS-1$
try {
extractZip(templatePath, exportDirectory.getAbsolutePath());
if (modelsPage.isInWorkspace()) {
project = importProject(exportDirectory, newProjectName);
}
} catch (final IOException ex) {
MessageDialog.openError(getShell(), "IO Error", ex.getMessage());
} catch (final CoreException ex) {
MessageDialog.openError(getShell(), "Core Error", ex.getMessage());
}
}
} else {
// Update
if (modelsPage.isInWorkspace()) {
project = modelsPage.getSelectedProject();
exportDirectory = project.getLocation().toFile();
} else {
exportDirectory = new File(modelsPage.getProjectPath());
}
}
// Update Application
final Set<EClass> eClasses = eClassPage.getSelectedEClasses();
final Set<Resource> viewModels = new HashSet<Resource>();
for (final IFile viewFile : viewModelPage.getSelectedViewModels()) {
final URI fileURI = URI.createFileURI(viewFile.getLocation().toString());
final Resource viewResource = resourceSet.getResource(fileURI, true);
viewModels.add(viewResource);
}
EcoreUtil.resolveAll(resourceSet);
final Emf2QbExporter exporter = new Emf2QbExporter();
exporter.export(ecoreResource, eClasses, viewModels, exportDirectory);
if (project != null) {
try {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (final CoreException e) {
MessageDialog.openError(getShell(), "Refresh Error", e.getMessage());
e.printStackTrace();
}
}
return true;
}
/**
* Extracts the given zip file to the given destination.
*
* @param zipFilePath
* The absolute path of the zip file.
* @param destinationPath
* The absolute path of the destination directory;
* @throws IOException when extracting or copying fails.
*/
private void extractZip(String zipFilePath, String destinationPath) throws IOException {
final ZipFile zipFile = new ZipFile(zipFilePath);
final Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
final File entryDestination = new File(destinationPath, entry.getName());
entryDestination.getParentFile().mkdirs();
if (entry.isDirectory()) {
entryDestination.mkdirs();
} else {
final InputStream in = zipFile.getInputStream(entry);
final OutputStream out = new FileOutputStream(entryDestination);
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
zipFile.close();
}
/**
* Imports the given project into the workspace with the specified name.
*
* @param projectDirectory
* The directory containing the project and the ".project" file.
* @param projectName
* The name for the new project.
* @return
* The imported project.
* @throws CoreException
*/
private IProject importProject(final File projectDirectory, final String projectName) throws CoreException {
final IProjectDescription description = ResourcesPlugin.getWorkspace().loadProjectDescription(
new Path(new File(projectDirectory, ".project").getAbsolutePath())); //$NON-NLS-1$
description.setName(projectName);
final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
project.create(description, null);
project.open(null);
return project;
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
for (@SuppressWarnings("unchecked")
final Iterator<Object> it = selection.iterator(); it.hasNext();) {
final Object selectedObject = it.next();
if (selectedObject instanceof IFile) {
final IFile file = (IFile) selectedObject;
if (file.getLocation().getFileExtension().equals("ecore")) { //$NON-NLS-1$
setEcoreModel(file);
} else if (file.getLocation().getFileExtension()
.equals("genmodel")) { //$NON-NLS-1$
genModel = file;
}
}
}
}
/**
* Transfers information from the {@link ModelPathsPage} to the {@link EClassPage} when changing the page.
*
* @see org.eclipse.jface.dialogs.IPageChangingListener#handlePageChanging(org.eclipse.jface.dialogs.PageChangingEvent)
*/
@Override
public void handlePageChanging(PageChangingEvent event) {
if (event.getCurrentPage() == modelsPage) {
final IFile ecoreModelFile = modelsPage.getEcoreModelFile();
if (ecoreModelFile != null) {
setEcoreModel(ecoreModelFile);
}
if (ecoreResource != eClassPage.getEcoreResource()) {
eClassPage.setNewResource(ecoreResource);
}
}
}
}
| epl-1.0 |
abstratt/textuml | plugins/com.abstratt.mdd.frontend.textuml.ui/src/com/abstratt/mdd/internal/ui/model/PrimitiveType.java | 1811 | /*******************************************************************************
* Copyright (c) 2006, 2008 Abstratt Technologies
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Rafael Chaves (Abstratt Technologies) - initial API and implementation
*******************************************************************************/
package com.abstratt.mdd.internal.ui.model;
import java.util.Collections;
import java.util.List;
import org.eclipse.swt.graphics.Image;
import com.abstratt.mdd.frontend.core.ASTNode;
import com.abstratt.mdd.frontend.textuml.grammar.node.APrimitiveDef;
import com.abstratt.mdd.frontend.textuml.grammar.node.Node;
import com.abstratt.mdd.frontend.textuml.grammar.node.Token;
import com.abstratt.mdd.ui.Activator;
import com.abstratt.mdd.ui.UIConstants;
public class PrimitiveType extends UIModelObject {
public PrimitiveType(UIModelObject parent, ASTNode<Token, Node> node) {
super(parent, node);
}
@Override
public Image getImage() {
return Activator.getDefault().getImageRegistry().get(UIConstants.ICON_INTERFACE);
}
private APrimitiveDef getModel() {
return (APrimitiveDef) node.getBaseNode();
}
public List getModelTargetConnections() {
return Collections.EMPTY_LIST;
}
@Override
public String getOriginalText() {
return getModel().getIdentifier().getText();
}
@Override
public Token getToken() {
APrimitiveDef definition = getModel();
return definition.getIdentifier();
}
} | epl-1.0 |
whizzosoftware/hobson-hub-rules | src/main/java/com/whizzosoftware/hobson/rules/condition/DeviceIndoorTempAboveConditionClass.java | 3883 | /*******************************************************************************
* Copyright (c) 2015 Whizzo Software, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.whizzosoftware.hobson.rules.condition;
import com.whizzosoftware.hobson.api.device.DeviceContext;
import com.whizzosoftware.hobson.api.event.device.DeviceVariablesUpdateEvent;
import com.whizzosoftware.hobson.api.plugin.PluginContext;
import com.whizzosoftware.hobson.api.property.*;
import com.whizzosoftware.hobson.api.task.condition.ConditionClassType;
import com.whizzosoftware.hobson.api.task.condition.ConditionEvaluationContext;
import com.whizzosoftware.hobson.api.variable.VariableConstants;
import org.apache.commons.lang3.StringUtils;
import org.jruleengine.rule.Assumption;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class DeviceIndoorTempAboveConditionClass extends AbstractRuleConditionClass {
public static final String ID = "inTempAbove";
public DeviceIndoorTempAboveConditionClass(PluginContext context) {
super(PropertyContainerClassContext.create(context, ID), "An indoor temperature rises above", "{devices} indoor temperature rises above {inTempF}");
}
@Override
public ConditionClassType getConditionClassType() {
return ConditionClassType.trigger;
}
@Override
public boolean evaluate(ConditionEvaluationContext context, PropertyContainer values) {
return true;
}
@Override
protected List<TypedProperty> createProperties() {
List<TypedProperty> props = new ArrayList<>();
props.add(new TypedProperty.Builder("devices", "Devices", "The device(s) reporting the temperature", TypedProperty.Type.DEVICES).
constraint(PropertyConstraintType.required, true).
constraint(PropertyConstraintType.deviceVariable, VariableConstants.INDOOR_TEMP_F).
build()
);
props.add(new TypedProperty.Builder(VariableConstants.INDOOR_TEMP_F, "Temperature", "The temperature in Fahrenheit", TypedProperty.Type.NUMBER).
constraint(PropertyConstraintType.required, true).
build()
);
return props;
}
@Override
public List<Assumption> createConditionAssumptions(PropertyContainer condition) {
List<Assumption> assumpList = new ArrayList<>();
Collection<DeviceContext> dctxs = (Collection<DeviceContext>)condition.getPropertyValue("devices");
assumpList.add(new Assumption(ConditionConstants.EVENT_ID, "=", DeviceVariablesUpdateEvent.ID));
assumpList.add(new Assumption("event.deviceCtx", "containsatleastone", "[" + StringUtils.join(dctxs, ',') + "]"));
assumpList.add(new Assumption("event.variableName", ">", VariableConstants.INDOOR_TEMP_F));
return assumpList;
}
@Override
public JSONArray createAssumptionJSON(PropertyContainer condition) {
JSONArray a = new JSONArray();
a.put(createJSONCondition(ConditionConstants.EVENT_ID, "=", DeviceVariablesUpdateEvent.ID));
Collection<DeviceContext> ctx = (Collection<DeviceContext>)condition.getPropertyValue("devices");
a.put(createJSONCondition(ConditionConstants.DEVICE_CTX, "containsatleastone", "[" + StringUtils.join(ctx, ',') + "]"));
a.put(createJSONCondition(ConditionConstants.VARIABLE_NAME, "=", VariableConstants.INDOOR_TEMP_F));
a.put(createJSONCondition(ConditionConstants.VARIABLE_VALUE, ">", condition.getStringPropertyValue(VariableConstants.INDOOR_TEMP_F)));
return a;
}
}
| epl-1.0 |
PuruGowda/Bindaas1 | BindaasTeam/src/com/wattabyte/bindaasteam/util/BindaasUtil.java | 1086 | package com.wattabyte.bindaasteam.util;
import java.util.ArrayList;
public class BindaasUtil {
private static String fbName;
private static String fbId;
private static String playerName;
private String teamName;
ArrayList<String> list;
static ArrayList<String> tName;
public BindaasUtil() {
}
public static String getFbName() {
return fbName;
}
public static void setFbName(String fbName) {
BindaasUtil.fbName = fbName;
}
public static String getFbId() {
return fbId;
}
public static void setFbId(String fbBirthDate) {
BindaasUtil.fbId = fbBirthDate;
}
public static String getPlayerName() {
return playerName;
}
public static void setPlayerName(String playerName) {
BindaasUtil.playerName = playerName;
}
public BindaasUtil(ArrayList<String> list)
{
this.list = list;
}
public ArrayList<String> getList() {
return list;
}
public void setList(ArrayList<String> list) {
this.list = list;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
}
| epl-1.0 |
TristanFAURE/query2Table | plugins/org.topcased.model2doc.query2table.ui/src/org/topcased/model2doc/query2table/ui/preferences/IPreferenceSaver.java | 591 | /*****************************************************************************
* Copyright (c) 2014 Atos.
*
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*
*****************************************************************************/
package org.topcased.model2doc.query2table.ui.preferences;
public interface IPreferenceSaver {
void add (IPreferenceSavable savable) ;
}
| epl-1.0 |
test-editor/test-editor | fitnesse/org.testeditor.fitnesse/src/test/java/org/testeditor/fitnesse/FitnesseTechnicalBindingsDSLMappingServiceTest.java | 5502 | /*******************************************************************************
* Copyright (c) 2012 - 2015 Signal Iduna Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Signal Iduna Corporation - initial API and implementation
* akquinet AG
*******************************************************************************/
package org.testeditor.fitnesse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.Test;
import org.testeditor.core.services.interfaces.TechnicalBindingsDSLMappingService;
/**
*
* Modultests for FitnesseTechnicalBindingsDSLMappingService.
*
*/
public class FitnesseTechnicalBindingsDSLMappingServiceTest {
private TechnicalBindingsDSLMappingService technicalBindingsDSLMappingService;
/**
* Init the Object under Test.
*/
@Before
public void initOUT() {
technicalBindingsDSLMappingService = new FitnesseTechnicalBindingsDSLMappingService();
}
/**
* Tests the Method name extraction.
*
* @throws Exception
* for test
*/
@Test
public void testMethodNameExtraction() throws Exception {
FitnesseTechnicalBindingsDSLMappingService fitnesseTecBindingService = (FitnesseTechnicalBindingsDSLMappingService) technicalBindingsDSLMappingService;
assertEquals("click ()", fitnesseTecBindingService.extractMethodNameFromTechnicalBinding("click ( \"hugo\")"));
assertEquals("click ()", fitnesseTecBindingService.extractMethodNameFromTechnicalBinding("click ( \"login\")"));
assertEquals("insertIntoField ()", fitnesseTecBindingService
.extractMethodNameFromTechnicalBinding("insertIntoField ( \"test\", \"usr\")"));
}
/**
* Test the Replacement for Parameters in the Fitnesse DSL with the actual
* Paramter of the technical binding method.
*
* @throws Exception
* for Test
*/
@Test
public void testReplaceFitnesseDSLParametersWithTechnicalBindingParameters() throws Exception {
FitnesseTechnicalBindingsDSLMappingService fitnesseTecBindingService = (FitnesseTechnicalBindingsDSLMappingService) technicalBindingsDSLMappingService;
assertEquals("|klicke auf|login|",
fitnesseTecBindingService.replaceFitnesseDSLParametersWithTechnicalBindingParameters(
new TecBindDslParameteMapper("|klicke auf|guiElement|", "guiElement"), "click ( \"login\")"));
assertEquals("|gebe in das Feld|usr|den Wert|test|ein|",
fitnesseTecBindingService.replaceFitnesseDSLParametersWithTechnicalBindingParameters(
new TecBindDslParameteMapper("|gebe in das Feld|guiid|den Wert|text|ein|", "text,guiid"),
"insertIntoField ( \"test\", \"usr\")"));
}
/**
* Test Remove of quotation from a string.
*
* @throws Exception
* for Test
*/
@Test
public void testFixPossibleQuotMarks() throws Exception {
FitnesseTechnicalBindingsDSLMappingService fitnesseTecBindingService = (FitnesseTechnicalBindingsDSLMappingService) technicalBindingsDSLMappingService;
assertEquals("1", fitnesseTecBindingService.fixPossibleQuotMarks("1"));
assertEquals("login", fitnesseTecBindingService.fixPossibleQuotMarks("\"login\""));
assertEquals("login", fitnesseTecBindingService.fixPossibleQuotMarks(" \"login\" "));
}
/**
* Test the Mapping for. click ( "Login" ) to: klicke auf|guiElement|
*
* @throws Exception
* for test
*/
@Test
public void testMappingForClick() throws Exception {
String mapping = technicalBindingsDSLMappingService.mapTechnicalBindingToTestDSL("click ( \"Login\" )");
assertEquals("|klicke auf|Login|", mapping);
}
/**
* Test the Mapping for. navigateToUrl (
* "http://localhost:8060/files/demo/ExampleApplication/WebApplicationDe/index.html"
* ) to: navigiere auf die Seite|url|
*
* @throws Exception
* for test
*/
@Test
public void testMappingForNavigate() throws Exception {
String mapping = technicalBindingsDSLMappingService.mapTechnicalBindingToTestDSL(
"navigateToUrl ( \"http://localhost:8060/files/demo/ExampleApplication/WebApplicationDe/index.html\" )");
assertEquals(
"|navigiere auf die Seite|http://localhost:8060/files/demo/ExampleApplication/WebApplicationDe/index.html|",
mapping);
}
/**
* Test the Mapping for. insertIntoField ( "test","Passwort" ) to: gebe in
* das Feld|guiid|den Wert|text|ein|
*
* @throws Exception
* for test
*/
@Test
public void testMappingForInsertIntoField() throws Exception {
String mapping = technicalBindingsDSLMappingService
.mapTechnicalBindingToTestDSL("insertIntoField ( \"test\",\"Passwort\" )");
assertEquals("|gebe in das Feld|Passwort|den Wert|test|ein|", mapping);
}
/**
* Test the Mapping for Elements that are technical nature and not used for
* the TestDSL. Examples are: waiting(2) setElementList("/path/")
*
* @throws Exception
* for test
*/
@Test
public void testMappingForNonTestDSLElements() throws Exception {
String mapping = technicalBindingsDSLMappingService.mapTechnicalBindingToTestDSL("wating ( 1 )");
assertNull("NoValue for waiting", mapping);
mapping = technicalBindingsDSLMappingService.mapTechnicalBindingToTestDSL("setElementlist ( \"/path\" )");
assertNull("NoValue for setElementlist", mapping);
}
}
| epl-1.0 |
occiware/OCCI-Studio | plugins/org.eclipse.cmf.occi.core.xtext.ui/xtend-gen/org/eclipse/cmf/occi/core/xtext/ui/quickfix/OCCIQuickfixProvider.java | 378 | /**
* generated by Xtext 2.10.0
*/
package org.eclipse.cmf.occi.core.xtext.ui.quickfix;
import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider;
/**
* Custom quickfixes.
*
* See https://www.eclipse.org/Xtext/documentation/310_eclipse_support.html#quick-fixes
*/
@SuppressWarnings("all")
public class OCCIQuickfixProvider extends DefaultQuickfixProvider {
}
| epl-1.0 |
georgeerhan/openhab2-addons | addons/binding/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/handler/IPBridgeHandler.java | 13821 | /**
* Copyright (c) 2010-2017 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.lutron.handler;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.eclipse.smarthome.config.discovery.DiscoveryService;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.eclipse.smarthome.core.thing.binding.BaseBridgeHandler;
import org.eclipse.smarthome.core.types.Command;
import org.openhab.binding.lutron.config.IPBridgeConfig;
import org.openhab.binding.lutron.internal.discovery.LutronDeviceDiscoveryService;
import org.openhab.binding.lutron.internal.net.TelnetSession;
import org.openhab.binding.lutron.internal.net.TelnetSessionListener;
import org.openhab.binding.lutron.internal.protocol.LutronCommand;
import org.openhab.binding.lutron.internal.protocol.LutronCommandType;
import org.openhab.binding.lutron.internal.protocol.LutronOperation;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handler responsible for communicating with the main Lutron control hub.
*
* @author Allan Tong - Initial contribution
*/
public class IPBridgeHandler extends BaseBridgeHandler {
private static final Pattern STATUS_REGEX = Pattern.compile("~(OUTPUT|DEVICE|SYSTEM),([^,]+),(.*)");
private static final String DB_UPDATE_DATE_FORMAT = "MM/dd/yyyy HH:mm:ss";
private static final Integer MONITOR_PROMPT = 12;
private static final Integer MONITOR_DISABLE = 2;
private static final Integer SYSTEM_DBEXPORTDATETIME = 10;
private static final int MAX_LOGIN_ATTEMPTS = 2;
private static final String DEFAULT_USER = "lutron";
private static final String DEFAULT_PASSWORD = "integration";
private Logger logger = LoggerFactory.getLogger(IPBridgeHandler.class);
private IPBridgeConfig config;
private TelnetSession session;
private BlockingQueue<LutronCommand> sendQueue = new LinkedBlockingQueue<>();
private ScheduledFuture<?> messageSender;
private ScheduledFuture<?> keepAlive;
private ScheduledFuture<?> keepAliveReconnect;
private Date lastDbUpdateDate;
private ServiceRegistration<DiscoveryService> discoveryServiceRegistration;
public IPBridgeHandler(Bridge bridge) {
super(bridge);
this.session = new TelnetSession();
this.session.addListener(new TelnetSessionListener() {
@Override
public void inputAvailable() {
parseUpdates();
}
@Override
public void error(IOException exception) {
}
});
}
public IPBridgeConfig getIPBridgeConfig() {
return this.config;
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
}
@Override
public void initialize() {
this.config = getThing().getConfiguration().as(IPBridgeConfig.class);
if (validConfiguration(this.config)) {
LutronDeviceDiscoveryService discovery = new LutronDeviceDiscoveryService(this);
this.discoveryServiceRegistration = this.bundleContext.registerService(DiscoveryService.class, discovery,
null);
this.scheduler.schedule(new Runnable() {
@Override
public void run() {
connect();
}
}, 0, TimeUnit.SECONDS);
}
}
private boolean validConfiguration(IPBridgeConfig config) {
if (this.config == null) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "bridge configuration missing");
return false;
}
if (StringUtils.isEmpty(this.config.getIpAddress())) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "bridge address not specified");
return false;
}
return true;
}
private synchronized void connect() {
if (this.session.isConnected()) {
return;
}
this.logger.debug("Connecting to bridge at {}", config.getIpAddress());
try {
if (!login(config)) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "invalid username/password");
return;
}
// Disable prompts
sendCommand(new LutronCommand(LutronOperation.EXECUTE, LutronCommandType.MONITORING, -1, MONITOR_PROMPT,
MONITOR_DISABLE));
// Check the time device database was last updated. On the initial connect, this will trigger
// a scan for paired devices.
sendCommand(
new LutronCommand(LutronOperation.QUERY, LutronCommandType.SYSTEM, -1, SYSTEM_DBEXPORTDATETIME));
} catch (IOException e) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
disconnect();
return;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR, "login interrupted");
disconnect();
return;
}
this.messageSender = this.scheduler.schedule(new Runnable() {
@Override
public void run() {
sendCommands();
}
}, 0, TimeUnit.SECONDS);
updateStatus(ThingStatus.ONLINE);
this.keepAlive = this.scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
sendKeepAlive();
}
}, 5, 5, TimeUnit.MINUTES);
}
private void sendCommands() {
try {
while (true) {
LutronCommand command = this.sendQueue.take();
this.logger.debug("Sending command " + command.toString());
try {
this.session.writeLine(command.toString());
} catch (IOException e) {
this.logger.error("Communication error, will try to reconnect", e);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
// Requeue command
this.sendQueue.add(command);
reconnect();
// reconnect() will start a new thread; terminate this one
break;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private synchronized void disconnect() {
this.logger.debug("Disconnecting from bridge");
if (this.keepAlive != null) {
this.keepAlive.cancel(true);
}
if (this.keepAliveReconnect != null) {
// This method can be called from the keepAliveReconnect thread. Make sure
// we don't interrupt ourselves, as that may prevent the reconnection attempt.
this.keepAliveReconnect.cancel(false);
}
if (this.messageSender != null) {
this.messageSender.cancel(true);
}
try {
this.session.close();
} catch (IOException e) {
this.logger.error("Error disconnecting", e);
}
}
private synchronized void reconnect() {
this.logger.debug("Keepalive timeout, attempting to reconnect to the bridge");
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.DUTY_CYCLE);
disconnect();
connect();
}
private boolean login(IPBridgeConfig config) throws IOException, InterruptedException {
this.session.open(config.getIpAddress());
this.session.waitFor("login:");
// Sometimes the Lutron Smart Bridge Pro will request login more than once.
for (int attempt = 0; attempt < MAX_LOGIN_ATTEMPTS; attempt++) {
this.session.writeLine(config.getUser() != null ? config.getUser() : DEFAULT_USER);
this.session.waitFor("password:");
this.session.writeLine(config.getPassword() != null ? config.getPassword() : DEFAULT_PASSWORD);
MatchResult matchResult = this.session.waitFor("(login:|GNET>)");
if ("GNET>".equals(matchResult.group())) {
return true;
}
this.logger.debug("got another login prompt, logging in again");
// we already got the login prompt so go straight to sending user
}
return false;
}
void sendCommand(LutronCommand command) {
this.sendQueue.add(command);
}
private LutronHandler findThingHandler(int integrationId) {
for (Thing thing : getThing().getThings()) {
if (thing.getHandler() instanceof LutronHandler) {
LutronHandler handler = (LutronHandler) thing.getHandler();
if (handler.getIntegrationId() == integrationId) {
return handler;
}
}
}
return null;
}
private void parseUpdates() {
for (String line : this.session.readLines()) {
if (line.trim().equals("")) {
// Sometimes we get an empty line (possibly only when prompts are disabled). Ignore them.
continue;
}
this.logger.debug("Received message " + line);
// System is alive, cancel reconnect task.
if (this.keepAliveReconnect != null) {
this.keepAliveReconnect.cancel(true);
}
Matcher matcher = STATUS_REGEX.matcher(line);
if (matcher.matches()) {
LutronCommandType type = LutronCommandType.valueOf(matcher.group(1));
if (type == LutronCommandType.SYSTEM) {
// SYSTEM messages are assumed to be a response to the SYSTEM_DBEXPORTDATETIME
// query. The response returns the last time the device database was updated.
setDbUpdateDate(matcher.group(2), matcher.group(3));
continue;
}
Integer integrationId = new Integer(matcher.group(2));
LutronHandler handler = findThingHandler(integrationId);
if (handler != null) {
String paramString = matcher.group(3);
try {
handler.handleUpdate(type, paramString.split(","));
} catch (Exception e) {
this.logger.error("Error processing update", e);
}
} else {
this.logger.info("No thing configured for integration ID " + integrationId);
}
} else {
this.logger.info("Ignoring message " + line);
}
}
}
private void sendKeepAlive() {
// Reconnect if no response is received within 30 seconds.
this.keepAliveReconnect = this.scheduler.schedule(new Runnable() {
@Override
public void run() {
reconnect();
}
}, 30, TimeUnit.SECONDS);
sendCommand(new LutronCommand(LutronOperation.QUERY, LutronCommandType.SYSTEM, -1, SYSTEM_DBEXPORTDATETIME));
}
private void setDbUpdateDate(String dateString, String timeString) {
try {
Date date = new SimpleDateFormat(DB_UPDATE_DATE_FORMAT).parse(dateString + " " + timeString);
if (this.lastDbUpdateDate == null || date.after(this.lastDbUpdateDate)) {
scanForDevices();
this.lastDbUpdateDate = date;
}
} catch (ParseException e) {
logger.error("Failed to parse DB update date {} {}", dateString, timeString);
}
}
private void scanForDevices() {
try {
DiscoveryService service = this.bundleContext.getService(this.discoveryServiceRegistration.getReference());
if (service != null) {
service.startScan(null);
}
} catch (Exception e) {
logger.error("Error scanning for paired devices", e);
}
}
@Override
public void thingUpdated(Thing thing) {
IPBridgeConfig newConfig = thing.getConfiguration().as(IPBridgeConfig.class);
boolean validConfig = validConfiguration(newConfig);
boolean needsReconnect = validConfig && !this.config.sameConnectionParameters(newConfig);
if (!validConfig || needsReconnect) {
dispose();
}
this.thing = thing;
this.config = newConfig;
if (needsReconnect) {
initialize();
}
}
@Override
public void dispose() {
disconnect();
if (this.discoveryServiceRegistration != null) {
this.discoveryServiceRegistration.unregister();
this.discoveryServiceRegistration = null;
}
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/page/ui/com.odcgroup.page.ui/src/main/java/com/odcgroup/page/ui/figure/Fragment.java | 576 | package com.odcgroup.page.ui.figure;
import com.odcgroup.page.model.Widget;
/**
* A fragment. This does not display anything by itself.
*
* @author Gary Hayes
*/
public class Fragment extends BoxFigure {
/**
* Creates a new Fragment.
*
* @param widget The Widget being displayed by this Figure
* @param figureContext The context providing information required for displaying the page correctly
*/
public Fragment(Widget widget, FigureContext figureContext) {
super(widget, figureContext);
setLayoutManager(new VerticalLayout(figureContext));
}
}
| epl-1.0 |
parraman/micobs | mclev/es.uah.aut.srg.micobs.mclev/src/es/uah/aut/srg/micobs/mclev/mclevdom/MIntegerParamIODSPSwitch.java | 1027 | /*******************************************************************************
* Copyright (c) 2013-2015 UAH Space Research Group.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* MICOBS SRG Team - Initial API and implementation
******************************************************************************/
package es.uah.aut.srg.micobs.mclev.mclevdom;
import es.uah.aut.srg.micobs.common.MIntegerParameter;
/**
* A representation of an integer attribute of an implementation-oriented
* domain whose default value is defined depending on the different supported
* platforms.
*
* @see es.uah.aut.srg.micobs.mclev.mclevdom.mclevdomPackage#getMIntegerParamIODSPSwitch()
* @model
* @generated
*/
public interface MIntegerParamIODSPSwitch extends MIntegerParameter, MParameterIODSPSwitch {
} | epl-1.0 |