repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
richardtynan/thornsec
src/core/iface/INetworkData.java
475
package core.iface; public interface INetworkData extends IData { public String[] getServerLabels(); public String[] getDeviceLabels(); public String[] getDeviceMacs(); public String[] getServerProfiles(String server); public String getServerData(String server, String label); public String getServerUser(String server); public String getServerIP(String server); public String getServerPort(String server); public String getServerUpdate(String server); }
gpl-3.0
squizzdotcom/squizz-platform-api-java-library
src/org/squizz/api/v1/endpoint/APIv1EndpointOrgSearchCustomerAccountRecords.java
7139
/** * Copyright (C) 2017 Squizz PTY LTD * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ package org.squizz.api.v1.endpoint; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.ResourceBundle; import javafx.util.Pair; import org.squizz.api.v1.APIv1Constants; import org.squizz.api.v1.APIv1HTTPRequest; import org.squizz.api.v1.APIv1OrgSession; import org.esd.EcommerceStandardsDocuments.*; import org.squizz.api.v1.endpoint.APIv1EndpointResponse; import org.squizz.api.v1.endpoint.APIv1EndpointResponseESD; /** * Class handles calling the SQUIZZ.com API endpoint to search for and retrieve records (such as invoices, sales orders, back orders, payments, credits, transactions) associated to a supplier organisation's customer account. See the full list at https://www.squizz.com/docs/squizz/Platform-API.html#section1035 * The data being retrieved is wrapped up in a Ecommerce Standards Document (ESD) that contains records storing data of a particular type */ public class APIv1EndpointOrgSearchCustomerAccountRecords { /** * Calls the platform's API endpoint and searches for a connected organisation's customer account records retrieved live from their connected business system * @param apiOrgSession existing organisation API session * @param endpointTimeoutMilliseconds amount of milliseconds to wait after calling the the API before giving up, set a positive number * @param recordType type of record data to search for. * @param supplierOrgID unique ID of the organisation in the SQUIZZ.com platform that has supplies the customer account * @param customerAccountCode code of the account organisation's customer account. Customer account only needs to be set if the supplier organisation has assigned multiple accounts to the organisation logged into the API session (customer org) and account specific data is being obtained * @param beginDateTime earliest date time to search for records for. Date time set as milliseconds since 1/1/1970 12am UTC epoch * @param endDateTime latest date time to search for records up to. Date time set as milliseconds since 1/1/1970 12am UTC epoch * @param pageNumber page number to obtain records from * @param recordsMaxAmount maximum number of records to return * @param outstandingRecords if true then only search for records that are marked as outstanding (such as unpaid invoices) * @param searchString search text to match records on * @param keyRecordIDs comma delimited list of records unique key record ID to match on. Each Key Record ID value needs to be URI encoded * @param searchType specifies the field to search for records on, matching the record's field with the search string given * @return response from calling the API endpoint */ public static APIv1EndpointResponseESD call( APIv1OrgSession apiOrgSession, int endpointTimeoutMilliseconds, String recordType, String supplierOrgID, String customerAccountCode, long beginDateTime, long endDateTime, int pageNumber, int recordsMaxAmount, boolean outstandingRecords, String searchString, String keyRecordIDs, String searchType) { ArrayList<Pair<String, String>> requestHeaders = new ArrayList<>(); APIv1EndpointResponseESD endpointResponse = new APIv1EndpointResponseESD(); ObjectReader endpointJSONReader = null; boolean callEndpoint = true; try{ //set endpoint parameters String endpointParams = "record_type="+recordType + "&supplier_org_id=" + URLEncoder.encode(supplierOrgID, StandardCharsets.UTF_8.name()) + "&customer_account_code="+URLEncoder.encode(customerAccountCode, StandardCharsets.UTF_8.name()) + "&begin_date_time=" + beginDateTime+ "&end_date_time=" + endDateTime+ "&page_number=" + pageNumber+ "&records_max_amount=" + recordsMaxAmount+ "&outstanding_records=" + (outstandingRecords?"Y":"N")+ "&search_string=" + URLEncoder.encode(searchString, StandardCharsets.UTF_8.name())+ "&key_record_ids=" + URLEncoder.encode(keyRecordIDs, StandardCharsets.UTF_8.name())+ "&search_type=" + URLEncoder.encode(searchType, StandardCharsets.UTF_8.name()); //create JSON deserializer to interpret the response from the endpoint ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); endpointJSONReader = jsonMapper.readerFor(ESDocumentCustomerAccountEnquiry.class); //make a HTTP request to the platform's API endpoint to search for the customer account records if(callEndpoint && endpointJSONReader != null) { endpointResponse = APIv1HTTPRequest.sendESDocumentHTTPRequest(APIv1Constants.HTTP_REQUEST_METHOD_GET, APIv1Constants.API_ORG_ENDPOINT_SEARCH_CUSTOMER_ACCOUNT_RECORDS_ESD+APIv1Constants.API_PATH_SLASH+apiOrgSession.getSessionID(), endpointParams, requestHeaders, "", null, endpointTimeoutMilliseconds, apiOrgSession.getLangBundle(), endpointJSONReader, endpointResponse); //check that the data was successfully retrieved if(!endpointResponse.result.equalsIgnoreCase(APIv1EndpointResponse.ENDPOINT_RESULT_SUCCESS)) { //check if the session still exists if(endpointResponse.result.equalsIgnoreCase(APIv1EndpointResponse.ENDPOINT_RESULT_CODE_ERROR_SESSION_INVALID)){ //mark that the session has expired apiOrgSession.markSessionExpired(); } } } } catch(Exception ex) { endpointResponse.result = APIv1EndpointResponse.ENDPOINT_RESULT_FAILURE; endpointResponse.result_code = APIv1EndpointResponse.ENDPOINT_RESULT_CODE_ERROR_UNKNOWN; endpointResponse.result_message = apiOrgSession.getLangBundle().getString(endpointResponse.result_code) + "\n" + ex.getLocalizedMessage(); } return endpointResponse; } }
gpl-3.0
kuhnmi/jukefox
JukefoxModel/src/ch/ethz/dcg/jukefox/model/collection/AllAlbumsRepresentative.java
1232
/* * Copyright 2008-2013, ETH Zürich, Samuel Welten, Michael Kuhn, Tobias Langner, * Sandro Affentranger, Lukas Bossard, Michael Grob, Rahul Jain, * Dominic Langenegger, Sonia Mayor Alonso, Roger Odermatt, Tobias Schlueter, * Yannick Stucki, Sebastian Wendland, Samuel Zehnder, Samuel Zihlmann, * Samuel Zweifel * * This file is part of Jukefox. * * Jukefox is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or any later version. Jukefox is * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * Jukefox. If not, see <http://www.gnu.org/licenses/>. */ package ch.ethz.dcg.jukefox.model.collection; import java.util.Arrays; public class AllAlbumsRepresentative extends MapAlbum { public AllAlbumsRepresentative(BaseArtist artist) { super(-1, "All Songs", new float[] {}, 0, Arrays.asList(artist)); } }
gpl-3.0
callaa/JGCGen
src/org/luolamies/jgcgen/shapes/surface/Image.java
7822
package org.luolamies.jgcgen.shapes.surface; import java.io.IOException; import org.luolamies.jgcgen.JGCGenerator; import org.luolamies.jgcgen.RenderException; import org.luolamies.jgcgen.path.Axis; import org.luolamies.jgcgen.path.Coordinate; import org.luolamies.jgcgen.path.NumericCoordinate; import org.luolamies.jgcgen.path.Path; import org.luolamies.jgcgen.path.PathGenerator; import org.luolamies.jgcgen.tools.Tool; public class Image implements PathGenerator { // Configuration private NumericCoordinate topleft = new NumericCoordinate(0.0, 0.0, 0.0); private String filename; private String strategy="simple"; private boolean invert, normalize, flip, mirror, rotate; private double xsize=-1, ysize=-1, zscale=1.0; private String stepover=""; private Tool tool; // Computed values private double width, height; private double dstepover; private Surface imgcache; /** * Get the configured tool * @return tool */ protected final Tool getTool() { return tool; } /** * Get the origin (topleft) point * @return origin */ protected final NumericCoordinate getOrigin() { return topleft; } /** * Set the name of the input image * @param name * @return */ public Image file(String name) { if(!name.equals(filename)) { filename = name; imgcache = null; } return this; } /** * Set image from a surface * @param surface * @return */ public Image src(Surface surface) { filename = null; imgcache = surface; return this; } /** * Set the image origin (topleft coordinate) * @param origin * @return this */ public Image origin(String origin) { NumericCoordinate nc; try { nc = (NumericCoordinate) Coordinate.parse(origin); } catch(ClassCastException e) { throw new IllegalArgumentException("Only numeric coordinates are supported!"); } if(!nc.isDefined(Axis.X) || !nc.isDefined(Axis.Y)) throw new IllegalArgumentException("X and Y axes must be defined!"); if(!nc.isDefined(Axis.Z)) nc.set(Axis.Z, 0.0); topleft = nc; return this; } /** * Invert the input image * @return */ public Image invert() { if(filename!=null) imgcache = null; invert = !invert; return this; } /** * Normalize the input image. This stretches the values so the smallest value will become 0 and the biggest 1. * @return */ public Image normalize() { if(filename!=null) imgcache = null; normalize = true; return this; } /** * Flip the image upside down * @return */ public Image flip() { if(filename!=null) imgcache = null; flip = !flip; return this; } /** * Mirror the image * @return */ public Image mirror() { if(filename!=null) imgcache = null; mirror = !mirror; return this; } /** * Rotate the image 90 degrees * @return */ public Image rotate() { if(filename!=null) imgcache = null; rotate = !rotate; return this; } /** * Set the height of the image. Image pixel zero value will correspond to origin Z - height and 1.0 to origin Z. * @param scale * @return */ public Image height(double scale) { this.zscale = scale; return this; } /** * Set the size of the carving area. The pixel size will be set so the image will * fit in the requested area. Aspect ratio is maintained. * @param x width in millimeters or inches * @param y height in millimeters or inches * @return */ public Image size(double x,double y) { if(x<=0 || y<=0) throw new IllegalArgumentException("Dimensions must be greater than zero!"); this.xsize = x; this.ysize = y; if(filename!=null) imgcache = null; return this; } /** * Set the maximum distance between adjacent rows or columns. * The stepover size determines how many pixel rows/columns are skipped between lines. * If zero is given, a stepover value is calculated automatically. * @param size stepover size in mm/inches * @return */ public Image stepover(double size) { if(size<0) throw new IllegalArgumentException("Stepover must be greater zero or greater!"); if(size==0) this.stepover = ""; else this.stepover = Double.toString(size); return this; } /** * Set the maximum distance between adjacent rows or columns. * The size should either be a number or a percentage. If a percentage is * used, the stepover size is calculated from the tool diameter. * <p>If a zero or empty string is given, the stepover will be calculated * automatically. * @param size * @return */ public Image stepover(String size) { if("0".equals(size)) stepover = ""; else stepover = size; return this; } /** * Select tool * <p> * Tool definition format is defined in {@link Tool#get(String)}. * @param tooldef * @return */ public Image tool(String tooldef) { this.tool = Tool.get(tooldef); return this; } /** * Set carving strategy * @param strategy * @return */ public Image strategy(String strategy) { this.strategy = strategy.toLowerCase(); return this; } /** * Get the width of the image * @return */ protected final double getWidth() { return width; } /** * Get the height of the image * @return */ protected final double getHeight() { return height; } /** * Get the distance between rows or columns * @return row/column gap */ protected final double getStepover() { return dstepover; } /** * Get the image surface * @return image surface */ public Surface getSurface() { if(xsize<0) throw new RenderException("Target size not set!"); if(imgcache==null) { // Load image try { imgcache = new ImageData(filename, normalize, invert, flip, mirror, rotate); } catch(IOException e) { throw new RenderException("Couldn't load image \"" + filename + "\": " + e.getMessage(), e); } // Set target size imgcache.setTargetSize(xsize, ysize, zscale); // Get true size // TODO maintain aspect ratio width = xsize; height = ysize; } else if(filename==null) { // Initialize external surface imgcache.setTargetSize(xsize, ysize, zscale); width = xsize; height = ysize; } return imgcache; } public Path toPath() { if(tool==null) throw new RenderException("Tool not set!"); if(filename==null && imgcache==null) throw new RenderException("Input file or source surface not set!"); // Select carving strategy ImageStrategy is; if("simple".equals(strategy)) is = new SimpleStrategy(this); else if(strategy.startsWith("simple ")) is = new SimpleStrategy(this, strategy.substring(7)); else if("rough".equals(strategy)) is = new RoughStrategy(this); else if(strategy.startsWith("rough ")) is = new RoughStrategy(this, strategy.substring(6)); else if(strategy.equals("outline")) is = new OutlineStrategy(this); else if(strategy.startsWith("outline ")) is = new OutlineStrategy(this, strategy.substring(8)); else throw new RenderException("Unknown strategy: " + strategy); // Make sure the image is loaded getSurface(); // Calculate the gap between rows or columns. if(stepover.length()==0) { // Zero stepover means the stategy will use some default value dstepover = 0; } else { // Stepover can be expressed in absolute units or as a percentage of tool diamater if(stepover.endsWith("%")) dstepover = Double.parseDouble(stepover.substring(0,stepover.length()-1)) / 100.0 * tool.getDiameter(); else dstepover = Double.parseDouble(stepover); } // Generate toolpath long time = System.currentTimeMillis(); Path path = is.toPath(imgcache); time = System.currentTimeMillis() - time; JGCGenerator.getLogger().status(is.getClass().getSimpleName() + " finished. Took " + String.format("%.2f", time/1000.0) + " seconds."); return path;//.reduce(); } }
gpl-3.0
lightstar/job4j-clinic
src/test/java/ru/lightstar/clinic/ui/action/AddClientTest.java
2035
package ru.lightstar.clinic.ui.action; import org.junit.Test; import ru.lightstar.clinic.exception.ActionException; import ru.lightstar.clinic.exception.NameException; import ru.lightstar.clinic.exception.ServiceException; import java.util.Arrays; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * <code>AddClient</code> action tests. * * @author LightStar * @since 0.0.1 */ public class AddClientTest extends ActionTest { /** * Constructs <code>AddClientTest</code> object. */ public AddClientTest() throws NameException, ServiceException { super(); } /** * {@inheritDoc} */ @Override protected Action createAction() { return new AddClient(this.clinicService); } /** * Test correctness of <code>getName</code> method. */ @Test public void whenGetNameThenResult() { assertThat(this.action.getName(), is("add")); } /** * Test correctness of <code>getDescription</code> object. */ @Test public void whenGetDescriptionThenResult() { assertThat(this.action.getDescription(), is("Add new client")); } /** * Test correctness of <code>run</code> method. */ @Test public void whenRunThenResult() throws ActionException, ServiceException { this.input.setIterator(Arrays.asList("Vova", "3").iterator()); this.action.run(); assertThat(this.output.toString(), is(this.helper.joinLines(new String[]{ "Client's name:", "Client's position:", "Client added." }))); assertThat(this.clinicService.getClientByPosition(2).getName(), is("Vova")); } /** * Test thrown exception on incorrect user input. */ @Test(expected = ActionException.class) public void whenRunWithIncorrectInputThenException() throws ActionException { this.input.setIterator(Arrays.asList("Vova", "a").iterator()); this.action.run(); } }
gpl-3.0
onycom-ankus/ankus_analyzer_G
trunk_web/ankus-web-services/src/main/java/org/ankus/web/account/Account.java
870
/** * This file is part of ankus. * * ankus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ankus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ankus. If not, see <http://www.gnu.org/licenses/>. */ package org.ankus.web.account; public class Account { private String name; private String username; private String password; private String mobile; private String telephone; }
gpl-3.0
wieliczk/as1
Asn1/app/src/main/java/com/example/sperk/asn1/Adding.java
7200
package com.example.sperk.asn1; import android.content.Context; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.reflect.Type; import java.util.ArrayList; /* * Adding adds a data entry to the saved list of entries * Has checks for the date as well as the floats * If all is correct, will save entries to Gson and * sends user back to MainActivity screen with a toast message * saying entry saved. */ public class Adding extends ActionBarActivity { private static String FILENAME = "file.sav"; private ArrayList<Data_Entry> D_logs = new ArrayList<Data_Entry>(); private int checker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); loadFromFile(); setContentView(R.layout.activity_adding); Button enterData = (Button) findViewById(R.id.enter_button); enterData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addData(); } }); } // backToMain_C is called from onClick funciton of the xml file // Cancel button clickable is applied to backToMain_C // Returns to MainActivity and sends Message public void backToMain_C(View view) { Intent cancels = new Intent(this, MainActivity.class); Toast dataCan = new Toast(getApplicationContext()); dataCan.makeText(Adding.this, "Data Entry Cancelled", dataCan.LENGTH_SHORT).show(); // Code take from http://stackoverflow.com/questions/11460896/button-to-go-back-to-mainactivity cancels.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(cancels); } // Returns to MainActivity and sends message public void saveToMain() { Toast dataSaved = new Toast(getApplicationContext()); dataSaved.makeText(Adding.this, "Data Entry Saved", dataSaved.LENGTH_SHORT).show(); Intent saved = new Intent(this, MainActivity.class); // Code take from http://stackoverflow.com/questions/11460896/button-to-go-back-to-mainactivity saved.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(saved); } // Checks proper date entry // If completes every check, only then is date accepted public int checkDate(String string) { int isWrong = 1; try { int year = Integer.parseInt(string.substring(0, 4)); String dash = string.substring(4,5); if(dash.equals("-")) { // Checks for proper month int month = Integer.parseInt(string.substring(5,7)); ArrayList<Integer> monthlist = new ArrayList<Integer>(); for (int i = 1; i < 13; i++) { monthlist.add(i); } if (monthlist.contains(month)) { String dash2 = string.substring(7,8); if (dash2.equals("-")) { // Checks for proper date int day = Integer.parseInt(string.substring(8)); ArrayList<Integer> dayList = new ArrayList<Integer>(); for (int i = 1; i < 32; i++) { dayList.add(i); } if (dayList.contains(day)) { isWrong = 0; } else { throw new Exception(); } } } else { throw new Exception(); } } } catch (Exception e) { // Do nothing } // Returns an int either 0 or 1 that sends proper message return isWrong; } // Taken from lonely Twitter public void loadFromFile() { try { FileInputStream fis = openFileInput(FILENAME); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); Gson gson = new Gson(); // Taken from Google Type listType = new TypeToken<ArrayList<Data_Entry>>() {}.getType(); D_logs = gson.fromJson(in, listType); } catch (FileNotFoundException e) { D_logs = new ArrayList<Data_Entry>(); // d_logs.setData_logs(D_logs); } } // Taken from lonely Twitter public void saveInFile() { try { FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos)); Gson gson = new Gson(); gson.toJson(D_logs, out); out.flush(); fos.close(); } catch (FileNotFoundException e) { // Do nothing } catch (IOException e) { throw new RuntimeException(); } } // Add data sets up collects and checks to make sure each entry is correct // If everything is correct data is added to file // If entry(s) are incorrect will send a toast message public void addData() { try { EditText setsStation = (EditText) findViewById(R.id.editStation); String station = setsStation.getText().toString(); EditText setsDate = (EditText) findViewById(R.id.editDate); String sDate = setsDate.getText().toString(); // Checks date else where to keep code clean checker = checkDate(sDate); if (checker == 1) { throw new RuntimeException(); } EditText setsflGrade = (EditText) findViewById(R.id.gradeText); String sFlGrade = setsflGrade.getText().toString(); EditText setsUint = (EditText) findViewById(R.id.editUnit); float sUnit = Float.valueOf(setsUint.getText().toString()); EditText setsAmount = (EditText) findViewById(R.id.editAmount); float sAmount = Float.valueOf(setsAmount.getText().toString()); EditText setsOdo = (EditText) findViewById(R.id.editOdo); float sOdo = Float.valueOf(setsOdo.getText().toString()); // Creates data log and goes back MainActivity Data_Entry log = new Data_Entry(station, sDate, sFlGrade, sAmount, sUnit, sOdo); log.findCost(); D_logs.add(log); saveInFile(); saveToMain(); } catch (Exception e) { // Do nothing Toast dataWrong = new Toast(getApplicationContext()); dataWrong.makeText(Adding.this, "Incorrect Entry", dataWrong.LENGTH_SHORT).show(); } } }
gpl-3.0
yeriomin/play-store-api
src/main/java/com/google/protobuf/Method.java
33825
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto package com.google.protobuf; /** * <pre> * Method represents a method of an api. * </pre> * * Protobuf type {@code google.protobuf.Method} */ public final class Method extends com.google.protobuf.GeneratedMessageLite< Method, Method.Builder> implements // @@protoc_insertion_point(message_implements:google.protobuf.Method) MethodOrBuilder { private Method() { name_ = ""; requestTypeUrl_ = ""; responseTypeUrl_ = ""; options_ = emptyProtobufList(); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; private java.lang.String name_; /** * <pre> * The simple name of this method. * </pre> * * <code>optional string name = 1;</code> */ public java.lang.String getName() { return name_; } /** * <pre> * The simple name of this method. * </pre> * * <code>optional string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { return com.google.protobuf.ByteString.copyFromUtf8(name_); } /** * <pre> * The simple name of this method. * </pre> * * <code>optional string name = 1;</code> */ private void setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; } /** * <pre> * The simple name of this method. * </pre> * * <code>optional string name = 1;</code> */ private void clearName() { name_ = getDefaultInstance().getName(); } /** * <pre> * The simple name of this method. * </pre> * * <code>optional string name = 1;</code> */ private void setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value.toStringUtf8(); } public static final int REQUEST_TYPE_URL_FIELD_NUMBER = 2; private java.lang.String requestTypeUrl_; /** * <pre> * A URL of the input message type. * </pre> * * <code>optional string request_type_url = 2;</code> */ public java.lang.String getRequestTypeUrl() { return requestTypeUrl_; } /** * <pre> * A URL of the input message type. * </pre> * * <code>optional string request_type_url = 2;</code> */ public com.google.protobuf.ByteString getRequestTypeUrlBytes() { return com.google.protobuf.ByteString.copyFromUtf8(requestTypeUrl_); } /** * <pre> * A URL of the input message type. * </pre> * * <code>optional string request_type_url = 2;</code> */ private void setRequestTypeUrl( java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestTypeUrl_ = value; } /** * <pre> * A URL of the input message type. * </pre> * * <code>optional string request_type_url = 2;</code> */ private void clearRequestTypeUrl() { requestTypeUrl_ = getDefaultInstance().getRequestTypeUrl(); } /** * <pre> * A URL of the input message type. * </pre> * * <code>optional string request_type_url = 2;</code> */ private void setRequestTypeUrlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestTypeUrl_ = value.toStringUtf8(); } public static final int REQUEST_STREAMING_FIELD_NUMBER = 3; private boolean requestStreaming_; /** * <pre> * If true, the request is streamed. * </pre> * * <code>optional bool request_streaming = 3;</code> */ public boolean getRequestStreaming() { return requestStreaming_; } /** * <pre> * If true, the request is streamed. * </pre> * * <code>optional bool request_streaming = 3;</code> */ private void setRequestStreaming(boolean value) { requestStreaming_ = value; } /** * <pre> * If true, the request is streamed. * </pre> * * <code>optional bool request_streaming = 3;</code> */ private void clearRequestStreaming() { requestStreaming_ = false; } public static final int RESPONSE_TYPE_URL_FIELD_NUMBER = 4; private java.lang.String responseTypeUrl_; /** * <pre> * The URL of the output message type. * </pre> * * <code>optional string response_type_url = 4;</code> */ public java.lang.String getResponseTypeUrl() { return responseTypeUrl_; } /** * <pre> * The URL of the output message type. * </pre> * * <code>optional string response_type_url = 4;</code> */ public com.google.protobuf.ByteString getResponseTypeUrlBytes() { return com.google.protobuf.ByteString.copyFromUtf8(responseTypeUrl_); } /** * <pre> * The URL of the output message type. * </pre> * * <code>optional string response_type_url = 4;</code> */ private void setResponseTypeUrl( java.lang.String value) { if (value == null) { throw new NullPointerException(); } responseTypeUrl_ = value; } /** * <pre> * The URL of the output message type. * </pre> * * <code>optional string response_type_url = 4;</code> */ private void clearResponseTypeUrl() { responseTypeUrl_ = getDefaultInstance().getResponseTypeUrl(); } /** * <pre> * The URL of the output message type. * </pre> * * <code>optional string response_type_url = 4;</code> */ private void setResponseTypeUrlBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); responseTypeUrl_ = value.toStringUtf8(); } public static final int RESPONSE_STREAMING_FIELD_NUMBER = 5; private boolean responseStreaming_; /** * <pre> * If true, the response is streamed. * </pre> * * <code>optional bool response_streaming = 5;</code> */ public boolean getResponseStreaming() { return responseStreaming_; } /** * <pre> * If true, the response is streamed. * </pre> * * <code>optional bool response_streaming = 5;</code> */ private void setResponseStreaming(boolean value) { responseStreaming_ = value; } /** * <pre> * If true, the response is streamed. * </pre> * * <code>optional bool response_streaming = 5;</code> */ private void clearResponseStreaming() { responseStreaming_ = false; } public static final int OPTIONS_FIELD_NUMBER = 6; private com.google.protobuf.Internal.ProtobufList<com.google.protobuf.Option> options_; /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public java.util.List<com.google.protobuf.Option> getOptionsList() { return options_; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public java.util.List<? extends com.google.protobuf.OptionOrBuilder> getOptionsOrBuilderList() { return options_; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public int getOptionsCount() { return options_.size(); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public com.google.protobuf.Option getOptions(int index) { return options_.get(index); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public com.google.protobuf.OptionOrBuilder getOptionsOrBuilder( int index) { return options_.get(index); } private void ensureOptionsIsMutable() { if (!options_.isModifiable()) { options_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(options_); } } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ private void setOptions( int index, com.google.protobuf.Option value) { if (value == null) { throw new NullPointerException(); } ensureOptionsIsMutable(); options_.set(index, value); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ private void setOptions( int index, com.google.protobuf.Option.Builder builderForValue) { ensureOptionsIsMutable(); options_.set(index, builderForValue.build()); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ private void addOptions(com.google.protobuf.Option value) { if (value == null) { throw new NullPointerException(); } ensureOptionsIsMutable(); options_.add(value); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ private void addOptions( int index, com.google.protobuf.Option value) { if (value == null) { throw new NullPointerException(); } ensureOptionsIsMutable(); options_.add(index, value); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ private void addOptions( com.google.protobuf.Option.Builder builderForValue) { ensureOptionsIsMutable(); options_.add(builderForValue.build()); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ private void addOptions( int index, com.google.protobuf.Option.Builder builderForValue) { ensureOptionsIsMutable(); options_.add(index, builderForValue.build()); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ private void addAllOptions( java.lang.Iterable<? extends com.google.protobuf.Option> values) { ensureOptionsIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, options_); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ private void clearOptions() { options_ = emptyProtobufList(); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ private void removeOptions(int index) { ensureOptionsIsMutable(); options_.remove(index); } public static final int SYNTAX_FIELD_NUMBER = 7; private int syntax_; /** * <pre> * The source syntax of this method. * </pre> * * <code>optional .google.protobuf.Syntax syntax = 7;</code> */ public int getSyntaxValue() { return syntax_; } /** * <pre> * The source syntax of this method. * </pre> * * <code>optional .google.protobuf.Syntax syntax = 7;</code> */ public com.google.protobuf.Syntax getSyntax() { com.google.protobuf.Syntax result = com.google.protobuf.Syntax.forNumber(syntax_); return result == null ? com.google.protobuf.Syntax.UNRECOGNIZED : result; } /** * <pre> * The source syntax of this method. * </pre> * * <code>optional .google.protobuf.Syntax syntax = 7;</code> */ private void setSyntaxValue(int value) { syntax_ = value; } /** * <pre> * The source syntax of this method. * </pre> * * <code>optional .google.protobuf.Syntax syntax = 7;</code> */ private void setSyntax(com.google.protobuf.Syntax value) { if (value == null) { throw new NullPointerException(); } syntax_ = value.getNumber(); } /** * <pre> * The source syntax of this method. * </pre> * * <code>optional .google.protobuf.Syntax syntax = 7;</code> */ private void clearSyntax() { syntax_ = 0; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!name_.isEmpty()) { output.writeString(1, getName()); } if (!requestTypeUrl_.isEmpty()) { output.writeString(2, getRequestTypeUrl()); } if (requestStreaming_ != false) { output.writeBool(3, requestStreaming_); } if (!responseTypeUrl_.isEmpty()) { output.writeString(4, getResponseTypeUrl()); } if (responseStreaming_ != false) { output.writeBool(5, responseStreaming_); } for (int i = 0; i < options_.size(); i++) { output.writeMessage(6, options_.get(i)); } if (syntax_ != com.google.protobuf.Syntax.SYNTAX_PROTO2.getNumber()) { output.writeEnum(7, syntax_); } } public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (!name_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(1, getName()); } if (!requestTypeUrl_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(2, getRequestTypeUrl()); } if (requestStreaming_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, requestStreaming_); } if (!responseTypeUrl_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(4, getResponseTypeUrl()); } if (responseStreaming_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(5, responseStreaming_); } for (int i = 0; i < options_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(6, options_.get(i)); } if (syntax_ != com.google.protobuf.Syntax.SYNTAX_PROTO2.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(7, syntax_); } memoizedSerializedSize = size; return size; } public static com.google.protobuf.Method parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static com.google.protobuf.Method parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static com.google.protobuf.Method parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static com.google.protobuf.Method parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static com.google.protobuf.Method parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static com.google.protobuf.Method parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static com.google.protobuf.Method parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static com.google.protobuf.Method parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static com.google.protobuf.Method parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static com.google.protobuf.Method parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.protobuf.Method prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } /** * <pre> * Method represents a method of an api. * </pre> * * Protobuf type {@code google.protobuf.Method} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< com.google.protobuf.Method, Builder> implements // @@protoc_insertion_point(builder_implements:google.protobuf.Method) com.google.protobuf.MethodOrBuilder { // Construct using com.google.protobuf.Method.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <pre> * The simple name of this method. * </pre> * * <code>optional string name = 1;</code> */ public java.lang.String getName() { return instance.getName(); } /** * <pre> * The simple name of this method. * </pre> * * <code>optional string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { return instance.getNameBytes(); } /** * <pre> * The simple name of this method. * </pre> * * <code>optional string name = 1;</code> */ public Builder setName( java.lang.String value) { copyOnWrite(); instance.setName(value); return this; } /** * <pre> * The simple name of this method. * </pre> * * <code>optional string name = 1;</code> */ public Builder clearName() { copyOnWrite(); instance.clearName(); return this; } /** * <pre> * The simple name of this method. * </pre> * * <code>optional string name = 1;</code> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setNameBytes(value); return this; } /** * <pre> * A URL of the input message type. * </pre> * * <code>optional string request_type_url = 2;</code> */ public java.lang.String getRequestTypeUrl() { return instance.getRequestTypeUrl(); } /** * <pre> * A URL of the input message type. * </pre> * * <code>optional string request_type_url = 2;</code> */ public com.google.protobuf.ByteString getRequestTypeUrlBytes() { return instance.getRequestTypeUrlBytes(); } /** * <pre> * A URL of the input message type. * </pre> * * <code>optional string request_type_url = 2;</code> */ public Builder setRequestTypeUrl( java.lang.String value) { copyOnWrite(); instance.setRequestTypeUrl(value); return this; } /** * <pre> * A URL of the input message type. * </pre> * * <code>optional string request_type_url = 2;</code> */ public Builder clearRequestTypeUrl() { copyOnWrite(); instance.clearRequestTypeUrl(); return this; } /** * <pre> * A URL of the input message type. * </pre> * * <code>optional string request_type_url = 2;</code> */ public Builder setRequestTypeUrlBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setRequestTypeUrlBytes(value); return this; } /** * <pre> * If true, the request is streamed. * </pre> * * <code>optional bool request_streaming = 3;</code> */ public boolean getRequestStreaming() { return instance.getRequestStreaming(); } /** * <pre> * If true, the request is streamed. * </pre> * * <code>optional bool request_streaming = 3;</code> */ public Builder setRequestStreaming(boolean value) { copyOnWrite(); instance.setRequestStreaming(value); return this; } /** * <pre> * If true, the request is streamed. * </pre> * * <code>optional bool request_streaming = 3;</code> */ public Builder clearRequestStreaming() { copyOnWrite(); instance.clearRequestStreaming(); return this; } /** * <pre> * The URL of the output message type. * </pre> * * <code>optional string response_type_url = 4;</code> */ public java.lang.String getResponseTypeUrl() { return instance.getResponseTypeUrl(); } /** * <pre> * The URL of the output message type. * </pre> * * <code>optional string response_type_url = 4;</code> */ public com.google.protobuf.ByteString getResponseTypeUrlBytes() { return instance.getResponseTypeUrlBytes(); } /** * <pre> * The URL of the output message type. * </pre> * * <code>optional string response_type_url = 4;</code> */ public Builder setResponseTypeUrl( java.lang.String value) { copyOnWrite(); instance.setResponseTypeUrl(value); return this; } /** * <pre> * The URL of the output message type. * </pre> * * <code>optional string response_type_url = 4;</code> */ public Builder clearResponseTypeUrl() { copyOnWrite(); instance.clearResponseTypeUrl(); return this; } /** * <pre> * The URL of the output message type. * </pre> * * <code>optional string response_type_url = 4;</code> */ public Builder setResponseTypeUrlBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setResponseTypeUrlBytes(value); return this; } /** * <pre> * If true, the response is streamed. * </pre> * * <code>optional bool response_streaming = 5;</code> */ public boolean getResponseStreaming() { return instance.getResponseStreaming(); } /** * <pre> * If true, the response is streamed. * </pre> * * <code>optional bool response_streaming = 5;</code> */ public Builder setResponseStreaming(boolean value) { copyOnWrite(); instance.setResponseStreaming(value); return this; } /** * <pre> * If true, the response is streamed. * </pre> * * <code>optional bool response_streaming = 5;</code> */ public Builder clearResponseStreaming() { copyOnWrite(); instance.clearResponseStreaming(); return this; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public java.util.List<com.google.protobuf.Option> getOptionsList() { return java.util.Collections.unmodifiableList( instance.getOptionsList()); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public int getOptionsCount() { return instance.getOptionsCount(); }/** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public com.google.protobuf.Option getOptions(int index) { return instance.getOptions(index); } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public Builder setOptions( int index, com.google.protobuf.Option value) { copyOnWrite(); instance.setOptions(index, value); return this; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public Builder setOptions( int index, com.google.protobuf.Option.Builder builderForValue) { copyOnWrite(); instance.setOptions(index, builderForValue); return this; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public Builder addOptions(com.google.protobuf.Option value) { copyOnWrite(); instance.addOptions(value); return this; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public Builder addOptions( int index, com.google.protobuf.Option value) { copyOnWrite(); instance.addOptions(index, value); return this; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public Builder addOptions( com.google.protobuf.Option.Builder builderForValue) { copyOnWrite(); instance.addOptions(builderForValue); return this; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public Builder addOptions( int index, com.google.protobuf.Option.Builder builderForValue) { copyOnWrite(); instance.addOptions(index, builderForValue); return this; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public Builder addAllOptions( java.lang.Iterable<? extends com.google.protobuf.Option> values) { copyOnWrite(); instance.addAllOptions(values); return this; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public Builder clearOptions() { copyOnWrite(); instance.clearOptions(); return this; } /** * <pre> * Any metadata attached to the method. * </pre> * * <code>repeated .google.protobuf.Option options = 6;</code> */ public Builder removeOptions(int index) { copyOnWrite(); instance.removeOptions(index); return this; } /** * <pre> * The source syntax of this method. * </pre> * * <code>optional .google.protobuf.Syntax syntax = 7;</code> */ public int getSyntaxValue() { return instance.getSyntaxValue(); } /** * <pre> * The source syntax of this method. * </pre> * * <code>optional .google.protobuf.Syntax syntax = 7;</code> */ public Builder setSyntaxValue(int value) { copyOnWrite(); instance.setSyntaxValue(value); return this; } /** * <pre> * The source syntax of this method. * </pre> * * <code>optional .google.protobuf.Syntax syntax = 7;</code> */ public com.google.protobuf.Syntax getSyntax() { return instance.getSyntax(); } /** * <pre> * The source syntax of this method. * </pre> * * <code>optional .google.protobuf.Syntax syntax = 7;</code> */ public Builder setSyntax(com.google.protobuf.Syntax value) { copyOnWrite(); instance.setSyntax(value); return this; } /** * <pre> * The source syntax of this method. * </pre> * * <code>optional .google.protobuf.Syntax syntax = 7;</code> */ public Builder clearSyntax() { copyOnWrite(); instance.clearSyntax(); return this; } // @@protoc_insertion_point(builder_scope:google.protobuf.Method) } protected final Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, Object arg0, Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new com.google.protobuf.Method(); } case IS_INITIALIZED: { return DEFAULT_INSTANCE; } case MAKE_IMMUTABLE: { options_.makeImmutable(); return null; } case NEW_BUILDER: { return new Builder(); } case VISIT: { Visitor visitor = (Visitor) arg0; com.google.protobuf.Method other = (com.google.protobuf.Method) arg1; name_ = visitor.visitString(!name_.isEmpty(), name_, !other.name_.isEmpty(), other.name_); requestTypeUrl_ = visitor.visitString(!requestTypeUrl_.isEmpty(), requestTypeUrl_, !other.requestTypeUrl_.isEmpty(), other.requestTypeUrl_); requestStreaming_ = visitor.visitBoolean(requestStreaming_ != false, requestStreaming_, other.requestStreaming_ != false, other.requestStreaming_); responseTypeUrl_ = visitor.visitString(!responseTypeUrl_.isEmpty(), responseTypeUrl_, !other.responseTypeUrl_.isEmpty(), other.responseTypeUrl_); responseStreaming_ = visitor.visitBoolean(responseStreaming_ != false, responseStreaming_, other.responseStreaming_ != false, other.responseStreaming_); options_= visitor.visitList(options_, other.options_); syntax_ = visitor.visitInt(syntax_ != 0, syntax_, other.syntax_ != 0, other.syntax_); if (visitor == com.google.protobuf.GeneratedMessageLite.MergeFromVisitor .INSTANCE) { bitField0_ |= other.bitField0_; } return this; } case MERGE_FROM_STREAM: { com.google.protobuf.CodedInputStream input = (com.google.protobuf.CodedInputStream) arg0; com.google.protobuf.ExtensionRegistryLite extensionRegistry = (com.google.protobuf.ExtensionRegistryLite) arg1; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!input.skipField(tag)) { done = true; } break; } case 10: { String s = input.readStringRequireUtf8(); name_ = s; break; } case 18: { String s = input.readStringRequireUtf8(); requestTypeUrl_ = s; break; } case 24: { requestStreaming_ = input.readBool(); break; } case 34: { String s = input.readStringRequireUtf8(); responseTypeUrl_ = s; break; } case 40: { responseStreaming_ = input.readBool(); break; } case 50: { if (!options_.isModifiable()) { options_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(options_); } options_.add( input.readMessage(com.google.protobuf.Option.parser(), extensionRegistry)); break; } case 56: { int rawValue = input.readEnum(); syntax_ = rawValue; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw new RuntimeException(e.setUnfinishedMessage(this)); } catch (java.io.IOException e) { throw new RuntimeException( new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this)); } finally { } } case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { if (PARSER == null) { synchronized (com.google.protobuf.Method.class) { if (PARSER == null) { PARSER = new DefaultInstanceBasedParser(DEFAULT_INSTANCE); } } } return PARSER; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:google.protobuf.Method) private static final com.google.protobuf.Method DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new Method(); DEFAULT_INSTANCE.makeImmutable(); } public static com.google.protobuf.Method getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<Method> PARSER; public static com.google.protobuf.Parser<Method> parser() { return DEFAULT_INSTANCE.getParserForType(); } }
gpl-3.0
mnemotron/Revenue
revenue.service/src/revenue/service/config/entity/ReqConfig.java
358
package revenue.service.config.entity; public class ReqConfig { private String key; private String value; public ReqConfig() { } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
gpl-3.0
multiplemonomials/Equivalent-Exchange-Reborn
src/main/java/net/multiplemonomials/eer/client/settings/Keybindings.java
380
package net.multiplemonomials.eer.client.settings; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.settings.KeyBinding; @SideOnly(Side.CLIENT) public class Keybindings { public static KeyBinding charge; public static KeyBinding extra; public static KeyBinding release; public static KeyBinding toggle; }
gpl-3.0
andreneonet/challenges
offline/src/test/java/anogueira/offline/lookup/impl/LibPhoneNumberLookupTest.java
1624
package anogueira.offline.lookup.impl; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import anogueira.offline.lookup.InvalidPhoneNumberException; import anogueira.offline.lookup.LookupService; import anogueira.offline.lookup.impl.LookupServiceImpl; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application.xml") @DirtiesContext public class LibPhoneNumberLookupTest{ private LookupService phoneNumberLookup = new LookupServiceImpl(); @Test public void validPhoneNumbers(){ Assert.assertNotNull(phoneNumberLookup.lookup("+12018840000")); Assert.assertNotNull(phoneNumberLookup.lookup("+15148710000")); Assert.assertNotNull(phoneNumberLookup.lookup("+14159690000")); Assert.assertNotNull(phoneNumberLookup.lookup("+351265120000")); Assert.assertNotNull(phoneNumberLookup.lookup("+351211230000")); Assert.assertNotNull(phoneNumberLookup.lookup("+351222220000")); Assert.assertNotNull(phoneNumberLookup.lookup("+33975180000")); Assert.assertNotNull(phoneNumberLookup.lookup("+441732600000")); Assert.assertNotNull(phoneNumberLookup.lookup("+14159690000")); } @Test(expected=InvalidPhoneNumberException.class) public void invalidPhoneNumbers(){ Assert.assertNull(phoneNumberLookup.lookup("+9690000")); Assert.assertNull(phoneNumberLookup.lookup("+351219087654321")); Assert.assertNull(phoneNumberLookup.lookup("+351299999999")); } }
gpl-3.0
adityamogadala/SemRelDocSearch
src/main/java/de/paul/similarity/entityScorers/LCAScorer.java
526
package de.paul.similarity.entityScorers; import de.paul.annotations.AncestorAnnotation; public class LCAScorer extends TaxonomicEntityPairScorer { private CommonAncestor lca; public LCAScorer(AncestorAnnotation ann1, AncestorAnnotation ann2) { super(ann1, ann2); // sets null if overlap is only root this.lca = ann1.lowestCommonAncestor(ann2); } @Override protected double score(AncestorAnnotation rightAnn, AncestorAnnotation leftAnn) { if (lca == null) return 0; else return lca.score(); } }
gpl-3.0
Merlijnv/MFM
src/main/java/com/AwesomeMerlijn/MFM/reference/Reference.java
425
package com.AwesomeMerlijn.MFM.reference; public class Reference { public static final String MOD_ID = "MFM"; public static final String MOD_NAME = "MFM"; public static final String VERSION = "1.9-12.16.1.1938-1.9.0"; public static final String SERVER_PROXY_CLASS = "com.AwesomeMerlijn.MFM.proxy.ServerProxy"; public static final String CLIENT_PROXY_CLASS = "com.AwesomeMerlijn.MFM.proxy.ClientProxy"; }
gpl-3.0
dykstrom/jcc
src/test/java/se/dykstrom/jcc/basic/compiler/BasicSyntaxVisitorIfTest.java
16329
/* * Copyright (C) 2017 Johan Dykstrom * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package se.dykstrom.jcc.basic.compiler; import org.junit.Test; import se.dykstrom.jcc.basic.ast.EndStatement; import se.dykstrom.jcc.basic.ast.PrintStatement; import se.dykstrom.jcc.common.ast.*; import java.util.List; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; /** * Tests class {@code BasicSyntaxVisitor}, especially functionality related to IF statements. * * @author Johan Dykstrom * @see BasicSyntaxVisitor */ public class BasicSyntaxVisitorIfTest extends AbstractBasicSyntaxVisitorTest { @Test public void shouldParseIfGotoNum() { Statement gs = new GotoStatement(0, 0, "20"); Statement is = IfStatement.builder(IL_5, gs).build(); List<Statement> expectedStatements = singletonList(new LabelledStatement("10", is)); parseAndAssert("10 if 5 goto 20", expectedStatements); } @Test public void shouldParseIfThenNum() { Statement gs = new GotoStatement(0, 0, "100"); Statement is = IfStatement.builder(BL_TRUE, gs).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if true then 100", expectedStatements); } @Test public void shouldParseIfThenGoto() { Statement gs = new GotoStatement(0, 0, "100"); Statement is = IfStatement.builder(BL_TRUE, gs).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if true then goto 100", expectedStatements); } @Test public void shouldParseIfThenPrint() { Statement ps = new PrintStatement(0, 0, singletonList(IL_10)); Statement is = IfStatement.builder(BL_FALSE, ps).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if false then print 10", expectedStatements); } @Test public void shouldParseIfThenAssign() { Statement as = new AssignStatement(0, 0, NAME_A, IL_4); Statement is = IfStatement.builder(BL_FALSE, as).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if false then a% = 4", expectedStatements); } @Test public void shouldParseIfThenMultiple() { Statement as = new AssignStatement(0, 0, NAME_A, IL_4); Statement ps = new PrintStatement(0, 0, singletonList(IDE_A)); Statement gs = new GotoStatement(0, 0, "10"); Statement is = IfStatement.builder(BL_FALSE, asList(as, ps, gs)).build(); List<Statement> expectedStatements = singletonList(new LabelledStatement("10", is)); parseAndAssert("10 if false then a% = 4 : print a% : goto 10", expectedStatements); } @Test public void shouldParseNestedIfThen() { Expression ee = new EqualExpression(0, 0, IL_1, IL_2); Statement ps = new PrintStatement(0, 0, singletonList(IL_5)); Statement is1 = IfStatement.builder(BL_TRUE, ps).build(); Statement is2 = IfStatement.builder(BL_FALSE, is1).build(); Statement is3 = IfStatement.builder(ee, is2).build(); List<Statement> expectedStatements = singletonList(is3); parseAndAssert("if 1 = 2 then if false then if true then print 5", expectedStatements); } @Test public void shouldParseIfGotoNumElseNum() { Statement gs1 = new GotoStatement(0, 0, "20"); Statement gs2 = new GotoStatement(0, 0, "30"); Statement is = IfStatement.builder(IL_10, gs1).elseStatements(gs2).build(); List<Statement> expectedStatements = singletonList(new LabelledStatement("10", is)); parseAndAssert("10 if 10 goto 20 else 30", expectedStatements); } @Test public void shouldParseIfThenNumElseNum() { Statement gs1 = new GotoStatement(0, 0, "20"); Statement gs2 = new GotoStatement(0, 0, "30"); Statement is = IfStatement.builder(IL_10, gs1).elseStatements(gs2).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if 10 then 20 else 30", expectedStatements); } @Test public void shouldParseIfThenNumElseGoto() { Statement gs1 = new GotoStatement(0, 0, "20"); Statement gs2 = new GotoStatement(0, 0, "30"); Statement is = IfStatement.builder(IL_10, gs1).elseStatements(gs2).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if 10 then 20 else goto 30", expectedStatements); } @Test public void shouldParseIfThenNumElsePrint() { Statement gs = new GotoStatement(0, 0, "20"); Statement ps = new PrintStatement(0, 0, singletonList(IL_4)); Statement is = IfStatement.builder(IL_10, gs).elseStatements(ps).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if 10 then 20 else print 4", expectedStatements); } @Test public void shouldParseIfThenMultipleElseMultiple() { Statement as1 = new AssignStatement(0, 0, NAME_A, IL_4); Statement ps1 = new PrintStatement(0, 0, singletonList(IDE_A)); Statement gs1 = new GotoStatement(0, 0, "10"); Statement ps2 = new PrintStatement(0, 0, singletonList(IL_2)); Statement gs2 = new GotoStatement(0, 0, "20"); Statement is = IfStatement.builder(BL_FALSE, asList(as1, ps1, gs1)).elseStatements(asList(ps2, gs2)).build(); List<Statement> expectedStatements = singletonList(new LabelledStatement("10", is)); parseAndAssert("10 if false then a% = 4 : print a% : goto 10 else print 2 : goto 20", expectedStatements); } @Test public void shouldParseIfThenBlock() { Statement ps = new PrintStatement(0, 0, singletonList(IL_4)); Statement is = IfStatement.builder(BL_TRUE, ps).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if true then print 4 end if", expectedStatements); } @Test public void shouldParseEmptyThenBlock() { Statement is = IfStatement.builder(BL_TRUE, emptyList()).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if true then end if", expectedStatements); } @Test public void shouldParseIfThenElseBlock() { Statement ps1 = new PrintStatement(0, 0, singletonList(IL_4)); Statement ps2 = new PrintStatement(0, 0, singletonList(IL_3)); Statement as = new AssignStatement(0, 0, NAME_A, IL_1); Statement ps3 = new PrintStatement(0, 0, singletonList(IDE_A)); Statement is = IfStatement.builder(BL_TRUE, asList(ps1, ps2)).elseStatements(asList(as, ps3)).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if true then print 4 print 3 else a% = 1 print a% end if", expectedStatements); } @Test public void shouldParseEmptyThenElseBlock() { Statement is = IfStatement.builder(BL_TRUE, emptyList()).elseStatements(emptyList()).build(); List<Statement> expectedStatements = singletonList(is); parseAndAssert("if true then else end if", expectedStatements); } @Test public void shouldParseNestedIfThenElseBlock() { Statement ps1 = new PrintStatement(0, 0, singletonList(IL_1)); Statement ps2 = new PrintStatement(0, 0, singletonList(IL_2)); Statement ps3 = new PrintStatement(0, 0, singletonList(IL_3)); Statement ps4 = new PrintStatement(0, 0, singletonList(IL_4)); Expression ge = new GreaterExpression(0, 0, IL_1, IL_2); Expression le = new LessExpression(0, 0, IL_1, IL_2); Statement is1 = IfStatement.builder(ge, ps1).elseStatements(ps2).build(); Statement is2 = IfStatement.builder(le, ps3).elseStatements(ps4).build(); Statement is3 = IfStatement.builder(BL_TRUE, is1).elseStatements(is2).build(); List<Statement> expectedStatements = singletonList(is3); parseAndAssert( "if true then " + " if 1 > 2 then " + " print 1 " + " else " + " print 2 " + " end if " + "else " + " if 1 < 2 then " + " print 3 " + " else " + " print 4 " + " end if " + "end if", expectedStatements); } @Test public void shouldParseEmptyElseIfBlock() { Statement is1 = IfStatement.builder(BL_FALSE, emptyList()).build(); Statement is2 = IfStatement.builder(BL_TRUE, emptyList()).elseStatements(is1).build(); List<Statement> expectedStatements = singletonList(is2); parseAndAssert("if true then elseif false then end if", expectedStatements); } @Test public void shouldParseElseIfBlock() { Statement ps1 = new PrintStatement(0, 0, singletonList(IL_1)); Statement secondIf = IfStatement.builder(BL_FALSE, ps1).build(); Statement ps2 = new PrintStatement(0, 0, singletonList(IL_2)); Statement firstIf = IfStatement.builder(BL_TRUE, ps2).elseStatements(secondIf).build(); List<Statement> expectedStatements = singletonList(firstIf); parseAndAssert("if true then print 2 elseif false then print 1 end if", expectedStatements); } @Test public void shouldParseElseIfElseBlock() { Statement ps4 = new PrintStatement(0, 0, singletonList(IL_4)); Statement ps1 = new PrintStatement(0, 0, singletonList(IL_1)); Statement secondIf = IfStatement.builder(BL_FALSE, ps1).elseStatements(ps4).build(); Statement ps2 = new PrintStatement(0, 0, singletonList(IL_2)); Statement firstIf = IfStatement.builder(BL_TRUE, ps2).elseStatements(secondIf).build(); List<Statement> expectedStatements = singletonList(firstIf); parseAndAssert("if true then print 2 elseif false then print 1 else print 4 end if", expectedStatements); } @Test public void shouldParseElseIfElseIfBlock() { Statement ps4 = new PrintStatement(0, 0, singletonList(IL_4)); Statement thirdIf = IfStatement.builder(BL_TRUE, ps4).build(); Statement ps1 = new PrintStatement(0, 0, singletonList(IL_1)); Statement secondIf = IfStatement.builder(BL_FALSE, ps1).elseStatements(thirdIf).build(); Statement ps2 = new PrintStatement(0, 0, singletonList(IL_2)); Statement firstIf = IfStatement.builder(BL_TRUE, ps2).elseStatements(secondIf).build(); List<Statement> expectedStatements = singletonList(firstIf); parseAndAssert("if true then print 2 elseif false then print 1 elseif true then print 4 end if", expectedStatements); } @Test public void shouldParseElseIfElseIfElseBlock() { Statement ps4 = new PrintStatement(0, 0, singletonList(IL_4)); Statement ps3 = new PrintStatement(0, 0, singletonList(IL_3)); Expression ee3 = new EqualExpression(0, 0, IDE_A, IL_3); Statement thirdIf = IfStatement.builder(ee3, ps3).elseStatements(ps4).build(); Statement ps2 = new PrintStatement(0, 0, singletonList(IL_2)); Expression ee2 = new EqualExpression(0, 0, IDE_A, IL_2); Statement secondIf = IfStatement.builder(ee2, ps2).elseStatements(thirdIf).build(); Statement ps1 = new PrintStatement(0, 0, singletonList(IL_1)); Expression ee1 = new EqualExpression(0, 0, IDE_A, IL_1); Statement firstIf = IfStatement.builder(ee1, ps1).elseStatements(secondIf).build(); List<Statement> expectedStatements = singletonList(firstIf); parseAndAssert("if a% = 1 then " + " print 1 " + "elseif a% = 2 then " + " print 2 " + "elseif a% = 3 then " + " print 3 " + "else " + " print 4 " + "end if", expectedStatements); } @Test public void shouldParseNestedElseIfBlock() { Statement ps3 = new PrintStatement(0, 0, singletonList(IL_3)); Statement fourthIf = IfStatement.builder(BL_FALSE, ps3).build(); Statement ps2 = new PrintStatement(0, 0, singletonList(IL_2)); Statement thirdIf = IfStatement.builder(BL_TRUE, ps2).elseStatements(fourthIf).build(); Expression ee2 = new EqualExpression(0, 0, IDE_A, IL_2); Statement secondIf = IfStatement.builder(ee2, thirdIf).build(); Statement ps1 = new PrintStatement(0, 0, singletonList(IL_1)); Expression ee1 = new EqualExpression(0, 0, IDE_A, IL_1); Statement firstIf = IfStatement.builder(ee1, ps1).elseStatements(secondIf).build(); List<Statement> expectedStatements = singletonList(firstIf); parseAndAssert("if a% = 1 then " + " print 1 " + "elseif a% = 2 then " + " if true then " + " print 2 " + " elseif false then " + " print 3 " + " end if " + "end if", expectedStatements); } @Test public void shouldParseThenBlockWithEndStatement() { Statement ps = new PrintStatement(0, 0, singletonList(IL_1)); Statement es = new EndStatement(0, 0); Statement expected = IfStatement.builder(BL_TRUE, ps, es).build(); parseAndAssert(""" if true then print 1 end end if """, expected); } @Test public void shouldParseElseBlockWithEndStatement() { Statement ps = new PrintStatement(0, 0, singletonList(IL_1)); Statement es = new EndStatement(0, 0); Statement expected = IfStatement.builder(BL_TRUE, ps).elseStatements(es).build(); parseAndAssert(""" if true then print 1 else end end if """, expected); } @Test public void shouldParseElseIfBlockWithEndStatement() { Statement ps = new PrintStatement(0, 0, singletonList(IL_1)); Statement es = new EndStatement(0, 0); Statement eis = IfStatement.builder(BL_FALSE, es).build(); Statement expected = IfStatement.builder(BL_TRUE, ps).elseStatements(eis).build(); parseAndAssert(""" if true then print 1 elseif false then end end if """, expected); } @Test public void shouldParseNestedIfBlockWithEndStatement() { Statement ps = new PrintStatement(0, 0, singletonList(IL_1)); Statement es = new EndStatement(0, 0); Statement nis = IfStatement.builder(BL_TRUE, es).build(); Statement eis = IfStatement.builder(BL_FALSE, nis).build(); Statement expected = IfStatement.builder(BL_TRUE, ps).elseStatements(eis).build(); parseAndAssert(""" if true then print 1 elseif false then if true then end end if end if """, expected); } // Negative tests: @Test(expected = IllegalStateException.class) public void shouldNotParseMissingThen() { parse(""" 10 if true 20 print 1 30 end if """); } }
gpl-3.0
yanxiaosheng/mis
src/com/jzctb/mis/db/ConnectManager.java
4406
package com.jzctb.mis.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.log4j.Logger; import com.jzctb.mis.action.MisAction; public class ConnectManager{ private ConnectManager(){ try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { String errmsg = String.format("加载oracle数据库驱动[%s]失败", "oracle.jdbc.driver.OracleDriver"); logger.error(errmsg); } } /** * 从配置文件context.xml中获取数据库连接 * @return Connection */ public static synchronized Connection getConnection() { Connection conn = null; try{ Context ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracle/mis"); conn = ds.getConnection(); }catch(NamingException e){ e.printStackTrace(); conn = null; }catch(SQLException e){ e.printStackTrace(); conn = null; } return conn; } /** * 根据dbname从数据库表T_DB查询数据库URL、UserName、PassWord后,生成数据库连接 * @param dbname 数据库名称:system@orcl * @return 数据库连接Connection */ public static synchronized Connection getConnection(String dbname){ logger.debug("dbname = ["+dbname+"]"); String dburl="",username="",passwd=""; String sql = "select db_url, db_user, db_passwd,db_sid from t_db where db_name=? "; Connection conn = null; PreparedStatement psm = null; ResultSet rs = null; try{ conn = getConnection(); psm = conn.prepareStatement(sql); psm.setString(1, dbname); rs = psm.executeQuery(); if(rs.next()){ dburl = rs.getString(1); username = rs.getString(2); passwd = new MisAction().passwd(rs.getString(3), rs.getString(4), 1); String info = String.format("dburl=[%s] username=[%s] passwd=[%s]",dburl,username,"********"); logger.debug(info); return DriverManager.getConnection(dburl, username, passwd); }else{ return null; } }catch(SQLException e){ String errmsg = String.format("获取数据库连接失败: url=[%s] username=[%s] passwd=[%s]",dburl,username,"********"); logger.error(errmsg); }finally{ closeResultSet(rs); closePreparedStatement(psm); closeConn(conn); } return null; } /** * 根据用户名、密码、数据库地址获取连接 * @param username - 用户名 * @param password - 密码 * @param ip - 数据库IP地址 * @param port - 数据库端口 * @param dbname - 数据库名称SID * @return <code>Connection</code> * @throws SQLException */ public static Connection getConnection(String username, String password,String ip, int port,String dbname) throws SQLException{ Connection conn = null; String dburl = String.format("jdbc:oracle:thin:@//%s:%d/%s", ip,port,dbname ); conn = DriverManager.getConnection(dburl, username, password); return conn; } /*** * 关闭数据库连接 * @param conn - 已打开的数据库连接 */ public static void closeConn(Connection conn){ try{ if(conn!=null){ conn.close(); } }catch(SQLException e){ e.printStackTrace(); } conn = null; } /*** * 关闭结果集 * @param rs - 待关闭的ResultSet对象 */ public static void closeResultSet(ResultSet rs){ if(rs!=null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); } } rs = null; } public static void closeStatement(Statement sm){ if(sm!=null){ try{ sm.close(); }catch(SQLException e){ e.printStackTrace(); } } sm = null; } public static void closePreparedStatement(PreparedStatement psm){ if(psm!=null){ try{ psm.close(); }catch(SQLException e){ e.printStackTrace(); } } psm = null; } private static Logger logger = Logger.getLogger(ConnectManager.class); }
gpl-3.0
CubeEngine/modules-extra
authorization/src/main/java/org/cubeengine/module/authorization/AuthPerms.java
1629
/* * This file is part of CubeEngine. * CubeEngine is licensed under the GNU General Public License Version 3. * * CubeEngine is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CubeEngine is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CubeEngine. If not, see <http://www.gnu.org/licenses/>. */ package org.cubeengine.module.authorization; import org.cubeengine.libcube.service.permission.Permission; import org.cubeengine.libcube.service.permission.PermissionContainer; import org.cubeengine.libcube.service.permission.PermissionManager; import javax.inject.Inject; public class AuthPerms extends PermissionContainer { @Inject public AuthPerms(PermissionManager pm) { super(pm, Authorization.class); } public final Permission COMMAND_CLEARPASSWORD_ALL = register("command.clearpassword.all", "Allows clearing all passwords", null); public final Permission COMMAND_CLEARPASSWORD_OTHER = register("command.clearpassword.other", "Allows clearing passwords of other players", null); public final Permission COMMAND_SETPASSWORD_OTHER = register("command.setpassword.other", "Allows setting passwords of other players", null); }
gpl-3.0
rozz/drools-presentation-and-examples
drools-example-parent/drools-example-01/src/main/java/lodzjug/presentation/drools/example01/model/ChestPain.java
227
package lodzjug.presentation.drools.example01.model; import java.util.Map; public class ChestPain extends Symptom { @Override void details(Map<String, Object> answerDetails) { // TODO Auto-generated method stub } }
gpl-3.0
Hadron67/jphp
src/com/hadroncfy/jphp/jzend/types/typeInterfaces/OperatableL1.java
212
package com.hadroncfy.jphp.jzend.types.typeInterfaces; /** * Created by cfy on 16-9-1. */ public interface OperatableL1 { Zval plus(Zval zval); Zval minus(Zval zval); Zval inc(); Zval dec(); }
gpl-3.0
SanderMertens/opensplice
src/api/dcps/java/saj/code/DDS/ErrorInfoInterfaceOperations.java
667
/* * OpenSplice DDS * * This software and documentation are Copyright 2006 to 2013 PrismTech * Limited and its licensees. All rights reserved. See file: * * $OSPL_HOME/LICENSE * * for full copyright notice and license terms. * */ package DDS; public interface ErrorInfoInterfaceOperations { /* operations */ int update(); int get_code(org.omg.CORBA.IntHolder code); int get_message(org.omg.CORBA.StringHolder message); int get_location(org.omg.CORBA.StringHolder location); int get_source_line(org.omg.CORBA.StringHolder source_line); int get_stack_trace(org.omg.CORBA.StringHolder stack_trace); }
gpl-3.0
zicuxoco/ratita-pos-service
src/main/java/com/ratita/pos/domain/Attribute.java
1711
package com.ratita.pos.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * @author z.martinez.ramirez on 09/03/2016. */ @XmlType(propOrder = { "name", "value", "createdBy", "timestamp", "metaValue" }) @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class Attribute { protected String name; protected String value; protected String createdBy; protected Date timestamp; protected boolean metaValue; public Attribute() { } public Attribute(String name, String value, String createdBy, Date timestamp) { this.name = name; this.value = value; this.createdBy = createdBy; this.timestamp = timestamp; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public boolean isMetaValue() { return metaValue; } public void setMetaValue(boolean metaValue) { this.metaValue = metaValue; } }
gpl-3.0
ccem-dev/otus-api
source/otus-activity/src/main/java/org/ccem/otus/model/survey/activity/User.java
572
package org.ccem.otus.model.survey.activity; public class User { private String name; private String surname; private String phone; private String email; public User() {} public User(String name, String email, String surname, String phone) { this.name = name; this.email = email; this.surname = surname; this.phone = phone; } public String getName() { return name; } public String getSurname() { return surname; } public String getPhone() { return phone; } public String getEmail() { return email; } }
gpl-3.0
wurfmaul/jooksiklased
src/at/jku/ssw/ssw/jooksiklased/Debugger.java
30962
package at.jku.ssw.ssw.jooksiklased; import static at.jku.ssw.ssw.jooksiklased.Debugger.Status.NOT_YET_RUNNING; import static at.jku.ssw.ssw.jooksiklased.Debugger.Status.RUNNING; import static at.jku.ssw.ssw.jooksiklased.Debugger.Status.TERMINATED; import static at.jku.ssw.ssw.jooksiklased.Message.BREAKPOINT_ERROR; import static at.jku.ssw.ssw.jooksiklased.Message.BREAKPOINT_NOT_FOUND; import static at.jku.ssw.ssw.jooksiklased.Message.DEFER_BREAKPOINT; import static at.jku.ssw.ssw.jooksiklased.Message.EXIT; import static at.jku.ssw.ssw.jooksiklased.Message.FIELD; import static at.jku.ssw.ssw.jooksiklased.Message.FIELDS_HEADER; import static at.jku.ssw.ssw.jooksiklased.Message.FIELD_INHERITED; import static at.jku.ssw.ssw.jooksiklased.Message.HIT_BREAKPOINT; import static at.jku.ssw.ssw.jooksiklased.Message.ILLEGAL_ARGUMENTS; import static at.jku.ssw.ssw.jooksiklased.Message.INVALID_CMD; import static at.jku.ssw.ssw.jooksiklased.Message.LIST_BREAKPOINTS; import static at.jku.ssw.ssw.jooksiklased.Message.METHOD_OVERLOAD; import static at.jku.ssw.ssw.jooksiklased.Message.NO_CLASS; import static at.jku.ssw.ssw.jooksiklased.Message.NO_FIELD; import static at.jku.ssw.ssw.jooksiklased.Message.NO_FIELDS; import static at.jku.ssw.ssw.jooksiklased.Message.NO_LOCALS; import static at.jku.ssw.ssw.jooksiklased.Message.NO_LOCAL_INFO; import static at.jku.ssw.ssw.jooksiklased.Message.NO_METHOD; import static at.jku.ssw.ssw.jooksiklased.Message.NO_SUCH_THREAD; import static at.jku.ssw.ssw.jooksiklased.Message.REMOVE_BREAKPOINT; import static at.jku.ssw.ssw.jooksiklased.Message.RUN; import static at.jku.ssw.ssw.jooksiklased.Message.SET_BREAKPOINT; import static at.jku.ssw.ssw.jooksiklased.Message.STEP; import static at.jku.ssw.ssw.jooksiklased.Message.THREAD_GROUP; import static at.jku.ssw.ssw.jooksiklased.Message.THREAD_STATUS; import static at.jku.ssw.ssw.jooksiklased.Message.THREAD_STATUS_BP; import static at.jku.ssw.ssw.jooksiklased.Message.TOO_MANY_ARGS; import static at.jku.ssw.ssw.jooksiklased.Message.TRACE; import static at.jku.ssw.ssw.jooksiklased.Message.TRACE_LOC; import static at.jku.ssw.ssw.jooksiklased.Message.TRACE_SRC; import static at.jku.ssw.ssw.jooksiklased.Message.UNABLE_TO_ATTACH; import static at.jku.ssw.ssw.jooksiklased.Message.UNABLE_TO_LAUNCH; import static at.jku.ssw.ssw.jooksiklased.Message.UNABLE_TO_START; import static at.jku.ssw.ssw.jooksiklased.Message.UNKNOWN; import static at.jku.ssw.ssw.jooksiklased.Message.USAGE; import static at.jku.ssw.ssw.jooksiklased.Message.VAR; import static at.jku.ssw.ssw.jooksiklased.Message.VM_NOT_RUNNING; import static at.jku.ssw.ssw.jooksiklased.Message.VM_RUNNING; import static at.jku.ssw.ssw.jooksiklased.Message.format; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayDeque; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; import com.sun.jdi.AbsentInformationException; import com.sun.jdi.ArrayReference; import com.sun.jdi.BooleanValue; import com.sun.jdi.Bootstrap; import com.sun.jdi.ByteValue; import com.sun.jdi.CharValue; import com.sun.jdi.DoubleValue; import com.sun.jdi.Field; import com.sun.jdi.FloatValue; import com.sun.jdi.IncompatibleThreadStateException; import com.sun.jdi.IntegerValue; import com.sun.jdi.LocalVariable; import com.sun.jdi.Location; import com.sun.jdi.LongValue; import com.sun.jdi.Method; import com.sun.jdi.ObjectReference; import com.sun.jdi.ReferenceType; import com.sun.jdi.ShortValue; import com.sun.jdi.StackFrame; import com.sun.jdi.StringReference; import com.sun.jdi.ThreadGroupReference; import com.sun.jdi.ThreadReference; import com.sun.jdi.VMDisconnectedException; import com.sun.jdi.Value; import com.sun.jdi.VirtualMachine; import com.sun.jdi.connect.AttachingConnector; import com.sun.jdi.connect.Connector; import com.sun.jdi.connect.Connector.Argument; import com.sun.jdi.connect.IllegalConnectorArgumentsException; import com.sun.jdi.connect.LaunchingConnector; import com.sun.jdi.connect.VMStartException; import com.sun.jdi.event.BreakpointEvent; import com.sun.jdi.event.Event; import com.sun.jdi.event.EventIterator; import com.sun.jdi.event.EventSet; import com.sun.jdi.event.MethodEntryEvent; import com.sun.jdi.event.MethodExitEvent; import com.sun.jdi.event.StepEvent; import com.sun.jdi.event.VMDisconnectEvent; import com.sun.jdi.event.VMStartEvent; import com.sun.jdi.request.BreakpointRequest; import com.sun.jdi.request.EventRequestManager; import com.sun.jdi.request.MethodEntryRequest; import com.sun.jdi.request.MethodExitRequest; import com.sun.jdi.request.StepRequest; import com.sun.tools.jdi.ObjectReferenceImpl; /** * Abstract base class of debugger. It provides the complete functionality. * * @author wurfmaul <wurfmaul@posteo.at> * */ public abstract class Debugger { protected static final int DEFAULT_PORT = 8000; /** Mapping from command to a boolean whether the vm has to be loaded. */ private static final Map<String, Status> NEEDS_STATUS; /** Flags if the vm is still active. */ protected Status status = NOT_YET_RUNNING; /** Output stream of debugger. */ protected OutputStream out = System.out; /** The environment for the debuggee. */ private VirtualMachine vm; /** The central request manager of the given vm. */ private EventRequestManager reqManager; /** A reference to the current thread. */ private ThreadReference curThread; /** Stack of currently active methods. */ private Stack<Method> methodStack; /** Breakpoints that were not yet set because vm is not loaded. */ private Queue<Breakpoint> pendingBreakpoints; /** Mapping from thread index to referenced thread. */ private Map<Integer, ThreadReference> threads; /** The name of the debuggee class. */ private String debuggee = null; /** * The attaching debugger needs the debuggee to be run itself using a * specific port. * * @param port * Number of port, to which to attach */ protected Debugger(final int port) { // find attaching connector AttachingConnector con = null; for (Connector x : Bootstrap.virtualMachineManager().allConnectors()) { if (x.name().equals("com.sun.jdi.SocketAttach")) con = (AttachingConnector) x; } // configure connector final Map<String, Argument> args = con.defaultArguments(); ((Argument) args.get("port")).setValue(Integer.toString(port)); // establish virtual machine for attached debuggee try { vm = con.attach(args); init(); } catch (IOException e) { print(UNABLE_TO_ATTACH, e.getMessage()); } catch (IllegalConnectorArgumentsException e) { print(ILLEGAL_ARGUMENTS, e.getMessage()); } } /** * The launching debugger does not need the debuggee to be started by * itself, but starts the vm itself. * * @param debuggee * The name of the class which is about to be debugged. * @param args * The debuggee's arguments. */ protected Debugger(final String... args) { // parse arguments assert args.length >= 1; this.debuggee = args[0]; final StringBuilder sb = new StringBuilder(); for (String s : args) { sb.append(s); sb.append(" "); } // establish connection LaunchingConnector con = Bootstrap.virtualMachineManager() .defaultConnector(); Map<String, Argument> arguments = con.defaultArguments(); ((Argument) arguments.get("main")).setValue(sb.toString()); // establish virtual machine for debuggee try { vm = con.launch(arguments); init(); } catch (IOException e) { print(UNABLE_TO_LAUNCH, e.getMessage()); } catch (IllegalConnectorArgumentsException e) { print(ILLEGAL_ARGUMENTS, e.getMessage()); } catch (VMStartException e) { print(UNABLE_TO_START, e.getMessage()); } } static { // e.g. "cont" needs the vm to be running // "run" needs the vm to be stopped // commands that are not listed here don't care about the status NEEDS_STATUS = new HashMap<>(); NEEDS_STATUS.put("cont", RUNNING); NEEDS_STATUS.put("dump", RUNNING); NEEDS_STATUS.put("fields", RUNNING); NEEDS_STATUS.put("locals", RUNNING); NEEDS_STATUS.put("next", RUNNING); NEEDS_STATUS.put("print", RUNNING); NEEDS_STATUS.put("run", NOT_YET_RUNNING); NEEDS_STATUS.put("step", RUNNING); NEEDS_STATUS.put("where", RUNNING); } /** * Initializes fields that re necessary for both constructors. */ private void init() { // make space for pending operations pendingBreakpoints = new ArrayDeque<>(); methodStack = new Stack<>(); threads = new LinkedHashMap<>(); // Establish Request Manager reqManager = vm.eventRequestManager(); // redirect IO streams Process proc = vm.process(); new Redirection(proc.getErrorStream(), out).start(); new Redirection(proc.getInputStream(), out).start(); vm.suspend(); // find current thread for (ThreadReference t : vm.allThreads()) { if (t.name().equals("main")) { curThread = t; break; } } assert curThread != null; } /** * Set a new breakpoint at given location. * * @param loc * Location to set breakpoint at. */ private void setBreakpoint(final Location loc) { final Method method = loc.method(); print(SET_BREAKPOINT, method, loc.lineNumber()); reqManager.createBreakpointRequest(loc).enable(); } /** * Enable possibility to step by one. */ private void setStep() { final StepRequest req = reqManager.createStepRequest(curThread, StepRequest.STEP_LINE, StepRequest.STEP_OVER); req.addCountFilter(1); req.enable(); } /** * Deletes a given breakpoint from list of pending breakpoints or from the * request manager's list. * * @param breakpoint */ private void performClear(final Breakpoint breakpoint) { if (status == NOT_YET_RUNNING) { // find within pending breakpoints if (pendingBreakpoints.remove(breakpoint)) { print(REMOVE_BREAKPOINT, breakpoint); } else { print(BREAKPOINT_NOT_FOUND, breakpoint); } return; } // find set breakpoint for (BreakpointRequest req : reqManager.breakpointRequests()) { final String className = req.location().declaringType().name(); final String methodName = req.location().method().name(); final int lineNumber = req.location().lineNumber(); if (className.equals(breakpoint.className) && (methodName.equals(breakpoint.methodName) || lineNumber == breakpoint.lineNumber)) { reqManager.deleteEventRequest(req); print(REMOVE_BREAKPOINT, breakpoint); return; } } // not found print(BREAKPOINT_NOT_FOUND, breakpoint); } /** * This method continues to next breakpoint or step event if the VM is * started. */ private void performCont() { // let vm run vm.resume(); // listen for events try { while (true) { final EventSet events = vm.eventQueue().remove(); final EventIterator iter = events.eventIterator(); while (iter.hasNext()) { Event e = iter.nextEvent(); if (e instanceof BreakpointEvent) { final BreakpointEvent be = (BreakpointEvent) e; final Location loc = be.location(); print(HIT_BREAKPOINT, be.thread().name(), loc.method(), loc.lineNumber(), loc.codeIndex()); return; } else if (e instanceof StepEvent) { final StepEvent se = (StepEvent) e; final Location loc = se.location(); print(STEP, ((StepEvent) e).thread().name(), loc.method(), loc.lineNumber(), loc.codeIndex()); // delete old step reqManager.deleteEventRequest(se.request()); return; } else if (e instanceof VMDisconnectEvent) { // update status status = TERMINATED; break; } else if (e instanceof MethodEntryEvent) { // push entered method on method stack final MethodEntryEvent mee = (MethodEntryEvent) e; final Method method = mee.method(); methodStack.push(method); // do not resume vm if a breakpoint is reached boolean isBreakpoint = false; for (BreakpointRequest bpr : reqManager .breakpointRequests()) { if (bpr.location().equals(mee.location())) isBreakpoint = true; } if (!isBreakpoint) { vm.resume(); } } else if (e instanceof MethodExitEvent) { // pop exited method from method stack final Method lastMet = methodStack.pop(); assert ((MethodExitEvent) e).method().equals(lastMet); vm.resume(); } } } } catch (InterruptedException e) { e.printStackTrace(); } catch (VMDisconnectedException e) { print(EXIT); } } /** * Reads fields from given class if vm is loaded. * * @param className * Name of class of which the fields are to be printed. */ private void performFields(final String className) { final ReferenceType clazz = findClass(className); if (clazz.visibleFields().size() > 0) { print(FIELDS_HEADER); for (Field f : clazz.visibleFields()) { if (!clazz.equals(f.declaringType())) { // extract declaring class (heritage) final String declClass = f.declaringType().name(); print(FIELD_INHERITED, f.typeName(), f.name(), declClass); } else { // not inherited print(FIELD, f.typeName(), f.name()); } } } else { print(NO_FIELDS, className); } } /** * Reads visible local variables at certain position, depending on the * current frame. */ private void performLocals() { try { final StackFrame curFrame = curThread.frame(0); if (curFrame.visibleVariables().size() > 0) { for (LocalVariable var : curFrame.visibleVariables()) { String value = valueToString(curFrame.getValue(var), false); print(VAR, var.typeName(), var.name(), value); } } else { print(NO_LOCALS); } } catch (IncompatibleThreadStateException e) { e.printStackTrace(); } catch (IndexOutOfBoundsException e) { } catch (AbsentInformationException e) { print(NO_LOCAL_INFO); } } /** * Prints a list of all set breakpoints. */ private void performPrintBreakpoints() { final StringBuilder sb = new StringBuilder(); final Iterator<BreakpointRequest> iter = reqManager .breakpointRequests().iterator(); while (iter.hasNext()) { final Location loc = iter.next().location(); sb.append("\t"); sb.append(loc.method().declaringType().name()); sb.append("."); sb.append(loc.method().name()); sb.append(": "); sb.append(loc.lineNumber()); if (iter.hasNext()) { sb.append("\n"); } } print(LIST_BREAKPOINTS, sb.toString()); } /** * Prints one specific field of given class. * * @param className * Name of class which contains the field or null for the current * position * @param fieldName * Name of field or local variable which is about to be * displayed. * @param dump * True if complex structures like classes or arrays should be * printed including their contents. False if only the name and * id should be printed. */ private void performPrint(String className, String varName, boolean dump) { if (className != null) { final ReferenceType clazz = findClass(className); final Field f = clazz.fieldByName(varName); if (f == null) { print(NO_FIELD, varName, className); } else if (f.isStatic()) { final String value = valueToString(clazz.getValue(f), dump); print(VAR, f.typeName(), f.name(), value); } else { print(FIELD, f.typeName(), className + "." + f.name()); } return; } // className = null try { final StackFrame curFrame = curThread.frame(0); LocalVariable var = curFrame.visibleVariableByName(varName); if (var != null) { // local variable String value = valueToString(curFrame.getValue(var), dump); print(VAR, var.typeName(), var.name(), value); return; } final ReferenceType type = curFrame.location().declaringType(); final Field f = type.fieldByName(varName); if (f == null) { print(UNKNOWN, varName); return; } // instance variable of static method Value val; if (curFrame.location().method().isStatic()) { final List<ObjectReference> instances = type.instances(0); if (instances.size() == 0) { // class not yet initiated print(FIELD, f.typeName(), f.name()); return; } // class already initiated assert instances.size() == 1; val = instances.get(0).getValue(f); } else { val = curFrame.thisObject().getValue(f); } print(VAR, f.typeName(), f.name(), valueToString(val, dump)); } catch (IncompatibleThreadStateException e) { e.printStackTrace(); } catch (AbsentInformationException e) { print(UNKNOWN, varName); } } /** * This method starts the VM and stops at first method entry. */ private void performRun() { print(RUN, debuggee); // supervise entered methods MethodEntryRequest req = reqManager.createMethodEntryRequest(); if (debuggee != null) req.addClassFilter(debuggee); req.addThreadFilter(curThread); req.enable(); // supervise exited methods MethodExitRequest meReq = reqManager.createMethodExitRequest(); if (debuggee != null) meReq.addClassFilter(debuggee); meReq.addThreadFilter(curThread); meReq.enable(); vm.resume(); boolean exit = false; while (!exit) { try { final EventSet events = vm.eventQueue().remove(); final EventIterator iter = events.eventIterator(); while (iter.hasNext()) { Event e = iter.nextEvent(); if (e instanceof MethodEntryEvent) { // push entered method to method stack methodStack.push(((MethodEntryEvent) e).method()); // tell everyone that we are running status = RUNNING; // initialization done, tell loop to exit exit = true; break; } else { assert e instanceof VMStartEvent; } vm.resume(); } } catch (InterruptedException e) { break; } } // perform pending operations while (pendingBreakpoints.size() > 0) { performStop(pendingBreakpoints.remove()); } if (curThread.isAtBreakpoint()) { try { final Location bp = curThread.frame(0).location(); print(HIT_BREAKPOINT, curThread.name(), bp.method(), bp.lineNumber(), bp.codeIndex()); } catch (IncompatibleThreadStateException e) { e.printStackTrace(); } } else { performCont(); } } /** * Performs a single step throughout the source file. */ private void performStep() { setStep(); performCont(); } /** * Find location by given breakpoint dummy and set breakpoint. * * @param breakpoint * A dummy object containing all information required to set a * breakpoint. */ private void performStop(final Breakpoint breakpoint) { final String className = breakpoint.className; final String methodName = breakpoint.methodName; final ReferenceType clazz = findClass(className); int lineNumber = breakpoint.lineNumber; if (lineNumber >= 0) { // find location by line number try { // define range final List<Location> allLines = clazz.allLineLocations(); final int lastLine = allLines.get(allLines.size() - 1) .lineNumber(); List<Location> locs; // find executable line in range do { locs = clazz.locationsOfLine(lineNumber++); } while (locs.size() < 1 && lineNumber < lastLine); if (locs.isEmpty()) { print(BREAKPOINT_ERROR, breakpoint, breakpoint.lineNumber, className); } else { setBreakpoint(locs.get(0)); } } catch (AbsentInformationException e) { e.printStackTrace(); } } else { // find location by method name final List<Method> methods = clazz.methodsByName(methodName); if (methods.size() == 1) { Method method = methods.get(0); // get first executable line try { List<Location> locs = method.allLineLocations(); assert locs.size() > 0; setBreakpoint(locs.get(0)); } catch (AbsentInformationException e) { e.printStackTrace(); } } else if (methods.size() == 0) { print(NO_METHOD, breakpoint, methodName, className); } else { print(METHOD_OVERLOAD, breakpoint, methodName); } } } /** * Print all currently active threads. */ private void performThreads() { // categorize threads final Map<ThreadGroupReference, List<ThreadReference>> groups = new LinkedHashMap<>(); for (ThreadReference t : vm.allThreads()) { ThreadGroupReference group = t.threadGroup(); if (!groups.containsKey(group)) groups.put(group, new LinkedList<ThreadReference>()); groups.get(group).add(t); } // prepare listing threads.clear(); int idx = 0; // print categories for (Entry<ThreadGroupReference, List<ThreadReference>> e : groups .entrySet()) { print(THREAD_GROUP, e.getKey().name()); // print threads String type, name, status; long id; for (ThreadReference t : e.getValue()) { threads.put(idx, t); type = t.type().name(); id = t.uniqueID(); name = t.name(); status = statusToString(t.status()); if (t.isAtBreakpoint()) print(THREAD_STATUS_BP, idx, type, id, name, status); else print(THREAD_STATUS, idx, type, id, name, status); idx++; } } } /** * Switch current thread to thread with given index. * * @param index * Index of thread which is to be the current thread from now. */ private void performThread(final int index) { if (threads.containsKey(index)) { curThread = threads.get(index); } else { print(NO_SUCH_THREAD, index); } } /** * Prints a method trace, i.e. all currently active methods. */ private void performWhere() { final int size = methodStack.size(); for (int i = 1; i <= size; ++i) { final Method method = methodStack.get(size - i); final String caller = method.declaringType().name(); try { final String sourceName = method.location().sourceName(); final Location curLoc = curThread.frame(0).location(); if (i == 1 && method.equals(curLoc.method())) { // current location final int line = curLoc.lineNumber(); print(TRACE_LOC, i, caller, method.name(), sourceName, line); } else { // TODO trace should always include line number print(TRACE_SRC, i, caller, method.name(), sourceName); } } catch (AbsentInformationException | IncompatibleThreadStateException e) { print(TRACE, i, caller, method.name()); } } } /** * Once the vm is loaded, the class object reference can be found using its * name. * * @param className * The name of the wanted class. * @return class reference according to given name. */ private ReferenceType findClass(final String className) { final List<ReferenceType> classes = vm.classesByName(className); assert classes.size() > 0 : className + " not found"; assert classes.size() <= 1; return classes.get(0); } /** * Prints message to the output stream * * @param msg * formatting string * @param args * formatting arguments */ private void print(Message msg, Object... args) { try { out.write(format(msg, args).getBytes()); } catch (IOException e) { e.printStackTrace(); } } /** * Returns human readable thread status from {@link ThreadReference} status * codes. * * @param status * Integer representing the status code. * @return String representation of thread status. */ private static String statusToString(final int status) { switch (status) { case ThreadReference.THREAD_STATUS_ZOMBIE: return "terminated"; case ThreadReference.THREAD_STATUS_RUNNING: return "running"; case ThreadReference.THREAD_STATUS_SLEEPING: return "sleeping"; case ThreadReference.THREAD_STATUS_MONITOR: return "cond. waiting"; case ThreadReference.THREAD_STATUS_WAIT: return "waiting"; case ThreadReference.THREAD_STATUS_NOT_STARTED: return "not started"; default: return "unknown"; } } /** * Convert values of type Value into human-readable String objects. * * @param val * Value which is about to be displayed. * @param dump * If true, complex types (arrays, objects, ...) are displayed * including elements or fields. Otherwise they are printed using * their name and id. * @return String representation of value. */ private static String valueToString(final Value val, final boolean dump) { if (val instanceof BooleanValue) { return ((BooleanValue) val).value() + ""; } else if (val instanceof ByteValue) { return ((ByteValue) val).value() + ""; } else if (val instanceof CharValue) { return ((CharValue) val).value() + ""; } else if (val instanceof DoubleValue) { return ((DoubleValue) val).value() + ""; } else if (val instanceof FloatValue) { return ((FloatValue) val).value() + ""; } else if (val instanceof IntegerValue) { return ((IntegerValue) val).value() + ""; } else if (val instanceof LongValue) { return ((LongValue) val).value() + ""; } else if (val instanceof ShortValue) { return ((ShortValue) val).value() + ""; } else if (val instanceof StringReference) { return "\"" + ((StringReference) val).value() + "\""; } else if (val instanceof ArrayReference) { final ArrayReference arr = (ArrayReference) val; final StringBuilder sb = new StringBuilder(); if (dump) { // print elements sb.append("{"); Iterator<Value> iter = arr.getValues().iterator(); while (iter.hasNext()) { sb.append(valueToString(iter.next(), true)); if (iter.hasNext()) { sb.append(", "); } } sb.append("}"); } else { final String type = arr.type().name(); final long id = arr.uniqueID(); sb.append("instance of " + type + " (id=" + id + ")"); } return sb.toString(); } else if (val instanceof ObjectReferenceImpl) { final ObjectReferenceImpl obj = (ObjectReferenceImpl) val; final StringBuilder sb = new StringBuilder(); if (dump) { // print fields sb.append("["); Iterator<Field> iter = obj.referenceType().allFields() .iterator(); while (iter.hasNext()) { Field f = iter.next(); sb.append(f.name()); sb.append("="); sb.append(valueToString(obj.getValue(f), true)); if (iter.hasNext()) { sb.append(", "); } } sb.append("]"); } else { final String type = obj.type().name(); final long id = obj.uniqueID(); sb.append("instance of " + type + " (id=" + id + ")"); } return sb.toString(); } else { if (val == null) return "<no value>"; throw new UnsupportedOperationException(val.getClass().getName()); } } /** * Close connections, terminate VM */ protected void close() { try { vm.dispose(); } catch (VMDisconnectedException e) { } } /** * Public interface of the debugger. Takes a command in form of a String and * performs necessary steps in order to follow the command. * * @param cmd * Debugging command in String form (e.g. "stop in MyClass.main") */ protected void perform(final String cmd) { StringTokenizer st = new StringTokenizer(cmd, " ."); Breakpoint breakpoint; String className = null; String methodName, varName; int lineNumber; try { final String command = st.nextToken(); // check whether the machine should be running for the command final Status wantedStatus = NEEDS_STATUS.get(command); if (wantedStatus != null && wantedStatus != status) { if (wantedStatus == RUNNING) print(VM_NOT_RUNNING, command); else print(VM_RUNNING); return; } // perform action according to command switch (command) { case "run": performRun(); break; case "cont": performCont(); break; case "dump": case "print": varName = st.nextToken().trim(); if (st.hasMoreTokens()) { // class.field performPrint(varName, st.nextToken(), command.equals("dump")); } else { // var performPrint(null, varName, command.equals("dump")); } break; case "locals": performLocals(); break; case "fields": if (st.hasMoreTokens()) performFields(st.nextToken().trim()); else print(NO_CLASS); break; case "stop": if (st.hasMoreTokens()) { // set new breakpoint switch (st.nextToken()) { case "in": // e.g. "stop in MyClass.main" className = st.nextToken().trim(); methodName = st.nextToken().trim(); breakpoint = new Breakpoint(className, methodName); break; case "at": // e.g. "stop at MyClass:22" className = st.nextToken(": ").trim(); lineNumber = Integer.parseInt(st.nextToken()); breakpoint = new Breakpoint(className, lineNumber); break; default: throw new UnsupportedOperationException(); } if (status == RUNNING) { performStop(breakpoint); } else { print(DEFER_BREAKPOINT, breakpoint); pendingBreakpoints.add(breakpoint); } } else { // print all breakpoints performPrintBreakpoints(); } break; case "where": performWhere(); break; case "step": case "next": performStep(); break; case "clear": // e.g. clear MyClass:45 if (st.hasMoreTokens()) { // delete breakpoints className = st.nextToken(".:").trim(); methodName = st.nextToken().trim(); try { lineNumber = Integer.parseInt(methodName); breakpoint = new Breakpoint(className, lineNumber); } catch (NumberFormatException e) { breakpoint = new Breakpoint(className, methodName); } performClear(breakpoint); } else { // print all breakpoints performPrintBreakpoints(); } break; case "threads": performThreads(); break; case "thread": int index = Integer.parseInt(st.nextToken()); performThread(index); break; // TODO case "catch": // TODO case "ignore": case "exit": case "quit": case "q": break; default: throw new UnsupportedOperationException(); } if (className != null) debuggee = className.trim(); if (st.hasMoreTokens()) { StringBuilder sb = new StringBuilder(); while (st.hasMoreTokens()) { sb.append(st.nextToken()); sb.append(" "); } print(TOO_MANY_ARGS, sb.toString().trim()); } } catch (NoSuchElementException | UnsupportedOperationException | NumberFormatException e) { print(INVALID_CMD, cmd); print(USAGE); } } /** * Returns the name of the current thread * * @return Name of the current thread. */ public String getThreadName() { return curThread.name(); } /** * Indicates the current status of the machine. */ static enum Status { RUNNING, TERMINATED, NOT_YET_RUNNING; } }
gpl-3.0
fesch/Moenagade
src/lu/fisch/moenagade/Ini.java
6199
/* Moenagade °°°°°°°°° Moenagade is a graphical programming tool for beginners. For this reason it is rather limited in its functionality. It aims to help students to gain knowledge about the programming structures. Due to the explicit conversion to real and executable Java code, it should help to make an easy from block programming to coding. Copyright (C) 2009 Bob Fisch This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package lu.fisch.moenagade; /****************************************************************************************************** * * Author: Bob Fisch * * Description: This class manages entries in the INI-file * ****************************************************************************************************** * * Revision List * * Author Date Description * ------ ---- ----------- * Bob Fisch 2008.05.02 First Issue * ****************************************************************************************************** * * Comment: * ******************************************************************************************************/// import java.io.*; import java.util.*; public class Ini { private static String dirname = ""; private static String ininame = "moenagade.ini"; private static String filename = ""; private static File dir = new File(dirname); private static File file = new File(filename); private static Properties p = new Properties(); private static Ini ini = null; public static String getDirname() { // mac if(System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0) { return System.getProperty("user.home")+"/Library/Application Support/Moenagade"; } // windows else if (System.getProperty("os.name").toLowerCase().indexOf( "win" ) >= 0) { String appData = System.getenv("APPDATA"); if(appData!=null) if (!appData.equals("")) { return appData+"\\Moenagade"; } return System.getProperty("user.home") + "\\Application Data\\Moenagade"; } else return System.getProperty("user.home")+System.getProperty("file.separator")+".moenagade"; } public static void set(String key, String value) { Ini ini = Ini.getInstance(); try { ini.load(); ini.setProperty(key, value); ini.save(); } catch (Exception ex) { // ignore any exception } } public static String get(String key, String defaultValue) { Ini ini = Ini.getInstance(); try { ini.load(); return ini.getProperty(key, defaultValue); } catch (Exception ex) { // ignore any exception } return null; } public static Ini getInstance() { try { dirname = getDirname(); //System.getProperty("user.home")+System.getProperty("file.separator")+".unimozer"; filename = dirname+System.getProperty("file.separator")+ininame; dir = new File(dirname); file = new File(filename); } catch(Error e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } if (ini==null) { ini = new Ini(); } return ini; } public void load() throws FileNotFoundException, IOException { File f = new File(filename); if(f.length()==0) { //System.out.println("File is empty!"); } else { //p.loadFromXML(new FileInputStream(filename)); p.load(new FileInputStream(filename)); } } public void save() throws FileNotFoundException, IOException { /*OutputStream os = new FileOutputStream(filename); p.storeToXML(os, "last updated " + new java.util.Date()); os.close(); */ //p.storeToXML(new FileOutputStream(filename), "last updated " + new java.util.Date()); p.store(new FileOutputStream(filename), "last updated " + new java.util.Date()); } public String getProperty(String _name, String _default) { if (p.getProperty(_name)==null) { return _default; } else { return p.getProperty(_name); } } public void setProperty(String _name, String _value) { p.setProperty(_name,_value); } public Set keySet() { return p.keySet(); } private Ini() { try { if(!dir.exists()) { dir.mkdir(); } if(!file.exists()) { try { File predefined = new File("unimozer.ini"); if(predefined.exists()) p.load(new FileInputStream(predefined.getAbsolutePath())); //setProperty("dummy","dummy"); save(); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } } catch(Error e) { System.out.println(e.getMessage()); } catch(Exception e) { System.out.println(e.getMessage()); } } }
gpl-3.0
rubenswagner/L2J-Global
java/com/l2jglobal/gameserver/model/actor/stat/PetStat.java
4423
/* * This file is part of the L2J Global project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jglobal.gameserver.model.actor.stat; import com.l2jglobal.gameserver.data.xml.impl.ExperienceData; import com.l2jglobal.gameserver.data.xml.impl.PetDataTable; import com.l2jglobal.gameserver.model.actor.instance.L2PetInstance; import com.l2jglobal.gameserver.network.SystemMessageId; import com.l2jglobal.gameserver.network.serverpackets.SocialAction; import com.l2jglobal.gameserver.network.serverpackets.SystemMessage; public class PetStat extends SummonStat { public PetStat(L2PetInstance activeChar) { super(activeChar); } public boolean addExp(int value) { if (getActiveChar().isUncontrollable() || !super.addExp(value)) { return false; } getActiveChar().updateAndBroadcastStatus(1); // The PetInfo packet wipes the PartySpelled (list of active spells' icons). Re-add them getActiveChar().updateEffectIcons(true); return true; } public boolean addExpAndSp(long addToExp, long addToSp) { if (getActiveChar().isUncontrollable() || !addExp(addToExp)) { return false; } final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.YOUR_PET_GAINED_S1_XP); sm.addLong(addToExp); getActiveChar().updateAndBroadcastStatus(1); getActiveChar().sendPacket(sm); return true; } @Override public final boolean addLevel(byte value) { if ((getLevel() + value) > (getMaxLevel() - 1)) { return false; } final boolean levelIncreased = super.addLevel(value); getActiveChar().broadcastStatusUpdate(); if (levelIncreased) { getActiveChar().broadcastPacket(new SocialAction(getActiveChar().getObjectId(), SocialAction.LEVEL_UP)); } // Send a Server->Client packet PetInfo to the L2PcInstance getActiveChar().updateAndBroadcastStatus(1); if (getActiveChar().getControlItem() != null) { getActiveChar().getControlItem().setEnchantLevel(getLevel()); } return levelIncreased; } @Override public final long getExpForLevel(int level) { try { return PetDataTable.getInstance().getPetLevelData(getActiveChar().getId(), level).getPetMaxExp(); } catch (NullPointerException e) { if (getActiveChar() != null) { _log.warning("Pet objectId:" + getActiveChar().getObjectId() + ", NpcId:" + getActiveChar().getId() + ", level:" + level + " is missing data from pets_stats table!"); } throw e; } } @Override public L2PetInstance getActiveChar() { return (L2PetInstance) super.getActiveChar(); } public final int getFeedBattle() { return getActiveChar().getPetLevelData().getPetFeedBattle(); } public final int getFeedNormal() { return getActiveChar().getPetLevelData().getPetFeedNormal(); } @Override public void setLevel(byte value) { getActiveChar().setPetData(PetDataTable.getInstance().getPetLevelData(getActiveChar().getTemplate().getId(), value)); if (getActiveChar().getPetLevelData() == null) { throw new IllegalArgumentException("No pet data for npc: " + getActiveChar().getTemplate().getId() + " level: " + value); } getActiveChar().stopFeed(); super.setLevel(value); getActiveChar().startFeed(); if (getActiveChar().getControlItem() != null) { getActiveChar().getControlItem().setEnchantLevel(getLevel()); } } public final int getMaxFeed() { return getActiveChar().getPetLevelData().getPetMaxFeed(); } @Override public int getPAtkSpd() { int val = super.getPAtkSpd(); if (getActiveChar().isHungry()) { val /= 2; } return val; } @Override public int getMAtkSpd() { int val = super.getMAtkSpd(); if (getActiveChar().isHungry()) { val /= 2; } return val; } @Override public int getMaxLevel() { return ExperienceData.getInstance().getMaxPetLevel(); } }
gpl-3.0
txstate-etc/gato
gato-component-faq/src/main/java/edu/txstate/its/gato/FaqItem.java
1905
package edu.txstate.its.gato; import info.magnolia.jcr.util.NodeTypes; import info.magnolia.jcr.util.NodeUtil; import info.magnolia.jcr.util.PropertyUtil; import info.magnolia.link.LinkUtil; import info.magnolia.link.LinkException; import info.magnolia.ui.vaadin.integration.jcr.JcrNodeAdapter; import info.magnolia.ui.vaadin.integration.jcr.JcrNewNodeAdapter; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import org.apache.commons.lang.StringUtils; import lombok.Getter; import java.util.ArrayList; import java.util.List; import com.vaadin.v7.data.util.ObjectProperty; public class FaqItem { @Getter public String id; @Getter public String nodetype; @Getter public String question; @Getter public String answer; @Getter public String title; @Getter public String uuid; @Getter public List<FaqItem> children = new ArrayList<FaqItem>(); public FaqItem(Node node) { nodetype = PropertyUtil.getString(node, "nodetype"); try { id = node.getName(); uuid = node.getIdentifier(); } catch (RepositoryException e) { e.printStackTrace(); } if ("group".equals(nodetype)) { title = PropertyUtil.getString(node, "title", ""); if (StringUtils.isEmpty(title)) { title = "--No Text Entered--"; } try { for (Node c : NodeUtil.getNodes(node, NodeTypes.Area.NAME)) { children.add(new FaqItem(c)); } } catch (RepositoryException e) { e.printStackTrace(); } } else { question = PropertyUtil.getString(node, "question", ""); answer = PropertyUtil.getString(node, "answer", ""); if (StringUtils.isEmpty(question)) { question = "--No Text Entered--"; } try { answer = LinkUtil.convertLinksFromUUIDPattern(answer); } catch (LinkException e) { e.printStackTrace(); } } } }
gpl-3.0
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/libraries-data/src/main/java/com/baeldung/flink/LineSplitter.java
601
package com.baeldung.flink; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.util.Collector; import java.util.stream.Stream; @SuppressWarnings("serial") public class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> { @Override public void flatMap(String value, Collector<Tuple2<String, Integer>> out) { String[] tokens = value.toLowerCase().split("\\W+"); Stream.of(tokens).filter(t -> t.length() > 0).forEach(token -> out.collect(new Tuple2<>(token, 1))); } }
gpl-3.0
TheGreatAndPowerfulWeegee/wipunknown
build/tmp/recompileMc/sources/net/minecraft/world/WorldServer.java
54694
package net.minecraft.world; import com.google.common.base.Predicate; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ListenableFuture; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import javax.annotation.Nullable; import net.minecraft.advancements.AdvancementManager; import net.minecraft.advancements.FunctionManager; import net.minecraft.block.Block; import net.minecraft.block.BlockEventData; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityTracker; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.INpc; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.passive.EntitySkeletonHorse; import net.minecraft.entity.passive.EntityWaterMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.network.Packet; import net.minecraft.network.play.server.SPacketBlockAction; import net.minecraft.network.play.server.SPacketChangeGameState; import net.minecraft.network.play.server.SPacketEntityStatus; import net.minecraft.network.play.server.SPacketExplosion; import net.minecraft.network.play.server.SPacketParticles; import net.minecraft.network.play.server.SPacketSpawnGlobalEntity; import net.minecraft.profiler.Profiler; import net.minecraft.scoreboard.ScoreboardSaveData; import net.minecraft.scoreboard.ServerScoreboard; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.PlayerChunkMap; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.IProgressUpdate; import net.minecraft.util.IThreadListener; import net.minecraft.util.ReportedException; import net.minecraft.util.WeightedRandom; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.village.VillageCollection; import net.minecraft.village.VillageSiege; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.BiomeProvider; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraft.world.chunk.storage.IChunkLoader; import net.minecraft.world.gen.ChunkProviderServer; import net.minecraft.world.gen.feature.WorldGeneratorBonusChest; import net.minecraft.world.gen.structure.StructureBoundingBox; import net.minecraft.world.gen.structure.template.TemplateManager; import net.minecraft.world.storage.ISaveHandler; import net.minecraft.world.storage.MapStorage; import net.minecraft.world.storage.WorldInfo; import net.minecraft.world.storage.WorldSavedDataCallableSave; import net.minecraft.world.storage.loot.LootTableManager; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class WorldServer extends World implements IThreadListener { private static final Logger LOGGER = LogManager.getLogger(); private final MinecraftServer mcServer; /** The entity tracker for this server world. */ private final EntityTracker entityTracker; /** The player chunk map for this server world. */ private final PlayerChunkMap playerChunkMap; private final Set<NextTickListEntry> pendingTickListEntriesHashSet = Sets.<NextTickListEntry>newHashSet(); /** All work to do in future ticks. */ private final TreeSet<NextTickListEntry> pendingTickListEntriesTreeSet = new TreeSet<NextTickListEntry>(); private final Map<UUID, Entity> entitiesByUuid = Maps.<UUID, Entity>newHashMap(); /** Whether level saving is disabled or not */ public boolean disableLevelSaving; /** is false if there are no players */ private boolean allPlayersSleeping; private int updateEntityTick; /** the teleporter to use when the entity is being transferred into the dimension */ private final Teleporter worldTeleporter; private final WorldEntitySpawner entitySpawner = new WorldEntitySpawner(); protected final VillageSiege villageSiege = new VillageSiege(this); private final WorldServer.ServerBlockEventList[] blockEventQueue = new WorldServer.ServerBlockEventList[] {new WorldServer.ServerBlockEventList(), new WorldServer.ServerBlockEventList()}; private int blockEventCacheIndex; private final List<NextTickListEntry> pendingTickListEntriesThisTick = Lists.<NextTickListEntry>newArrayList(); /** Stores the recently processed (lighting) chunks */ protected Set<ChunkPos> doneChunks = new java.util.HashSet<ChunkPos>(); public List<Teleporter> customTeleporters = new ArrayList<Teleporter>(); public WorldServer(MinecraftServer server, ISaveHandler saveHandlerIn, WorldInfo info, int dimensionId, Profiler profilerIn) { super(saveHandlerIn, info, net.minecraftforge.common.DimensionManager.createProviderFor(dimensionId), profilerIn, false); this.mcServer = server; this.entityTracker = new EntityTracker(this); this.playerChunkMap = new PlayerChunkMap(this); // Guarantee the dimension ID was not reset by the provider int providerDim = this.provider.getDimension(); this.provider.setWorld(this); this.provider.setDimension(providerDim); this.chunkProvider = this.createChunkProvider(); perWorldStorage = new MapStorage(new net.minecraftforge.common.WorldSpecificSaveHandler((WorldServer)this, saveHandlerIn)); this.worldTeleporter = new Teleporter(this); this.calculateInitialSkylight(); this.calculateInitialWeather(); this.getWorldBorder().setSize(server.getMaxWorldSize()); net.minecraftforge.common.DimensionManager.setWorld(dimensionId, this, mcServer); } public World init() { this.mapStorage = new MapStorage(this.saveHandler); String s = VillageCollection.fileNameForProvider(this.provider); VillageCollection villagecollection = (VillageCollection)this.perWorldStorage.getOrLoadData(VillageCollection.class, s); if (villagecollection == null) { this.villageCollection = new VillageCollection(this); this.perWorldStorage.setData(s, this.villageCollection); } else { this.villageCollection = villagecollection; this.villageCollection.setWorldsForAll(this); } this.worldScoreboard = new ServerScoreboard(this.mcServer); ScoreboardSaveData scoreboardsavedata = (ScoreboardSaveData)this.mapStorage.getOrLoadData(ScoreboardSaveData.class, "scoreboard"); if (scoreboardsavedata == null) { scoreboardsavedata = new ScoreboardSaveData(); this.mapStorage.setData("scoreboard", scoreboardsavedata); } scoreboardsavedata.setScoreboard(this.worldScoreboard); ((ServerScoreboard)this.worldScoreboard).addDirtyRunnable(new WorldSavedDataCallableSave(scoreboardsavedata)); this.lootTable = new LootTableManager(new File(new File(this.saveHandler.getWorldDirectory(), "data"), "loot_tables")); this.advancementManager = new AdvancementManager(new File(new File(this.saveHandler.getWorldDirectory(), "data"), "advancements")); this.functionManager = new FunctionManager(new File(new File(this.saveHandler.getWorldDirectory(), "data"), "functions"), this.mcServer); this.getWorldBorder().setCenter(this.worldInfo.getBorderCenterX(), this.worldInfo.getBorderCenterZ()); this.getWorldBorder().setDamageAmount(this.worldInfo.getBorderDamagePerBlock()); this.getWorldBorder().setDamageBuffer(this.worldInfo.getBorderSafeZone()); this.getWorldBorder().setWarningDistance(this.worldInfo.getBorderWarningDistance()); this.getWorldBorder().setWarningTime(this.worldInfo.getBorderWarningTime()); if (this.worldInfo.getBorderLerpTime() > 0L) { this.getWorldBorder().setTransition(this.worldInfo.getBorderSize(), this.worldInfo.getBorderLerpTarget(), this.worldInfo.getBorderLerpTime()); } else { this.getWorldBorder().setTransition(this.worldInfo.getBorderSize()); } this.initCapabilities(); return this; } /** * Runs a single tick for the world */ public void tick() { super.tick(); if (this.getWorldInfo().isHardcoreModeEnabled() && this.getDifficulty() != EnumDifficulty.HARD) { this.getWorldInfo().setDifficulty(EnumDifficulty.HARD); } this.provider.getBiomeProvider().cleanupCache(); if (this.areAllPlayersAsleep()) { if (this.getGameRules().getBoolean("doDaylightCycle")) { long i = this.getWorldTime() + 24000L; this.setWorldTime(i - i % 24000L); } this.wakeAllPlayers(); } this.profiler.startSection("mobSpawner"); if (this.getGameRules().getBoolean("doMobSpawning") && this.worldInfo.getTerrainType() != WorldType.DEBUG_ALL_BLOCK_STATES) { this.entitySpawner.findChunksForSpawning(this, this.spawnHostileMobs, this.spawnPeacefulMobs, this.worldInfo.getWorldTotalTime() % 400L == 0L); } this.profiler.endStartSection("chunkSource"); this.chunkProvider.tick(); int j = this.calculateSkylightSubtracted(1.0F); if (j != this.getSkylightSubtracted()) { this.setSkylightSubtracted(j); } this.worldInfo.setWorldTotalTime(this.worldInfo.getWorldTotalTime() + 1L); if (this.getGameRules().getBoolean("doDaylightCycle")) { this.setWorldTime(this.getWorldTime() + 1L); } this.profiler.endStartSection("tickPending"); this.tickUpdates(false); this.profiler.endStartSection("tickBlocks"); this.updateBlocks(); this.profiler.endStartSection("chunkMap"); this.playerChunkMap.tick(); this.profiler.endStartSection("village"); this.villageCollection.tick(); this.villageSiege.tick(); this.profiler.endStartSection("portalForcer"); this.worldTeleporter.removeStalePortalLocations(this.getTotalWorldTime()); for (Teleporter tele : customTeleporters) { tele.removeStalePortalLocations(getTotalWorldTime()); } this.profiler.endSection(); this.sendQueuedBlockEvents(); } @Nullable public Biome.SpawnListEntry getSpawnListEntryForTypeAt(EnumCreatureType creatureType, BlockPos pos) { List<Biome.SpawnListEntry> list = this.getChunkProvider().getPossibleCreatures(creatureType, pos); list = net.minecraftforge.event.ForgeEventFactory.getPotentialSpawns(this, creatureType, pos, list); return list != null && !list.isEmpty() ? (Biome.SpawnListEntry)WeightedRandom.getRandomItem(this.rand, list) : null; } public boolean canCreatureTypeSpawnHere(EnumCreatureType creatureType, Biome.SpawnListEntry spawnListEntry, BlockPos pos) { List<Biome.SpawnListEntry> list = this.getChunkProvider().getPossibleCreatures(creatureType, pos); list = net.minecraftforge.event.ForgeEventFactory.getPotentialSpawns(this, creatureType, pos, list); return list != null && !list.isEmpty() ? list.contains(spawnListEntry) : false; } /** * Updates the flag that indicates whether or not all players in the world are sleeping. */ public void updateAllPlayersSleepingFlag() { this.allPlayersSleeping = false; if (!this.playerEntities.isEmpty()) { int i = 0; int j = 0; for (EntityPlayer entityplayer : this.playerEntities) { if (entityplayer.isSpectator()) { ++i; } else if (entityplayer.isPlayerSleeping()) { ++j; } } this.allPlayersSleeping = j > 0 && j >= this.playerEntities.size() - i; } } protected void wakeAllPlayers() { this.allPlayersSleeping = false; for (EntityPlayer entityplayer : this.playerEntities) { if (entityplayer.isPlayerSleeping()) { entityplayer.wakeUpPlayer(false, false, true); } } if (this.getGameRules().getBoolean("doWeatherCycle")) { this.resetRainAndThunder(); } } /** * Clears the current rain and thunder weather states. */ private void resetRainAndThunder() { this.provider.resetRainAndThunder(); } /** * Checks if all players in this world are sleeping. */ public boolean areAllPlayersAsleep() { if (this.allPlayersSleeping && !this.isRemote) { for (EntityPlayer entityplayer : this.playerEntities) { if (!entityplayer.isSpectator() && !entityplayer.isPlayerFullyAsleep()) { return false; } } return true; } else { return false; } } /** * Sets a new spawn location by finding an uncovered block at a random (x,z) location in the chunk. */ @SideOnly(Side.CLIENT) public void setInitialSpawnLocation() { if (this.worldInfo.getSpawnY() <= 0) { this.worldInfo.setSpawnY(this.getSeaLevel() + 1); } int i = this.worldInfo.getSpawnX(); int j = this.worldInfo.getSpawnZ(); int k = 0; while (this.getGroundAboveSeaLevel(new BlockPos(i, 0, j)).getMaterial() == Material.AIR) { i += this.rand.nextInt(8) - this.rand.nextInt(8); j += this.rand.nextInt(8) - this.rand.nextInt(8); ++k; if (k == 10000) { break; } } this.worldInfo.setSpawnX(i); this.worldInfo.setSpawnZ(j); } protected boolean isChunkLoaded(int x, int z, boolean allowEmpty) { return this.getChunkProvider().chunkExists(x, z); } protected void playerCheckLight() { this.profiler.startSection("playerCheckLight"); if (!this.playerEntities.isEmpty()) { int i = this.rand.nextInt(this.playerEntities.size()); EntityPlayer entityplayer = this.playerEntities.get(i); int j = MathHelper.floor(entityplayer.posX) + this.rand.nextInt(11) - 5; int k = MathHelper.floor(entityplayer.posY) + this.rand.nextInt(11) - 5; int l = MathHelper.floor(entityplayer.posZ) + this.rand.nextInt(11) - 5; this.checkLight(new BlockPos(j, k, l)); } this.profiler.endSection(); } protected void updateBlocks() { this.playerCheckLight(); if (this.worldInfo.getTerrainType() == WorldType.DEBUG_ALL_BLOCK_STATES) { Iterator<Chunk> iterator1 = this.playerChunkMap.getChunkIterator(); while (iterator1.hasNext()) { ((Chunk)iterator1.next()).onTick(false); } } else { int i = this.getGameRules().getInt("randomTickSpeed"); boolean flag = this.isRaining(); boolean flag1 = this.isThundering(); this.profiler.startSection("pollingChunks"); for (Iterator<Chunk> iterator = getPersistentChunkIterable(this.playerChunkMap.getChunkIterator()); iterator.hasNext(); this.profiler.endSection()) { this.profiler.startSection("getChunk"); Chunk chunk = iterator.next(); int j = chunk.x * 16; int k = chunk.z * 16; this.profiler.endStartSection("checkNextLight"); chunk.enqueueRelightChecks(); this.profiler.endStartSection("tickChunk"); chunk.onTick(false); this.profiler.endStartSection("thunder"); if (this.provider.canDoLightning(chunk) && flag && flag1 && this.rand.nextInt(100000) == 0) { this.updateLCG = this.updateLCG * 3 + 1013904223; int l = this.updateLCG >> 2; BlockPos blockpos = this.adjustPosToNearbyEntity(new BlockPos(j + (l & 15), 0, k + (l >> 8 & 15))); if (this.isRainingAt(blockpos)) { DifficultyInstance difficultyinstance = this.getDifficultyForLocation(blockpos); if (this.getGameRules().getBoolean("doMobSpawning") && this.rand.nextDouble() < (double)difficultyinstance.getAdditionalDifficulty() * 0.01D) { EntitySkeletonHorse entityskeletonhorse = new EntitySkeletonHorse(this); entityskeletonhorse.setTrap(true); entityskeletonhorse.setGrowingAge(0); entityskeletonhorse.setPosition((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ()); this.spawnEntity(entityskeletonhorse); this.addWeatherEffect(new EntityLightningBolt(this, (double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), true)); } else { this.addWeatherEffect(new EntityLightningBolt(this, (double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), false)); } } } this.profiler.endStartSection("iceandsnow"); if (this.provider.canDoRainSnowIce(chunk) && this.rand.nextInt(16) == 0) { this.updateLCG = this.updateLCG * 3 + 1013904223; int j2 = this.updateLCG >> 2; BlockPos blockpos1 = this.getPrecipitationHeight(new BlockPos(j + (j2 & 15), 0, k + (j2 >> 8 & 15))); BlockPos blockpos2 = blockpos1.down(); if (this.canBlockFreezeNoWater(blockpos2)) { this.setBlockState(blockpos2, Blocks.ICE.getDefaultState()); } if (flag && this.canSnowAt(blockpos1, true)) { this.setBlockState(blockpos1, Blocks.SNOW_LAYER.getDefaultState()); } if (flag && this.getBiome(blockpos2).canRain()) { this.getBlockState(blockpos2).getBlock().fillWithRain(this, blockpos2); } } this.profiler.endStartSection("tickBlocks"); if (i > 0) { for (ExtendedBlockStorage extendedblockstorage : chunk.getBlockStorageArray()) { if (extendedblockstorage != Chunk.NULL_BLOCK_STORAGE && extendedblockstorage.needsRandomTick()) { for (int i1 = 0; i1 < i; ++i1) { this.updateLCG = this.updateLCG * 3 + 1013904223; int j1 = this.updateLCG >> 2; int k1 = j1 & 15; int l1 = j1 >> 8 & 15; int i2 = j1 >> 16 & 15; IBlockState iblockstate = extendedblockstorage.get(k1, i2, l1); Block block = iblockstate.getBlock(); this.profiler.startSection("randomTick"); if (block.getTickRandomly()) { block.randomTick(this, new BlockPos(k1 + j, i2 + extendedblockstorage.getYLocation(), l1 + k), iblockstate, this.rand); } this.profiler.endSection(); } } } } } this.profiler.endSection(); } } protected BlockPos adjustPosToNearbyEntity(BlockPos pos) { BlockPos blockpos = this.getPrecipitationHeight(pos); AxisAlignedBB axisalignedbb = (new AxisAlignedBB(blockpos, new BlockPos(blockpos.getX(), this.getHeight(), blockpos.getZ()))).grow(3.0D); List<EntityLivingBase> list = this.getEntitiesWithinAABB(EntityLivingBase.class, axisalignedbb, new Predicate<EntityLivingBase>() { public boolean apply(@Nullable EntityLivingBase p_apply_1_) { return p_apply_1_ != null && p_apply_1_.isEntityAlive() && WorldServer.this.canSeeSky(p_apply_1_.getPosition()); } }); if (!list.isEmpty()) { return ((EntityLivingBase)list.get(this.rand.nextInt(list.size()))).getPosition(); } else { if (blockpos.getY() == -1) { blockpos = blockpos.up(2); } return blockpos; } } public boolean isBlockTickPending(BlockPos pos, Block blockType) { NextTickListEntry nextticklistentry = new NextTickListEntry(pos, blockType); return this.pendingTickListEntriesThisTick.contains(nextticklistentry); } /** * Returns true if the identified block is scheduled to be updated. */ public boolean isUpdateScheduled(BlockPos pos, Block blk) { NextTickListEntry nextticklistentry = new NextTickListEntry(pos, blk); return this.pendingTickListEntriesHashSet.contains(nextticklistentry); } public void scheduleUpdate(BlockPos pos, Block blockIn, int delay) { this.updateBlockTick(pos, blockIn, delay, 0); } public void updateBlockTick(BlockPos pos, Block blockIn, int delay, int priority) { Material material = blockIn.getDefaultState().getMaterial(); if (this.scheduledUpdatesAreImmediate && material != Material.AIR) { if (blockIn.requiresUpdates()) { //Keeping here as a note for future when it may be restored. boolean isForced = getPersistentChunks().containsKey(new ChunkPos(pos)); int range = isForced ? 0 : 8; if (this.isAreaLoaded(pos.add(-range, -range, -range), pos.add(range, range, range))) { IBlockState iblockstate = this.getBlockState(pos); if (iblockstate.getMaterial() != Material.AIR && iblockstate.getBlock() == blockIn) { iblockstate.getBlock().updateTick(this, pos, iblockstate, this.rand); } } return; } delay = 1; } NextTickListEntry nextticklistentry = new NextTickListEntry(pos, blockIn); if (this.isBlockLoaded(pos)) { if (material != Material.AIR) { nextticklistentry.setScheduledTime((long)delay + this.worldInfo.getWorldTotalTime()); nextticklistentry.setPriority(priority); } if (!this.pendingTickListEntriesHashSet.contains(nextticklistentry)) { this.pendingTickListEntriesHashSet.add(nextticklistentry); this.pendingTickListEntriesTreeSet.add(nextticklistentry); } } } /** * Called by CommandClone and AnvilChunkLoader to force a block update. */ public void scheduleBlockUpdate(BlockPos pos, Block blockIn, int delay, int priority) { if (blockIn == null) return; //Forge: Prevent null blocks from ticking, can happen if blocks are removed in old worlds. TODO: Fix real issue causing block to be null. NextTickListEntry nextticklistentry = new NextTickListEntry(pos, blockIn); nextticklistentry.setPriority(priority); Material material = blockIn.getDefaultState().getMaterial(); if (material != Material.AIR) { nextticklistentry.setScheduledTime((long)delay + this.worldInfo.getWorldTotalTime()); } if (!this.pendingTickListEntriesHashSet.contains(nextticklistentry)) { this.pendingTickListEntriesHashSet.add(nextticklistentry); this.pendingTickListEntriesTreeSet.add(nextticklistentry); } } /** * Updates (and cleans up) entities and tile entities */ public void updateEntities() { if (this.playerEntities.isEmpty() && getPersistentChunks().isEmpty()) { if (this.updateEntityTick++ >= 300) { return; } } else { this.resetUpdateEntityTick(); } this.provider.onWorldUpdateEntities(); super.updateEntities(); } protected void tickPlayers() { super.tickPlayers(); this.profiler.endStartSection("players"); for (int i = 0; i < this.playerEntities.size(); ++i) { Entity entity = this.playerEntities.get(i); Entity entity1 = entity.getRidingEntity(); if (entity1 != null) { if (!entity1.isDead && entity1.isPassenger(entity)) { continue; } entity.dismountRidingEntity(); } this.profiler.startSection("tick"); if (!entity.isDead) { try { this.updateEntity(entity); } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Ticking player"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Player being ticked"); entity.addEntityCrashInfo(crashreportcategory); throw new ReportedException(crashreport); } } this.profiler.endSection(); this.profiler.startSection("remove"); if (entity.isDead) { int j = entity.chunkCoordX; int k = entity.chunkCoordZ; if (entity.addedToChunk && this.isChunkLoaded(j, k, true)) { this.getChunkFromChunkCoords(j, k).removeEntity(entity); } this.loadedEntityList.remove(entity); this.onEntityRemoved(entity); } this.profiler.endSection(); } } /** * Resets the updateEntityTick field to 0 */ public void resetUpdateEntityTick() { this.updateEntityTick = 0; } /** * Runs through the list of updates to run and ticks them */ public boolean tickUpdates(boolean runAllPending) { if (this.worldInfo.getTerrainType() == WorldType.DEBUG_ALL_BLOCK_STATES) { return false; } else { int i = this.pendingTickListEntriesTreeSet.size(); if (i != this.pendingTickListEntriesHashSet.size()) { throw new IllegalStateException("TickNextTick list out of synch"); } else { if (i > 65536) { i = 65536; } this.profiler.startSection("cleaning"); for (int j = 0; j < i; ++j) { NextTickListEntry nextticklistentry = this.pendingTickListEntriesTreeSet.first(); if (!runAllPending && nextticklistentry.scheduledTime > this.worldInfo.getWorldTotalTime()) { break; } this.pendingTickListEntriesTreeSet.remove(nextticklistentry); this.pendingTickListEntriesHashSet.remove(nextticklistentry); this.pendingTickListEntriesThisTick.add(nextticklistentry); } this.profiler.endSection(); this.profiler.startSection("ticking"); Iterator<NextTickListEntry> iterator = this.pendingTickListEntriesThisTick.iterator(); while (iterator.hasNext()) { NextTickListEntry nextticklistentry1 = iterator.next(); iterator.remove(); //Keeping here as a note for future when it may be restored. //boolean isForced = getPersistentChunks().containsKey(new ChunkPos(nextticklistentry.xCoord >> 4, nextticklistentry.zCoord >> 4)); //byte b0 = isForced ? 0 : 8; int k = 0; if (this.isAreaLoaded(nextticklistentry1.position.add(0, 0, 0), nextticklistentry1.position.add(0, 0, 0))) { IBlockState iblockstate = this.getBlockState(nextticklistentry1.position); if (iblockstate.getMaterial() != Material.AIR && Block.isEqualTo(iblockstate.getBlock(), nextticklistentry1.getBlock())) { try { iblockstate.getBlock().updateTick(this, nextticklistentry1.position, iblockstate, this.rand); } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception while ticking a block"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being ticked"); CrashReportCategory.addBlockInfo(crashreportcategory, nextticklistentry1.position, iblockstate); throw new ReportedException(crashreport); } } } else { this.scheduleUpdate(nextticklistentry1.position, nextticklistentry1.getBlock(), 0); } } this.profiler.endSection(); this.pendingTickListEntriesThisTick.clear(); return !this.pendingTickListEntriesTreeSet.isEmpty(); } } } @Nullable public List<NextTickListEntry> getPendingBlockUpdates(Chunk chunkIn, boolean remove) { ChunkPos chunkpos = chunkIn.getPos(); int i = (chunkpos.x << 4) - 2; int j = i + 16 + 2; int k = (chunkpos.z << 4) - 2; int l = k + 16 + 2; return this.getPendingBlockUpdates(new StructureBoundingBox(i, 0, k, j, 256, l), remove); } @Nullable public List<NextTickListEntry> getPendingBlockUpdates(StructureBoundingBox structureBB, boolean remove) { List<NextTickListEntry> list = null; for (int i = 0; i < 2; ++i) { Iterator<NextTickListEntry> iterator; if (i == 0) { iterator = this.pendingTickListEntriesTreeSet.iterator(); } else { iterator = this.pendingTickListEntriesThisTick.iterator(); } while (iterator.hasNext()) { NextTickListEntry nextticklistentry = iterator.next(); BlockPos blockpos = nextticklistentry.position; if (blockpos.getX() >= structureBB.minX && blockpos.getX() < structureBB.maxX && blockpos.getZ() >= structureBB.minZ && blockpos.getZ() < structureBB.maxZ) { if (remove) { if (i == 0) { this.pendingTickListEntriesHashSet.remove(nextticklistentry); } iterator.remove(); } if (list == null) { list = Lists.<NextTickListEntry>newArrayList(); } list.add(nextticklistentry); } } } return list; } /** * Updates the entity in the world if the chunk the entity is in is currently loaded or its forced to update. */ public void updateEntityWithOptionalForce(Entity entityIn, boolean forceUpdate) { if (!this.canSpawnAnimals() && (entityIn instanceof EntityAnimal || entityIn instanceof EntityWaterMob)) { entityIn.setDead(); } if (!this.canSpawnNPCs() && entityIn instanceof INpc) { entityIn.setDead(); } super.updateEntityWithOptionalForce(entityIn, forceUpdate); } private boolean canSpawnNPCs() { return this.mcServer.getCanSpawnNPCs(); } private boolean canSpawnAnimals() { return this.mcServer.getCanSpawnAnimals(); } /** * Creates the chunk provider for this world. Called in the constructor. Retrieves provider from worldProvider? */ protected IChunkProvider createChunkProvider() { IChunkLoader ichunkloader = this.saveHandler.getChunkLoader(this.provider); return new ChunkProviderServer(this, ichunkloader, this.provider.createChunkGenerator()); } public boolean isBlockModifiable(EntityPlayer player, BlockPos pos) { return super.isBlockModifiable(player, pos); } public boolean canMineBlockBody(EntityPlayer player, BlockPos pos) { return !this.mcServer.isBlockProtected(this, pos, player) && this.getWorldBorder().contains(pos); } public void initialize(WorldSettings settings) { if (!this.worldInfo.isInitialized()) { try { this.createSpawnPosition(settings); if (this.worldInfo.getTerrainType() == WorldType.DEBUG_ALL_BLOCK_STATES) { this.setDebugWorldSettings(); } super.initialize(settings); } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception initializing level"); try { this.addWorldInfoToCrashReport(crashreport); } catch (Throwable var5) { ; } throw new ReportedException(crashreport); } this.worldInfo.setServerInitialized(true); } } private void setDebugWorldSettings() { this.worldInfo.setMapFeaturesEnabled(false); this.worldInfo.setAllowCommands(true); this.worldInfo.setRaining(false); this.worldInfo.setThundering(false); this.worldInfo.setCleanWeatherTime(1000000000); this.worldInfo.setWorldTime(6000L); this.worldInfo.setGameType(GameType.SPECTATOR); this.worldInfo.setHardcore(false); this.worldInfo.setDifficulty(EnumDifficulty.PEACEFUL); this.worldInfo.setDifficultyLocked(true); this.getGameRules().setOrCreateGameRule("doDaylightCycle", "false"); } /** * creates a spawn position at random within 256 blocks of 0,0 */ private void createSpawnPosition(WorldSettings settings) { if (!this.provider.canRespawnHere()) { this.worldInfo.setSpawn(BlockPos.ORIGIN.up(this.provider.getAverageGroundLevel())); } else if (this.worldInfo.getTerrainType() == WorldType.DEBUG_ALL_BLOCK_STATES) { this.worldInfo.setSpawn(BlockPos.ORIGIN.up()); } else { if (net.minecraftforge.event.ForgeEventFactory.onCreateWorldSpawn(this, settings)) return; this.findingSpawnPoint = true; BiomeProvider biomeprovider = this.provider.getBiomeProvider(); List<Biome> list = biomeprovider.getBiomesToSpawnIn(); Random random = new Random(this.getSeed()); BlockPos blockpos = biomeprovider.findBiomePosition(0, 0, 256, list, random); int i = 8; int j = this.provider.getAverageGroundLevel(); int k = 8; if (blockpos != null) { i = blockpos.getX(); k = blockpos.getZ(); } else { LOGGER.warn("Unable to find spawn biome"); } int l = 0; while (!this.provider.canCoordinateBeSpawn(i, k)) { i += random.nextInt(64) - random.nextInt(64); k += random.nextInt(64) - random.nextInt(64); ++l; if (l == 1000) { break; } } this.worldInfo.setSpawn(new BlockPos(i, j, k)); this.findingSpawnPoint = false; if (settings.isBonusChestEnabled()) { this.createBonusChest(); } } } /** * Creates the bonus chest in the world. */ protected void createBonusChest() { WorldGeneratorBonusChest worldgeneratorbonuschest = new WorldGeneratorBonusChest(); for (int i = 0; i < 10; ++i) { int j = this.worldInfo.getSpawnX() + this.rand.nextInt(6) - this.rand.nextInt(6); int k = this.worldInfo.getSpawnZ() + this.rand.nextInt(6) - this.rand.nextInt(6); BlockPos blockpos = this.getTopSolidOrLiquidBlock(new BlockPos(j, 0, k)).up(); if (worldgeneratorbonuschest.generate(this, this.rand, blockpos)) { break; } } } /** * Returns null for anything other than the End */ @Nullable public BlockPos getSpawnCoordinate() { return this.provider.getSpawnCoordinate(); } /** * Saves all chunks to disk while updating progress bar. */ public void saveAllChunks(boolean all, @Nullable IProgressUpdate progressCallback) throws MinecraftException { ChunkProviderServer chunkproviderserver = this.getChunkProvider(); if (chunkproviderserver.canSave()) { if (progressCallback != null) { progressCallback.displaySavingString("Saving level"); } this.saveLevel(); if (progressCallback != null) { progressCallback.displayLoadingString("Saving chunks"); } chunkproviderserver.saveChunks(all); net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.world.WorldEvent.Save(this)); for (Chunk chunk : Lists.newArrayList(chunkproviderserver.getLoadedChunks())) { if (chunk != null && !this.playerChunkMap.contains(chunk.x, chunk.z)) { chunkproviderserver.queueUnload(chunk); } } } } /** * Flushes all pending chunks fully back to disk */ public void flushToDisk() { ChunkProviderServer chunkproviderserver = this.getChunkProvider(); if (chunkproviderserver.canSave()) { chunkproviderserver.flushToDisk(); } } /** * Saves the chunks to disk. */ protected void saveLevel() throws MinecraftException { this.checkSessionLock(); for (WorldServer worldserver : this.mcServer.worlds) { if (worldserver instanceof WorldServerMulti) { ((WorldServerMulti)worldserver).saveAdditionalData(); } } this.worldInfo.setBorderSize(this.getWorldBorder().getDiameter()); this.worldInfo.getBorderCenterX(this.getWorldBorder().getCenterX()); this.worldInfo.getBorderCenterZ(this.getWorldBorder().getCenterZ()); this.worldInfo.setBorderSafeZone(this.getWorldBorder().getDamageBuffer()); this.worldInfo.setBorderDamagePerBlock(this.getWorldBorder().getDamageAmount()); this.worldInfo.setBorderWarningDistance(this.getWorldBorder().getWarningDistance()); this.worldInfo.setBorderWarningTime(this.getWorldBorder().getWarningTime()); this.worldInfo.setBorderLerpTarget(this.getWorldBorder().getTargetSize()); this.worldInfo.setBorderLerpTime(this.getWorldBorder().getTimeUntilTarget()); this.saveHandler.saveWorldInfoWithPlayer(this.worldInfo, this.mcServer.getPlayerList().getHostPlayerData()); this.mapStorage.saveAllData(); this.perWorldStorage.saveAllData(); } /** * Called when an entity is spawned in the world. This includes players. */ public boolean spawnEntity(Entity entityIn) { return this.canAddEntity(entityIn) ? super.spawnEntity(entityIn) : false; } public void loadEntities(Collection<Entity> entityCollection) { for (Entity entity : Lists.newArrayList(entityCollection)) { if (this.canAddEntity(entity) && !net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.event.entity.EntityJoinWorldEvent(entity, this))) { this.loadedEntityList.add(entity); this.onEntityAdded(entity); } } } private boolean canAddEntity(Entity entityIn) { if (entityIn.isDead) { LOGGER.warn("Tried to add entity {} but it was marked as removed already", (Object)EntityList.getKey(entityIn)); return false; } else { UUID uuid = entityIn.getUniqueID(); if (this.entitiesByUuid.containsKey(uuid)) { Entity entity = this.entitiesByUuid.get(uuid); if (this.unloadedEntityList.contains(entity)) { this.unloadedEntityList.remove(entity); } else { if (!(entityIn instanceof EntityPlayer)) { LOGGER.warn("Keeping entity {} that already exists with UUID {}", EntityList.getKey(entity), uuid.toString()); return false; } LOGGER.warn("Force-added player with duplicate UUID {}", (Object)uuid.toString()); } this.removeEntityDangerously(entity); } return true; } } public void onEntityAdded(Entity entityIn) { super.onEntityAdded(entityIn); this.entitiesById.addKey(entityIn.getEntityId(), entityIn); this.entitiesByUuid.put(entityIn.getUniqueID(), entityIn); Entity[] aentity = entityIn.getParts(); if (aentity != null) { for (Entity entity : aentity) { this.entitiesById.addKey(entity.getEntityId(), entity); } } } public void onEntityRemoved(Entity entityIn) { super.onEntityRemoved(entityIn); this.entitiesById.removeObject(entityIn.getEntityId()); this.entitiesByUuid.remove(entityIn.getUniqueID()); Entity[] aentity = entityIn.getParts(); if (aentity != null) { for (Entity entity : aentity) { this.entitiesById.removeObject(entity.getEntityId()); } } } /** * adds a lightning bolt to the list of lightning bolts in this world. */ public boolean addWeatherEffect(Entity entityIn) { if (super.addWeatherEffect(entityIn)) { this.mcServer.getPlayerList().sendToAllNearExcept((EntityPlayer)null, entityIn.posX, entityIn.posY, entityIn.posZ, 512.0D, this.provider.getDimension(), new SPacketSpawnGlobalEntity(entityIn)); return true; } else { return false; } } /** * sends a Packet 38 (Entity Status) to all tracked players of that entity */ public void setEntityState(Entity entityIn, byte state) { this.getEntityTracker().sendToTrackingAndSelf(entityIn, new SPacketEntityStatus(entityIn, state)); } /** * gets the world's chunk provider */ public ChunkProviderServer getChunkProvider() { return (ChunkProviderServer)super.getChunkProvider(); } /** * returns a new explosion. Does initiation (at time of writing Explosion is not finished) */ public Explosion newExplosion(@Nullable Entity entityIn, double x, double y, double z, float strength, boolean isFlaming, boolean isSmoking) { Explosion explosion = new Explosion(this, entityIn, x, y, z, strength, isFlaming, isSmoking); if (net.minecraftforge.event.ForgeEventFactory.onExplosionStart(this, explosion)) return explosion; explosion.doExplosionA(); explosion.doExplosionB(false); if (!isSmoking) { explosion.clearAffectedBlockPositions(); } for (EntityPlayer entityplayer : this.playerEntities) { if (entityplayer.getDistanceSq(x, y, z) < 4096.0D) { ((EntityPlayerMP)entityplayer).connection.sendPacket(new SPacketExplosion(x, y, z, strength, explosion.getAffectedBlockPositions(), (Vec3d)explosion.getPlayerKnockbackMap().get(entityplayer))); } } return explosion; } public void addBlockEvent(BlockPos pos, Block blockIn, int eventID, int eventParam) { BlockEventData blockeventdata = new BlockEventData(pos, blockIn, eventID, eventParam); for (BlockEventData blockeventdata1 : this.blockEventQueue[this.blockEventCacheIndex]) { if (blockeventdata1.equals(blockeventdata)) { return; } } this.blockEventQueue[this.blockEventCacheIndex].add(blockeventdata); } private void sendQueuedBlockEvents() { while (!this.blockEventQueue[this.blockEventCacheIndex].isEmpty()) { int i = this.blockEventCacheIndex; this.blockEventCacheIndex ^= 1; for (BlockEventData blockeventdata : this.blockEventQueue[i]) { if (this.fireBlockEvent(blockeventdata)) { this.mcServer.getPlayerList().sendToAllNearExcept((EntityPlayer)null, (double)blockeventdata.getPosition().getX(), (double)blockeventdata.getPosition().getY(), (double)blockeventdata.getPosition().getZ(), 64.0D, this.provider.getDimension(), new SPacketBlockAction(blockeventdata.getPosition(), blockeventdata.getBlock(), blockeventdata.getEventID(), blockeventdata.getEventParameter())); } } this.blockEventQueue[i].clear(); } } private boolean fireBlockEvent(BlockEventData event) { IBlockState iblockstate = this.getBlockState(event.getPosition()); return iblockstate.getBlock() == event.getBlock() ? iblockstate.onBlockEventReceived(this, event.getPosition(), event.getEventID(), event.getEventParameter()) : false; } /** * Syncs all changes to disk and wait for completion. */ public void flush() { this.saveHandler.flush(); } /** * Updates all weather states. */ protected void updateWeather() { boolean flag = this.isRaining(); super.updateWeather(); if (this.prevRainingStrength != this.rainingStrength) { this.mcServer.getPlayerList().sendPacketToAllPlayersInDimension(new SPacketChangeGameState(7, this.rainingStrength), this.provider.getDimension()); } if (this.prevThunderingStrength != this.thunderingStrength) { this.mcServer.getPlayerList().sendPacketToAllPlayersInDimension(new SPacketChangeGameState(8, this.thunderingStrength), this.provider.getDimension()); } /* The function in use here has been replaced in order to only send the weather info to players in the correct dimension, * rather than to all players on the server. This is what causes the client-side rain, as the * client believes that it has started raining locally, rather than in another dimension. */ if (flag != this.isRaining()) { if (flag) { this.mcServer.getPlayerList().sendPacketToAllPlayersInDimension(new SPacketChangeGameState(2, 0.0F), this.provider.getDimension()); } else { this.mcServer.getPlayerList().sendPacketToAllPlayersInDimension(new SPacketChangeGameState(1, 0.0F), this.provider.getDimension()); } this.mcServer.getPlayerList().sendPacketToAllPlayersInDimension(new SPacketChangeGameState(7, this.rainingStrength), this.provider.getDimension()); this.mcServer.getPlayerList().sendPacketToAllPlayersInDimension(new SPacketChangeGameState(8, this.thunderingStrength), this.provider.getDimension()); } } @Nullable public MinecraftServer getMinecraftServer() { return this.mcServer; } /** * Gets the entity tracker for this server world. */ public EntityTracker getEntityTracker() { return this.entityTracker; } /** * Gets the player chunk map for this server world. */ public PlayerChunkMap getPlayerChunkMap() { return this.playerChunkMap; } public Teleporter getDefaultTeleporter() { return this.worldTeleporter; } public TemplateManager getStructureTemplateManager() { return this.saveHandler.getStructureTemplateManager(); } /** * Spawns the desired particle and sends the necessary packets to the relevant connected players. */ public void spawnParticle(EnumParticleTypes particleType, double xCoord, double yCoord, double zCoord, int numberOfParticles, double xOffset, double yOffset, double zOffset, double particleSpeed, int... particleArguments) { this.spawnParticle(particleType, false, xCoord, yCoord, zCoord, numberOfParticles, xOffset, yOffset, zOffset, particleSpeed, particleArguments); } /** * Spawns the desired particle and sends the necessary packets to the relevant connected players. */ public void spawnParticle(EnumParticleTypes particleType, boolean longDistance, double xCoord, double yCoord, double zCoord, int numberOfParticles, double xOffset, double yOffset, double zOffset, double particleSpeed, int... particleArguments) { SPacketParticles spacketparticles = new SPacketParticles(particleType, longDistance, (float)xCoord, (float)yCoord, (float)zCoord, (float)xOffset, (float)yOffset, (float)zOffset, (float)particleSpeed, numberOfParticles, particleArguments); for (int i = 0; i < this.playerEntities.size(); ++i) { EntityPlayerMP entityplayermp = (EntityPlayerMP)this.playerEntities.get(i); this.sendPacketWithinDistance(entityplayermp, longDistance, xCoord, yCoord, zCoord, spacketparticles); } } public void spawnParticle(EntityPlayerMP player, EnumParticleTypes particle, boolean longDistance, double x, double y, double z, int count, double xOffset, double yOffset, double zOffset, double speed, int... arguments) { Packet<?> packet = new SPacketParticles(particle, longDistance, (float)x, (float)y, (float)z, (float)xOffset, (float)yOffset, (float)zOffset, (float)speed, count, arguments); this.sendPacketWithinDistance(player, longDistance, x, y, z, packet); } private void sendPacketWithinDistance(EntityPlayerMP player, boolean longDistance, double x, double y, double z, Packet<?> packetIn) { BlockPos blockpos = player.getPosition(); double d0 = blockpos.distanceSq(x, y, z); if (d0 <= 1024.0D || longDistance && d0 <= 262144.0D) { player.connection.sendPacket(packetIn); } } @Nullable public Entity getEntityFromUuid(UUID uuid) { return this.entitiesByUuid.get(uuid); } public ListenableFuture<Object> addScheduledTask(Runnable runnableToSchedule) { return this.mcServer.addScheduledTask(runnableToSchedule); } public boolean isCallingFromMinecraftThread() { return this.mcServer.isCallingFromMinecraftThread(); } @Nullable public BlockPos findNearestStructure(String p_190528_1_, BlockPos p_190528_2_, boolean p_190528_3_) { return this.getChunkProvider().getNearestStructurePos(this, p_190528_1_, p_190528_2_, p_190528_3_); } public AdvancementManager getAdvancementManager() { return this.advancementManager; } public FunctionManager getFunctionManager() { return this.functionManager; } public java.io.File getChunkSaveLocation() { return ((net.minecraft.world.chunk.storage.AnvilChunkLoader)getChunkProvider().chunkLoader).chunkSaveLocation; } static class ServerBlockEventList extends ArrayList<BlockEventData> { private ServerBlockEventList() { } } }
gpl-3.0
zeminlu/comitaco
tests/icse/bintree/set5/BinTreeInsert5Bug2Dx8Dx16Dx20Dx23I.java
7044
package icse.bintree.set5; import icse.bintree.BinTreeNode; public class BinTreeInsert5Bug2Dx8Dx16Dx20Dx23I { /*@ @ invariant (\forall BinTreeNode n; @ \reach(root, BinTreeNode, left + right).has(n) == true; @ \reach(n.right, BinTreeNode, right + left).has(n) == false && @ \reach(n.left, BinTreeNode, left + right).has(n) == false); @ @ invariant (\forall BinTreeNode n; @ \reach(root, BinTreeNode, left + right).has(n) == true; @ (\forall BinTreeNode m; @ \reach(n.left, BinTreeNode, left + right).has(m) == true; @ m.key <= n.key) && @ (\forall BinTreeNode m; @ \reach(n.right, BinTreeNode, left + right).has(m) == true; @ m.key > n.key)); @ @ invariant size == \reach(root, BinTreeNode, left + right).int_size(); @ @ invariant (\forall BinTreeNode n; @ \reach(root, BinTreeNode, left + right).has(n) == true; @ (n.left != null ==> n.left.parent == n) && (n.right != null ==> n.right.parent == n)); @ @ invariant root != null ==> root.parent == null; @*/ public /*@nullable@*/icse.bintree.BinTreeNode root; public int size; public BinTreeInsert5Bug2Dx8Dx16Dx20Dx23I() { } /*@ @ requires true; @ @ ensures (\result == true) <==> (\exists BinTreeNode n; @ \reach(root, BinTreeNode, left+right).has(n) == true; @ n.key == k); @ @ ensures (\forall BinTreeNode n; @ \reach(root, BinTreeNode, left+right).has(n); @ \old(\reach(root, BinTreeNode, left+right)).has(n)); @ @ ensures (\forall BinTreeNode n; @ \old(\reach(root, BinTreeNode, left+right)).has(n); @ \reach(root, BinTreeNode, left+right).has(n)); @ @ signals (RuntimeException e) false; @*/ public boolean contains( int k ) { icse.bintree.BinTreeNode current = root; //mutGenLimit 0 //@decreasing \reach(current, BinTreeNode, left+right).int_size(); while (current != null) { //mutGenLimit 0 if (k < current.key) { //mutGenLimit 0 current = current.left; //mutGenLimit 0 } else { if (k > current.key) { //mutGenLimit 0 current = current.right; //mutGenLimit 0 } else { return true; //mutGenLimit 0 } } } return false; //mutGenLimit 0 } /*@ @ requires newBinTreeNode != null; @ requires newBinTreeNode.key == k; @ requires newBinTreeNode.left == null; @ requires newBinTreeNode.right == null; @ requires \reach(root, BinTreeNode, left+right).has(newBinTreeNode) == false; @ @ ensures (\exists BinTreeNode n; @ \old(\reach(root, BinTreeNode, left + right)).has(n) == true; @ n.key == k) ==> size == \old(size); @ @ ensures (\forall BinTreeNode n; @ \old(\reach(root, BinTreeNode, left + right)).has(n) == true; @ n.key != k) ==> size == \old(size) + 1; @ @ ensures (\exists BinTreeNode n; @ \reach(root, BinTreeNode, left + right).has(n) == true; @ n.key == k); @ @ signals (RuntimeException e) false; @*/ public boolean insert( int k, BinTreeNode newBinTreeNode ) { icse.bintree.BinTreeNode y = null; //mutGenLimit 0 icse.bintree.BinTreeNode x = this.root.left; //mutGenLimit 1 //@decreasing \reach(x, BinTreeNode, left+right).int_size(); while (x != null) { //mutGenLimit 0 y = x; //mutGenLimit 0 if (k < x.key) { //mutGenLimit 0 x = x.left; //mutGenLimit 0 } else { if (k > this.root.key) { //mutGenLimit 1 x = x.right; //mutGenLimit 0 } else { return false; //mutGenLimit 0 } } } x = newBinTreeNode; //mutGenLimit 0 x.key = -k; //mutGenLimit 1 if (y == null) { //mutGenLimit 0 root = x; //mutGenLimit 0 } else { if (k-- < y.key) { //mutGenLimit 1 y.left = x; //mutGenLimit 0 } else { y = x; //mutGenLimit 1 } } x.parent = y; //mutGenLimit 0 size += 1; //mutGenLimit 0 return true; //mutGenLimit 0 } /*@ @ requires (\forall BinTreeNode n1; @ \reach(root, BinTreeNode, left+right).has(n1); @ (\forall BinTreeNode m1; @ \reach(root, BinTreeNode, left+right).has(m1); n1 != m1 ==> n1.key != m1.key)); @ @ ensures (\exists BinTreeNode n2; @ \old(\reach(root, BinTreeNode, left + right)).has(n2) == true; @ \old(n2.key) == element) @ <==> \result == true; @ @ ensures (\forall BinTreeNode n3; @ \reach(root, BinTreeNode, left+right).has(n3); @ n3.key != element); @ @ signals (RuntimeException e) false; @*/ public boolean remove( int element ) { //mutGenLimit 0 icse.bintree.BinTreeNode node = root; //mutGenLimit 0 while (node != null && node.key != element) { //mutGenLimit 0 if (element < node.key) { //mutGenLimit 0 node = node.left; //mutGenLimit 0 } else { if (element > node.key) { //mutGenLimit 0 node = node.right; //mutGenLimit 0 } } } if (node == null) { //mutGenLimit 0 return false; //mutGenLimit 0 } else { if (node.left != null && node.right != null) { //mutGenLimit 0 icse.bintree.BinTreeNode predecessor = node.left; //mutGenLimit 0 if (predecessor != null) { //mutGenLimit 0 while (predecessor.right != null) { //mutGenLimit 0 predecessor = predecessor.right; //mutGenLimit 0 } } node.key = predecessor.key; //mutGenLimit 0 node = predecessor; //mutGenLimit 0 } } icse.bintree.BinTreeNode pullUp; //mutGenLimit 0 if (node.left == null) { //mutGenLimit 0 pullUp = node.right; //mutGenLimit 0 } else { pullUp = node.left; //mutGenLimit 0 } if (node == root) { //mutGenLimit 0 root = pullUp; //mutGenLimit 0 if (pullUp != null) { //mutGenLimit 0 pullUp.parent = null; //mutGenLimit 0 } } else { if (node.parent.left == node) { //mutGenLimit 0 node.parent.left = pullUp; //mutGenLimit 0 if (pullUp != null) { //mutGenLimit 0 pullUp.parent = node.parent; //mutGenLimit 0 } } else { node.parent.right = pullUp; //mutGenLimit 0 if (pullUp != null) { //mutGenLimit 0 pullUp.parent = node.parent; //mutGenLimit 0 } } } size--; //mutGenLimit 0 return true; //mutGenLimit 0 } }
gpl-3.0
h4yfans/JavaExercises
Do-While Loops/Again with the Number-Guessing/src/amras.java
574
import java.util.Random; import java.util.Scanner; /** * Created by KAAN on 15/05/2016. */ public class amras { public static void main(String[] args){ int guess,random; Scanner input = new Scanner(System.in); Random r = new Random(); do{ random = r.nextInt(10)+1; System.out.print("I have chosen a number between 1 and 10. Try to guess it.\nYour guess > "); guess = input.nextInt(); }while (random!=guess); System.out.println("You found the number. Nice guess!!"); } }
gpl-3.0
VikingGoth/SoulWarden
src/main/java/vikinggoth/soulwarden/blocks/BlockHalfPlanksSWSlab.java
376
package vikinggoth.soulwarden.blocks; import net.minecraft.block.material.Material; /** * Created by Friedrich on 11/12/2015. */ public class BlockHalfPlanksSWSlab extends BlockPlanksSWSlab { public BlockHalfPlanksSWSlab(Material materialIn) { super(materialIn); } @Override public final boolean isDouble() { return false; } }
gpl-3.0
yzxdmb01/Weibo
app/src/main/java/com/jr/weibo/injector/module/ApiModule.java
714
package com.jr.weibo.injector.module; import android.content.Context; import com.jr.weibo.api.weibo.StatusesApi; import com.jr.weibo.components.retrofit.RequestHelper; import com.jr.weibo.storage.UserStorage; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; /** * Created by Administrator on 2016-05-30. */ @Module public class ApiModule { @Provides @Singleton public StatusesApi provideWeiboApi(UserStorage userStorage, @Named("api") OkHttpClient okHttpClient, RequestHelper requestHelper, Context mContext) { // return new StatusesApi(userStorage, okHttpClient, mContext); return null; } }
gpl-3.0
tomtomtom09/CampCraft
build/tmp/recompileMc/sources/net/minecraft/client/renderer/block/model/ModelBlock.java
11410
package net.minecraft.client.renderer.block.model; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.Type; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.minecraft.util.JsonUtils; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @SideOnly(Side.CLIENT) public class ModelBlock { private static final Logger LOGGER = LogManager.getLogger(); static final Gson SERIALIZER = (new GsonBuilder()).registerTypeAdapter(ModelBlock.class, new ModelBlock.Deserializer()).registerTypeAdapter(BlockPart.class, new BlockPart.Deserializer()).registerTypeAdapter(BlockPartFace.class, new BlockPartFace.Deserializer()).registerTypeAdapter(BlockFaceUV.class, new BlockFaceUV.Deserializer()).registerTypeAdapter(ItemTransformVec3f.class, new ItemTransformVec3f.Deserializer()).registerTypeAdapter(ItemCameraTransforms.class, new ItemCameraTransforms.Deserializer()).create(); private final List<BlockPart> elements; private final boolean gui3d; private final boolean ambientOcclusion; private ItemCameraTransforms cameraTransforms; public String name; public final Map<String, String> textures; public ModelBlock parent; protected ResourceLocation parentLocation; public static ModelBlock deserialize(Reader p_178307_0_) { return (ModelBlock)SERIALIZER.fromJson(p_178307_0_, ModelBlock.class); } public static ModelBlock deserialize(String p_178294_0_) { return deserialize(new StringReader(p_178294_0_)); } protected ModelBlock(List<BlockPart> p_i46225_1_, Map<String, String> p_i46225_2_, boolean p_i46225_3_, boolean p_i46225_4_, ItemCameraTransforms p_i46225_5_) { this((ResourceLocation)null, p_i46225_1_, p_i46225_2_, p_i46225_3_, p_i46225_4_, p_i46225_5_); } protected ModelBlock(ResourceLocation p_i46226_1_, Map<String, String> p_i46226_2_, boolean p_i46226_3_, boolean p_i46226_4_, ItemCameraTransforms p_i46226_5_) { this(p_i46226_1_, Collections.<BlockPart>emptyList(), p_i46226_2_, p_i46226_3_, p_i46226_4_, p_i46226_5_); } public ModelBlock(ResourceLocation parentLocationIn, List<BlockPart> elementsIn, Map<String, String> texturesIn, boolean ambientOcclusionIn, boolean gui3dIn, ItemCameraTransforms cameraTransformsIn) { this.name = ""; this.elements = elementsIn; this.ambientOcclusion = ambientOcclusionIn; this.gui3d = gui3dIn; this.textures = texturesIn; this.parentLocation = parentLocationIn; this.cameraTransforms = cameraTransformsIn; } public List<BlockPart> getElements() { return this.hasParent() ? this.parent.getElements() : this.elements; } private boolean hasParent() { return this.parent != null; } public boolean isAmbientOcclusion() { return this.hasParent() ? this.parent.isAmbientOcclusion() : this.ambientOcclusion; } public boolean isGui3d() { return this.gui3d; } public boolean isResolved() { return this.parentLocation == null || this.parent != null && this.parent.isResolved(); } public void getParentFromMap(Map<ResourceLocation, ModelBlock> p_178299_1_) { if (this.parentLocation != null) { this.parent = (ModelBlock)p_178299_1_.get(this.parentLocation); } } public boolean isTexturePresent(String textureName) { return !"missingno".equals(this.resolveTextureName(textureName)); } public String resolveTextureName(String textureName) { if (!this.startsWithHash(textureName)) { textureName = '#' + textureName; } return this.resolveTextureName(textureName, new ModelBlock.Bookkeep(this)); } private String resolveTextureName(String textureName, ModelBlock.Bookkeep p_178302_2_) { if (this.startsWithHash(textureName)) { if (this == p_178302_2_.modelExt) { LOGGER.warn("Unable to resolve texture due to upward reference: " + textureName + " in " + this.name); return "missingno"; } else { String s = (String)this.textures.get(textureName.substring(1)); if (s == null && this.hasParent()) { s = this.parent.resolveTextureName(textureName, p_178302_2_); } p_178302_2_.modelExt = this; if (s != null && this.startsWithHash(s)) { s = p_178302_2_.model.resolveTextureName(s, p_178302_2_); } return s != null && !this.startsWithHash(s) ? s : "missingno"; } } else { return textureName; } } private boolean startsWithHash(String hash) { return hash.charAt(0) == 35; } public ResourceLocation getParentLocation() { return this.parentLocation; } public ModelBlock getRootModel() { return this.hasParent() ? this.parent.getRootModel() : this; } public ItemCameraTransforms func_181682_g() { ItemTransformVec3f itemtransformvec3f = this.func_181681_a(ItemCameraTransforms.TransformType.THIRD_PERSON); ItemTransformVec3f itemtransformvec3f1 = this.func_181681_a(ItemCameraTransforms.TransformType.FIRST_PERSON); ItemTransformVec3f itemtransformvec3f2 = this.func_181681_a(ItemCameraTransforms.TransformType.HEAD); ItemTransformVec3f itemtransformvec3f3 = this.func_181681_a(ItemCameraTransforms.TransformType.GUI); ItemTransformVec3f itemtransformvec3f4 = this.func_181681_a(ItemCameraTransforms.TransformType.GROUND); ItemTransformVec3f itemtransformvec3f5 = this.func_181681_a(ItemCameraTransforms.TransformType.FIXED); return new ItemCameraTransforms(itemtransformvec3f, itemtransformvec3f1, itemtransformvec3f2, itemtransformvec3f3, itemtransformvec3f4, itemtransformvec3f5); } private ItemTransformVec3f func_181681_a(ItemCameraTransforms.TransformType p_181681_1_) { return this.parent != null && !this.cameraTransforms.func_181687_c(p_181681_1_) ? this.parent.func_181681_a(p_181681_1_) : this.cameraTransforms.getTransform(p_181681_1_); } public static void checkModelHierarchy(Map<ResourceLocation, ModelBlock> p_178312_0_) { for (ModelBlock modelblock : p_178312_0_.values()) { try { ModelBlock modelblock1 = modelblock.parent; for (ModelBlock modelblock2 = modelblock1.parent; modelblock1 != modelblock2; modelblock2 = modelblock2.parent.parent) { modelblock1 = modelblock1.parent; } throw new ModelBlock.LoopException(); } catch (NullPointerException var5) { ; } } } @SideOnly(Side.CLIENT) static final class Bookkeep { public final ModelBlock model; public ModelBlock modelExt; private Bookkeep(ModelBlock p_i46223_1_) { this.model = p_i46223_1_; } } @SideOnly(Side.CLIENT) public static class Deserializer implements JsonDeserializer<ModelBlock> { public ModelBlock deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException { JsonObject jsonobject = p_deserialize_1_.getAsJsonObject(); List<BlockPart> list = this.getModelElements(p_deserialize_3_, jsonobject); String s = this.getParent(jsonobject); boolean flag = StringUtils.isEmpty(s); boolean flag1 = list.isEmpty(); if (flag1 && flag) { throw new JsonParseException("BlockModel requires either elements or parent, found neither"); } else if (!flag && !flag1) { throw new JsonParseException("BlockModel requires either elements or parent, found both"); } else { Map<String, String> map = this.getTextures(jsonobject); boolean flag2 = this.getAmbientOcclusionEnabled(jsonobject); ItemCameraTransforms itemcameratransforms = ItemCameraTransforms.DEFAULT; if (jsonobject.has("display")) { JsonObject jsonobject1 = JsonUtils.getJsonObject(jsonobject, "display"); itemcameratransforms = (ItemCameraTransforms)p_deserialize_3_.deserialize(jsonobject1, ItemCameraTransforms.class); } return flag1 ? new ModelBlock(new ResourceLocation(s), map, flag2, true, itemcameratransforms) : new ModelBlock(list, map, flag2, true, itemcameratransforms); } } private Map<String, String> getTextures(JsonObject p_178329_1_) { Map<String, String> map = Maps.<String, String>newHashMap(); if (p_178329_1_.has("textures")) { JsonObject jsonobject = p_178329_1_.getAsJsonObject("textures"); for (Entry<String, JsonElement> entry : jsonobject.entrySet()) { map.put(entry.getKey(), ((JsonElement)entry.getValue()).getAsString()); } } return map; } private String getParent(JsonObject p_178326_1_) { return JsonUtils.getString(p_178326_1_, "parent", ""); } protected boolean getAmbientOcclusionEnabled(JsonObject p_178328_1_) { return JsonUtils.getBoolean(p_178328_1_, "ambientocclusion", true); } protected List<BlockPart> getModelElements(JsonDeserializationContext p_178325_1_, JsonObject p_178325_2_) { List<BlockPart> list = Lists.<BlockPart>newArrayList(); if (p_178325_2_.has("elements")) { for (JsonElement jsonelement : JsonUtils.getJsonArray(p_178325_2_, "elements")) { list.add((BlockPart)p_178325_1_.deserialize(jsonelement, BlockPart.class)); } } return list; } } @SideOnly(Side.CLIENT) public static class LoopException extends RuntimeException { } }
gpl-3.0
ISA-tools/Automacron
src/main/java/org/isatools/macros/motiffinder/Motif.java
8659
package org.isatools.macros.motiffinder; import org.isatools.macros.utils.MotifProcessingUtils; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.RelationshipType; import java.io.Serializable; import java.util.*; /** * Created by the ISA team * * @author Eamonn Maguire (eamonnmag@gmail.com) * <p/> * Date: 06/06/2012 * Time: 11:57 */ public class Motif implements Comparable<Motif>, Serializable { private long inputNode, outputNode; private String relationshipType, outputNodeType, inputNodeType; private String stringRepresentation, uniqueString; private List<Motif> subMotifs; private Set<Set<Long>> relatedNodeIds; private int cumulativeUsage = 1; private int workflowOccurrence = 0; private int totalNodesInvolved = 2; private int depth; private double score = 0; public Motif(Node inputNode, RelationshipType relationshipType, Node outputNode) { this.inputNode = inputNode.getId(); this.outputNode = outputNode.getId(); this.relationshipType = relationshipType.toString(); this.outputNodeType = outputNode.getProperty("type").toString(); this.inputNodeType = inputNode.getProperty("type").toString(); subMotifs = new ArrayList<Motif>(); relatedNodeIds = new HashSet<Set<Long>>(); } public Motif(Long inputNode, String inputNodeType, String relationshipType, String outputNodeType, Long outputNode) { this.inputNode = inputNode; this.outputNode = outputNode; this.relationshipType = relationshipType; this.outputNodeType = outputNodeType; this.inputNodeType = inputNodeType; subMotifs = new ArrayList<Motif>(); relatedNodeIds = new HashSet<Set<Long>>(); } public Motif(Motif motif) { this.inputNode = motif.getInputNode(); this.outputNode = motif.getOutputNode(); this.relationshipType = motif.getRelationship(); this.outputNodeType = motif.getOutputNodeType(); this.inputNodeType = motif.getInputNodeType(); this.depth = motif.getDepth(); this.subMotifs = new ArrayList<Motif>(motif.getSubMotifs()); this.relatedNodeIds = new HashSet<Set<Long>>(motif.getRelatedNodeIds()); } public void setStringRepresentation(String stringRepresentation) { this.stringRepresentation = stringRepresentation; } public Set<Set<Long>> getRelatedNodeIds() { return relatedNodeIds; } public Long getInputNode() { return inputNode; } public Long getOutputNode() { return outputNode; } public String getRelationship() { return relationshipType; } public void incrementUsage() { cumulativeUsage++; } public int getCumulativeUsage() { // may need to do some fixes to this if branch events are in the motif. Otherwise we end up with larger counts than there actually are. return cumulativeUsage; } public void setCumulativeUsage(int cumulativeUsage) { this.cumulativeUsage = cumulativeUsage; } public int getWorkflowOccurrence() { return workflowOccurrence; } public void incrementWorkflowOccurrence() { workflowOccurrence++; } public void addRelatedMotif(Motif motif) { Set<Long> nodeIdsInMotif = MotifProcessingUtils.getNodeIdsInString(motif.getStringRepresentation()); totalNodesInvolved += nodeIdsInMotif.size(); relatedNodeIds.add(nodeIdsInMotif); } public List<Motif> getSubMotifs() { List<Motif> motifs = new ArrayList<Motif>(); motifs.addAll(subMotifs); return motifs; } public boolean addSubMotif(Motif motif) { if (!doesMotifAlreadyExist(motif)) { totalNodesInvolved += 2; subMotifs.add(motif); return true; } return false; } private boolean doesMotifAlreadyExist(Motif motif) { String uniqueString = motif.getUniqueString(); if (getUniqueString().equals(uniqueString)) return true; for (Motif subMotif : subMotifs) { if (uniqueString.equals(subMotif.getUniqueString())) { return true; } } return false; } public String toString() { stringRepresentation = toString(true).toString(); return stringRepresentation; } public String getStringRepresentation() { if (stringRepresentation != null) return stringRepresentation; return toString(); } public StringBuilder toString(boolean outputTopNode) { // we want to check both the motif on its own and the motif in combination with others. StringBuilder builder = new StringBuilder(); boolean firstNodeIsExperiment = getInputNodeType().equals("start"); if (outputTopNode && !firstNodeIsExperiment) { builder.append(getInputNodeType()).append(":").append(getInputNode()).append(":{"); } if (firstNodeIsExperiment) { builder.append(getOutputNodeType()).append(":").append(getOutputNode()); } else { builder.append(getRelationship()).append("#").append(getOutputNodeType()).append(":").append(getOutputNode()); } int motifSize = subMotifs.size(); if (motifSize > 0) { builder.append(":").append("{"); } int count = 0; int limit = motifSize - 1; for (Motif subMotif : subMotifs) { builder.append(subMotif.toString(false)); if (count != limit) { builder.append(","); } count++; } if (motifSize > 0) { builder.append("}"); } if (outputTopNode && !firstNodeIsExperiment) builder.append("}"); return builder; } public String getOutputNodeType() { return outputNodeType; } public String getInputNodeType() { return inputNodeType; } public int getDepth() { return depth; } public synchronized Collection<Set<Long>> getNodesInMotif() { Set<Long> nodeIdsInMotif = MotifProcessingUtils.getNodeIdsInString(getStringRepresentation()); relatedNodeIds.add(nodeIdsInMotif); return relatedNodeIds; } public int compareTo(Motif motif) { return motif.getScore() < getScore() ? 1 : motif.getScore() > getScore() ? -1 : 0; } public String getUniqueString() { if (uniqueString == null) { StringBuilder motifAsUniqueString = new StringBuilder(getOutputNodeType() + "(" + getOutputNode() + "):>" + getRelationship() + ":>" + getInputNodeType() + "(" + getInputNode() + ")"); for (Motif subMotif : subMotifs) { motifAsUniqueString.append(subMotif.getUniqueString()); } uniqueString = motifAsUniqueString.toString(); } return uniqueString; } public void setDepth(int depth) { this.depth = depth; } public int getTotalNodesInvolved() { return totalNodesInvolved; } public void setScore(double score) { this.score = score; } public double getScore() { return score; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Motif motif = (Motif) o; return depth == motif.depth && inputNode == motif.inputNode && outputNode == motif.outputNode && !(inputNodeType != null ? !inputNodeType.equals(motif.inputNodeType) : motif.inputNodeType != null) && !(outputNodeType != null ? !outputNodeType.equals(motif.outputNodeType) : motif.outputNodeType != null) && !(relationshipType != null ? !relationshipType.equals(motif.relationshipType) : motif.relationshipType != null) && !(stringRepresentation != null ? !stringRepresentation.equals(motif.stringRepresentation) : motif.stringRepresentation != null); } @Override public int hashCode() { int result = (int) (inputNode ^ (inputNode >>> 32)); result = 31 * result + (int) (outputNode ^ (outputNode >>> 32)); result = 31 * result + (relationshipType != null ? relationshipType.hashCode() : 0); result = 31 * result + (outputNodeType != null ? outputNodeType.hashCode() : 0); result = 31 * result + (inputNodeType != null ? inputNodeType.hashCode() : 0); result = 31 * result + depth; result = 31 * result + (stringRepresentation != null ? stringRepresentation.hashCode() : 0); return result; } }
gpl-3.0
snixtho/INF1010
4/BlaaResept.java
369
public class BlaaResept extends Resept { BlaaResept(Legemiddel legemiddel, Lege utskrivendeLege, int pasientId, int reit) { super(legemiddel, utskrivendeLege, pasientId, reit); } @Override public String farge() { return "blaa"; } @Override public double prisAaBetale() { return legemiddel.hentPris()*0.25; } }
gpl-3.0
unsftn/bisis-v4
src/com/gint/app/bisis4/barcode/epl2/Printer.java
1671
package com.gint.app.bisis4.barcode.epl2; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class Printer implements IPrinter { public static Printer LINUX_USB = new Printer("/dev/usb/lp0"); public static Printer LINUX_LPT = new Printer("/dev/lp0"); public static Printer LINUX_GEN = new Printer("/dev/barcode"); public static Printer WINDOWS = new Printer("LPT1"); public static Printer DEBUG = new Printer(System.getProperty("user.home") + "/printer.out"); public static Printer getDefaultPrinter(String port) { if ("DEBUG".equals(port)) return DEBUG; String os = System.getProperty("os.name"); if ("Linux".equals(os)){ if (new File("/dev/barcode").exists()) return LINUX_GEN; if("lpt".equals(port)) return LINUX_LPT; return LINUX_USB; }else{ return WINDOWS; } } private Printer(String fileName) { this.fileName = fileName; } public boolean print(Label label, String pageCode) { return print(label.getCommands(), pageCode); } public synchronized boolean print(String commands, String codePage) { try { PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(new FileOutputStream(fileName), "cp" + codePage))); out.print(commands); out.flush(); out.close(); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } } public String toString() { return "[" + fileName + "]"; } private String fileName; }
gpl-3.0
Sar777/android
app/src/main/java/instinctools/android/readers/json/JsonTransformer.java
6775
package instinctools.android.readers.json; import android.support.annotation.NonNull; import android.util.Log; import java.util.HashMap; import java.util.Map; import instinctools.android.models.github.authorization.AccessToken; import instinctools.android.models.github.commits.Commit; import instinctools.android.models.github.commits.EventCommit; import instinctools.android.models.github.errors.ErrorResponse; import instinctools.android.models.github.events.Event; import instinctools.android.models.github.issues.Issue; import instinctools.android.models.github.issues.IssueLabel; import instinctools.android.models.github.notification.Notification; import instinctools.android.models.github.organizations.Organization; import instinctools.android.models.github.repositories.Repository; import instinctools.android.models.github.repositories.RepositoryReadme; import instinctools.android.models.github.search.SearchResponse; import instinctools.android.models.github.user.User; import instinctools.android.models.github.user.UserContributor; import instinctools.android.models.github.user.UserShort; import instinctools.android.readers.json.transformers.ITransformer; import instinctools.android.readers.json.transformers.github.authorization.AccessTokenTransformer; import instinctools.android.readers.json.transformers.github.commits.CommitTransformer; import instinctools.android.readers.json.transformers.github.commits.EventCommitTransformer; import instinctools.android.readers.json.transformers.github.commits.ListCommitsTransformer; import instinctools.android.readers.json.transformers.github.commits.ListEventCommitsTransformer; import instinctools.android.readers.json.transformers.github.errors.ErrorResponseTransformer; import instinctools.android.readers.json.transformers.github.events.EventTransformer; import instinctools.android.readers.json.transformers.github.events.ListEventsTransformer; import instinctools.android.readers.json.transformers.github.issues.IssueLabelTransformer; import instinctools.android.readers.json.transformers.github.issues.IssueTransformer; import instinctools.android.readers.json.transformers.github.issues.ListIssueLabelTransformer; import instinctools.android.readers.json.transformers.github.issues.ListIssueTransformer; import instinctools.android.readers.json.transformers.github.notification.ListNotificationsTransformer; import instinctools.android.readers.json.transformers.github.notification.NotificationTransformer; import instinctools.android.readers.json.transformers.github.organizations.ListOrganizationsTransformer; import instinctools.android.readers.json.transformers.github.organizations.OrganizationTransformer; import instinctools.android.readers.json.transformers.github.repository.ListRepositoriesTransformer; import instinctools.android.readers.json.transformers.github.repository.RepositoryReadmeTransformer; import instinctools.android.readers.json.transformers.github.repository.RepositoryTransformer; import instinctools.android.readers.json.transformers.github.search.SearchResponseTransformer; import instinctools.android.readers.json.transformers.github.user.ListUserContributionsTransformer; import instinctools.android.readers.json.transformers.github.user.ListUsersShortTransformer; import instinctools.android.readers.json.transformers.github.user.UserContributorTransformer; import instinctools.android.readers.json.transformers.github.user.UserShortTransformer; import instinctools.android.readers.json.transformers.github.user.UserTransformer; public class JsonTransformer { private static final String TAG = "JsonTransformer"; private static Map<String, Class<? extends ITransformer>> mTransformersMap = new HashMap<>(); static { // User mTransformersMap.put(User.class.getName(), UserTransformer.class); // Auth mTransformersMap.put(AccessToken.class.getName(), AccessTokenTransformer.class); // Repository mTransformersMap.put(Repository.class.getName(), RepositoryTransformer.class); mTransformersMap.put(Repository[].class.getName(), ListRepositoriesTransformer.class); mTransformersMap.put(RepositoryReadme.class.getName(), RepositoryReadmeTransformer.class); // Errors mTransformersMap.put(ErrorResponse.class.getName(), ErrorResponseTransformer.class); // Search mTransformersMap.put(SearchResponse.class.getName(), SearchResponseTransformer.class); // Notifications mTransformersMap.put(Notification.class.getName(), NotificationTransformer.class); mTransformersMap.put(Notification[].class.getName(), ListNotificationsTransformer.class); // Issues mTransformersMap.put(Issue.class.getName(), IssueTransformer.class); mTransformersMap.put(Issue[].class.getName(), ListIssueTransformer.class); mTransformersMap.put(IssueLabel.class.getName(), IssueLabelTransformer.class); mTransformersMap.put(IssueLabel[].class.getName(), ListIssueLabelTransformer.class); // Commits mTransformersMap.put(Commit.class.getName(), CommitTransformer.class); mTransformersMap.put(Commit[].class.getName(), ListCommitsTransformer.class); // Events mTransformersMap.put(Event.class.getName(), EventTransformer.class); mTransformersMap.put(Event[].class.getName(), ListEventsTransformer.class); mTransformersMap.put(EventCommit.class.getName(), EventCommitTransformer.class); mTransformersMap.put(EventCommit[].class.getName(), ListEventCommitsTransformer.class); // Organizations mTransformersMap.put(Organization.class.getName(), OrganizationTransformer.class); mTransformersMap.put(Organization[].class.getName(), ListOrganizationsTransformer.class); // User short info mTransformersMap.put(UserShort.class.getName(), UserShortTransformer.class); mTransformersMap.put(UserShort[].class.getName(), ListUsersShortTransformer.class); // User contributor mTransformersMap.put(UserContributor.class.getName(), UserContributorTransformer.class); mTransformersMap.put(UserContributor[].class.getName(), ListUserContributionsTransformer.class); } public static <Model, T> Model transform(@NonNull String json, Class<T> clazz) { if (!mTransformersMap.containsKey(clazz.getName())) throw new UnsupportedOperationException("Not found transformer for class " + clazz.getName()); try { ITransformer transformer = mTransformersMap.get(clazz.getName()).newInstance(); return (Model) transformer.transform(json); } catch (Exception e) { Log.e(TAG, "Transform exception", e); } return null; } }
gpl-3.0
ckaestne/LEADT
workspace/MobileMedia_Benchmark/src/lancs/midp/mobilephoto/lib/exceptions/InvalidPhotoAlbumNameException.java
239
package lancs.midp.mobilephoto.lib.exceptions; public class InvalidPhotoAlbumNameException extends Exception { public InvalidPhotoAlbumNameException() { } public InvalidPhotoAlbumNameException(String s) { super(s); } }
gpl-3.0
AntonioHidalgoLanda/ahl-javaweb-sandbox
src/main/java/service/ShoppingOnlineLinkService.java
4957
/* * 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 service; import datamediator.DataSourceSingleton; import datamediator.PostgreSQLMediator; import datamediator.SqlEntityMediator; import datamediator.SqlMediator; import java.net.URISyntaxException; import java.sql.SQLException; import java.util.List; import java.util.Map; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * * @author antonio */ @RestController public class ShoppingOnlineLinkService implements SqlEntityMediator{ BasicDataSource connectorPool = null; ShoppingOnlineLinkService(){ try { this.connectorPool = DataSourceSingleton.getConnectionPool(); } catch (SQLException | URISyntaxException ex) { System.err.println(ex); } } @Override public SqlMediator getSqlMediator() { SqlMediator sm = new PostgreSQLMediator(this.connectorPool); sm.setTable("shoppingOnlineLink") .setAccessTable("reseller") .setAccessId("resellerId") .addFindField("id") .addFindField("url") .addFindField("productId") .addFindField("resellerId"); return sm; } @Override public SqlEntityMediator grantAccess(int entityId, List<Integer> listUsers) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public SqlEntityMediator grantAccess(int entityId) { // do nothing, access is managed in Resellert Service return this; } @Override public SqlEntityMediator revokeAccess(int entityId, List<Integer> listUsers) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public SqlEntityMediator revokeAccess(int entityId) { // do nothing; access is managed in Reseller Service return this; } @RequestMapping(value = "/shoppingOnlineLinks", method = RequestMethod.GET) public @ResponseBody List<Map<String, Object>> find( @RequestParam(value="id", required=false, defaultValue="-1") int shoppingOnlineLinkID, @RequestParam(value="url", required=false, defaultValue="") String url, @RequestParam(value="productId", required=false, defaultValue="-1") int productId, @RequestParam(value="resellerId", required=false, defaultValue="-1") int resellerId ){ SqlMediator sm = this.getSqlMediator(); if (shoppingOnlineLinkID >= 0){ sm.addFindParam("id", shoppingOnlineLinkID, 1); } if (!url.isEmpty()){ sm.addFindParam("url", url, 1); } if (productId > 0){ sm.addFindParam("productId", productId, 1); } if (resellerId > 0){ sm.addFindParam("resellerId", resellerId, 1); } sm.runFind(); return sm.getResultsFind(); } @RequestMapping(value = "/shoppingOnlineLink", method = RequestMethod.POST) public @ResponseBody String upsert( @RequestParam(value="id", required=false, defaultValue="-1") int shoppingOnlineLinkID, @RequestParam(value="url", required=false, defaultValue="") String url, @RequestParam(value="productId", required=false, defaultValue="-1") int productId, @RequestParam(value="resellerId", required=false, defaultValue="-1") int resellerId ){ SqlMediator sm = this.getSqlMediator(); if (shoppingOnlineLinkID >= 0){ sm.addId(shoppingOnlineLinkID); } if (!url.isEmpty()){ sm.addUpsertParam("url", url); } if (productId > 0){ sm.addUpsertParam("productId", productId); } if (resellerId > 0){ sm.addUpsertParam("resellerId", resellerId); } sm.runUpsert(); this.grantAccess(shoppingOnlineLinkID); return sm.getId(); } @RequestMapping(value = "/shoppingOnlineLink", method = RequestMethod.DELETE) public @ResponseBody String delete( @RequestParam(value="id", required=true) int shoppingOnlineLinkID ){ this.revokeAccess(shoppingOnlineLinkID); SqlMediator sm = this.getSqlMediator(); sm.addFindParam("id", shoppingOnlineLinkID, 1) .runDelete(); return ""+shoppingOnlineLinkID; } }
gpl-3.0
mstine/polyglot-osgi
lib/osgi/felix/org.apache.felix.framework-1.8.1/src/main/java/org/apache/felix/framework/util/manifestparser/R4LibraryClause.java
17347
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.framework.util.manifestparser; import java.util.*; import org.apache.felix.framework.FilterImpl; import org.apache.felix.framework.Logger; import org.apache.felix.framework.util.FelixConstants; import org.apache.felix.framework.util.VersionRange; import org.osgi.framework.*; public class R4LibraryClause { private final String[] m_libraryEntries; private final String[] m_osnames; private final String[] m_processors; private final String[] m_osversions; private final String[] m_languages; private final String m_selectionFilter; public R4LibraryClause(String[] libraryEntries, String[] osnames, String[] processors, String[] osversions, String[] languages, String selectionFilter) { m_libraryEntries = libraryEntries; m_osnames = osnames; m_processors = processors; m_osversions = osversions; m_languages = languages; m_selectionFilter = selectionFilter; } public R4LibraryClause(R4LibraryClause library) { m_libraryEntries = library.m_libraryEntries; m_osnames = library.m_osnames; m_osversions = library.m_osversions; m_processors = library.m_processors; m_languages = library.m_languages; m_selectionFilter = library.m_selectionFilter; } public String[] getLibraryEntries() { return m_libraryEntries; } public String[] getOSNames() { return m_osnames; } public String[] getProcessors() { return m_processors; } public String[] getOSVersions() { return m_osversions; } public String[] getLanguages() { return m_languages; } public String getSelectionFilter() { return m_selectionFilter; } public boolean match(Map configMap) throws BundleException { String normal_osname = normalizeOSName((String) configMap.get(Constants.FRAMEWORK_OS_NAME)); String normal_processor = normalizeProcessor((String) configMap.get(Constants.FRAMEWORK_PROCESSOR)); String normal_osversion = normalizeOSVersion((String) configMap.get(Constants.FRAMEWORK_OS_VERSION)); String normal_language = (String) configMap.get(Constants.FRAMEWORK_LANGUAGE); // Check library's osname. if (!checkOSNames(normal_osname, getOSNames())) { return false; } // Check library's processor. if (!checkProcessors(normal_processor, getProcessors())) { return false; } // Check library's osversion if specified. if ((getOSVersions() != null) && (getOSVersions().length > 0) && !checkOSVersions(normal_osversion, getOSVersions())) { return false; } // Check library's language if specified. if ((getLanguages() != null) && (getLanguages().length > 0) && !checkLanguages(normal_language, getLanguages())) { return false; } // Check library's selection-filter if specified. if ((getSelectionFilter() != null) && (getSelectionFilter().length() >= 0) && !checkSelectionFilter(configMap, getSelectionFilter())) { return false; } return true; } private boolean checkOSNames(String currentOSName, String[] osnames) { boolean win32 = currentOSName.startsWith("win") && (currentOSName.equals("windows95") || currentOSName.equals("windows98") || currentOSName.equals("windowsnt") || currentOSName.equals("windows2000") || currentOSName.equals("windowsxp") || currentOSName.equals("windowsce") || currentOSName.equals("windowsvista")); for (int i = 0; (osnames != null) && (i < osnames.length); i++) { if (osnames[i].equals(currentOSName) || ("win32".equals(osnames[i]) && win32)) { return true; } } return false; } private boolean checkProcessors(String currentProcessor, String[] processors) { for (int i = 0; (processors != null) && (i < processors.length); i++) { if (processors[i].equals(currentProcessor)) { return true; } } return false; } private boolean checkOSVersions(String currentOSVersion, String[] osversions) throws BundleException { for (int i = 0; (osversions != null) && (i < osversions.length); i++) { try { VersionRange range = VersionRange.parse(osversions[i]); if (range.isInRange(new Version(currentOSVersion))) { return true; } } catch (Exception ex) { throw new BundleException( "Error evaluating osversion: " + osversions[i], ex); } } return false; } private boolean checkLanguages(String currentLanguage, String[] languages) { for (int i = 0; (languages != null) && (i < languages.length); i++) { if (languages[i].equals(currentLanguage)) { return true; } } return false; } private boolean checkSelectionFilter(Map configMap, String expr) throws BundleException { // Get all framework properties Dictionary dict = new Hashtable(); for (Iterator i = configMap.keySet().iterator(); i.hasNext(); ) { Object key = i.next(); dict.put(key, configMap.get(key)); } // Compute expression try { FilterImpl filter = new FilterImpl(expr); return filter.match(dict); } catch (Exception ex) { throw new BundleException( "Error evaluating filter expression: " + expr, ex); } } public static R4LibraryClause parse(Logger logger, String s) { try { if ((s == null) || (s.length() == 0)) { return null; } if (s.equals(FelixConstants.BUNDLE_NATIVECODE_OPTIONAL)) { return new R4LibraryClause(null, null, null, null, null, null); } // The tokens are separated by semicolons and may include // any number of libraries along with one set of associated // properties. StringTokenizer st = new StringTokenizer(s, ";"); String[] libEntries = new String[st.countTokens()]; List osNameList = new ArrayList(); List osVersionList = new ArrayList(); List processorList = new ArrayList(); List languageList = new ArrayList(); String selectionFilter = null; int libCount = 0; while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.indexOf('=') < 0) { // Remove the slash, if necessary. libEntries[libCount] = (token.charAt(0) == '/') ? token.substring(1) : token; libCount++; } else { // Check for valid native library properties; defined as // a property name, an equal sign, and a value. // NOTE: StringTokenizer can not be used here because // a value can contain one or more "=" too, e.g., // selection-filter="(org.osgi.framework.windowing.system=gtk)" String property = null; String value = null; if (!(token.indexOf("=") > 1)) { throw new IllegalArgumentException( "Bundle manifest native library entry malformed: " + token); } else { property = (token.substring(0, token.indexOf("="))) .trim().toLowerCase(); value = (token.substring(token.indexOf("=") + 1, token .length())).trim(); } // Values may be quoted, so remove quotes if present. if (value.charAt(0) == '"') { // This should always be true, otherwise the // value wouldn't be properly quoted, but we // will check for safety. if (value.charAt(value.length() - 1) == '"') { value = value.substring(1, value.length() - 1); } else { value = value.substring(1); } } // Add the value to its corresponding property list. if (property.equals(Constants.BUNDLE_NATIVECODE_OSNAME)) { osNameList.add(normalizeOSName(value)); } else if (property.equals(Constants.BUNDLE_NATIVECODE_OSVERSION)) { osVersionList.add(normalizeOSVersion(value)); } else if (property.equals(Constants.BUNDLE_NATIVECODE_PROCESSOR)) { processorList.add(normalizeProcessor(value)); } else if (property.equals(Constants.BUNDLE_NATIVECODE_LANGUAGE)) { languageList.add(value); } else if (property.equals(Constants.SELECTION_FILTER_ATTRIBUTE)) { // TODO: NATIVE - I believe we can have multiple selection filters too. selectionFilter = value; } } } if (libCount == 0) { return null; } // Shrink lib file array. String[] actualLibEntries = new String[libCount]; System.arraycopy(libEntries, 0, actualLibEntries, 0, libCount); return new R4LibraryClause( actualLibEntries, (String[]) osNameList.toArray(new String[osNameList.size()]), (String[]) processorList.toArray(new String[processorList.size()]), (String[]) osVersionList.toArray(new String[osVersionList.size()]), (String[]) languageList.toArray(new String[languageList.size()]), selectionFilter); } catch (RuntimeException ex) { logger.log(Logger.LOG_ERROR, "Error parsing native library header.", ex); throw ex; } } public static String normalizeOSName(String value) { value = value.toLowerCase(); if (value.startsWith("win")) { String os = "win"; if (value.indexOf("32") >= 0 || value.indexOf("*") >= 0) { os = "win32"; } else if (value.indexOf("95") >= 0) { os = "windows95"; } else if (value.indexOf("98") >= 0) { os = "windows98"; } else if (value.indexOf("nt") >= 0) { os = "windowsnt"; } else if (value.indexOf("2000") >= 0) { os = "windows2000"; } else if (value.indexOf("xp") >= 0) { os = "windowsxp"; } else if (value.indexOf("ce") >= 0) { os = "windowsce"; } else if (value.indexOf("vista") >= 0) { os = "windowsvista"; } return os; } else if (value.startsWith("linux")) { return "linux"; } else if (value.startsWith("aix")) { return "aix"; } else if (value.startsWith("digitalunix")) { return "digitalunix"; } else if (value.startsWith("hpux")) { return "hpux"; } else if (value.startsWith("irix")) { return "irix"; } else if (value.startsWith("macos") || value.startsWith("mac os")) { return "macos"; } else if (value.startsWith("netware")) { return "netware"; } else if (value.startsWith("openbsd")) { return "openbsd"; } else if (value.startsWith("netbsd")) { return "netbsd"; } else if (value.startsWith("os2") || value.startsWith("os/2")) { return "os2"; } else if (value.startsWith("qnx") || value.startsWith("procnto")) { return "qnx"; } else if (value.startsWith("solaris")) { return "solaris"; } else if (value.startsWith("sunos")) { return "sunos"; } else if (value.startsWith("vxworks")) { return "vxworks"; } return value; } public static String normalizeProcessor(String value) { value = value.toLowerCase(); if (value.startsWith("x86-64") || value.startsWith("amd64")) { return "x86-64"; } else if (value.startsWith("x86") || value.startsWith("pentium") || value.startsWith("i386") || value.startsWith("i486") || value.startsWith("i586") || value.startsWith("i686")) { return "x86"; } else if (value.startsWith("68k")) { return "68k"; } else if (value.startsWith("arm")) { return "arm"; } else if (value.startsWith("alpha")) { return "alpha"; } else if (value.startsWith("ignite") || value.startsWith("psc1k")) { return "ignite"; } else if (value.startsWith("mips")) { return "mips"; } else if (value.startsWith("parisc")) { return "parisc"; } else if (value.startsWith("powerpc") || value.startsWith("power") || value.startsWith("ppc")) { return "powerpc"; } else if (value.startsWith("sparc")) { return "sparc"; } return value; } public static String normalizeOSVersion(String value) { // Header: 'Bundle-NativeCode', Parameter: 'osversion' // Standardized 'osversion': major.minor.micro, only digits String VERSION_DELIM = "."; String QUALIFIER_DELIM = "-"; int major = 0; int minor = 0; int micro = 0; try { StringTokenizer st = new StringTokenizer(value, VERSION_DELIM, true); major = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) { st.nextToken(); // consume delimiter minor = Integer.parseInt(st.nextToken()); if (st.hasMoreTokens()) { st.nextToken(); // consume delimiter String microStr = st.nextToken(); if (microStr.indexOf(QUALIFIER_DELIM) < 0) { micro = Integer.parseInt(microStr); } else { micro = Integer.parseInt(microStr.substring(0, microStr .indexOf(QUALIFIER_DELIM))); } } } } catch (Exception ex) { return Version.emptyVersion.toString(); } return major + "." + minor + "." + micro; } }
gpl-3.0
LucieneCavalcanti/ProjetoAulas
ProjetoIntroducaoJava/src/br/pro/luciene/ProjetoAulasJava/aula02/ExemploIf.java
409
package br.pro.luciene.ProjetoAulasJava.aula02; /** * @author @author Luciene Cavalcanti Rodrigues */ public class ExemploIf { public static void main(String args[]) { int var1 = 20; int var2 = 10; // modo de uso: if (condicao) if (var1 > var2) { // bloco de comandos do if System.out.println("var1 é maior que var2"); } } }
gpl-3.0
Relicum/Ipsum
src/main/java/com/relicum/ipsum/Permission/package-info.java
931
/* * Ipsum is a rapid development API for Minecraft, developer by Relicum * Copyright (C) 2014. Chris Lutte * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Permission contains permission related class including a permission manager. * * @author Relicum * @version 0.0.1 */ package com.relicum.ipsum.Permission;
gpl-3.0
lsu-ub-uu/cora-bookkeeper
src/test/java/se/uu/ub/cora/bookkeeper/validator/MetadataMatchDataTest.java
10042
/* * Copyright 2015 Uppsala University Library * * This file is part of Cora. * * Cora is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Cora is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cora. If not, see <http://www.gnu.org/licenses/>. */ package se.uu.ub.cora.bookkeeper.validator; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import se.uu.ub.cora.bookkeeper.DataGroupSpy; import se.uu.ub.cora.bookkeeper.linkcollector.DataAtomicFactorySpy; import se.uu.ub.cora.bookkeeper.linkcollector.DataGroupFactorySpy; import se.uu.ub.cora.bookkeeper.metadata.CollectionItem; import se.uu.ub.cora.bookkeeper.metadata.CollectionVariable; import se.uu.ub.cora.bookkeeper.metadata.ItemCollection; import se.uu.ub.cora.bookkeeper.metadata.MetadataElement; import se.uu.ub.cora.bookkeeper.metadata.MetadataGroup; import se.uu.ub.cora.bookkeeper.metadata.MetadataHolder; import se.uu.ub.cora.data.DataAtomicProvider; import se.uu.ub.cora.data.DataElement; import se.uu.ub.cora.data.DataGroup; import se.uu.ub.cora.data.DataGroupProvider; public class MetadataMatchDataTest { private static final String NAME_IN_DATA = "nameInData"; private MetadataHolder metadataHolder; private MetadataMatchData metadataMatch; private DataGroupFactorySpy dataGroupFactory; private DataAtomicFactorySpy dataAtomicFactory; @BeforeMethod public void setUp() { dataGroupFactory = new DataGroupFactorySpy(); DataGroupProvider.setDataGroupFactory(dataGroupFactory); dataAtomicFactory = new DataAtomicFactorySpy(); DataAtomicProvider.setDataAtomicFactory(dataAtomicFactory); metadataHolder = new MetadataHolder(); metadataMatch = MetadataMatchDataImp.withMetadataHolder(metadataHolder); } @Test public void testMatchingNameInDataOnGroup() { MetadataElement metadataElement = MetadataGroup.withIdAndNameInDataAndTextIdAndDefTextId( "id", NAME_IN_DATA, "textId", "defTextId"); DataElement dataElement = new DataGroupSpy(NAME_IN_DATA); assertTrue(dataIsMatching(metadataElement, dataElement)); } private boolean dataIsMatching(MetadataElement metadataElement, DataElement dataElement) { return metadataMatch.metadataSpecifiesData(metadataElement, dataElement).dataIsValid(); } @Test public void testNoMatchNameInDataOnGroupWrongNameInData() { MetadataElement metadataElement = MetadataGroup.withIdAndNameInDataAndTextIdAndDefTextId( "id", NAME_IN_DATA, "textId", "defTextId"); DataElement dataElement = new DataGroupSpy("NOT_nameInData"); assertFalse(dataIsMatching(metadataElement, dataElement)); } @Test public void testMatchingAttributeOnGroup() { addCollectionVariableToMetadataHolder(); addCollectionVariableChildWithFinalValue(); MetadataGroup metadataElement = MetadataGroup.withIdAndNameInDataAndTextIdAndDefTextId("id", NAME_IN_DATA, "textId", "defTextId"); metadataElement.addAttributeReference("collectionVariableChildId"); DataGroup dataElement = new DataGroupSpy(NAME_IN_DATA); dataElement.addAttributeByIdWithValue("collectionVariableNameInData", "collectionItem2NameInData"); assertTrue(dataIsMatching(metadataElement, dataElement)); } private void addCollectionVariableToMetadataHolder() { CollectionItem collectionItem1 = new CollectionItem("collectionItem1Id", "collectionItem1NameInData", "collectionItem1TextId", "collectionItem1DefTextId"); metadataHolder.addMetadataElement(collectionItem1); CollectionItem collectionItem2 = new CollectionItem("collectionItem2Id", "collectionItem2NameInData", "collectionItem2TextId", "collectionItem2DefTextId"); metadataHolder.addMetadataElement(collectionItem2); CollectionItem collectionItem3 = new CollectionItem("collectionItem3Id", "collectionItem3NameInData", "collectionItem3TextId", "collectionItem3DefTextId"); metadataHolder.addMetadataElement(collectionItem3); ItemCollection itemCollection = new ItemCollection("itemCollectionId", "itemCollectionNameInData", "itemCollectionTextId", "itemCollectionDefTextId"); metadataHolder.addMetadataElement(itemCollection); itemCollection.addItemReference("collectionItem1Id"); itemCollection.addItemReference("collectionItem2Id"); itemCollection.addItemReference("collectionItem3Id"); } private void addCollectionVariableChildWithFinalValue() { CollectionVariable collectionVariable = new CollectionVariable("collectionVariableId", "collectionVariableNameInData", "collectionVariableTextId", "collectionVariableDefTextId", "itemCollectionId"); metadataHolder.addMetadataElement(collectionVariable); CollectionVariable collectionVariableChild = new CollectionVariable( "collectionVariableChildId", "collectionVariableNameInData", "collectionVariableChildTextId", "collectionVariableChildDefTextId", "itemCollectionId"); metadataHolder.addMetadataElement(collectionVariableChild); collectionVariableChild.setRefParentId("collectionVariableId"); collectionVariableChild.setFinalValue("collectionItem2NameInData"); } @Test public void testNoMatchAttributeOnGroupWrongCollectionItem() { addCollectionVariableToMetadataHolder(); addCollectionVariableChildWithFinalValue(); MetadataGroup metadataElement = MetadataGroup.withIdAndNameInDataAndTextIdAndDefTextId("id", NAME_IN_DATA, "textId", "defTextId"); metadataElement.addAttributeReference("collectionVariableChildId"); DataGroup dataElement = new DataGroupSpy(NAME_IN_DATA); dataElement.addAttributeByIdWithValue("collectionVariableNameInData", "collectionItem1NameInData"); assertFalse(dataIsMatching(metadataElement, dataElement)); } @Test public void testNoMatchAttributeOnGroupNoAttributeInData() { addCollectionVariableToMetadataHolder(); addCollectionVariableChildWithFinalValue(); MetadataGroup metadataElement = MetadataGroup.withIdAndNameInDataAndTextIdAndDefTextId("id", NAME_IN_DATA, "textId", "defTextId"); metadataElement.addAttributeReference("collectionVariableChildId"); DataGroup dataElement = new DataGroupSpy(NAME_IN_DATA); assertFalse(dataIsMatching(metadataElement, dataElement)); } @Test public void testNoMatchAttributeOnGroupAttributeButNotTheOneWeAreLookingForInData() { addCollectionVariableToMetadataHolder(); addCollectionVariableChildWithFinalValue(); MetadataGroup metadataElement = MetadataGroup.withIdAndNameInDataAndTextIdAndDefTextId("id", NAME_IN_DATA, "textId", "defTextId"); metadataElement.addAttributeReference("collectionVariableChildId"); DataGroup dataElement = new DataGroupSpy(NAME_IN_DATA); dataElement.addAttributeByIdWithValue("NOT_collectionVariableNameInData", "collectionItem2NameInData"); assertFalse(dataIsMatching(metadataElement, dataElement)); } @Test public void testNoMatchAttributeOnGroupExtraAttributeInData() { addCollectionVariableToMetadataHolder(); addCollectionVariableChildWithFinalValue(); MetadataGroup metadataElement = MetadataGroup.withIdAndNameInDataAndTextIdAndDefTextId("id", NAME_IN_DATA, "textId", "defTextId"); metadataElement.addAttributeReference("collectionVariableChildId"); DataGroup dataElement = new DataGroupSpy(NAME_IN_DATA); dataElement.addAttributeByIdWithValue("collectionVariableNameInData", "collectionItem2NameInData"); dataElement.addAttributeByIdWithValue("NOT_collectionVariableNameInData", "collectionItem2NameInData"); assertFalse(dataIsMatching(metadataElement, dataElement)); } @Test public void testNoMatchMetadataDoesNotSpecifyAnyAttributeExtraAttributeInData() { MetadataElement metadataElement = MetadataGroup.withIdAndNameInDataAndTextIdAndDefTextId( "id", NAME_IN_DATA, "textId", "defTextId"); DataGroup dataElement = new DataGroupSpy(NAME_IN_DATA); dataElement.addAttributeByIdWithValue("collectionVariableNameInData", "collectionItem2NameInData"); assertFalse(dataIsMatching(metadataElement, dataElement)); } @Test public void testMatchingTwoAttributeOnGroup() { addCollectionVariableToMetadataHolder(); addCollectionVariableChildWithFinalValue(); addCollectionVariableChildWithFinalValue3(); MetadataGroup metadataElement = MetadataGroup.withIdAndNameInDataAndTextIdAndDefTextId("id", NAME_IN_DATA, "textId", "defTextId"); metadataElement.addAttributeReference("collectionVariableChildId"); metadataElement.addAttributeReference("collectionVariableChild3Id"); DataGroup dataElement = new DataGroupSpy(NAME_IN_DATA); dataElement.addAttributeByIdWithValue("collectionVariableNameInData", "collectionItem2NameInData"); dataElement.addAttributeByIdWithValue("collectionVariable3NameInData", "collectionItem3NameInData"); assertTrue(dataIsMatching(metadataElement, dataElement)); } private void addCollectionVariableChildWithFinalValue3() { CollectionVariable collectionVariable = new CollectionVariable("collectionVariable3Id", "collectionVariable3NameInData", "collectionVariableTextId", "collectionVariableDefTextId", "itemCollectionId"); metadataHolder.addMetadataElement(collectionVariable); CollectionVariable collectionVariableChild = new CollectionVariable( "collectionVariableChild3Id", "collectionVariable3NameInData", "collectionVariableChild3TextId", "collectionVariableChild3DefTextId", "itemCollectionId"); metadataHolder.addMetadataElement(collectionVariableChild); collectionVariableChild.setRefParentId("collectionVariable3Id"); collectionVariableChild.setFinalValue("collectionItem3NameInData"); } }
gpl-3.0
RichardSilveira/MoviesOfTheYear
app/src/androidTest/java/com/richardlee/moviesoftheyear/ExampleInstrumentedTest.java
764
package com.richardlee.moviesoftheyear; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.richardlee.moviesoftheyear", appContext.getPackageName()); } }
gpl-3.0
lipki/TFCNT
src/Common/com/bioxx/tfc/Core/WeatherManager.java
1919
package com.bioxx.tfc.Core; import java.util.Random; import net.minecraft.world.World; public class WeatherManager { protected static final WeatherManager instance = new WeatherManager(); private Random rand = new Random(); private Random clientRand = new Random(); public static final WeatherManager getInstance() { return instance; } public long seed = 0; public WeatherManager() { } private Random getRandom(World world) { if(world.isRemote) return clientRand; return rand; } public float getDailyTemp() { rand.setSeed(seed + TFC_Time.getTotalDays()); return (rand.nextInt(200) - 100) / 10; } public float getDailyTemp(int day) { rand.setSeed(seed + day); return (rand.nextInt(200) - 100) / 20; } public float getWeeklyTemp(int week) { rand.setSeed(seed + week); return (rand.nextInt(200) - 100) / 10; } public static int getDayOfWeek(long day) { long days = day / 6; long days2 = day - (days * 6); return (int)days2; } public static boolean canSnow(World world, int x, int y, int z) { if(TFC_Climate.getHeightAdjustedTemp(world, x, y, z) <= 0) return true; return false; } public float getLocalFog(World world, int x, int y, int z) { if(world.isRemote) { int hour = TFC_Time.getHour(); if(hour >= 4 && hour < 9) { clientRand.setSeed(TFC_Time.getTotalDays()); float rain = TFC_Climate.getRainfall(world, x, y, z); float strength = clientRand.nextFloat(); if(rain >= 500 && clientRand.nextInt(3) == 0) { float mult = 1f; if(9-hour < 2) mult = 0.5f; return strength*mult;//Makes the fog weaker as time goes on. } } } return 0; } public float getSnowStrength() { int hour = TFC_Time.getHour(); clientRand.setSeed(TFC_Time.getTotalDays()+hour); return clientRand.nextFloat(); } }
gpl-3.0
luis-r-izquierdo/netlogo-fuzzy-logic-extension
fuzzy/src/tfg/fuzzy/general/SupportFunctions.java
9999
package tfg.fuzzy.general; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import org.nlogo.api.Context; import org.nlogo.api.ExtensionException; //import org.nlogo.api.I18N; import org.nlogo.core.LogoList; //import org.nlogo.nvm.ExtensionContext; //import org.nlogo.window.GUIWorkspace; import tfg.fuzzy.sets.general.FuzzySet; /** * This class is used by all creation of fuzzy sets primitives. * * @author Marcos Almendres. * */ public class SupportFunctions { /** * Number of points to evaluate continuous sets. */ private static double resolution = 32; /** * Get the resolution of the model. * * @return the resolution. */ public static double getResolution() { return resolution; } /** * Sets the resolution of the model. * * @param d * The resolution we want to set. */ public static void setResolution(double d) { resolution = d; } /** * Calculate the universe of the parameters that comes from netlogo. * * @param params * Parameters of a fuzzy set. * @return the universe of the parameters. */ public static double[] universe(LogoList params) { double[] universe = new double[2]; // Save the first and the last x value[x1,x2] LogoList first = (LogoList) params.first(); LogoList last = (LogoList) params.get(params.size() - 1); universe[0] = (Double) first.first(); universe[1] = (Double) last.first(); return universe; } /** * Checks the format of the sets defined with points. * * @param params * Parameters of the fuzzy set. * @return A valid list with the parameters of the set sorted. * @throws ExtensionException */ public static List<double[]> checkListFormat(LogoList params) throws ExtensionException { int n = 0; List<double[]> sortingList = new ArrayList<double[]>(); double[] point = new double[2]; // If this is an empty list throw and exception if (params.size() == 0) { throw new ExtensionException( "The list is empty, please enter a valid list: [[a b] [c d] [e f]]"); } // Iterate over the parameters Iterator<Object> it = params.javaIterator(); while (it.hasNext()) { Object o = it.next(); // Checks the elements are lists if (!(o instanceof LogoList)) { throw new ExtensionException( "List of 2 elements lists expected. The element in the position " + Double.valueOf(n) + " is not a list"); } LogoList l = (LogoList) o; // Checks if the lists contains 2 elements if (l.size() != 2) { throw new ExtensionException( "List of 2 elements lists expected. The element in the position " + Double.valueOf(n) + " is not a list of two elements"); } point[0] = (Double) l.first(); point[1] = (Double) l.get(1); // Add to a list to use the Collections.sort method sortingList.add(point.clone()); // Checks if the elements are doubles if ((Double) l.get(1) > 1 || (Double) l.get(1) < 0) { throw new ExtensionException( "The second number of each list should be between 0 and 1 " + Double.valueOf(n) + " is not between 0 and 1"); } n++; } return sortListOfPoints(sortingList); } /** * Sort the points inside a list. * * @param list * the list with all points. * @return The sorted list. */ public static List<double[]> sortListOfPoints(List<double[]> list) { // Implement the Comparator for double[2] Comparator<double[]> comp = new Comparator<double[]>() { public int compare(double[] a, double[] b) { // Returns required by comparators(1 if the first is bigger, -1 // if smaller and 0 if equal) if (a[0] > b[0]) { return 1; } else if (b[0] > a[0]) { return -1; } else { return 0; } } }; Collections.sort(list, comp); // Build the sorted List to store in the FuzzySet return list; } /** * Checks the format of Logistic,Exponential and Gaussian sets * * @param params * the parameters of the set * @param n * Integer to check if 3 or 4 parameters required * @return The universe of the set [lower-limit, upper-limit] * @throws ExtensionException */ public static double[] LGEFormat(LogoList params, int n) throws ExtensionException { double[] universe = new double[2]; // Checks the number of elements, could be 3 or 4 actually if (params.size() != n) { throw new ExtensionException("must be a list with " + (n - 1) + " numbers and one 2-number list"); } // Iterate over the parameters for (int i = 0; i < params.size(); i++) { // The last element is the universe, the other n-1 the paramers if (i < n - 1) { // The first n-1 elements must be doubles if (!(params.get(i) instanceof Double)) { throw new ExtensionException("The first " + (n - 1) + " parameters must be numbers"); } } else { // The last element must be a logo list if (!(params.get(i) instanceof LogoList)) { throw new ExtensionException("The " + n + "th item must be a list of 2 elements list"); } LogoList l = (LogoList) params.get(i); // If the universe are not 2 elements if (l.size() != 2) { throw new ExtensionException("The " + n + "th item must be a list of 2 elements list"); } universe = new double[] { (Double) l.first(), (Double) l.get(1) }; } } return universe; } /** * Checks the parameters of Interval with points sets. * @param params The parameters of the set. * @return The universe of the set. * @throws ExtensionException */ public static double[] IWPFormat(LogoList params) throws ExtensionException { // Checks the list cointains two lists if (!(params.first() instanceof LogoList) || !(params.get(1) instanceof LogoList)) { throw new ExtensionException("The list should contain 2 lists"); } LogoList f = (LogoList) params.first(); // Checks the first parameter is a 2 element list with the first element // a list and the second a number if (f.size() != 2 || !(f.first() instanceof LogoList) || !(f.get(1) instanceof Double)) { throw new ExtensionException( "The first element of parameters must look like [[low-limit high-limit] value]"); } LogoList interval = (LogoList) f.first(); // Checks the first element(of the first parameter) is a list of 2 // numbers if (interval.size() != 2 || !(interval.first() instanceof Double) || !(interval.get(1) instanceof Double)) { throw new ExtensionException( "The interval must be a list of two numbers"); } // The universe in interval with point sets is stored in a different // way. // [lower-limit,higher-limit] this is the normal way to store universes. // [lower-limit,higher-limit,default-value] this is how universe is // stored in interval with point sets. double[] universe = new double[] { (Double) interval.first(), (Double) interval.get(1), (Double) f.get(1) }; // If the first point of the universe is greater than the last throw an // exception if (universe[0] >= universe[1]) { throw new ExtensionException( "The interval should be like[lower higher]"); } return universe; } /** * Checks the format of the trapezoidal sets. * * @param params * The parameters of the trapezoidal set. * @return The parameters in a list. * @throws ExtensionException */ public static List<double[]> trapezoidalFormat(LogoList params) throws ExtensionException { // Checks the list has 7 parameters if (params.size() != 7) { throw new ExtensionException( "The first argument must be a list of 7 numbers"); } List<double[]> resultParams = new ArrayList<double[]>(); for (int i = 0; i <= 6; i++) { // Checks the list has only Doubles inside if (!(params.get(i) instanceof Double)) { throw new ExtensionException( "The list can only contain numbers"); } // list-of-parameters is a list [a, b, c, d, e, f, HEIGHT] // The membership function equals 0 in the interval [a,b], // increases linearly from 0 to HEIGHT in the range b to c, // is equal to HEIGHT in the range c to d, // decreases linearly from HEIGHT to 0 in the range d to e, // and equals 0 in the interval [e,f]. if (i <= 1) { resultParams.add(new double[] { (Double) params.get(i), 0 }); } else if (i <= 3) { resultParams.add(new double[] { (Double) params.get(i), (Double) params.get(6) }); } else if (i <= 5) { resultParams.add(new double[] { (Double) params.get(i), 0 }); } } return resultParams; } /** * Add the fuzzy set with label to the registry of sets. * * @param f * The fuzzy set. * @param name * The label of the fuzzy set. * @param c * The context of netlogo. * @throws ExtensionException */ public static void addToRegistry(FuzzySet f, String name, Context c) throws ExtensionException { Map<String, FuzzySet> registry = FuzzyLogic.getRegistry(); // If the label is already registered just override it. if (registry.containsKey(name)) { /* * GUIWorkspace gw = (GUIWorkspace) ((ExtensionContext) c).workspace(); * String text = "The label: " + name + " had been previously assigned to an existing fuzzy set. The label " + name + " is now assigned to another fuzzy set"; * registry.remove(name); * registry.put(name, f); * org.nlogo.swing.OptionDialog.show(gw.getFrame(), "warning", text, new String[] { I18N.gui().get("common.buttons.ok") }); */ throw new ExtensionException("You cannot assign the same label (" + name + ") to two different fuzzy sets."); // If the fuzzy set is already registered throw an exception } else if (registry.containsValue(f)) { throw new ExtensionException( "You cannot assign two labels to the same fuzzy set."); } else { registry.put(name, f); } } }
gpl-3.0
andrey-gabchak/JavaRushLabs
com/javarush/test/level06/lesson05/task01/Cat.java
389
package com.javarush.test.level06.lesson05.task01; /* Метод finalize класса Cat В классе Cat создать метод protected void finalize() throws Throwable */ public class Cat { String name; Cat(String name) { this.name = name; } protected void finalize() throws Throwable { System.out.println(name + " destroyed"); } }
gpl-3.0
Danstahr/Geokuk
src/main/java/cz/geokuk/util/lang/AObject0.java
685
package cz.geokuk.util.lang; import java.io.Serializable; /** * Title: Evidence exemplářů a dodávek * Description: V první fázi zde bude implementace přidání dodávky a jejích exemplářů * Copyright: Copyright (c) 2001 * Company: TurboConsult s.r.o. * @author * @version 1.0 */ public abstract class AObject0 implements Serializable, IAtomString { /** * */ private static final long serialVersionUID = 1096188445300191688L; /** * Určuje, zda je hodnota atomického typu z jistého pohledu validní. * @return Předek vrací true, potomek musí případně přepsat. */ public boolean isValid() { return true; } }
gpl-3.0
PapenfussLab/PathOS
Tools/Hl7Tools/src/main/java/org/petermac/hl7/model/v251/message/RRE_O12.java
11304
/* * This class is an auto-generated source file for a HAPI * HL7 v2.x standard structure class. * * For more information, visit: http://hl7api.sourceforge.net/ * * The contents of this file are subject to the Mozilla Public License Version 1.1 * (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.mozilla.org/MPL/ * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the * specific language governing rights and limitations under the License. * * The Original Code is "[file_name]". Description: * "[one_line_description]" * * The Initial Developer of the Original Code is University Health Network. Copyright (C) * 2012. All Rights Reserved. * * Contributor(s): ______________________________________. * * Alternatively, the contents of this file may be used under the terms of the * GNU General Public License (the "GPL"), in which case the provisions of the GPL are * applicable instead of those above. If you wish to allow use of your version of this * file only under the terms of the GPL and not to allow others to use your version * of this file under the MPL, indicate your decision by deleting the provisions above * and replace them with the notice and other provisions required by the GPL License. * If you do not delete the provisions above, a recipient may use your version of * this file under either the MPL or the GPL. * */ package org.petermac.hl7.model.v251.message; import org.petermac.hl7.model.v251.group.*; import org.petermac.hl7.model.v251.segment.*; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.parser.ModelClassFactory; import ca.uhn.hl7v2.parser.DefaultModelClassFactory; import ca.uhn.hl7v2.model.*; /** * <p>Represents a RRE_O12 message structure (see chapter 4.13.6). This structure contains the * following elements: </p> * <ul> * <li>1: MSH (Message Header) <b> </b> </li> * <li>2: MSA (Message Acknowledgment) <b> </b> </li> * <li>3: ERR (Error) <b>optional repeating</b> </li> * <li>4: SFT (Software Segment) <b>optional repeating</b> </li> * <li>5: NTE (Notes and Comments) <b>optional repeating</b> </li> * <li>6: RRE_O12_RESPONSE (a Group object) <b>optional </b> </li> * </ul> */ //@SuppressWarnings("unused") public class RRE_O12 extends AbstractMessage { /** * Creates a new RRE_O12 message with DefaultModelClassFactory. */ public RRE_O12() { this(new DefaultModelClassFactory()); } /** * Creates a new RRE_O12 message with custom ModelClassFactory. */ public RRE_O12(ModelClassFactory factory) { super(factory); init(factory); } private void init(ModelClassFactory factory) { try { this.add(MSH.class, true, false); this.add(MSA.class, true, false); this.add(ERR.class, false, true); this.add(SFT.class, false, true); this.add(NTE.class, false, true); this.add(RRE_O12_RESPONSE.class, false, false); } catch(HL7Exception e) { log.error("Unexpected error creating RRE_O12 - this is probably a bug in the source code generator.", e); } } /** * Returns "2.5.1" */ public String getVersion() { return "2.5.1"; } /** * <p> * Returns * MSH (Message Header) - creates it if necessary * </p> * * */ public MSH getMSH() { return getTyped("MSH", MSH.class); } /** * <p> * Returns * MSA (Message Acknowledgment) - creates it if necessary * </p> * * */ public MSA getMSA() { return getTyped("MSA", MSA.class); } /** * <p> * Returns * the first repetition of * ERR (Error) - creates it if necessary * </p> * * */ public ERR getERR() { return getTyped("ERR", ERR.class); } /** * <p> * Returns a specific repetition of * ERR (Error) - creates it if necessary * </p> * * * @param rep The repetition index (0-indexed, i.e. the first repetition is at index 0) * @throws HL7Exception if the repetition requested is more than one * greater than the number of existing repetitions. */ public ERR getERR(int rep) { return getTyped("ERR", rep, ERR.class); } /** * <p> * Returns the number of existing repetitions of ERR * </p> * */ public int getERRReps() { return getReps("ERR"); } /** * <p> * Returns a non-modifiable List containing all current existing repetitions of ERR. * <p> * <p> * Note that unlike {@link #getERR()}, this method will not create any reps * if none are already present, so an empty list may be returned. * </p> * */ public java.util.List<ERR> getERRAll() throws HL7Exception { return getAllAsList("ERR", ERR.class); } /** * <p> * Inserts a specific repetition of ERR (Error) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public void insertERR(ERR structure, int rep) throws HL7Exception { super.insertRepetition( "ERR", structure, rep); } /** * <p> * Inserts a specific repetition of ERR (Error) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public ERR insertERR(int rep) throws HL7Exception { return (ERR)super.insertRepetition("ERR", rep); } /** * <p> * Removes a specific repetition of ERR (Error) * </p> * * * @see AbstractGroup#removeRepetition(String, int) */ public ERR removeERR(int rep) throws HL7Exception { return (ERR)super.removeRepetition("ERR", rep); } /** * <p> * Returns * the first repetition of * SFT (Software Segment) - creates it if necessary * </p> * * */ public SFT getSFT() { return getTyped("SFT", SFT.class); } /** * <p> * Returns a specific repetition of * SFT (Software Segment) - creates it if necessary * </p> * * * @param rep The repetition index (0-indexed, i.e. the first repetition is at index 0) * @throws HL7Exception if the repetition requested is more than one * greater than the number of existing repetitions. */ public SFT getSFT(int rep) { return getTyped("SFT", rep, SFT.class); } /** * <p> * Returns the number of existing repetitions of SFT * </p> * */ public int getSFTReps() { return getReps("SFT"); } /** * <p> * Returns a non-modifiable List containing all current existing repetitions of SFT. * <p> * <p> * Note that unlike {@link #getSFT()}, this method will not create any reps * if none are already present, so an empty list may be returned. * </p> * */ public java.util.List<SFT> getSFTAll() throws HL7Exception { return getAllAsList("SFT", SFT.class); } /** * <p> * Inserts a specific repetition of SFT (Software Segment) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public void insertSFT(SFT structure, int rep) throws HL7Exception { super.insertRepetition( "SFT", structure, rep); } /** * <p> * Inserts a specific repetition of SFT (Software Segment) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public SFT insertSFT(int rep) throws HL7Exception { return (SFT)super.insertRepetition("SFT", rep); } /** * <p> * Removes a specific repetition of SFT (Software Segment) * </p> * * * @see AbstractGroup#removeRepetition(String, int) */ public SFT removeSFT(int rep) throws HL7Exception { return (SFT)super.removeRepetition("SFT", rep); } /** * <p> * Returns * the first repetition of * NTE (Notes and Comments) - creates it if necessary * </p> * * */ public NTE getNTE() { return getTyped("NTE", NTE.class); } /** * <p> * Returns a specific repetition of * NTE (Notes and Comments) - creates it if necessary * </p> * * * @param rep The repetition index (0-indexed, i.e. the first repetition is at index 0) * @throws HL7Exception if the repetition requested is more than one * greater than the number of existing repetitions. */ public NTE getNTE(int rep) { return getTyped("NTE", rep, NTE.class); } /** * <p> * Returns the number of existing repetitions of NTE * </p> * */ public int getNTEReps() { return getReps("NTE"); } /** * <p> * Returns a non-modifiable List containing all current existing repetitions of NTE. * <p> * <p> * Note that unlike {@link #getNTE()}, this method will not create any reps * if none are already present, so an empty list may be returned. * </p> * */ public java.util.List<NTE> getNTEAll() throws HL7Exception { return getAllAsList("NTE", NTE.class); } /** * <p> * Inserts a specific repetition of NTE (Notes and Comments) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public void insertNTE(NTE structure, int rep) throws HL7Exception { super.insertRepetition( "NTE", structure, rep); } /** * <p> * Inserts a specific repetition of NTE (Notes and Comments) * </p> * * * @see AbstractGroup#insertRepetition(Structure, int) */ public NTE insertNTE(int rep) throws HL7Exception { return (NTE)super.insertRepetition("NTE", rep); } /** * <p> * Removes a specific repetition of NTE (Notes and Comments) * </p> * * * @see AbstractGroup#removeRepetition(String, int) */ public NTE removeNTE(int rep) throws HL7Exception { return (NTE)super.removeRepetition("NTE", rep); } /** * <p> * Returns * RESPONSE (a Group object) - creates it if necessary * </p> * * */ public RRE_O12_RESPONSE getRESPONSE() { return getTyped("RESPONSE", RRE_O12_RESPONSE.class); } }
gpl-3.0
zerokullneo/PCTR
PCTR-Codigos/Codigos_tema8/hMenInmortal.java
1046
import javax.realtime.*; public class Main extends RealtimeThread { public Main() { System.out.println("In Main constructor"); } public void run() { System.out.println("in Main run()"); // Set immortal memory as allocation context ImmortalMemory.instance().enter(this); System.out.println("In IM context"); // Create NHRT (within immortal memory) NoHeapRealtimeThread nhrt = new NoHeapRealtimeThread( null, ImmortalMemory.instance()) { public void run() { // Execute NHRT code here... System.out.println("I'm in an NHRT!"); } }; nhrt.start(); } public static void main(String[] args) throws Exception { // Create and start a RealtimeThread object System.out.println("Creating Main object"); Main app = new Main(); System.out.println("Starting Main"); app.start(); app.join(); } }
gpl-3.0
Nick2324/tesis_red_social
Prototipo/Construccion/SNADeportivo/app/src/main/java/sportsallaround/snadeportivo/eventos/peticiones/CreaInvitadoEvento.java
4069
package sportsallaround.snadeportivo.eventos.peticiones; import android.app.AlertDialog; import android.content.Context; import android.widget.Toast; import com.sna_deportivo.pojo.evento.ConstantesEventos; import com.sna_deportivo.pojo.evento.Evento; import com.sna_deportivo.pojo.usuarios.ConstantesUsuarios; import com.sna_deportivo.pojo.usuarios.Usuario; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import sportsallaround.snadeportivo.R; import sportsallaround.utils.generales.Constants; import sportsallaround.utils.generales.Peticion; /** * Created by nicolas on 17/10/15. */ public class CreaInvitadoEvento extends Peticion { private Context contexto; private String tipoEvento; private Evento evento; private Usuario usuario; public CreaInvitadoEvento(Context contexto, String tipoEvento, Evento evento, Usuario usuario) { this.contexto = contexto; this.tipoEvento = tipoEvento; this.evento = evento; this.usuario = usuario; } @Override public void calcularMetodo() { super.metodo = "POST"; } @Override public void calcularServicio() { super.servicio = Constants.SERVICES_PATH_EVENTOS + this.tipoEvento + "/" + this.evento.getId() + "/" + Constants.SERVICES_PATH_EVE_INVITACIONES; } @Override public void calcularParams() { super.params = new JSONObject(); try { //PONIENDO USUARIO JSONArray arrayUsuarios = new JSONArray(); arrayUsuarios.put(new JSONObject(this.usuario.stringJson())); JSONObject parametrosUsuario = new JSONObject(); parametrosUsuario.put(this.usuario.getClass().getSimpleName(), arrayUsuarios); super.params.put(ConstantesUsuarios.ELEMENTO_MENSAJE_SERVICIO_USU, parametrosUsuario); //PONIENDO EVENTO //Los eventos deben estar activos JSONArray arrayEventos = new JSONArray(); arrayEventos.put(new JSONObject(this.evento.stringJson())); JSONObject parametrosEvento = new JSONObject(); parametrosEvento.put(this.evento.getClass().getSimpleName(), arrayEventos); super.params.put(ConstantesEventos.ELEMENTO_MENSAJE_SERVICIO_EVE, parametrosEvento); } catch (JSONException e) { e.printStackTrace(); } } @Override public void doInBackground() {} @Override public void onPostExcecute(String resultadoPeticion) { if(resultadoPeticion != null){ try { JSONObject resultado = new JSONObject(resultadoPeticion); if(resultado.getString("caracterAceptacion") != null && ("200".equals(resultado.getString("caracterAceptacion")) || "204".equals(resultado.getString("caracterAceptacion")))){ Toast.makeText(this.contexto, this.contexto.getResources(). getString(R.string.toast_invita_usu_eve), Toast.LENGTH_SHORT).show(); }else{ this.alertError(); } } catch (JSONException e) { this.alertError(); e.printStackTrace(); } }else{ this.alertError(); } } private void alertError(){ new AlertDialog.Builder(this.contexto). setTitle(this.contexto.getResources(). getString(R.string.alert_invita_usu_eve_tit)). setMessage(this.contexto.getResources(). getString(R.string.alert_error_invita_usu_eve_msn)). setNeutralButton(this.contexto.getResources(). getString(R.string.BOTON_NEUTRAL), null). create().show(); } }
gpl-3.0
janaroj/dependency-track
src/main/java/org/owasp/dependencytrack/controller/AbstractController.java
1745
/* * This file is part of Dependency-Track. * * Dependency-Track is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Dependency-Track is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Dependency-Track. If not, see http://www.gnu.org/licenses/. * * Copyright (c) Axway. All Rights Reserved. */ package org.owasp.dependencytrack.controller; import org.owasp.dependencytrack.Config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import javax.servlet.ServletContext; /** * Base controller that all other controllers inherent from. * * @author Steve Springett (steve.springett@owasp.org) */ public abstract class AbstractController { /** * The ServletContext in which Dependency-Track is running in */ @Autowired private ServletContext servletContext; /** * Spring Environment */ @Autowired private Environment environment; /** * Dependency-Track's centralized Configuration class */ @Autowired private Config config; public ServletContext getServletContext() { return servletContext; } public Environment getEnvironment() { return environment; } public Config getConfig() { return config; } }
gpl-3.0
mediashelf/fedora-client
fedora-client-core/src/test/java/com/yourmediashelf/fedora/client/request/ListMethodsIT.java
1717
/** * Copyright (C) 2010 MediaShelf <http://www.yourmediashelf.com/> * * This file is part of fedora-client. * * fedora-client is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * fedora-client is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with fedora-client. If not, see <http://www.gnu.org/licenses/>. */ package com.yourmediashelf.fedora.client.request; import static com.yourmediashelf.fedora.client.FedoraClient.listMethods; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.yourmediashelf.fedora.client.FedoraClientException; import com.yourmediashelf.fedora.client.response.ListMethodsResponse; import com.yourmediashelf.fedora.generated.access.ObjectMethods; public class ListMethodsIT extends BaseFedoraRequestIT { @Test public void testListMethods() throws Exception { ListMethodsResponse response = listMethods(testPid).execute(); ObjectMethods methods = response.getObjectMethods(); assertEquals(testPid, methods.getPid()); //System.out.println(response.getEntity(String.class)); } @Override public void testNoDefaultClientRequest() throws FedoraClientException { testNoDefaultClientRequest(listMethods(testPid), 200); } }
gpl-3.0
Yunfeng/weniu
weniu-service/src/main/java/cn/buk/api/wechat/work/dto/WwpPreAuthCode.java
671
package cn.buk.api.wechat.work.dto; import cn.buk.api.wechat.dto.BaseResponse; /** * wwp - work weixin provider 企业微信服务商 * 获取预授权码 */ public class WwpPreAuthCode extends BaseResponse { private String pre_auth_code; //预授权码,最长为512字节 private int expires_in; //有效期 public String getPre_auth_code() { return pre_auth_code; } public void setPre_auth_code(String pre_auth_code) { this.pre_auth_code = pre_auth_code; } public int getExpires_in() { return expires_in; } public void setExpires_in(int expires_in) { this.expires_in = expires_in; } }
gpl-3.0
joyceshenhui/tieba
tieba/src/main/java/com/yc/tieba/util/RandomNumUtil.java
481
package com.yc.tieba.util; import java.util.Random; public class RandomNumUtil { public static int getRandomNumber(){ int[] array = {0,1,2,3,4,5,6,7,8,9}; Random rand = new Random(); for (int i = 10; i > 1; i--) { int index = rand.nextInt(i); int tmp = array[index]; array[index] = array[i - 1]; array[i - 1] = tmp; } int result = 0; for(int i = 0; i < 6; i++) result = result * 10 + array[i]; return result; } }
gpl-3.0
groberts619/WeBikeSD
CyclePhillyAndroid/src/main/java/org/phillyopen/mytracks/cyclephilly/IRecordService.java
1669
/** WeBikeSD, Copyright 2014 Code for Philly * * @author Lloyd Emelle <lloyd@codeforamerica.org> * @author Christopher Le Dantec <ledantec@gatech.edu> * @author Anhong Guo <guoanhong15@gmail.com> * * Updated/Modified for Philly's app deployment. Based on the * CycleTracks codebase for SFCTA and Cycle Atlanta. * * CycleTracks, Copyright 2009,2010 San Francisco County Transportation Authority * San Francisco, CA, USA * * @author Billy Charlton <billy.charlton@sfcta.org> * * This file is part of CycleTracks. * * CycleTracks is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CycleTracks is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CycleTracks. If not, see <http://www.gnu.org/licenses/>. */ package org.phillyopen.mytracks.cyclephilly; public interface IRecordService { public int getState(); public void startRecording(TripData trip); public void cancelRecording(); public long finishRecording(); // returns trip-id public long getCurrentTrip(); // returns trip-id public void pauseRecording(); public void resumeRecording(); public void reset(); public void setListener(RecordingActivity ra); }
gpl-3.0
droidefense/engine
mods/core/src/main/java/droidefense/emulator/machine/base/exceptions/VirtualMachineRuntimeException.java
279
package droidefense.emulator.machine.base.exceptions; import java.io.Serializable; public class VirtualMachineRuntimeException extends RuntimeException implements Serializable { public VirtualMachineRuntimeException(final String message) { super(message); } }
gpl-3.0
jedwards1211/Jhrome
src/main/java/org/sexydock/tabs/IFloatingTabHandler.java
1024
/* Copyright 2012 James Edwards This file is part of Jhrome. Jhrome is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Jhrome is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Jhrome. If not, see <http://www.gnu.org/licenses/>. */ package org.sexydock.tabs; import java.awt.Point; import java.awt.dnd.DragSourceDragEvent; public interface IFloatingTabHandler { void onFloatingBegin( Tab draggedTab , Point grabPoint ); void onFloatingTabDragged( DragSourceDragEvent dsde , Tab draggedTab , double grabX ); void onFloatingEnd( ); }
gpl-3.0
ogarcia/opensudoku
app/src/main/java/org/moire/opensudoku/gui/exporting/FileExportTask.java
6377
package org.moire.opensudoku.gui.exporting; import android.content.Context; import android.database.Cursor; import android.os.AsyncTask; import android.os.Handler; import android.util.Log; import android.util.Xml; import org.moire.opensudoku.db.SudokuColumns; import org.moire.opensudoku.db.SudokuDatabase; import org.moire.opensudoku.utils.Const; import org.xmlpull.v1.XmlSerializer; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; /** * Must be created on GUI thread. * * @author romario */ public class FileExportTask extends AsyncTask<FileExportTaskParams, Integer, Void> { private Context mContext; private Handler mGuiHandler; private OnExportFinishedListener mOnExportFinishedListener; public FileExportTask(Context context) { mContext = context; mGuiHandler = new Handler(); } public OnExportFinishedListener getOnExportFinishedListener() { return mOnExportFinishedListener; } public void setOnExportFinishedListener(OnExportFinishedListener listener) { mOnExportFinishedListener = listener; } @Override protected Void doInBackground(FileExportTaskParams... params) { for (FileExportTaskParams par : params) { final FileExportTaskResult res = saveToFile(par); mGuiHandler.post(() -> { if (mOnExportFinishedListener != null) { mOnExportFinishedListener.onExportFinished(res); } }); } return null; } private FileExportTaskResult saveToFile(FileExportTaskParams par) { if (par.folderID == null && par.sudokuID == null) { throw new IllegalArgumentException("Exactly one of folderID and sudokuID must be set."); } else if (par.folderID != null && par.sudokuID != null) { throw new IllegalArgumentException("Exactly one of folderID and sudokuID must be set."); } if (par.file == null) { throw new IllegalArgumentException("Filename must be set."); } long start = System.currentTimeMillis(); FileExportTaskResult result = new FileExportTaskResult(); result.successful = false; result.filename = par.filename; SudokuDatabase database = null; Cursor cursor = null; Writer writer = null; try { database = new SudokuDatabase(mContext); boolean generateFolders; if (par.folderID != null) { cursor = database.exportFolder(par.folderID); generateFolders = true; } else { cursor = database.exportFolder(par.sudokuID); generateFolders = false; } XmlSerializer serializer = Xml.newSerializer(); writer = new BufferedWriter(new OutputStreamWriter(par.file)); serializer.setOutput(writer); serializer.startDocument("UTF-8", true); serializer.startTag("", "opensudoku"); serializer.attribute("", "version", "2"); long currentFolderId = -1; while (cursor.moveToNext()) { if (generateFolders && currentFolderId != cursor.getLong(cursor.getColumnIndex("folder_id"))) { // next folder if (currentFolderId != -1) { serializer.endTag("", "folder"); } currentFolderId = cursor.getLong(cursor.getColumnIndex("folder_id")); serializer.startTag("", "folder"); attribute(serializer, "name", cursor, "folder_name"); attribute(serializer, "created", cursor, "folder_created"); } String data = cursor.getString(cursor.getColumnIndex(SudokuColumns.DATA)); if (data != null) { serializer.startTag("", "game"); attribute(serializer, "created", cursor, SudokuColumns.CREATED); attribute(serializer, "state", cursor, SudokuColumns.STATE); attribute(serializer, "time", cursor, SudokuColumns.TIME); attribute(serializer, "last_played", cursor, SudokuColumns.LAST_PLAYED); attribute(serializer, "data", cursor, SudokuColumns.DATA); attribute(serializer, "note", cursor, SudokuColumns.PUZZLE_NOTE); attribute(serializer, "command_stack", cursor, SudokuColumns.COMMAND_STACK); serializer.endTag("", "game"); } } if (generateFolders && currentFolderId != -1) { serializer.endTag("", "folder"); } serializer.endTag("", "opensudoku"); serializer.endDocument(); } catch (IOException e) { Log.e(Const.TAG, "Error while exporting file.", e); result.successful = false; return result; } finally { if (cursor != null) cursor.close(); if (database != null) database.close(); if (writer != null) { try { writer.close(); } catch (IOException e) { Log.e(Const.TAG, "Error while exporting file.", e); result.successful = false; return result; } } } long end = System.currentTimeMillis(); Log.i(Const.TAG, String.format("Exported in %f seconds.", (end - start) / 1000f)); result.successful = true; return result; } private void attribute(XmlSerializer serializer, String attributeName, Cursor cursor, String columnName) throws IllegalArgumentException, IllegalStateException, IOException { String value = cursor.getString(cursor.getColumnIndex(columnName)); if (value != null) { serializer.attribute("", attributeName, value); } } public interface OnExportFinishedListener { /** * Occurs when export is finished. * * @param result The result of the export */ void onExportFinished(FileExportTaskResult result); } }
gpl-3.0
kwanghoon/MySmallBasic
MySmallBasic/src/com/coducation/smallbasic/PropertyExpr.java
342
package com.coducation.smallbasic; public class PropertyExpr extends Expr { public PropertyExpr(String obj, String name) { super(); this.obj = obj; this.name = name; } // Builder public String getObj() { return obj; } public String getName() { return name; } private String obj, name; // cf. obj . name }
gpl-3.0
ArcticLabs/Opendoor
app/src/test/java/me/willeponken/opendoor/ExampleUnitTest.java
1066
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.willeponken.opendoor; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
gpl-3.0
hpclab/TheMatrixProject
src/it/cnr/isti/thematrix/test/TestCSVFile.java
2147
/* * Copyright (c) 2010-2014 "HPCLab at ISTI-CNR" * * This file is part of TheMatrix. * * TheMatrix is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package it.cnr.isti.thematrix.test; import it.cnr.isti.thematrix.configuration.ConfigSingleton; import it.cnr.isti.thematrix.configuration.Dynamic; import it.cnr.isti.thematrix.configuration.setting.TheMatrix; import it.cnr.isti.thematrix.mapping.creator.ValueRemapper; import it.cnr.isti.thematrix.mapping.utils.CSVFile; import java.io.IOException; import java.security.NoSuchAlgorithmException; import javax.xml.bind.JAXBException; /** * Tests the usage of a <code>CSVFile</code>. */ public class TestCSVFile { public static void main(String[] args) throws JAXBException, IOException, NoSuchAlgorithmException { /********************************************************* * Argument processing */ Dynamic.getDynamicInfo(); // we need to initialize our singleton System.out.println("Test letture file csv"); TheMatrix matrix = ConfigSingleton.getInstance().theMatrix; String TheFile = "DRUG"; String path = matrix.getPath().getIad(); String version = matrix.getVersion(); System.out.println("File esistente: " + CSVFile.checkExistence(path, TheFile) + " - File valido: " + CSVFile.validateCheckSum(path, TheFile)); CSVFile csv = new CSVFile(path, TheFile, version); while (csv.hasNext()) { csv.loadBatch(20000); csv.saveTo(path, "prova", true); } CSVFile.createMetaXml(path, "prova", matrix.getVersion()); System.out.println("Finito"); } }
gpl-3.0
CubeEngine/modules-extra
fun/src/main/java/org/cubeengine/module/fun/commands/PlayerCommands.java
12124
/* * This file is part of CubeEngine. * CubeEngine is licensed under the GNU General Public License Version 3. * * CubeEngine is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CubeEngine is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CubeEngine. If not, see <http://www.gnu.org/licenses/>. */ package org.cubeengine.module.fun.commands; import static org.cubeengine.libcube.service.i18n.formatter.MessageType.NEGATIVE; import static org.cubeengine.libcube.service.i18n.formatter.MessageType.NEUTRAL; import static org.cubeengine.libcube.service.i18n.formatter.MessageType.POSITIVE; import static org.spongepowered.api.data.type.HandTypes.MAIN_HAND; import com.flowpowered.math.vector.Vector3d; import org.cubeengine.butler.parametric.Command; import org.cubeengine.butler.parametric.Flag; import org.cubeengine.butler.parametric.Named; import org.cubeengine.butler.parametric.Optional; import org.cubeengine.libcube.service.i18n.I18n; import org.cubeengine.libcube.service.matcher.MaterialMatcher; import org.cubeengine.module.fun.Fun; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.property.item.EquipmentProperty; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityTypes; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.weather.Lightning; import org.spongepowered.api.event.cause.entity.damage.DamageTypes; import org.spongepowered.api.event.cause.entity.damage.source.DamageSource; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.equipment.EquipmentType; import org.spongepowered.api.item.inventory.equipment.EquipmentTypes; import org.spongepowered.api.util.blockray.BlockRay; import org.spongepowered.api.util.blockray.BlockRayHit; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.api.world.explosion.Explosion; public class PlayerCommands { private final Fun module; private final I18n i18n; private MaterialMatcher materialMatcher; public PlayerCommands(Fun module, I18n i18n, MaterialMatcher materialMatcher) { this.module = module; this.i18n = i18n; this.materialMatcher = materialMatcher; } @Command(desc = "Gives a player a hat") public void hat(CommandSource context, @Optional String item, @Named({"player", "p"}) Player player, @Flag boolean quiet) { ItemStack head; if(player != null) { if(!context.hasPermission(module.perms().COMMAND_HAT_OTHER.getId())) { i18n.send(context, NEGATIVE, "You can't set the hat of an other player."); return; } } else if(context instanceof Player) { player = (Player)context; } else { i18n.send(context, NEGATIVE, "You have to specify a player!"); return; } if(item != null) { if(!context.hasPermission(module.perms().COMMAND_HAT_ITEM.getId())) { i18n.send(context, NEGATIVE, "You can only use your item in hand!"); return; } head = materialMatcher.itemStack(item); if(head == null) { i18n.send(context, NEGATIVE, "Item not found!"); return; } } else if (context instanceof Player) { head = ((Player)context).getItemInHand(MAIN_HAND).orElse(null); } else { i18n.send(context, NEGATIVE, "Trying to be Notch? No hat for you!"); i18n.send(context, NEUTRAL, "Please specify an item!"); return; } if (head == null) { i18n.send(context, NEGATIVE, "You do not have any item in your hand!"); return; } EquipmentType type = head.getType().getDefaultProperty(EquipmentProperty.class) .map(EquipmentProperty::getValue).orElse(null); if (type == null || type != EquipmentTypes.HEADWEAR) { if (!context.hasPermission(module.perms().COMMAND_HAT_MORE_ARMOR.getId())) { i18n.send(context, NEGATIVE, "You are not allowed to use other armor as headpiece"); return; } } head.setQuantity(1); if(item == null && context instanceof Player) { ItemStack clone = head.copy(); clone.setQuantity(head.getQuantity() - 1); ((Player)context).setItemInHand(MAIN_HAND, clone); } if(player.getHelmet().isPresent()) { player.getInventory().offer(player.getHelmet().get()); } player.setHelmet(head); if(!(quiet && context.hasPermission(module.perms().COMMAND_HAT_QUIET.getId())) && player.hasPermission(module.perms().COMMAND_HAT_NOTIFY.getId())) { i18n.send(player, POSITIVE, "Your hat was changed"); } } @Command(desc = "Creates an explosion") public void explosion(CommandSource context, @Optional Integer damage, @Named({"player", "p"}) Player player, @Flag boolean unsafe, @Flag boolean fire, @Flag boolean blockDamage, @Flag boolean playerDamage) { damage = damage == null ? 1 : damage; if (damage > this.module.getConfig().command.explosion.power) { i18n.send(context, NEGATIVE, "The power of the explosion shouldn't be greater than {integer}", this.module.getConfig().command.explosion.power); return; } Location<World> loc; if (player != null) { if (!context.equals(player)) { if (!context.hasPermission(module.perms().COMMAND_EXPLOSION_OTHER.getId())) { i18n.send(context, NEGATIVE, "You are not allowed to specify a player."); return; } } loc = player.getLocation(); } else { if (!(context instanceof Player)) { i18n.send(context, NEGATIVE, "This command can only be used by a player!"); return; } java.util.Optional<BlockRayHit<World>> end = BlockRay.from(((Player)context)).distanceLimit( module.getConfig().command.explosion.distance).stopFilter(BlockRay.onlyAirFilter()).build().end(); if (end.isPresent()) { loc = end.get().getLocation(); } else { throw new IllegalStateException(); } } if (!context.hasPermission(module.perms().COMMAND_EXPLOSION_BLOCK_DAMAGE.getId()) && (blockDamage || unsafe)) { i18n.send(context, NEGATIVE, "You are not allowed to break blocks"); return; } if (!context.hasPermission(module.perms().COMMAND_EXPLOSION_FIRE.getId()) && (fire || unsafe)) { i18n.send(context, NEGATIVE, "You are not allowed to set fireticks"); return; } if (!context.hasPermission(module.perms().COMMAND_EXPLOSION_PLAYER_DAMAGE.getId()) && (playerDamage || unsafe)) { i18n.send(context, NEGATIVE, "You are not allowed to damage another player"); return; } Explosion explosion = Explosion.builder().location(loc).canCauseFire( fire || unsafe).shouldDamageEntities(playerDamage || unsafe).shouldBreakBlocks( blockDamage || unsafe).build(); Sponge.getCauseStackManager().pushCause(context); loc.getExtent().triggerExplosion(explosion); } @Command(alias = "strike", desc = "Throws a lightning bolt at a player or where you're looking") public void lightning(CommandSource context, @Optional Integer damage, @Named({"player","p"}) Player player, @Named({"fireticks", "f"}) Integer seconds, @Flag boolean unsafe) { damage = damage == null ? -1 : damage; if (damage != -1 && !context.hasPermission(module.perms().COMMAND_LIGHTNING_PLAYER_DAMAGE.getId())) { i18n.send(context, NEGATIVE, "You are not allowed to specify the damage!"); return; } if ((damage != -1 && damage < 0) || damage > 20) { i18n.send(context, NEGATIVE, "The damage value has to be a number from 1 to 20"); return; } if (unsafe && !context.hasPermission(module.perms().COMMAND_LIGHTNING_UNSAFE.getId())) { i18n.send(context, NEGATIVE, "You are not allowed to use the unsafe flag"); return; } Location<World> location; if (player != null) { location = player.getLocation(); player.offer(Keys.FIRE_TICKS, 20 * (seconds == null ? 0 : seconds)); if (damage != -1) { player.damage(damage, DamageSource.builder().type(DamageTypes.CONTACT).build()); // TODO better source } } else { if (!(context instanceof Player)) { i18n.send(context, NEGATIVE, "This command can only be used by a player!"); return; } java.util.Optional<BlockRayHit<World>> end = BlockRay.from(((Player)context)).distanceLimit( module.getConfig().command.lightning.distance).stopFilter(BlockRay.onlyAirFilter()).build().end(); if (end.isPresent()) { location = end.get().getLocation(); } else { throw new IllegalStateException(); } } Entity entity = location.getExtent().createEntity(EntityTypes.LIGHTNING, location.getPosition()); if (!unsafe) { ((Lightning)entity).setEffect(true); } Sponge.getCauseStackManager().pushCause(context); location.getExtent().spawnEntity(entity); } @Command(desc = "Slaps a player") public void slap(CommandSource context, Player player, @Optional Integer damage) { damage = damage == null ? 3 : damage; if (damage < 1 || damage > 20) { i18n.send(context, NEGATIVE, "Only damage values from 1 to 20 are allowed!"); return; } final Vector3d userDirection = player.getTransform().getRotationAsQuaternion().getDirection().mul(-1); Sponge.getCauseStackManager().pushCause(context); player.damage(damage, DamageSource.builder().type(DamageTypes.ATTACK).absolute().build()); player.setVelocity(new Vector3d(userDirection.getX() * damage / 2, userDirection.getY() * damage / 20, userDirection.getZ() * damage / 2)); } @Command(desc = "Burns a player") public void burn(CommandSource context, Player player, @Optional Integer seconds, @Flag boolean unset) { seconds = seconds == null ? 5 : seconds; if (unset) { seconds = 0; } else if (seconds < 1 || seconds > this.module.getConfig().command.burn.maxTime) { i18n.send(context, NEGATIVE, "Only 1 to {integer} seconds are allowed!", this.module.getConfig().command.burn.maxTime); return; } player.offer(Keys.FIRE_TICKS, seconds * 20); } }
gpl-3.0
PhoenixDevTeam/Phoenix-for-VK
app/src/main/java/biz/dealnote/messenger/model/VideoPlatform.java
266
package biz.dealnote.messenger.model; public class VideoPlatform { public static final String COUB = "Coub"; public static final String YOUTUBE = "YouTube"; public static final String VIMEO = "Vimeo"; public static final String RUTUBE = "Rutube"; }
gpl-3.0
automenta/adams-core
src/test/java/adams/data/baseline/PassThroughTest.java
2215
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * PassThroughTest.java * Copyright (C) 2010 University of Waikato, Hamilton, New Zealand */ package adams.data.baseline; import junit.framework.Test; import junit.framework.TestSuite; import adams.env.Environment; /** * Test class for the PassThrough baseline correction scheme. Run from the command line with: <p/> * java adams.data.baseline.PassThroughTest * <p/> * Note: dummy test * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 4584 $ */ public class PassThroughTest extends AbstractBaselineCorrectionTestCase { /** * Constructs the test case. Called by subclasses. * * @param name the name of the test */ public PassThroughTest(String name) { super(name); } /** * Returns the filenames (without path) of the input data files to use * in the regression test. * * @return the filenames */ protected String[] getRegressionInputFiles() { return new String[0]; } /** * Returns the setups to use in the regression test. * * @return the setups */ protected AbstractBaselineCorrection[] getRegressionSetups() { return new AbstractBaselineCorrection[0]; } /** * Returns the test suite. * * @return the suite */ public static Test suite() { return new TestSuite(PassThroughTest.class); } /** * Runs the test from commandline. * * @param args ignored */ public static void main(String[] args) { Environment.setEnvironmentClass(Environment.class); runTest(suite()); } }
gpl-3.0
FauDroids/BabyFace
app/src/main/java/org/faudroids/babyface/ui/ShowPhotosActivity.java
5923
package org.faudroids.babyface.ui; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.squareup.picasso.Picasso; import org.faudroids.babyface.R; import org.faudroids.babyface.faces.Face; import org.faudroids.babyface.photo.PhotoInfo; import org.faudroids.babyface.photo.PhotoManager; import org.parceler.Parcels; import java.text.DateFormat; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import roboguice.inject.ContentView; import roboguice.inject.InjectView; import timber.log.Timber; /** * Displays all photos for one face. */ @ContentView(R.layout.activity_show_photos) public class ShowPhotosActivity extends AbstractActivity { public static final String EXTRA_FACE = "EXTRA_FACE"; private final DateFormat dateFormat = DateFormat.getDateInstance(); @InjectView(R.id.img_photo) private ImageView photoView; @InjectView(R.id.list_photos) private RecyclerView photosList; private PhotoAdapter photoAdapter; @Inject private PhotoManager photoManager; private PhotoInfo selectedPhoto; public ShowPhotosActivity() { super(true, false); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Face face = Parcels.unwrap(getIntent().getParcelableExtra(EXTRA_FACE)); // prep photos list photosList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); photoAdapter = new PhotoAdapter(); photosList.setAdapter(photoAdapter); // photosList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)); // get photos List<PhotoInfo> photos = photoManager.getPhotosForFace(face); if (!photos.isEmpty()) setSelectedPhoto(photos.get(0)); setupPhotos(photos); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_show_photos, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.delete: if (photoAdapter.getItemCount() == 0) return true; // ignore new AlertDialog.Builder(ShowPhotosActivity.this) .setTitle(R.string.delete_photo_title) .setMessage(R.string.delete_photo_msg) .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final PhotoInfo photoToDelete = selectedPhoto; // find closest photo to select List<PhotoInfo> photos = photoAdapter.getPhotos(); int idx = photos.indexOf(photoToDelete); photos.remove(idx); if (idx >= photos.size()) --idx; if (idx < 0) setSelectedPhoto(null); else setSelectedPhoto(photos.get(idx)); setupPhotos(photos); // actually delete photo photoManager.deletePhoto(photoToDelete); photoManager.requestPhotoSync(); } }) .setNegativeButton(android.R.string.cancel, null) .show(); return true; } return super.onOptionsItemSelected(item); } private void setupPhotos(List<PhotoInfo> photos) { Timber.d("loaded " + photos.size() + " photos"); int actionVisibility = photos.isEmpty() ? View.GONE : View.VISIBLE; photoAdapter.setPhotos(photos); } private void setSelectedPhoto(PhotoInfo photo) { if (photo != null) Timber.d("selecting " + photo.getPhotoFile().getAbsolutePath()); selectedPhoto = photo; if (photo == null) { photoView.setImageResource(android.R.color.transparent); setTitle(""); } else { Picasso.with(this).load(photo.getPhotoFile()).into(photoView); setTitle(dateFormat.format(photo.getCreationDate())); } } private class PhotoAdapter extends RecyclerView.Adapter<PhotoViewHolder> { private final List<PhotoInfo> photos = new ArrayList<>(); public void setPhotos(List<PhotoInfo> photos) { this.photos.clear(); this.photos.addAll(photos); notifyDataSetChanged(); } public List<PhotoInfo> getPhotos() { return new ArrayList<>(photos); } @Override public PhotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, parent, false); return new PhotoViewHolder(view); } @Override public void onBindViewHolder(PhotoViewHolder photoViewHolder, int position) { photoViewHolder.setPhoto(photos.get(position)); } @Override public int getItemCount() { return photos.size(); } } private class PhotoViewHolder extends RecyclerView.ViewHolder { private final ImageView photoView, photoRollView; public PhotoViewHolder(View itemView) { super(itemView); this.photoView = (ImageView) itemView.findViewById(R.id.img_photo); this.photoRollView = (ImageView) itemView.findViewById(R.id.img_photo_roll); } public void setPhoto(final PhotoInfo photo) { Picasso.with(ShowPhotosActivity.this).load(photo.getPhotoFile()).resizeDimen(R.dimen.photo_thumbnail_width, R.dimen.photo_thumbnail_height).centerCrop().into(photoView); photoView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setSelectedPhoto(photo); photoRollView.setImageResource(R.drawable.ic_movie_roll_overlay_selected); photoAdapter.notifyDataSetChanged(); } }); if (photo.equals(selectedPhoto)) photoRollView.setImageResource(R.drawable.ic_movie_roll_overlay_selected); else photoRollView.setImageResource(R.drawable.ic_movie_roll_overlay); } } }
gpl-3.0
MoriaDev/MinesOfMoria
app/src/main/java/com/temenoi/minesofmoria/items/weapon/missiles/Shuriken.java
1602
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.temenoi.minesofmoria.items.weapon.missiles; import com.temenoi.minesofmoria.items.Item; import com.temenoi.minesofmoria.sprites.ItemSpriteSheet; import com.temenoi.utils.Random; public class Shuriken extends MissileWeapon { { name = "shuriken"; image = ItemSpriteSheet.SHURIKEN; STR = 13; DLY = 0.5f; } public Shuriken() { this( 1 ); } public Shuriken( int number ) { super(); quantity = number; } @Override public int min() { return 2; } @Override public int max() { return 6; } @Override public String desc() { return "Star-shaped pieces of metal with razor-sharp blades do significant damage " + "when they hit a target. They can be thrown at very high rate."; } @Override public Item random() { quantity = Random.Int( 5, 15 ); return this; } @Override public int price() { return 15 * quantity; } }
gpl-3.0
epsilony/mf
src/main/java/net/epsilony/mf/model/influence/config/EnsureNodesNumConfig.java
3081
/* * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.epsilony.mf.model.influence.config; import net.epsilony.mf.model.influence.EnsureNodesNumInfluenceRadiusCalculator; import net.epsilony.mf.model.support_domain.SupportDomainSearcher; import net.epsilony.mf.model.support_domain.config.SupportDomainBaseConfig; import net.epsilony.mf.util.bus.WeakBus; import net.epsilony.mf.util.spring.ApplicationContextAwareImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Scope; /** * @author Man YUAN <epsilon@epsilony.net> * */ @Configuration @Import(InfluenceBaseConfig.class) public class EnsureNodesNumConfig extends ApplicationContextAwareImpl { public static final String ENSURE_NODES_NUM_INIT_RADIUS_BUS = "ensureNodesNumInitRadiusBus"; public static final String ENSURE_NODES_NUM_LOWER_BOUND_BUS = "ensureNodesLowerBoundBus"; @Bean(name = InfluenceBaseConfig.INFLUENCE_RADIUS_CALCULATOR_PROTO) @Scope("prototype") public EnsureNodesNumInfluenceRadiusCalculator influenceRadiusCalculatorPrototype() { return ensureNodesNumPrototype(); } @Bean(name = ENSURE_NODES_NUM_INIT_RADIUS_BUS) public WeakBus<Double> ensureNodesNumInitRadiusBus() { return new WeakBus<>(ENSURE_NODES_NUM_INIT_RADIUS_BUS); } @Bean(name = ENSURE_NODES_NUM_LOWER_BOUND_BUS) public WeakBus<Integer> ensureNodesNumLowerBoundBus() { return new WeakBus<>(ENSURE_NODES_NUM_LOWER_BOUND_BUS); } @Bean @Scope("prototype") public EnsureNodesNumInfluenceRadiusCalculator ensureNodesNumPrototype() { EnsureNodesNumInfluenceRadiusCalculator ensureNodesNum = new EnsureNodesNumInfluenceRadiusCalculator(); SupportDomainSearcher supportDomainSearcher = applicationContext.getBean( SupportDomainBaseConfig.SUPPORT_DOMAIN_SEARCHER_PROTO, SupportDomainSearcher.class); ensureNodesNum.setSupportDomainSearcher(supportDomainSearcher); ensureNodesNumInitRadiusBus().register(EnsureNodesNumInfluenceRadiusCalculator::setInitSearchRad, ensureNodesNum); ensureNodesNumLowerBoundBus().register(EnsureNodesNumInfluenceRadiusCalculator::setNodesNumLowerBound, ensureNodesNum); return ensureNodesNum; } }
gpl-3.0
se-esss-litterbox/linac-lego
LinacLegoV2WebApp/src/se/esss/litterbox/linaclego/v2/webapp/client/gskel/GskelStatusTextArea.java
1447
package se.esss.litterbox.linaclego.v2.webapp.client.gskel; import java.util.ArrayList; import java.util.Date; import com.google.gwt.user.client.ui.TextArea; public class GskelStatusTextArea extends TextArea { private int panelWidth = 285; private int panelHeight = 130; private ArrayList<String> statusList = new ArrayList<String>(); private int maxBufferSize = 100; public int getPanelWidth() {return panelWidth;} public int getPanelHeight() {return panelHeight;} public GskelStatusTextArea(int panelWidth, int panelHeight) { super(); this.panelWidth = panelWidth; this.panelHeight = panelHeight; setSize(panelWidth + "px", panelHeight+ "px"); } public void setSize(int panelWidth, int panelHeight) { this.panelWidth = panelWidth; this.panelHeight = panelHeight; setSize(panelWidth + "px", panelHeight+ "px"); } public void addStatus(String status) { statusList.add(0, new Date().toString() + ": " + status); int statusListSize = statusList.size(); while (statusListSize > maxBufferSize) { statusList.remove(statusListSize - 1); statusListSize = statusList.size(); } String text = ""; for (int ii = 0; ii < statusListSize; ++ii) { text = text + statusList.get(ii) + "\n"; } setText(text); } public int getBufferMaxSize() {return maxBufferSize;} public void setMaxBufferSize(int maxBufferSize) {this.maxBufferSize = maxBufferSize;} }
gpl-3.0
Lumaceon/ClockworkPhase2
src/main/java/lumaceon/mods/clockworkphase2/tile/temporal/TileTimezoneModulator.java
170
package lumaceon.mods.clockworkphase2.tile.temporal; import lumaceon.mods.clockworkphase2.tile.generic.TileMod; public class TileTimezoneModulator extends TileMod { }
gpl-3.0
qbicsoftware/qnavigator
QBiCMainPortlet/src/model/notes/Notes.java
3068
/******************************************************************************* * QBiC Project qNavigator enables users to manage their projects. * Copyright (C) "2016” Christopher Mohr, David Wojnar, Andreas Friedrich * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-147 // 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.06.25 at 04:13:23 PM CEST // package model.notes; 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; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{}note" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "note" }) @XmlRootElement(name = "notes") public class Notes { @XmlElement(required = true) protected List<Note> note; /** * Gets the value of the note 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 note property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNote().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Note } * * */ public List<Note> getNote() { if (note == null) { note = new ArrayList<Note>(); } return this.note; } }
gpl-3.0
norris-zhang/venus
parent/dao/src/main/java/com/xinxilanr/venus/dao/PictureDao.java
120
/** * */ package com.xinxilanr.venus.dao; /** * @author norris * */ public interface PictureDao extends Dao { }
gpl-3.0
biafra23/mapsforge
src/org/mapsforge/android/maps/CircleContainer.java
1003
/* * Copyright 2010 mapsforge.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mapsforge.android.maps; class CircleContainer extends ShapeContainer { final float radius; final float x; final float y; CircleContainer(float x, float y, float radius) { this.x = x; this.y = y; this.radius = radius; } @Override ShapeType getShapeType() { return ShapeType.CIRCLE; } }
gpl-3.0
redsoftbiz/executequery
src/org/executequery/gui/SystemPropertiesDockedTab.java
3002
/* * SystemPropertiesDockedTab.java * * Copyright (C) 2002-2017 Takis Diakoumis * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.executequery.gui; import org.underworldlabs.swing.HeapMemoryPanel; import javax.swing.*; import java.awt.*; /** * System properties docked component. * * @author Takis Diakoumis */ public class SystemPropertiesDockedTab extends AbstractDockedTabActionPanel { public static final String TITLE = "System Properties"; /** * the system properties panel */ private SystemPropertiesPanel propertiesPanel; /** * the heap resources panel */ private HeapMemoryPanel resourcesPanel; /** * Creates a new instance of SystemPropertiesDockedTab */ public SystemPropertiesDockedTab() { super(new BorderLayout()); init(); } private void init() { propertiesPanel = new SystemPropertiesPanel(); resourcesPanel = new HeapMemoryPanel(); JTabbedPane tabs = new JTabbedPane(); tabs.add("System", propertiesPanel); tabs.add("Resources", resourcesPanel); add(tabs, BorderLayout.CENTER); } /** * Override to clean up the mem thread. */ public boolean tabViewClosing() { resourcesPanel.stopTimer(); return true; } /** * Override to make sure the timer has started. */ public boolean tabViewSelected() { propertiesPanel.reload(); resourcesPanel.startTimer(); return true; } // ---------------------------------------- // DockedTabView Implementation // ---------------------------------------- public static final String MENU_ITEM_KEY = "viewSystemProperties"; public static final String PROPERTY_KEY = "system.display.systemprops"; /** * Returns the display title for this view. * * @return the title displayed for this view */ public String getTitle() { return TITLE; } /** * Returns the name defining the property name for this docked tab view. * * @return the key */ public String getPropertyKey() { return PROPERTY_KEY; } /** * Returns the name defining the menu cache property * for this docked tab view. * * @return the preferences key */ public String getMenuItemKey() { return MENU_ITEM_KEY; } }
gpl-3.0
Power-Switch/PowerSwitch_Android
Smartphone/src/androidTest/java/eu/power_switch/obj/device/elro/AB440ID_Test.java
6877
/* * PowerSwitch by Max Rosin & Markus Ressel * Copyright (C) 2015 Markus Ressel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.power_switch.obj.device.elro; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Method; import java.util.LinkedList; import eu.power_switch.R; import eu.power_switch.obj.ReceiverTest; import eu.power_switch.obj.receiver.device.elro.AB440ID; /** * Created by Markus on 08.08.2015. */ public class AB440ID_Test extends ReceiverTest { private static AB440ID receiver; @Test public void testCodeGeneration00000000() throws Exception { LinkedList<Boolean> dips = new LinkedList<>(); dips.add(false); // 1 dips.add(false); // 2 dips.add(false); // 3 dips.add(false); // 4 dips.add(false); // 5 dips.add(false); // 6 dips.add(false); // 7 dips.add(false); // 8 receiver = new AB440ID(getContext(), (long) 0, "Name", dips, (long) 0); Method method = receiver.getClass().getDeclaredMethod("getSignal", argClassesGetSignal); method.setAccessible(true); Object[] argObjects = new Object[]{connAir, getContext().getString(R.string.on)}; String generatedMessage = (String) method.invoke(receiver, argObjects); // ON String expectedMessage = "TXP:0,0,10,5600,350,25,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,1,3,1,3,3,1,1,14;"; Assert.assertEquals(expectedMessage, generatedMessage); argObjects = new Object[]{connAir, getContext().getString(R.string.off)}; generatedMessage = (String) method.invoke(receiver, argObjects); // OFF expectedMessage = "TXP:0,0,10,5600,350,25,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,1,3,1,14;"; Assert.assertEquals(expectedMessage, generatedMessage); } @Test public void testCodeGeneration10000000() throws Exception { LinkedList<Boolean> dips = new LinkedList<>(); dips.add(true); // 1 dips.add(false); // 2 dips.add(false); // 3 dips.add(false); // 4 dips.add(false); // 5 dips.add(false); // 6 dips.add(false); // 7 dips.add(false); // 8 receiver = new AB440ID(getContext(), (long) 0, "Name", dips, (long) 0); String methodName = "getSignal"; Method method = receiver.getClass().getDeclaredMethod(methodName, argClassesGetSignal); method.setAccessible(true); Object[] argObjects = new Object[]{connAir, getContext().getString(R.string.on)}; String generatedMessage = (String) method.invoke(receiver, argObjects); // ON String expectedMessage = "TXP:0,0,10,5600,350,25,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,1,3,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,1,3,1,3,3,1,1,14;"; Assert.assertEquals(expectedMessage, generatedMessage); argObjects = new Object[]{connAir, getContext().getString(R.string.off)}; generatedMessage = (String) method.invoke(receiver, argObjects); // OFF expectedMessage = "TXP:0,0,10,5600,350,25,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,1,3,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,1,3,1,14;"; Assert.assertEquals(expectedMessage, generatedMessage); } @Test public void testCodeGeneration10000100() throws Exception { LinkedList<Boolean> dips = new LinkedList<>(); dips.add(true); // 1 dips.add(false); // 2 dips.add(false); // 3 dips.add(false); // 4 dips.add(false); // 5 dips.add(true); // 6 dips.add(false); // 7 dips.add(false); // 8 receiver = new AB440ID(getContext(), (long) 0, "Name", dips, (long) 0); String methodName = "getSignal"; Method method = receiver.getClass().getDeclaredMethod(methodName, argClassesGetSignal); method.setAccessible(true); Object[] argObjects = new Object[]{connAir, getContext().getString(R.string.on)}; String generatedMessage = (String) method.invoke(receiver, argObjects); // ON String expectedMessage = "TXP:0,0,10,5600,350,25,1,3,1,3,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,1,3,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,1,3,1,3,3,1,1,14;"; Assert.assertEquals(expectedMessage, generatedMessage); argObjects = new Object[]{connAir, getContext().getString(R.string.off)}; generatedMessage = (String) method.invoke(receiver, argObjects); // OFF expectedMessage = "TXP:0,0,10,5600,350,25,1,3,1,3,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,1,3,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,1,3,1,14;"; Assert.assertEquals(expectedMessage, generatedMessage); } @Test public void testCodeGeneration11111111() throws Exception { LinkedList<Boolean> dips = new LinkedList<>(); dips.add(true); // 1 dips.add(true); // 2 dips.add(true); // 3 dips.add(true); // 4 dips.add(true); // 5 dips.add(true); // 6 dips.add(true); // 7 dips.add(true); // 8 receiver = new AB440ID(getContext(), (long) 0, "Name", dips, (long) 0); String methodName = "getSignal"; Method method = receiver.getClass().getDeclaredMethod(methodName, argClassesGetSignal); method.setAccessible(true); Object[] argObjects = new Object[]{connAir, getContext().getString(R.string.on)}; String generatedMessage = (String) method.invoke(receiver, argObjects); // ON String expectedMessage = "TXP:0,0,10,5600,350,25,1,3,1,3,1,3,1,3,1,3,1,3,1,3,3,1,1,3,3,1,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,3,1,1,14;"; Assert.assertEquals(expectedMessage, generatedMessage); argObjects = new Object[]{connAir, getContext().getString(R.string.off)}; generatedMessage = (String) method.invoke(receiver, argObjects); // OFF expectedMessage = "TXP:0,0,10,5600,350,25,1,3,1,3,1,3,1,3,1,3,1,3,1,3,3,1,1,3,3,1,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,3,1,1,3,1,3,1,14;"; Assert.assertEquals(expectedMessage, generatedMessage); } }
gpl-3.0
TKlerx/JSAT
JSAT/src/jsat/utils/GridDataGenerator.java
5548
package jsat.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import jsat.SimpleDataSet; import jsat.classifiers.CategoricalData; import jsat.classifiers.DataPoint; import jsat.distributions.Distribution; import jsat.distributions.Uniform; import jsat.linear.DenseVector; /** * This is a utility to generate data in a grid fashion. * Each data point will belong to a different class. By default, * the data is generated such that the classes are trivially separable. * <br><br> * All data points belong to a specific axis, and have noises added to them. * For example, a 1 dimensional grid with 2 classes would have data points * of the form 0+noise, and 1+noise. So long as the noise is less than 0.5, * the data can be easily separated. * * @author Edward Raff */ public class GridDataGenerator { private Distribution noiseSource; private int[] dimensions; private Random rand; private CategoricalData[] catDataInfo; /** * Creates a new Grid data generator, that can be queried for new data sets. * * @param noiseSource the distribution that describes the noise that will be added to each data point. If no noise is used, each data point would lie exactly on its local axis. * @param rand the source of randomness that the noise will use * @param dimensions an array describing how many groups there will be. * The length of the array dictates the number of dimensions in the data * set, each value describes how many axis of that dimensions to use. The * total number of classes is the product of these values. * * @throws ArithmeticException if one of the dimension values is not a positive value, or a zero number of dimensions is given */ public GridDataGenerator(Distribution noiseSource, Random rand, int... dimensions) { this.noiseSource = noiseSource; this.rand = rand; this.dimensions = dimensions; for(int i = 0; i < dimensions.length; i++) if(dimensions[i] <= 0) throw new ArithmeticException("The " + i + "'th dimensino contains the non positive value " + dimensions[i]); } /** * Creates a new Grid data generator, that can be queried for new data sets. * * @param noiseSource the distribution that describes the noise that will be added to each data point. If no noise is used, each data point would lie exactly on its local axis. * @param dimensions an array describing how many groups there will be. * The length of the array dictates the number of dimensions in the data * set, each value describes how many axis of that dimensions to use. The * total number of classes is the product of these values. * * @throws ArithmeticException if one of the dimension values is not a positive value, or a zero number of dimensions is given */ public GridDataGenerator(Distribution noiseSource, int... dimensions) { this(noiseSource, new Random(), dimensions); } /** * Creates a new grid data generator for a 2 x 5 with uniform noise in the range [-1/4, 1/4] */ public GridDataGenerator() { this(new Uniform(-0.25, 0.25), new Random(), 2, 5); } /** * Helper function * @param curClass used as a pointer to an integer so that we dont have to add class tracking logic * @param curDim the current dimension to split on. If we are at the last dimension, we add data points instead. * @param samples the number of samples to take for each class * @param dataPoints the location to put the data points in * @param dim the array specifying the current point we are working from. */ private void addSamples(int[] curClass, int curDim, int samples, List<DataPoint> dataPoints, int[] dim) { if(curDim < dimensions.length-1) for(int i = 0; i < dimensions[curDim+1]; i++ ) { int[] nextDim = Arrays.copyOf(dim, dim.length); nextDim[curDim+1] = i; addSamples(curClass, curDim+1, samples, dataPoints, nextDim); } else//Add data points! { for(int i = 0; i < samples; i++) { DenseVector dv = new DenseVector(dim.length); for(int j = 0; j < dim.length; j++) dv.set(j, dim[j]+noiseSource.invCdf(rand.nextDouble())); dataPoints.add(new DataPoint(dv, new int[]{ curClass[0] }, catDataInfo)); } curClass[0]++; } } /** * Generates a new data set. * * @param samples the number of sample data points to create for each class in the data set. * @return A data set the contains the data points with matching class labels. */ public SimpleDataSet generateData(int samples) { int totalClasses = 1; for(int d : dimensions) totalClasses *= d; catDataInfo = new CategoricalData[] { new CategoricalData(totalClasses) } ; List<DataPoint> dataPoints = new ArrayList<DataPoint>(totalClasses*samples); int[] curClassPointer = new int[1]; for(int i = 0; i < dimensions[0]; i++) { int[] curDim = new int[dimensions.length]; curDim[0] = i; addSamples(curClassPointer, 0, samples, dataPoints, curDim); } return new SimpleDataSet(dataPoints); } }
gpl-3.0
OWASP-Ruhrpott/owasp-workshop-android-pentest
Vuln_app_1/app/src/main/java/ruhrpott/owasp/com/vuln_app_1/challenges/LogcatOutput.java
1569
package ruhrpott.owasp.com.vuln_app_1.challenges; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.util.Log; import android.widget.TextView; import org.w3c.dom.Text; import java.util.UUID; import ruhrpott.owasp.com.vuln_app_1.R; public class LogcatOutput extends Fragment{ public static LogcatOutput newInstance() { LogcatOutput fragment = new LogcatOutput(); return fragment; } public LogcatOutput() { } Button ClickMe; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_logcat_output, container, false); ClickMe = (Button) rootView.findViewById(R.id.button); ClickMe.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { doLogcat(); TextView tv = (TextView) rootView.findViewById(R.id.textView_result); tv.setText(getString(R.string.challenge_logcat_output_status)); } }); return rootView; } public void doLogcat (){ for(int i =0;i<1000;i++) { Log.w("owasp", UUID.randomUUID().toString()); if(i == 593) { Log.w("owasp-key", "You learned to filter logcat :)"); } } } }
gpl-3.0
ogarcia/opensudoku
app/src/main/java/org/moire/opensudoku/gui/importing/ExtrasImportTask.java
862
package org.moire.opensudoku.gui.importing; import org.moire.opensudoku.db.SudokuInvalidFormatException; /** * Handles import of puzzles via intent's extras. * * @author romario */ public class ExtrasImportTask extends AbstractImportTask { private String mFolderName; private String mGames; private boolean mAppendToFolder; public ExtrasImportTask(String folderName, String games, boolean appendToFolder) { mFolderName = folderName; mGames = games; mAppendToFolder = appendToFolder; } @Override protected void processImport() throws SudokuInvalidFormatException { if (mAppendToFolder) { appendToFolder(mFolderName); } else { importFolder(mFolderName); } for (String game : mGames.split("\n")) { importGame(game); } } }
gpl-3.0
iFixit/iFixitAndroid
App/src/com/dozuki/ifixit/ui/topic/TopicRelatedWikisFragment.java
2283
package com.dozuki.ifixit.ui.topic; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.dozuki.ifixit.R; import com.dozuki.ifixit.model.guide.GuideInfo; import com.dozuki.ifixit.model.topic.TopicLeaf; import com.dozuki.ifixit.ui.BaseFragment; import com.dozuki.ifixit.ui.EndlessRecyclerViewScrollListener; import com.dozuki.ifixit.ui.GuideListRecyclerAdapter; import com.dozuki.ifixit.ui.WikiListRecyclerAdapter; import java.util.ArrayList; public class TopicRelatedWikisFragment extends BaseFragment { private static final int LIMIT = 20; private static final int OFFSET = 0; protected static final String SAVED_TOPIC = "SAVED_TOPIC"; public static final String TOPIC_LEAF_KEY = "TOPIC_LEAF_KEY"; private TopicLeaf mTopicLeaf; private RecyclerView mRecycleView; private GridLayoutManager mLayoutManager; private EndlessRecyclerViewScrollListener mScrollListener; private WikiListRecyclerAdapter mRecycleAdapter; /** * Required for restoring fragments */ public TopicRelatedWikisFragment() {} @Override public void onCreate(Bundle savedState) { super.onCreate(savedState); mTopicLeaf = (TopicLeaf)this.getArguments().getSerializable(TOPIC_LEAF_KEY); if (savedState != null && mTopicLeaf == null) { mTopicLeaf = (TopicLeaf)savedState.getSerializable(SAVED_TOPIC); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.topic_wiki_list, container, false); mRecycleView = (RecyclerView)view.findViewById(R.id.topic_wiki_grid); mLayoutManager = new GridLayoutManager(inflater.getContext(), 1); mRecycleView.setLayoutManager(mLayoutManager); mRecycleAdapter = new WikiListRecyclerAdapter(getContext(), mTopicLeaf.getRelatedWikis(), false); mRecycleView.setAdapter(mRecycleAdapter); return view; } @Override public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putSerializable(SAVED_TOPIC, mTopicLeaf); } }
gpl-3.0
cerndb/metrics-monitor
src/main/java/ch/cern/exdemon/monitor/analysis/types/htm/HTMParameters.java
4168
package ch.cern.exdemon.monitor.analysis.types.htm; import static org.numenta.nupic.algorithms.Anomaly.KEY_ESTIMATION_SAMPLES; import static org.numenta.nupic.algorithms.Anomaly.KEY_LEARNING_PERIOD; import java.util.HashMap; import java.util.Map; import org.numenta.nupic.Parameters; import org.numenta.nupic.Parameters.KEY; import org.numenta.nupic.model.Persistable; import org.numenta.nupic.util.Tuple; public class HTMParameters implements Persistable{ private static final long serialVersionUID = 4118240112485895557L; public static final String TIMESTAMP_FORMAT = "YYYY-MM-dd'T'HH:mm:ssZ"; private Parameters p; public void setModelParameters(float minValue, float maxValue, boolean timeOfDay, boolean dateOfWeek, boolean isWeekend) { Map<String, Map<String, Object>> fieldEncodings = setupEncoderMap( null, 0, // n 0, // w 0, 0, 0, 0, null, null, null, "timestamp", "datetime", "DateEncoder"); fieldEncodings = setupEncoderMap( fieldEncodings, 50, 21, minValue, maxValue, 0, 0.1, null, Boolean.TRUE, null, "value", "float", "ScalarEncoder"); if(timeOfDay) fieldEncodings.get("timestamp").put(KEY.DATEFIELD_TOFD.getFieldName(), new Tuple(21,9.5)); if(dateOfWeek) fieldEncodings.get("timestamp").put(KEY.DATEFIELD_DOFW.getFieldName(), new Tuple(21,9.5)); if(isWeekend) fieldEncodings.get("timestamp").put(KEY.DATEFIELD_WKEND.getFieldName(), new Tuple(21,9.5)); fieldEncodings.get("timestamp").put(KEY.DATEFIELD_PATTERN.getFieldName(), TIMESTAMP_FORMAT); //p = Parameters.getEncoderDefaultParameters(); p = Parameters.getAllDefaultParameters(); p.set(KEY.GLOBAL_INHIBITION, true); p.set(KEY.COLUMN_DIMENSIONS, new int[] { 2048 }); p.set(KEY.INPUT_DIMENSIONS, new int[] { 2048 }); p.set(KEY.CELLS_PER_COLUMN, 32); p.set(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 40.0); p.set(KEY.POTENTIAL_PCT, 0.85); p.set(KEY.SYN_PERM_CONNECTED,0.2); p.set(KEY.SYN_PERM_ACTIVE_INC, 0.003); p.set(KEY.SYN_PERM_INACTIVE_DEC, 0.0005); p.set(KEY.MAX_BOOST, 1.0); p.set(KEY.MAX_NEW_SYNAPSE_COUNT, 20); p.set(KEY.INITIAL_PERMANENCE, 0.21); p.set(KEY.PERMANENCE_INCREMENT, 0.04); p.set(KEY.PERMANENCE_DECREMENT, 0.008); p.set(KEY.MIN_THRESHOLD, 13); p.set(KEY.ACTIVATION_THRESHOLD, 20); p.set(KEY.CLIP_INPUT, true); p.set(KEY.FIELD_ENCODING_MAP, fieldEncodings); } public Parameters getParameters() { return p; } public static Map<String, Map<String, Object>> setupEncoderMap( Map<String, Map<String, Object>> map, int n, int w, double min, double max, double radius, double resolution, Boolean periodic, Boolean clip, Boolean forced, String fieldName, String fieldType, String encoderType) { if(map == null) { map = new HashMap<String, Map<String, Object>>(); } Map<String, Object> inner = null; if((inner = map.get(fieldName)) == null) { map.put(fieldName, inner = new HashMap<String, Object>()); } inner.put("n", n); inner.put("w", w); inner.put("minVal", min); inner.put("maxVal", max); inner.put("radius", radius); inner.put("resolution", resolution); if(periodic != null) inner.put("periodic", periodic); if(clip != null) inner.put("clipInput", clip); if(forced != null) inner.put("forced", forced); if(fieldName != null) inner.put("fieldName", fieldName); if(fieldType != null) inner.put("fieldType", fieldType); if(encoderType != null) inner.put("encoderType", encoderType); return map; } public static Map<String, Object> getAnomalyLikelihoodParams(){ Map<String, Object> p = new HashMap<>(); p.put(KEY_LEARNING_PERIOD, 100); p.put(KEY_ESTIMATION_SAMPLES, 100); return p; } }
gpl-3.0
dr-jts/jeql
modules/jeql/src/main/java/jeql/syntax/CaseNode.java
2313
package jeql.syntax; import java.util.List; import jeql.engine.Scope; import jeql.util.TypeUtil; import org.locationtech.jts.util.Assert; public class CaseNode extends ParseTreeNode { // A non-null valueExpr indicates a simple case expression private ParseTreeNode valueExpr; private ParseTreeNode[] whenExpr; private ParseTreeNode[] thenExpr; private ParseTreeNode elseExpr; private int nCases = 0; public CaseNode(ParseTreeNode valueExpr, List caseList, ParseTreeNode elseExpr) { this.valueExpr = valueExpr; this.elseExpr = elseExpr; Assert.isTrue(caseList.size() > 0); Assert.isTrue(caseList.size() % 2 == 0); nCases = caseList.size() / 2; whenExpr = new ParseTreeNode[nCases]; thenExpr = new ParseTreeNode[nCases]; for (int i = 0; i < nCases; i++) { int caseIndex = 2 * i; whenExpr[i] = (ParseTreeNode) caseList.get(caseIndex); thenExpr[i] = (ParseTreeNode) caseList.get(caseIndex + 1); } } public Class getType(Scope scope) { return thenExpr[0].getType(scope); } public void bind(Scope scope) { if (valueExpr != null) valueExpr.bind(scope); for (int i = 0; i < whenExpr.length; i++) { whenExpr[i].bind(scope); thenExpr[i].bind(scope); } if (elseExpr != null) elseExpr.bind(scope); } public Object eval(Scope scope) { if (valueExpr != null) return evalSimple(scope); return evalSearched(scope); } public Object evalSimple(Scope scope) { Object value = valueExpr.eval(scope); if (value == null) return null; for (int i = 0; i < whenExpr.length; i++) { Object whenVal = whenExpr[i].eval(scope); if (whenVal == null) continue; if (TypeUtil.compareValue(value, whenVal) == 0) { return thenExpr[i].eval(scope); } } if (elseExpr != null) { return elseExpr.eval(scope); } return null; } public Object evalSearched(Scope scope) { for (int i = 0; i < whenExpr.length; i++) { Boolean whenVal = (Boolean) whenExpr[i].eval(scope); if (whenVal == null) continue; if (whenVal.booleanValue()) return thenExpr[i].eval(scope); } if (elseExpr != null) { return elseExpr.eval(scope); } return null; } }
gpl-3.0
Booksonic-Server/madsonic-main
src/main/java/org/madsonic/domain/VideoTranscodingSettings.java
1893
/* This file is part of Madsonic. Madsonic is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Madsonic is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Madsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2009-2016 (C) Sindre Mehus, Martin Karel */ package org.madsonic.domain; /** * Parameters used when transcoding videos. * * @author Sindre Mehus, Martin Karel */ public class VideoTranscodingSettings { private final int width; private final int height; private final int timeOffset; private final int duration; private final boolean hls; private final boolean dash; private final Integer audioTrack; public VideoTranscodingSettings(int width, int height, int timeOffset, int duration, boolean hls, boolean dash, Integer audioTrack) { this.width = width; this.height = height; this.timeOffset = timeOffset; this.duration = duration; this.hls = hls; this.dash = dash; this.audioTrack = audioTrack; } public int getWidth() { return width; } public int getHeight() { return height; } public int getTimeOffset() { return timeOffset; } public int getDuration() { return duration; } public boolean isHls() { return hls; } public boolean isDash() { return dash; } public Integer getAudioTrack() { return audioTrack; } }
gpl-3.0
Emudofus/d2j
src/org/d2j/game/game/statistics/IStatistics.java
548
package org.d2j.game.game.statistics; /** * User: Blackrush * Date: 12/11/11 * Time: 10:43 * IDE : IntelliJ IDEA */ public interface IStatistics { ICharacteristic get(CharacteristicType type); short getLife(); void setLife(short life); void setLifeByPercent(int percent); short addLife(short life); short getMaxLife(); short getUsedPods(); short getMaxPods(); IStatistics reset(); IStatistics resetContext(); IStatistics resetEquipments(); IStatistics refresh(); IStatistics copy(); }
gpl-3.0
Alex20132013/SISBIESEAPIIS
src/java/Controlador/prueba.java
3363
package Controlador; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author EAPIIS-Biblioteca */ @WebServlet(name = "prueba", urlPatterns = {"/prueba"}) public class prueba extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); ServletOutputStream out = response.getOutputStream(); ServletOutputStream soutImage = response.getOutputStream(); try { HttpSession hsPrintDewey=request.getSession(true); List<Object[]> linsertTemp=null; // List<Object[]> linsertTemp=null; if (hsPrintDewey.getAttribute("Dewey_barrra")!=null ) { linsertTemp=(ArrayList<Object[]>)hsPrintDewey.getAttribute("Dewey_barrra"); } for (int i = 0; i < linsertTemp.size(); i++) { Object[] objects = linsertTemp.get(i); out.println(objects[0].toString()); out.println(objects[1].toString()); out.println(objects[2].toString()); out.println(objects[3].toString()); out.println("<br/>"); } } catch (Exception ex) { soutImage.println("ERROR!:"+ex.getLocalizedMessage()); } finally { soutImage.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
gpl-3.0
CloudLandGame/CloudLand-Server
src/main/java/org/dragonet/cloudland/server/network/handler/ClientRemoveBlockHandler.java
600
package org.dragonet.cloudland.server.network.handler; import org.dragonet.cloudland.net.protocol.Map; import org.dragonet.cloudland.server.network.Session; import org.dragonet.cloudland.server.network.protocol.CLMessageHandler; /** * Created on 2017/1/18. */ public class ClientRemoveBlockHandler implements CLMessageHandler<Map.ClientRemoveBlockMessage> { @Override public void handle(Session session, Map.ClientRemoveBlockMessage message) { if(!session.isAuthenticated()) return; session.getPlayer().endBreaking(message.getX(), message.getY(), message.getZ()); } }
gpl-3.0
EboMike/EboLogger
ebologger-ui/src/com/ebomike/ebologger/client/ui/TimelineTooltip.java
2472
package com.ebomike.ebologger.client.ui; import com.ebomike.ebologger.client.model.LogMsg; import com.ebomike.ebologger.client.transport.Connection; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.ListView; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class TimelineTooltip implements Initializable { private Parent root; @FXML private ListView loglist; private ObservableList<LogMsg> logs = FXCollections.observableArrayList(); public Node getRoot() { return root; } public static TimelineTooltip create(Application application, Connection connection) { try { FXMLLoader loader = new FXMLLoader( application.getClass().getResource( "ui/popup.fxml" ) ); Parent root = loader.load(); TimelineTooltip controller = loader.getController(); root.setOpacity(0.9); controller.root = root; // root.addEventFilter(MouseEvent.MOUSE_MOVED, controller::onMouseMove); return controller; } catch (IOException ex) { throw new RuntimeException(ex); } } public void setContents(Timeline.RenderBucket renderBucket) { logs.clear(); int maxItems = 15; for (LogMsg msg : renderBucket.getLogs()) { logs.add(msg); } } public void move(double x, double y) { // double w = root.getBoundsInParent().getWidth(); // double h = root.getBoundsInParent().getHeight(); double w = loglist.getWidth(); double h = loglist.getHeight(); System.out.println("Move: " + x + "/" + y + ", dim=" + w + "/" + h); System.out.println("layoutY=" + root.getLayoutY() + ", boundsMinY=" + root.getLayoutBounds().getMinY()); root.setTranslateX(x - w / 2.0); root.setTranslateY(y - h / 2.0); } @Override public void initialize(URL location, ResourceBundle resources) { loglist.setItems(logs); } }
gpl-3.0
ustits/ColleagueBot
core/src/main/java/ru/ustits/colleague/repositories/records/IgnoreTriggerRecord.java
690
package ru.ustits.colleague.repositories.records; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.Value; import javax.persistence.*; /** * @author ustits */ @Entity @Table(name = "ignore_triggers") @Value @AllArgsConstructor @NoArgsConstructor(access = AccessLevel.PRIVATE, force = true) public final class IgnoreTriggerRecord { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "chat_id") private Long chatId; @Column(name = "user_id") private Long userId; public IgnoreTriggerRecord(final Long chatId, final Long userId) { this(null, chatId, userId); } }
gpl-3.0
edmundoa/graylog2-server
graylog2-server/src/main/java/org/graylog2/rest/resources/tools/GrokTesterResource.java
4213
/** * This file is part of Graylog. * * Graylog is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Graylog is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog2.rest.resources.tools; import com.codahale.metrics.annotation.Timed; import com.google.common.collect.Lists; import oi.thekraken.grok.api.Grok; import oi.thekraken.grok.api.Match; import oi.thekraken.grok.api.exception.GrokException; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.graylog2.audit.jersey.NoAuditEvent; import org.graylog2.grok.GrokPattern; import org.graylog2.grok.GrokPatternService; import org.graylog2.rest.models.tools.requests.GrokTestRequest; import org.graylog2.rest.resources.tools.responses.GrokTesterResponse; import org.graylog2.shared.rest.resources.RestResource; import javax.inject.Inject; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @RequiresAuthentication @Path("/tools/grok_tester") @Produces(MediaType.APPLICATION_JSON) public class GrokTesterResource extends RestResource { private final GrokPatternService grokPatternService; @Inject public GrokTesterResource(GrokPatternService grokPatternService) { this.grokPatternService = grokPatternService; } @GET @Timed public GrokTesterResponse grokTest(@QueryParam("pattern") @NotEmpty String pattern, @QueryParam("string") @NotNull String string, @QueryParam("named_captures_only") @NotNull boolean namedCapturesOnly) throws GrokException { return doTestGrok(string, pattern, namedCapturesOnly); } @POST @Timed @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @NoAuditEvent("only used to test Grok patterns") public GrokTesterResponse testGrok(@Valid @NotNull GrokTestRequest grokTestRequest) throws GrokException { return doTestGrok(grokTestRequest.string(), grokTestRequest.pattern(), grokTestRequest.namedCapturesOnly()); } private GrokTesterResponse doTestGrok(String string, String pattern, boolean namedCapturesOnly) throws GrokException { final Set<GrokPattern> grokPatterns = grokPatternService.loadAll(); final Grok grok = new Grok(); for (GrokPattern grokPattern : grokPatterns) { grok.addPattern(grokPattern.name(), grokPattern.pattern()); } grok.compile(pattern, namedCapturesOnly); final Match match = grok.match(string); match.captures(); final Map<String, Object> matches = match.toMap(); final GrokTesterResponse response; if (matches.isEmpty()) { response = GrokTesterResponse.create(false, Collections.<GrokTesterResponse.Match>emptyList(), pattern, string); } else { final List<GrokTesterResponse.Match> responseMatches = Lists.newArrayList(); for (final Map.Entry<String, Object> entry : matches.entrySet()) { final Object value = entry.getValue(); if (value != null) { responseMatches.add(GrokTesterResponse.Match.create(entry.getKey(), value.toString())); } } response = GrokTesterResponse.create(true, responseMatches, pattern, string); } return response; } }
gpl-3.0
magneticflux-/Java-NEAT
src/main/java/org/javaneat/evolution/nsgaii/mutators/NEATEnableGeneMutator.java
1214
package org.javaneat.evolution.nsgaii.mutators; import org.javaneat.genome.ConnectionGene; import org.javaneat.genome.NEATGenome; import org.jnsgaii.operators.Mutator; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; /** * Created by Mitchell Skaggs on 3/24/2016. * <p> * DO NOT USE! Breaks NEAT because splitting nodes relies on connections staying disabled * Nevermind lol */ public class NEATEnableGeneMutator extends Mutator<NEATGenome> { @Override public String[] getAspectDescriptions() { return new String[]{"Enable Gene Mutation Strength", "Enable Gene Mutation Probability"}; } @SuppressWarnings("AssignmentToMethodParameter") @Override protected NEATGenome mutate(NEATGenome object, double mutationStrength, double mutationProbability) { NEATGenome newObject = object.copy(); List<ConnectionGene> validGenes = newObject.getConnectionGeneList().stream().filter(gene -> !gene.getEnabled()).collect(Collectors.toList()); if (validGenes.size() > 0) validGenes.get(ThreadLocalRandom.current().nextInt(validGenes.size())).setEnabled(true); return newObject; } }
gpl-3.0
ZargorNET/QuickBedwars
src/main/java/de/zargornet/qbw/commands/worldmanagement/SetTeamBed.java
2272
package de.zargornet.qbw.commands.worldmanagement; import de.zargornet.qbw.Qbw; import de.zargornet.qbw.commands.IQbwCommand; import de.zargornet.qbw.commands.QbwCommandPath; import de.zargornet.qbw.commands.QbwCommandUtil; import de.zargornet.qbw.game.QbwLocation; import de.zargornet.qbw.game.worlds.QbwTeam; import de.zargornet.qbw.game.worlds.QbwWorld; import de.zargornet.qbw.game.worlds.TeamColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Set; /** * Set a team's bed */ @QbwCommandPath( path = "setteambed", permission = "qbw.setteambed" ) public class SetTeamBed implements IQbwCommand { @Override public void onCommand(CommandSender sender, Command cmd, String[] args) { if (args.length != 2) { sender.sendMessage(Qbw.getInstance().getPrefix() + "§cPlease use: §e/QBW setteambed <World name> <Team color>"); return; } if (!QbwCommandUtil.senderIsPlayer(sender)) { return; } QbwWorld world = Qbw.getInstance().getDatabaseQueries().getWorld(args[0]); if (!QbwCommandUtil.worldAdded(sender, world)) { return; } if (QbwCommandUtil.getTeamColorIfValid(sender, args[1]) == null) { return; } if (!QbwCommandUtil.isTeamAdded(sender, world, args[1])) { return; } if (!QbwCommandUtil.checkIfWorldIsNotUsed(sender, args[0])) { return; } Player p = (Player) sender; if (p.getTargetBlock((Set<Material>) null, 5).getType() != Material.BED_BLOCK) { sender.sendMessage(Qbw.getInstance().getPrefix() + "§cBlock where you're looking at isn't a bed"); return; } QbwTeam team = world.getTeams().stream().filter(team1 -> team1.getColor() == TeamColor.valueOf(args[1].toUpperCase())).findFirst().get(); team.setTeamBedLoc(new QbwLocation(p.getTargetBlock((Set<Material>) null, 5).getLocation())); Qbw.getInstance().getDatabaseQueries().setWorld(world); sender.sendMessage(Qbw.getInstance().getPrefix() + "§aSuccess setted bed location on your looking location!"); } }
gpl-3.0
ursfassler/rizzly
src/metadata/parser/Scanner.java
3837
/** * This file is part of Rizzly. * * Rizzly is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Rizzly is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Rizzly. If not, see <http://www.gnu.org/licenses/>. */ package metadata.parser; import parser.PeekReader; import ast.meta.MetaList; import ast.meta.MetaListImplementation; import ast.meta.SourcePosition; import error.ErrorType; import error.RError; /** * * @author urs */ public class Scanner implements PeekReader<Token> { private MetadataReader reader; private Token next; public Scanner(MetadataReader reader) { this.reader = reader; next(); } private Token token(TokenType value, MetaList info) { return new Token(value, info); } private Token token(TokenType value, String id, MetaList info) { return new Token(value, id, info); } @Override public boolean hasNext() { return peek() != null; } @Override public Token peek() { return next; } private Token specialToken(TokenType value) { MetaList meta = new MetaListImplementation(); meta.add(new SourcePosition("", 0, 0)); // FIXME use correct filename return new Token(value, meta); } @Override public Token next() { Token res = next; do { if (!reader.hasNext()) { next = specialToken(TokenType.EOF); break; } next = getNext(); } while (next.getType() == TokenType.IGNORE); return res; } private Token getNext() { if (!reader.hasNext()) { return specialToken(TokenType.EOF); } MetaList info = reader.getInfo(); Character sym = reader.next(); switch (sym) { case ' ': case '\t': case 13: case '\n': return token(TokenType.IGNORE, info); case '=': return token(TokenType.EQUAL, info); case '\"': return read_22(info); default: if (isAlphaNummeric(sym)) { String id = readIdentifier(Character.toString(sym)); TokenType type; type = TokenType.IDENTIFIER; Token toc = token(type, id, info); return toc; } else { RError.err(ErrorType.Error, "Unexpected character: #" + Integer.toHexString(sym) + " (" + sym + ")", info); return specialToken(TokenType.IGNORE); } } } // EBNF id: alpha { alpha | numeric} private String readIdentifier(String prefix) { String text = prefix; while (isAlphaNummeric(reader.peek())) { text = text + reader.next(); } return text; } // EBNF alpha: "a".."z" | "A".."Z" private boolean isAlpha(char sym) { return (sym >= 'a' && sym <= 'z') || (sym >= 'A' && sym <= 'Z') || (sym == '_'); } // EBNF numeric: "0".."9" private boolean isNummeric(char sym) { return (sym >= '0' && sym <= '9'); } private boolean isAlphaNummeric(char sym) { return isAlpha(sym) || isNummeric(sym); } // " private Token read_22(MetaList sym) { String value = readTilEndString(); return token(TokenType.STRING, value, sym); } private String readTilEndString() { String ret = ""; char sym; while (reader.hasNext()) { sym = reader.next(); if (sym == '\"') { return ret; } else { ret += sym; } } RError.err(ErrorType.Error, "String over end of file", reader.getInfo()); return null; } }
gpl-3.0
DmitryRemezow/veraPDF-library
modelimplementation/src/main/java/org/verapdf/model/impl/pb/pd/images/PBoxPDXImage.java
1655
package org.verapdf.model.impl.pb.pd.images; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.verapdf.model.baselayer.*; import org.verapdf.model.baselayer.Object; import org.verapdf.model.pdlayer.PDColorSpace; import org.verapdf.model.pdlayer.PDXImage; import java.util.ArrayList; import java.util.List; /** * @author Evgeniy Muravitskiy */ public class PBoxPDXImage extends PBoxPDXObject implements PDXImage { public static final String IMAGE_CS = "imageCS"; public static final String ALTERNATES = "Alternates"; public PBoxPDXImage(PDImageXObject simplePDObject) { super(simplePDObject); setType("PDXImage"); } @Override public Boolean getInterpolate() { return Boolean.valueOf(((PDImageXObject) simplePDObject).getInterpolate()); } @Override public List<? extends Object> getLinkedObjects(String link) { List<? extends Object> list; switch (link) { case IMAGE_CS: list = getImageCS(); break; case ALTERNATES: list = getAlternates(); break; default: list = super.getLinkedObjects(link); break; } return list; } //TODO : implement this private List<PDColorSpace> getImageCS() { List<PDColorSpace> cs = new ArrayList<>(1); // look at pdfbox. how they are choose correct constructor return new ArrayList<>(); } //TODO : implement this private List<PDXImage> getAlternates() { // look at pdfbox return new ArrayList<>(); } }
gpl-3.0
aqucy/AqucyFramework
src/com/v246/commonWebFramework/utils/ShiroExt.java
5458
package com.v246.commonWebFramework.utils; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.Map; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; //import org.bee.tl.core.GroupTemplate; /*gt.registerFunctionPackage("so",new ShiroExt ()); @if(so.isGuest()) { */ public class ShiroExt { /** * The guest tag * * @return */ public boolean isGuest() { return getSubject() == null || getSubject().getPrincipal() == null; } /** * The user tag * * @return */ public boolean isUser() { return getSubject() != null && getSubject().getPrincipal() != null; } /** * The authenticated tag * * @return */ public boolean isAuthenticated() { return getSubject() != null && getSubject().isAuthenticated(); } public boolean isNotAuthenticated() { return !isAuthenticated(); } /** * The principal tag * * @param map * @return */ public String principal(Map map) { String strValue = null; if (getSubject() != null) { // Get the principal to print out Object principal; String type = map != null ? (String) map.get("type") : null; if (type == null) { principal = getSubject().getPrincipal(); } else { principal = getPrincipalFromClassName(type); } String property = map != null ? (String) map.get("property") : null; // Get the string value of the principal if (principal != null) { if (property == null) { strValue = principal.toString(); } else { strValue = getPrincipalProperty(principal, property); } } } if (strValue != null) { return strValue; } else { return null; } } /** * The hasRole tag * * @param roleName * @return */ public boolean hasRole(String roleName) { return getSubject() != null && getSubject().hasRole(roleName); } /** * The lacksRole tag * * @param roleName * @return */ public boolean lacksRole(String roleName) { boolean hasRole = getSubject() != null && getSubject().hasRole(roleName); return !hasRole; } /** * The hasAnyRole tag * * @param roleNames * @return */ public boolean hasAnyRole(String roleNames) { boolean hasAnyRole = false; Subject subject = getSubject(); if (subject != null) { // Iterate through roles and check to see if the user has one of the // roles for (String role : roleNames.split(",")) { if (subject.hasRole(role.trim())) { hasAnyRole = true; break; } } } return hasAnyRole; } /** * The hasPermission tag * * @param p * @return */ public boolean hasPermission(String p) { return getSubject() != null && getSubject().isPermitted(p); } /** * The lacksPermission tag * * @param p * @return */ public boolean lacksPermission(String p) { return !hasPermission(p); } @SuppressWarnings({"unchecked"}) private Object getPrincipalFromClassName(String type) { Object principal = null; try { Class cls = Class.forName(type); principal = getSubject().getPrincipals().oneByType(cls); } catch (ClassNotFoundException e) { } return principal; } private String getPrincipalProperty(Object principal, String property) { String strValue = null; try { BeanInfo bi = Introspector.getBeanInfo(principal.getClass()); // Loop through the properties to get the string value of the // specified property boolean foundProperty = false; for (PropertyDescriptor pd : bi.getPropertyDescriptors()) { if (pd.getName().equals(property)) { Object value = pd.getReadMethod().invoke(principal, (Object[]) null); strValue = String.valueOf(value); foundProperty = true; break; } } if (!foundProperty) { final String message = "Property [" + property + "] not found in principal of type [" + principal.getClass().getName() + "]"; throw new RuntimeException(message); } } catch (Exception e) { final String message = "Error reading property [" + property + "] from principal of type [" + principal.getClass().getName() + "]"; throw new RuntimeException(message, e); } return strValue; } protected Subject getSubject() { return SecurityUtils.getSubject(); } public static void main(String[] args) { // GroupTemplate gt = new GroupTemplate(); // gt.registerFunctionPackage("shiro", new ShiroExt()); } }
gpl-3.0
doc-rj/smartcard-reader
app/src/main/java/org/docrj/smartcard/reader/EmvReadActivity.java
10814
/* * Copyright 2014 Ryan Jones * * This file is part of smartcard-reader, package org.docrj.smartcard.reader. * * smartcard-reader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * smartcard-reader is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with smartcard-reader. If not, see <http://www.gnu.org/licenses/>. */ package org.docrj.smartcard.reader; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.ShareActionProvider; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.media.AudioManager; import android.media.SoundPool; import android.nfc.NfcAdapter.ReaderCallback; import android.nfc.Tag; import android.nfc.tech.IsoDep; import android.os.Bundle; import android.os.Vibrator; import android.preference.PreferenceManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.ViewSwitcher; import com.afollestad.materialdialogs.AlertDialogWrapper; import org.docrj.smartcard.emv.EMVTerminal; public class EmvReadActivity extends AppCompatActivity implements ReaderXcvr.UiCallbacks, ReaderCallback, SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = LaunchActivity.TAG; // dialogs private static final int DIALOG_ENABLE_NFC = AppSelectActivity.DIALOG_ENABLE_NFC; // tap feedback values private static final int TAP_FEEDBACK_NONE = AppSelectActivity.TAP_FEEDBACK_NONE; private static final int TAP_FEEDBACK_VIBRATE = AppSelectActivity.TAP_FEEDBACK_VIBRATE; private static final int TAP_FEEDBACK_AUDIO = AppSelectActivity.TAP_FEEDBACK_AUDIO; // test modes private static final int TEST_MODE_EMV_READ = Launcher.TEST_MODE_EMV_READ; private NavDrawer mNavDrawer; private Editor mEditor; private NfcManager mNfcManager; private Console mConsole; private boolean mAutoClear; private boolean mShowMsgSeparators; private int mTapFeedback; private int mTapSound; private SoundPool mSoundPool; private Vibrator mVibrator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.drawer_activity_emv_read); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.emv_drawer_layout); mNavDrawer = new NavDrawer(this, savedInstanceState, R.id.emv_read, drawerLayout, toolbar); ListView listView = (ListView) findViewById(R.id.msg_list); ViewSwitcher switcher = (ViewSwitcher) findViewById(R.id.switcher); mConsole = new Console(this, savedInstanceState, TEST_MODE_EMV_READ, listView, switcher); mNfcManager = new NfcManager(this, this); ApduParser.init(this); EMVTerminal.loadProperties(getResources()); // persistent "shared preferences" SharedPreferences ss = getSharedPreferences("prefs", Context.MODE_PRIVATE); mEditor = ss.edit(); // persistent settings and settings listener SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.registerOnSharedPreferenceChangeListener(this); mAutoClear = prefs.getBoolean("pref_auto_clear", true); mShowMsgSeparators = prefs.getBoolean("pref_show_separators", true); String tapFeedback = prefs.getString("pref_tap_feedback", "1"); mTapFeedback = Integer.valueOf(tapFeedback); mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mNavDrawer.onPostCreate(); } @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (key.equals("pref_auto_clear")){ mAutoClear = prefs.getBoolean("pref_auto_clear", true); } else if (key.equals("pref_show_separators")) { mShowMsgSeparators = prefs.getBoolean("pref_show_separators", true); clearMessages(true); } else if (key.equals("pref_tap_feedback")) { String tapFeedback = prefs.getString("pref_tap_feedback", "1"); mTapFeedback = Integer.valueOf(tapFeedback); } } @Override public void onResume() { super.onResume(); mNfcManager.onResume(); mConsole.onResume(); mNavDrawer.onResume(); initSoundPool(); } @Override public void onPause() { super.onPause(); writePrefs(); releaseSoundPool(); mConsole.onPause(); mNfcManager.onPause(); } @Override public void onStop() { super.onStop(); // dismiss enable NFC dialog mNfcManager.onStop(); } @Override public void onBackPressed() { if (mNavDrawer.onBackPressed()) { return; } mConsole.clearShareIntent(); super.onBackPressed(); } @Override protected void onSaveInstanceState(Bundle outstate) { mNavDrawer.onSaveInstanceState(outstate); mConsole.onSaveInstanceState(outstate); } @SuppressWarnings("deprecation") @Override protected Dialog onCreateDialog(int id) { //AlertDialog.Builder builder = new AlertDialog.Builder( // EmvReadActivity.this, R.style.dialog); AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(this); final LayoutInflater li = getLayoutInflater(); Dialog dialog = null; switch (id) { case DIALOG_ENABLE_NFC: { dialog = mNfcManager.onCreateDialog(id, builder, li); break; } } return dialog; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_emv_read, menu); MenuItem item = menu.findItem(R.id.menu_share_msgs); mConsole.setShareProvider((ShareActionProvider) MenuItemCompat.getActionProvider(item)); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean drawerOpen = mNavDrawer.isOpen(); MenuItem item = menu.findItem(R.id.menu_share_msgs); item.setVisible(!drawerOpen); item = menu.findItem(R.id.menu_clear_msgs); item.setVisible(!drawerOpen); mConsole.setShareIntent(); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mNavDrawer.onOptionsItemSelected(item)) { return true; } switch (item.getItemId()) { case R.id.menu_clear_msgs: clearMessages(true); return true; } return super.onOptionsItemSelected(item); } private void initSoundPool() { synchronized (this) { if (mSoundPool == null) { mSoundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0); mTapSound = mSoundPool.load(this, R.raw.tap, 1); } } } private void releaseSoundPool() { synchronized (this) { if (mSoundPool != null) { mSoundPool.release(); mSoundPool = null; } } } private void doTapFeedback() { if (mTapFeedback == TAP_FEEDBACK_AUDIO) { mSoundPool.play(mTapSound, 1.0f, 1.0f, 0, 0, 1.0f); } else if (mTapFeedback == TAP_FEEDBACK_VIBRATE) { long[] pattern = {0, 50, 50, 50}; mVibrator.vibrate(pattern, -1); } } @Override public void onTagDiscovered(Tag tag) { doTapFeedback(); clearImage(); // maybe clear console or show separator, depends on settings if (mAutoClear) { clearMessages(); } else { addMessageSeparator(); } // get IsoDep handle and run xcvr thread IsoDep isoDep = IsoDep.get(tag); if (isoDep == null) { onError(getString(R.string.wrong_tag_err)); } else { ReaderXcvr xcvr = new PaymentReaderXcvr(isoDep, "", this, TEST_MODE_EMV_READ); new Thread(xcvr).start(); } } @Override public void onMessageSend(final String raw, final String name) { mConsole.write(raw, MessageAdapter.MSG_SEND, name, null); } @Override public void onMessageRcv(final String raw, final String name, final String parsed) { mConsole.write(raw, MessageAdapter.MSG_RCV, name, parsed); } @Override public void onOkay(final String message) { mConsole.write(message, MessageAdapter.MSG_OKAY, null, null); } @Override public void onError(final String message) { mConsole.write(message, MessageAdapter.MSG_ERROR, null, null); } @Override public void onSeparator() { addMessageSeparator(); } @Override public void clearMessages() { mConsole.clear(); } private void clearMessages(boolean showImg) { mConsole.clear(showImg); } private void clearImage() { mConsole.showImage(false); } @Override public void setUserSelectListener(final ReaderXcvr.UiListener callback) { } @Override public void onFinish(boolean err) { // nothing yet! animation cleanup worked better elsewhere } private void addMessageSeparator() { if (mShowMsgSeparators) { mConsole.writeSeparator(); } } private void writePrefs() { mEditor.putInt("test_mode", TEST_MODE_EMV_READ); mEditor.commit(); } }
gpl-3.0
ranaldmiao/sg_noi_archive
2021_finals/tasks/archaeologist/managers/stub.java
3779
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.ByteOrder; public class stub { private static final byte COMMAND_END = 0; private static final byte COMMAND_SETLIGHT = 1; private static final byte COMMAND_TAKEPATH = 2; private static BufferedInputStream reader; private static BufferedOutputStream writer; public static class RoomPathsPair { public int room; public int[] paths; } private static void readExact(BufferedInputStream reader, byte[] target) throws IOException { int count = target.length; int ret = count; int off = 0; while (count > 0) { int res = reader.read(target, off, count); if (res <= 0) throw new RuntimeException(); count -= res; off += res; } } private static int readExactInt(BufferedInputStream reader) throws IOException { ByteBuffer buf = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); readExact(reader, buf.array()); return buf.getInt(); } private static int[] readExactVector(BufferedInputStream reader) throws IOException { int len = readExactInt(reader); if (len == 0) return new int[0]; ByteBuffer buf2 = ByteBuffer.allocate(4*len).order(ByteOrder.LITTLE_ENDIAN); readExact(reader, buf2.array()); IntBuffer ib = buf2.asIntBuffer(); int[] arr = new int[ib.remaining()]; ib.get(arr); return arr; } private static void writeInt(BufferedOutputStream writer, int val) throws IOException { ByteBuffer buf = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); buf.putInt(val); writer.write(buf.array()); } public static RoomPathsPair take_path(int corridor) { try { writer.write(COMMAND_TAKEPATH); writeInt(writer, corridor); writer.flush(); RoomPathsPair ret = new RoomPathsPair(); ret.room = readExactInt(reader); ret.paths = readExactVector(reader); return ret; } catch (IOException e) { throw new RuntimeException(e); } } public static void set_light(int level) { try { writer.write(COMMAND_SETLIGHT); writeInt(writer, level); writer.flush(); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args) throws IOException { System.in.close(); System.out.close(); System.err.close(); reader = new BufferedInputStream(new FileInputStream(args[0])); writer = new BufferedOutputStream(new FileOutputStream(args[1])); while (true) { try { int N = readExactInt(reader); int K = readExactInt(reader); int L = readExactInt(reader); int[] parent = new int[N]; ByteBuffer buf2 = ByteBuffer.allocate(4*N).order(ByteOrder.LITTLE_ENDIAN); readExact(reader, buf2.array()); IntBuffer ib = buf2.asIntBuffer(); ib.get(parent); int initial_level = readExactInt(reader); int[] paths = readExactVector(reader); (new Archaeologist()).archaeologist(N, K, L, parent, initial_level, paths); writer.write(COMMAND_END); writer.flush(); } catch (RuntimeException e) { break; } } } }
gpl-3.0
manhcuongkd/blynk-server
server/notifications/email/src/main/java/cc/blynk/server/notifications/mail/SparkPostMailClient.java
3886
package cc.blynk.server.notifications.mail; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.activation.DataHandler; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.*; import javax.mail.util.ByteArrayDataSource; import java.util.Properties; /** * The Blynk Project. * Created by Dmitriy Dumanskiy. * Created on 14.09.16. */ public class SparkPostMailClient implements MailClient { private static final Logger log = LogManager.getLogger(SparkPostMailClient.class); private final Session session; private final InternetAddress from; private final String host; private final String username; private final String password; public SparkPostMailClient(Properties mailProperties) { this.username = mailProperties.getProperty("mail.smtp.username"); this.password = mailProperties.getProperty("mail.smtp.password"); this.host = mailProperties.getProperty("mail.smtp.host"); log.info("Initializing SparkPost smtp mail transport. Username : {}. SMTP host : {}:{}", username, host, mailProperties.getProperty("mail.smtp.port")); this.session = Session.getInstance(mailProperties); try { this.from = new InternetAddress(mailProperties.getProperty("mail.from")); } catch (AddressException e) { throw new RuntimeException("Error initializing MailWrapper."); } } @Override public void sendText(String to, String subj, String body) throws Exception { send(to, subj, body, "text/plain; charset=UTF-8"); } @Override public void sendHtml(String to, String subj, String body) throws Exception { send(to, subj, body, "text/html; charset=UTF-8"); } private void send(String to, String subj, String body, String contentType) throws Exception { MimeMessage message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subj, "UTF-8"); message.setContent(body, contentType); Transport transport = session.getTransport(); try { transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); } finally { transport.close(); } log.trace("Mail to {} was sent. Subj : {}, body : {}", to, subj, body); } @Override public void sendHtmlWithAttachment(String to, String subj, String body, QrHolder[] attachments) throws Exception { MimeMessage message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subj, "UTF-8"); Multipart multipart = new MimeMultipart(); MimeBodyPart bodyMessagePart = new MimeBodyPart(); bodyMessagePart.setContent(body, "text/html; charset=UTF-8"); multipart.addBodyPart(bodyMessagePart); for (QrHolder qrHolder : attachments) { MimeBodyPart attachmentsPart = new MimeBodyPart(); attachmentsPart.setDataHandler(new DataHandler(new ByteArrayDataSource(qrHolder.data, "image/jpeg"))); attachmentsPart.setFileName(qrHolder.makeQRFilename()); multipart.addBodyPart(attachmentsPart); } message.setContent(multipart); Transport transport = session.getTransport(); try { transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); } finally { transport.close(); } log.trace("Mail to {} was sent. Subj : {}, body : {}", to, subj, body); } }
gpl-3.0
szabob94/TarsashazKonyvelo
src/test/java/hu/unideb/inf/konyvelo/InsertServicesTest.java
4456
/** * */ package hu.unideb.inf.konyvelo; import java.util.ArrayList; import java.util.List; import hu.unideb.inf.konyvelo.Control.InsertServices; import hu.unideb.inf.konyvelo.DAO.DAODelete; import hu.unideb.inf.konyvelo.DAO.DAOGet; import hu.unideb.inf.konyvelo.Model.Lakas; import hu.unideb.inf.konyvelo.Model.Tarsashaz; import hu.unideb.inf.konyvelo.Model.TranzakcioL; import hu.unideb.inf.konyvelo.Model.TranzakcioT; import org.joda.time.DateTime; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; /** * @author Bence * */ public class InsertServicesTest { @Test public void testInsertTranzakcioL(){ InsertServices inS = new InsertServices(); TranzakcioL ures = new TranzakcioL(); assertNotNull("Üres", ures); DAOGet get = new DAOGet(); List<TranzakcioL> tranzakciok = get.getTranzakciokL(); int size=tranzakciok.size(); TranzakcioL tranzakcio = new TranzakcioL(1594, 4, 1000, new DateTime(2015,9,15,14,40), "valami", "valaki"); inS.insertTranzakcioL(tranzakcio); tranzakciok=get.getTranzakciokL(); assertEquals("Nem egyenlőek", size+1, tranzakciok.size()); TranzakcioL tranzakcio2 = new TranzakcioL(1595, 4, 3540, new DateTime(2015,9,15,14,40), "valami", "valaki"); inS.insertTranzakcioL(tranzakcio2); tranzakciok=get.getTranzakciokL(); assertEquals("Nem egyenlőek", size+2, tranzakciok.size()); DAODelete delete = new DAODelete(); delete.deleteTranzakcioL(tranzakcio); delete.deleteTranzakcioL(tranzakcio2); } @Test public void testInsertTranzakcioT(){ InsertServices inS = new InsertServices(); TranzakcioT ures = new TranzakcioT(); assertNotNull("Üres", ures); DAOGet get = new DAOGet(); List<TranzakcioT> tranzakciok = get.getTranzakciokT(); int size=tranzakciok.size(); TranzakcioT tranzakcio = new TranzakcioT(1594, 4, 1000, new DateTime(2015,9,15,14,40), "valami", "valaki"); inS.insertTranzakcioT(tranzakcio); tranzakciok=get.getTranzakciokT(); assertEquals("Nem egyenlőek", size+1, tranzakciok.size()); TranzakcioT tranzakcio2 = new TranzakcioT(1595, 4, 3540, new DateTime(2015,9,15,14,40), "valami", "valaki"); inS.insertTranzakcioT(tranzakcio2); tranzakciok=get.getTranzakciokT(); assertEquals("Nem egyenlőek", size+2, tranzakciok.size()); DAODelete delete = new DAODelete(); delete.deleteTranzakcioT(tranzakcio); delete.deleteTranzakcioT(tranzakcio2); } @Test public void testInsertLakas(){ InsertServices inS = new InsertServices(); Lakas ures = new Lakas(); assertNotNull("Üres", ures); ures.setAjto(5); assertEquals("5-nek kéne hogy legyen", 5, ures.getAjto()); ures.setEmelet(4); assertEquals("4-nek kéne hogy legyen", 4, ures.getEmelet()); ures.setTulajdonos("valaki"); assertEquals("valaki", ures.getTulajdonos()); ures.setId(5); assertEquals("5-nek kéne hogy legyen", 5, ures.getId()); DAOGet get = new DAOGet(); List<Lakas> lakasok = get.getLakasokEgyszeru(); int size=lakasok.size(); Lakas lakas = new Lakas(21231,"Mekk Elek",25535,1,1,0,new ArrayList<TranzakcioL>()); inS.insertLakas(lakas); lakasok=get.getLakasokEgyszeru(); assertEquals("Nem egyenlőek", size+1, lakasok.size()); Lakas lakas2 = new Lakas(21232,"Adat bá",25535,1,2,40000,new ArrayList<TranzakcioL>()); inS.insertLakas(lakas2); lakasok=get.getLakasokEgyszeru(); assertEquals("Nem egyenlőek", size+2, lakasok.size()); DAODelete delete = new DAODelete(); delete.deleteLakas(lakas); delete.deleteLakas(lakas2); } @Test public void testInsertTarsashaz(){ InsertServices inS = new InsertServices(); Tarsashaz ures = new Tarsashaz(); assertNotNull("Üres", ures); DAOGet get = new DAOGet(); List<Tarsashaz> tarsashazak = get.getTarsashazakEgyszeru(); int size=tarsashazak.size(); Tarsashaz tarsashaz = new Tarsashaz(25535,"A cim",8,16,0,new ArrayList<Lakas>(),new ArrayList<TranzakcioT>()); inS.insertTarsashaz(tarsashaz); tarsashazak=get.getTarsashazakEgyszeru(); assertEquals("Nem egyenlőek", size+1, tarsashazak.size()); Tarsashaz tarsashaz2 = new Tarsashaz(25536,"Masik cim",3,4,21500,new ArrayList<Lakas>(),new ArrayList<TranzakcioT>()); inS.insertTarsashaz(tarsashaz2); tarsashazak=get.getTarsashazakEgyszeru(); assertEquals("Nem egyenlőek", size+2, tarsashazak.size()); DAODelete delete = new DAODelete(); delete.deleteTarsashaz(tarsashaz); delete.deleteTarsashaz(tarsashaz2); } }
gpl-3.0
micromata/projectforge
projectforge-wicket/src/main/java/org/projectforge/web/wicket/flowlayout/FieldProperties.java
3821
///////////////////////////////////////////////////////////////////////////// // // Project ProjectForge Community Edition // www.projectforge.org // // Copyright (C) 2001-2022 Micromata GmbH, Germany (www.micromata.com) // // ProjectForge is dual-licensed. // // This community edition is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 3 of the License. // // This community edition is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General // Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, see http://www.gnu.org/licenses/. // ///////////////////////////////////////////////////////////////////////////// package org.projectforge.web.wicket.flowlayout; import org.apache.wicket.model.IModel; import org.apache.wicket.model.PropertyModel; /** * For sharing functionality (refer {@link org.projectforge.web.address.AddressPageSupport} as an example). * @author Kai Reinhard (k.reinhard@micromata.de) * */ public class FieldProperties<T> { private final String label; private String labelDescription; private boolean translateLabelDecsription = true; private final IModel<T> model; private FieldType fieldType; private String valueAsString; public FieldProperties(final String label, final IModel<T> model) { this.label = label; this.model = model; } /** * @return the label (i18n key at default). */ public String getLabel() { return label; } /** * @return the model */ public IModel<T> getModel() { return model; } /** * @return the model which will be cast to PropertyModel<T> first. * @throws ClassCastException if the model isn't an instance of {@link PropertyModel}. */ public PropertyModel<T> getPropertyModel() { return (PropertyModel<T>) model; } /** * @return the fieldType */ public FieldType getFieldType() { return fieldType; } /** * @param fieldType the fieldType to set * @return this for chaining. */ public FieldProperties<T> setFieldType(final FieldType fieldType) { this.fieldType = fieldType; return this; } public T getValue() { return model.getObject(); } /** * @return the valueAsString */ public String getValueAsString() { return valueAsString; } /** * @param valueAsString the valueAsString to set * @return this for chaining. */ public FieldProperties<T> setValueAsString(final String valueAsString) { this.valueAsString = valueAsString; return this; } /** * Is only supported by FieldsetPanel (in desktop version). * @return the labelDescription */ public String getLabelDescription() { return labelDescription; } /** * @param labelDescription the labelDescription to set * @return this for chaining. */ public FieldProperties<T> setLabelDescription(final String labelDescription) { return setLabelDescription(labelDescription, true); } /** * @param labelDescription the labelDescription to set * @param translate if true (default) then the label description is an i18n key which has to be translated. * @return this for chaining. */ public FieldProperties<T> setLabelDescription(final String labelDescription, final boolean translate) { this.labelDescription = labelDescription; this.translateLabelDecsription = translate; return this; } /** * If true (default) then the label description is an i18n key which has to be translated. * @return the translateLabelDecsription */ public boolean isTranslateLabelDecsription() { return translateLabelDecsription; } }
gpl-3.0
gegy1000/PokeGOAPI-Java
library/src/main/java/com/pokegoapi/api/pokemon/PokemonCpUtils.java
6880
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pokegoapi.api.pokemon; import POGOProtos.Enums.PokemonIdOuterClass.PokemonId; import POGOProtos.Settings.Master.Pokemon.StatsAttributesOuterClass.StatsAttributes; import POGOProtos.Settings.Master.PokemonSettingsOuterClass.PokemonSettings; import POGOProtos.Settings.Master.PokemonUpgradeSettingsOuterClass.PokemonUpgradeSettings; import com.pokegoapi.api.PokemonGo; import com.pokegoapi.api.settings.templates.ItemTemplates; import com.pokegoapi.exceptions.NoSuchItemException; /** * Information in this class is based on: * http://pokemongo.gamepress.gg/cp-multiplier * and * http://pokemongo.gamepress.gg/pokemon-stats-advanced */ public class PokemonCpUtils { private static float getLevel(double combinedCpMultiplier) { double level; if (combinedCpMultiplier < 0.734f) { // compute polynomial approximation obtained by regression level = 58.35178527 * combinedCpMultiplier * combinedCpMultiplier - 2.838007664 * combinedCpMultiplier + 0.8539209906; } else { // compute linear approximation obtained by regression level = 171.0112688 * combinedCpMultiplier - 95.20425243; } // round to nearest .5 value and return return (float) (Math.round((level) * 2) / 2.0); } /** * Get the level from the cp multiplier * * @param combinedCpMultiplier All CP multiplier values combined * @return Level */ public static float getLevelFromCpMultiplier(double combinedCpMultiplier) { return getLevel(combinedCpMultiplier); } /** * Calculate CP based on raw values * * @param attack All attack values combined * @param defense All defense values combined * @param stamina All stamina values combined * @param combinedCpMultiplier All CP multiplier values combined * @return CP */ public static int getCp(int attack, int defense, int stamina, double combinedCpMultiplier) { return (int) Math.round(attack * Math.pow(defense, 0.5) * Math.pow(stamina, 0.5) * Math.pow(combinedCpMultiplier, 2) / 10f); } /** * Get the maximum CP from the values * * @param api the current api * @param attack All attack values combined * @param defense All defense values combined * @param stamina All stamina values combined * @return Maximum CP for these levels */ public static int getMaxCp(PokemonGo api, int attack, int defense, int stamina) { return getMaxCpForPlayer(api, attack, defense, stamina, 40); } /** * Get the absolute maximum CP for pokemons with their PokemonId. * * @param api the current api * @param id The {@link PokemonId} of the Pokemon to get CP for. * @return The absolute maximum CP * @throws NoSuchItemException If the PokemonId value cannot be found in the {@link ItemTemplates}. */ public static int getAbsoluteMaxCp(PokemonGo api, PokemonId id) throws NoSuchItemException { PokemonSettings settings = api.getItemTemplates().getPokemonSettings(id); if (settings == null) { throw new NoSuchItemException("Cannot find meta data for " + id); } StatsAttributes stats = settings.getStats(); int attack = 15 + stats.getBaseAttack(); int defense = 15 + stats.getBaseDefense(); int stamina = 15 + stats.getBaseStamina(); return getMaxCpForPlayer(api, attack, defense, stamina, 40); } /** * Get the maximum CP from the values * * @param api the current api * @param attack All attack values combined * @param defense All defense values combined * @param stamina All stamina values combined * @param playerLevel The player level * @return Maximum CP for these levels */ public static int getMaxCpForPlayer(PokemonGo api, int attack, int defense, int stamina, int playerLevel) { float maxLevel = Math.min(playerLevel + 1.5F, 40.0F); double maxCpMultplier = api.getItemTemplates().getLevelCpMultiplier(maxLevel); return getCp(attack, defense, stamina, maxCpMultplier); } /** * Get the CP after powerup * * @param cp Current CP level * @param combinedCpMultiplier All CP multiplier values combined * @return New CP */ public static int getCpAfterPowerup(int cp, double combinedCpMultiplier) { // Based on http://pokemongo.gamepress.gg/power-up-costs double level = getLevelFromCpMultiplier(combinedCpMultiplier); if (level <= 10) { return cp + (int) Math.round((cp * 0.009426125469) / Math.pow(combinedCpMultiplier, 2)); } if (level <= 20) { return cp + (int) Math.round((cp * 0.008919025675) / Math.pow(combinedCpMultiplier, 2)); } if (level <= 30) { return cp + (int) Math.round((cp * 0.008924905903) / Math.pow(combinedCpMultiplier, 2)); } return cp + (int) Math.round((cp * 0.00445946079) / Math.pow(combinedCpMultiplier, 2)); } /** * Get the new additional multiplier after powerup * * @param api the current api * @param cpMultiplier Multiplier * @param additionalCpMultiplier Additional multiplier * @return Additional CP multiplier after upgrade */ public static double getAdditionalCpMultiplierAfterPowerup(PokemonGo api, double cpMultiplier, double additionalCpMultiplier) { float nextLevel = getLevelFromCpMultiplier(cpMultiplier + additionalCpMultiplier) + .5f; return api.getItemTemplates().getLevelCpMultiplier(nextLevel) - cpMultiplier; } /** * Get the amount of stardust required to do a powerup * * @param api the current api * @param combinedCpMultiplier All CP multiplier values combined * @return Amount of stardust */ public static int getStartdustCostsForPowerup(PokemonGo api, double combinedCpMultiplier) { PokemonUpgradeSettings upgradeSettings = api.getItemTemplates().getUpgradeSettings(); int level = (int) getLevelFromCpMultiplier(combinedCpMultiplier); if (level < upgradeSettings.getStardustCostCount()) { return upgradeSettings.getStardustCost(level); } return 0; } /** * Get the amount of candy required to do a powerup * * @param api the current api * @param combinedCpMultiplier All CP multiplier values combined * @return Amount of candy */ public static int getCandyCostsForPowerup(PokemonGo api, double combinedCpMultiplier) { int level = (int) getLevelFromCpMultiplier(combinedCpMultiplier); return api.getItemTemplates().getUpgradeSettings().getCandyCost(level); } }
gpl-3.0
NoGrief/QueueMonitor
src/com/gwssi/queue/dispatcher/PolicyWorkerDispatcher.java
2587
package com.gwssi.queue.dispatcher; import java.util.Observable; import java.util.Observer; import org.apache.log4j.Logger; import com.gwssi.queue.api.IExcuteOperation; import com.gwssi.queue.api.QueueApi; import com.gwssi.queue.exception.QueueBizRuntimeException; import com.gwssi.queue.model.ITaskObject; import com.gwssi.queue.storage.TaskInfoStorage; import com.gwssi.queue.thread.TaskThread; import com.gwssi.queue.util.UUIDGenerator; public class PolicyWorkerDispatcher extends Observable implements Observer { private static final Logger logger = Logger.getLogger(PolicyWorkerDispatcher.class); private IExcuteOperation excutor; private String typeId; public String getTypeId() { return typeId; } public void setTypeId(String typeId) { this.typeId = typeId; } public void update(Observable o, Object arg) { if (o instanceof ThreadWorkerDispatcher) { logger.debug("收到线程管理器通知,执行任务策略!"); this.taskOperation(arg); }else if(o instanceof TaskInfoStorage){ updateTaskInfo(); } } private void updateTaskInfo() { excutor.updateTaskInfo(); } private synchronized void taskOperation(Object arg) { this.excutor = (IExcuteOperation) arg; ITaskObject task = ThreadWorkerDispatcher.taskInfoStorageMap.get(this.typeId).SWAP_QUEUE.poll(); if (task == null) { return; } else { prepareTask(task); } this.excutor = (IExcuteOperation) arg; task.getTaskStatus().setOptStatus(1); logger.debug("执行任务策略"); if (!doPolicy(task)) { return; } else { sendTask(); } } private void prepareTask(ITaskObject task) { UUIDGenerator uuidGenerator = new UUIDGenerator(); String flowId = uuidGenerator.generate().toString(); TaskThread taskThread = new TaskThread(task, excutor); taskThread.setFlowId(flowId); taskThread.getTask().setFlowId(flowId); TaskInfoStorage tis = QueueApi.getTaskInfoStorage(typeId); tis.putPerparingMap(flowId, taskThread); excutor.setTaskObject(task); try { excutor.perparing(); } catch (QueueBizRuntimeException e) { logger.error("用户API添加任务时出错,有可能是执行IExcuteOperation的实现中perparing方法出错!"); throw new RuntimeException(e); } } private boolean doPolicy(ITaskObject task) { return true; } public IExcuteOperation getExcutor() { return excutor; } public void setExcutor(IExcuteOperation excutor) { this.excutor = excutor; } public synchronized void sendTask() { logger.debug("发送任务通知到任务调度器!"); this.setChanged(); this.notifyObservers(); } }
gpl-3.0
DarioGT/OMS-PluginXML
org.modelsphere.jack/src/org/modelsphere/jack/awt/JackSeparator.java
2773
/************************************************************************* Copyright (C) 2009 Grandite This file is part of Open ModelSphere. Open ModelSphere is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/. You can redistribute and/or modify this particular file even under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. You should have received a copy of the GNU Lesser General Public License (LGPL) along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/. You can reach Grandite at: 20-1220 Lebourgneuf Blvd. Quebec, QC Canada G2K 2G4 or open-modelsphere@grandite.com **********************************************************************/ package org.modelsphere.jack.awt; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JComponent; public class JackSeparator extends JComponent { private static final int SEP_WIDTH = 4; private static final int SEP_HEIGHT = 22; public JackSeparator() { setToolTipText(null); setBorder(null); } protected void paintComponent(Graphics g) { int h = getHeight(); int w = getWidth(); if (w >= 2) { int x = (w / 2) - 1; Color c = getBackground(); g.setColor(c); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(c.darker()); g.drawLine(x, 0, x, h); g.setColor(c.brighter()); g.drawLine(x + 1, 0, x + 1, h); } } public Dimension getPreferredSize() { return new Dimension(SEP_WIDTH, SEP_HEIGHT); } public Dimension getMinimumSize() { return new Dimension(SEP_WIDTH, SEP_HEIGHT); } public Dimension getMaximumSize() { return new Dimension(SEP_WIDTH, SEP_HEIGHT); } }
gpl-3.0