repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
raphaelrodrigues/tvcalendar | src/main/java/io/tvcalendar/config/audit/AuditEventConverter.java | 3282 | package io.tvcalendar.config.audit;
import io.tvcalendar.domain.PersistentAuditEvent;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.time.ZoneId;
import java.util.*;
@Component
public class AuditEventConverter {
/**
* Convert a list of PersistentAuditEvent to a list of AuditEvent
*
* @param persistentAuditEvents the list to convert
* @return the converted list.
*/
public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
if (persistentAuditEvents == null) {
return Collections.emptyList();
}
List<AuditEvent> auditEvents = new ArrayList<>();
for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
auditEvents.add(convertToAuditEvent(persistentAuditEvent));
}
return auditEvents;
}
/**
* Convert a PersistentAuditEvent to an AuditEvent
*
* @param persistentAuditEvent the event to convert
* @return the converted list.
*/
public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) {
Instant instant = persistentAuditEvent.getAuditEventDate().atZone(ZoneId.systemDefault()).toInstant();
return new AuditEvent(Date.from(instant), persistentAuditEvent.getPrincipal(),
persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
}
/**
* Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
*
* @param data the data to convert
* @return a map of String, Object
*/
public Map<String, Object> convertDataToObjects(Map<String, String> data) {
Map<String, Object> results = new HashMap<>();
if (data != null) {
for (String key : data.keySet()) {
results.put(key, data.get(key));
}
}
return results;
}
/**
* Internal conversion. This method will allow to save additional data.
* By default, it will save the object as string
*
* @param data the data to convert
* @return a map of String, String
*/
public Map<String, String> convertDataToStrings(Map<String, Object> data) {
Map<String, String> results = new HashMap<>();
if (data != null) {
for (String key : data.keySet()) {
Object object = data.get(key);
// Extract the data that will be saved.
if (object instanceof WebAuthenticationDetails) {
WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
results.put("remoteAddress", authenticationDetails.getRemoteAddress());
results.put("sessionId", authenticationDetails.getSessionId());
} else if (object != null) {
results.put(key, object.toString());
} else {
results.put(key, "null");
}
}
}
return results;
}
}
| mit |
stachu540/HiRezAPI | api/src/main/java/hirez/api/HiRezException.java | 481 | package hirez.api;
import hirez.api.object.interfaces.ReturnedMessage;
public class HiRezException extends RuntimeException {
public HiRezException(ReturnedMessage message) {
this(message.getReturnedMessage());
}
public HiRezException(String message) {
super(message);
}
public HiRezException(Throwable cause) {
super(cause);
}
public HiRezException(String message, Throwable cause) {
super(message, cause);
}
}
| mit |
NutriCampus/NutriCampus | app/src/main/java/com/nutricampus/app/adapters/AbasPagerAdapter.java | 1575 | package com.nutricampus.app.adapters;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.nutricampus.app.R;
import com.nutricampus.app.entities.Animal;
import com.nutricampus.app.entities.Propriedade;
import com.nutricampus.app.fragments.DadosAnimalFragment;
import com.nutricampus.app.fragments.DadosComplementaresFragment;
/**
* Created by Felipe on 19/07/2017.
* For project NutriCampus.
* Contact: <felipeguimaraes540@gmail.com>
*/
public class AbasPagerAdapter extends FragmentPagerAdapter {
private final String[] titulos;
private final Animal animal;
private final Propriedade propriedade;
public AbasPagerAdapter(Animal animal, Context context, FragmentManager fm, Propriedade propriedade) {
super(fm);
titulos = context.getResources().getStringArray(R.array.titulos);
this.animal = animal;
this.propriedade = propriedade;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return DadosAnimalFragment.newInstance(this.animal, this.propriedade);
case 1:
return DadosComplementaresFragment.newInstance(this.animal);
default:
return null;
}
}
@Override
public int getCount() {
return titulos.length;
}
@Override
public CharSequence getPageTitle(int position) {
return titulos[position];
}
}
| mit |
gfoster-pivotal/spring-streaming-processing | portfolio/src/main/java/io/portfolio/order/SellOrder.java | 399 | package io.portfolio.order;
/**
* Created by gfoster on 9/25/15.
*/
public class SellOrder {
private String stock;
private int numShares;
public SellOrder(String stock, int numShares) {
this.stock = stock;
this.numShares = numShares;
}
public String getStock() {
return stock;
}
public int getNumShares() {
return numShares;
}
}
| mit |
mmithril/XChange | xchange-examples/src/main/java/org/knowm/xchange/examples/anx/v2/marketdata/ANXDepthDemo.java | 1199 | package org.knowm.xchange.examples.anx.v2.marketdata;
import java.io.IOException;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.examples.anx.v2.ANXExamplesUtils;
import org.knowm.xchange.service.polling.marketdata.PollingMarketDataService;
public class ANXDepthDemo {
public static void main(String[] args) throws IOException {
// Use the factory to get the version 2 MtGox exchange API using default settings
Exchange anx = ANXExamplesUtils.createExchange();
// Interested in the public market data feed (no authentication)
PollingMarketDataService marketDataService = anx.getPollingMarketDataService();
// Get the current orderbook
OrderBook orderBook = marketDataService.getOrderBook(CurrencyPair.BTC_USD);
System.out.println("Current Order Book size for BTC / USD: " + (orderBook.getAsks().size() + orderBook.getBids().size()));
System.out.println("First Ask: " + orderBook.getAsks().get(0).toString());
System.out.println("First Bid: " + orderBook.getBids().get(0).toString());
System.out.println(orderBook.toString());
}
}
| mit |
puntopepe/SfogliaFilm | app/src/main/java/com/example/fab/android/sfogliafilm/data/JSONApiTmdbSfogliaMovie.java | 12412 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Fabrizio.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.example.fab.android.sfogliafilm.data;
import android.content.ContentValues;
import android.util.Log;
import com.example.fab.android.sfogliafilm.Utility;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Vector;
public class JSONApiTmdbSfogliaMovie {
private static final String LOG_TAG=JSONApiTmdbSfogliaMovie.class.getSimpleName();
public static final String APIVERSION="3";
// These are the names of the JSON objects that need to be extracted.
// Prefix: TMDB_
public static final String TMDB_MOVIE_ID="id";
public static final String TMDB_TITLE="title";
public static final String TMDB_TAGLINE="tagline";
public static final String TMDB_RUNTIME="runtime";
public static final String TMDB_BACKDROP_PATH="backdrop_path";
public static final String TMDB_OVERVIEW="overview";
public static final String TMDB_POSTER_PATH="poster_path";
public static final String TMDB_RELEASE_DATE="release_date";
public static final String TMDB_PROD_COMPANIES="production_companies"; //ARRAY
public static final String TMDB_PROD_COUNTRIES="production_countries"; //ARRAY
public static final String TMDB_GENRES="genres"; //ARRAY
public static final String TMDB_HOMEPAGE="homepage";
public static final String TMDB_IMDB_ID="imdb_id";
public static final String TMDB_ORIGINAL_TITLE="original_title";
public static final String TMDB_STATUS="status";
public static final String TMDB_SPOKEN_LANGUAGES="spoken_languages"; //ARRAY
public static final String TMDB_ADULT="adult";
//subFields to select
public static final String ISO_COUNTRIES_CODE="iso_3166_1";
public static final String ISO_LANG_CODE="iso_639_1";
public static final String MOVIE_API_BASE_URL="https://api.themoviedb.org/3/movie";
public static final String TMDB_API_URL="http://api.themoviedb.org/3";
public static final String API_UPCOMING="upcoming";
public static String TMDBImageURL;
public static String pSmallPosterWidth;
public static String pLargePosterWidth;
public static void getGeneralConfigurationFromJson(String configuratioJsonStr)throws JSONException {
JSONObject confJson = new JSONObject(configuratioJsonStr);
JSONObject confImagesJson=confJson.getJSONObject("images");
TMDBImageURL=confImagesJson.getString("base_url");
JSONArray pSizes = confImagesJson.getJSONArray("poster_sizes");
pLargePosterWidth= pSizes.getString(4);
pSmallPosterWidth= pSizes.getString(0);
//Log.d("JSON configuration","base "+ TMDBImageURL);
//Log.d("JSON configuration","poster large "+pLargePosterWidth);
//Log.d("JSON configuration","poster small "+pSmallPosterWidth);
}
public static void getMovieFromJson(String oneMovieJsonStr,ContentValues amovie)
throws JSONException {
JSONObject theFullMovieJson = new JSONObject(oneMovieJsonStr);
String nsfw= theFullMovieJson.getString(TMDB_ADULT);
if (nsfw == "true") return;
String value= theFullMovieJson.getString(TMDB_BACKDROP_PATH);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_BACKDROP_PATH,value);
value= theFullMovieJson.getString(TMDB_HOMEPAGE);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_HOMEPAGE,value);
value= theFullMovieJson.getString(TMDB_IMDB_ID);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_MOVIE_ID,value);
value= theFullMovieJson.getString(TMDB_ORIGINAL_TITLE);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_ORIGINAL_TITLE,value);
value= theFullMovieJson.getString(TMDB_OVERVIEW);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_OVERVIEW,value);
value= theFullMovieJson.getString(TMDB_POSTER_PATH);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_POSTER_PATH,value);
value= theFullMovieJson.getString(TMDB_RELEASE_DATE);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_RELEASE_DATE,value);
value= theFullMovieJson.getString(TMDB_RUNTIME);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_RUNTIME,value);
value= theFullMovieJson.getString(TMDB_TAGLINE);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_TAGLINE,value);
value= theFullMovieJson.getString(TMDB_TITLE);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_TITLE,value);
Long movieID= theFullMovieJson.getLong(TMDB_MOVIE_ID);
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_MOVIE_ID,movieID);
amovie.put(SfogliaFilmContract.MovieEntry._ID,movieID);
JSONArray prodCompaniesA= theFullMovieJson.getJSONArray(TMDB_PROD_COMPANIES);
value="";
for (int i = 0; i < prodCompaniesA.length(); i++) {
JSONObject jo=prodCompaniesA.getJSONObject(i);
value+=" "+jo.getString("name");
}
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_PROD_COMPANIES,value);
JSONArray prodCountriesA= theFullMovieJson.getJSONArray(TMDB_PROD_COUNTRIES);
value="";
for(int i=0; i< prodCountriesA.length(); i++) {
JSONObject jo=prodCountriesA.getJSONObject(i);
value+=" "+jo.getString(ISO_COUNTRIES_CODE);
}
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_PROD_COUNTRIES,value);
JSONArray spokenLanguagesA= theFullMovieJson.getJSONArray(TMDB_SPOKEN_LANGUAGES);
value="";
for(int i = 0; i < spokenLanguagesA.length(); i++) {
JSONObject jo= spokenLanguagesA.getJSONObject(i);
value+=" "+ jo.getString(ISO_LANG_CODE);
}
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_SPOKEN_LANGUAGES,value);
}
public static void getUpcomingMoviesVectorFromJson(String upcomingJsonStr,Vector<ContentValues> filling)
throws JSONException {
ContentValues amovie;
JSONObject upcomings= new JSONObject(upcomingJsonStr);
Integer paging_page=upcomings.getInt("page");
String paging_page_min=upcomings.getJSONObject("dates").getString("minimum");
String paging_page_max=upcomings.getJSONObject("dates").getString("maximum");
Integer paging_total_pages=upcomings.getInt("total_pages");
Integer paging_total_results=upcomings.getInt("total_results"); // org.json.JSONException: No value for totale_results
JSONArray resultList=upcomings.getJSONArray("results");
//Log.d(LOG_TAG,"JSON: "+resultList.length());
Calendar cal = Calendar.getInstance();
String justInTime=SfogliaFilmContract.getDbDateTimeString(cal.getTime());
for (int i = 0; i < resultList.length(); i++) {
JSONObject jo=resultList.getJSONObject(i);
String nsfw = jo.getString(TMDB_ADULT);
if ( nsfw.equals("true")) continue;
amovie = new ContentValues();
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_BACKDROP_PATH,jo.getString(TMDB_BACKDROP_PATH));
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_MOVIE_ID,jo.getLong(TMDB_MOVIE_ID));
amovie.put(SfogliaFilmContract.MovieEntry._ID,jo.getLong(TMDB_MOVIE_ID));
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_ORIGINAL_TITLE,jo.getString(TMDB_ORIGINAL_TITLE));
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_RELEASE_DATE,SfogliaFilmContract.getValidDateString(jo.getString(TMDB_RELEASE_DATE)));
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_POSTER_PATH,jo.getString(TMDB_POSTER_PATH));
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_TITLE,jo.getString(TMDB_TITLE));
amovie.put(SfogliaFilmContract.MovieEntry.COLUMN_INSERTTIME,justInTime);
filling.add(amovie);
}
}
public static String fetchJsonResponse(String stringUrl){
URL url = null;
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String jsonResponse = "";
String logTag="fetchJsonResponse";
try {
url = new URL(stringUrl);
Log.v(logTag, "GET / " + url.toString());
//Connection request
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
// Nothing to do.
return "";
}
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
//pretty for DEBUG
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty
return "";
} else {
Log.v(logTag, "GET / " + buffer.length() + " Chars!");
jsonResponse = buffer.toString();
//Log.d(logTag, "CONTENT \n" + jsonResponse + " ");
}
} catch (IOException e) {
Log.e(logTag, "Error ", e);
return "";
}finally {
if (urlConnection != null) { //CLOSE connection
urlConnection.disconnect();
}
if (reader != null) { //CLOSE stream
try {
reader.close();
} catch (final IOException e) {
Log.e(logTag, "Error closing stream", e);
}
}
}
return jsonResponse;
}
public static String getDirectorsFromJson(String jsonMovieCredits) throws JSONException {
String theList="";
JSONObject credits= new JSONObject(jsonMovieCredits);
JSONArray allCrew=credits.getJSONArray("crew");
String[] dirs= new String[allCrew.length()];
int d=0;
for (int i = 0; i < allCrew.length(); i++) {
JSONObject jo=allCrew.getJSONObject(i);
if (jo.getString("job").equals("Director")){
dirs[d]=jo.getString("name");
//Log.d("JSONX", "Director "+dirs[d]);
d++;
}
//Log.d("JSONX", "NO-director "+jo.getString("job"));
}
theList=Utility.strJoin(dirs,", ");
//Log.d("JSONX", " List "+theList);
return theList;
}
public static String getCastCrewFromJson(String jsonMovieCredits) throws JSONException {
String theList="";
JSONObject credits= new JSONObject(jsonMovieCredits);
JSONArray allCrew=credits.getJSONArray("cast");
String[] acts= new String[allCrew.length()];
for (int i = 0; i < allCrew.length(); i++) {
JSONObject jo=allCrew.getJSONObject(i);
acts[i]=jo.getString("name");
}
theList=Utility.strJoin(acts,", ");
return theList;
}
}
| mit |
trein/gtfs-java | gtfs-otp/src/main/java/org/opentripplanner/standalone/Graph.java | 30664 | package org.opentripplanner.standalone;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import org.onebusaway.gtfs.impl.calendar.CalendarServiceImpl;
import org.onebusaway.gtfs.model.Agency;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.calendar.CalendarServiceData;
import org.onebusaway.gtfs.model.calendar.ServiceDate;
import org.onebusaway.gtfs.services.calendar.CalendarService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multiset;
import com.google.common.collect.Sets;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
/**
* A graph is really just one or more indexes into a set of vertexes. It used to keep edgelists for
* each vertex, but those are in the vertex now.
*/
public class Graph implements Serializable {
private static final long serialVersionUID = MavenVersion.VERSION.getUID();
private final MavenVersion mavenVersion = MavenVersion.VERSION;
private static final Logger LOG = LoggerFactory.getLogger(Graph.class);
public String routerId;
private final Map<Edge, Set<AlertPatch>> alertPatches = new HashMap<Edge, Set<AlertPatch>>(0);
// transit feed validity information in seconds since epoch
private long transitServiceStarts = Long.MAX_VALUE;
private long transitServiceEnds = 0;
private final Map<Class<?>, Object> _services = new HashMap<Class<?>, Object>();
private final TransferTable transferTable = new TransferTable();
private GraphBundle bundle;
/* vertex index by name is reconstructed from edges */
private transient Map<String, Vertex> vertices;
private transient CalendarService calendarService;
private final boolean debugData = true;
// TODO this would be more efficient if it was just an array.
private transient Map<Integer, Vertex> vertexById;
private transient Map<Integer, Edge> edgeById;
public transient StreetVertexIndexService streetIndex;
public transient GraphIndex index;
private transient GeometryIndex geomIndex;
private transient SampleFactory sampleFactory;
public final Deduplicator deduplicator = new Deduplicator();
/**
* Map from GTFS ServiceIds to integers close to 0. Allows using BitSets instead of Set<Object>.
* An empty Map is created before the Graph is built to allow registering IDs from multiple
* feeds.
*/
public final Map<AgencyAndId, Integer> serviceCodes = Maps.newHashMap();
public transient TimetableSnapshotSource timetableSnapshotSource = null;
private transient List<GraphBuilderAnnotation> graphBuilderAnnotations = new LinkedList<GraphBuilderAnnotation>(); // initialize
// for
// tests
private final Collection<String> agenciesIds = new HashSet<String>();
private final Collection<Agency> agencies = new HashSet<Agency>();
private transient Set<Edge> temporaryEdges;
private VertexComparatorFactory vertexComparatorFactory = new MortonVertexComparatorFactory();
private transient TimeZone timeZone = null;
private transient GraphMetadata graphMetadata = null;
private transient Geometry hull = null;
/** The density center of the graph for determining the initial geographic extent in the client. */
private final Coordinate center = null;
/**
* Makes it possible to embed a default configuration inside a graph.
*/
public Properties embeddedPreferences = null;
/**
* Manages all updaters of this graph. Is created by the GraphUpdaterConfigurator when there are
* graph updaters defined in the configuration.
*
* @see GraphUpdaterConfigurator
*/
public transient GraphUpdaterManager updaterManager = null;
public final Date buildTime = new Date();
public Graph(Graph basedOn) {
this();
this.bundle = basedOn.getBundle();
}
public Graph() {
this.vertices = new ConcurrentHashMap<String, Vertex>();
this.temporaryEdges = Collections.newSetFromMap(new ConcurrentHashMap<Edge, Boolean>());
this.edgeById = new ConcurrentHashMap<Integer, Edge>();
this.vertexById = new ConcurrentHashMap<Integer, Vertex>();
}
/**
* Add the given vertex to the graph. Ideally, only vertices should add themselves to the graph,
* when they are constructed or deserialized.
*/
public void addVertex(Vertex v) {
Vertex old = this.vertices.put(v.getLabel(), v);
if (old != null) {
if (old == v) {
LOG.error("repeatedly added the same vertex: {}", v);
} else {
LOG.error("duplicate vertex label in graph (added vertex to graph anyway): {}", v);
}
}
}
/**
* Removes a vertex from the graph. Called from streetutils, must be public for now
*
* @param v
*/
public void removeVertex(Vertex v) {
if (this.vertices.remove(v.getLabel()) != v) {
LOG.error("attempting to remove vertex that is not in graph (or mapping value was null): {}", v);
}
}
/* Fetching vertices by label is convenient in tests and such, but avoid using in general. */
@VisibleForTesting
public Vertex getVertex(String label) {
return this.vertices.get(label);
}
/**
* Returns the vertex with the given ID or null if none is present. NOTE: you may need to run
* rebuildVertexAndEdgeIndices() for the indices to be accurate.
*
* @param id
* @return
*/
public Vertex getVertexById(int id) {
return this.vertexById.get(id);
}
/**
* Get all the vertices in the graph.
*
* @return
*/
public Collection<Vertex> getVertices() {
return this.vertices.values();
}
/**
* Returns the edge with the given ID or null if none is present. NOTE: you may need to run
* rebuildVertexAndEdgeIndices() for the indices to be accurate.
*
* @param id
* @return
*/
public Edge getEdgeById(int id) {
return this.edgeById.get(id);
}
/**
* Return all the edges in the graph.
*
* @return
*/
public Collection<Edge> getEdges() {
Set<Edge> edges = new HashSet<Edge>();
for (Vertex v : this.getVertices()) {
edges.addAll(v.getOutgoing());
}
return edges;
}
/**
* Add an {@link AlertPatch} to the {@link AlertPatch} {@link Set} belonging to an {@link Edge}.
*
* @param edge
* @param alertPatch
*/
public void addAlertPatch(Edge edge, AlertPatch alertPatch) {
if ((edge == null) || (alertPatch == null)) { return; }
synchronized (this.alertPatches) {
Set<AlertPatch> alertPatches = this.alertPatches.get(edge);
if (alertPatches == null) {
this.alertPatches.put(edge, Collections.singleton(alertPatch));
} else if (alertPatches instanceof HashSet) {
alertPatches.add(alertPatch);
} else {
alertPatches = new HashSet<AlertPatch>(alertPatches);
if (alertPatches.add(alertPatch)) {
this.alertPatches.put(edge, alertPatches);
}
}
}
}
/**
* Remove an {@link AlertPatch} from the {@link AlertPatch} {@link Set} belonging to an
* {@link Edge}.
*
* @param edge
* @param alertPatch
*/
public void removeAlertPatch(Edge edge, AlertPatch alertPatch) {
if ((edge == null) || (alertPatch == null)) { return; }
synchronized (this.alertPatches) {
Set<AlertPatch> alertPatches = this.alertPatches.get(edge);
if ((alertPatches != null) && alertPatches.contains(alertPatch)) {
if (alertPatches.size() < 2) {
this.alertPatches.remove(edge);
} else {
alertPatches.remove(alertPatch);
}
}
}
}
/**
* Get the {@link AlertPatch} {@link Set} that belongs to an {@link Edge} and build a new array.
*
* @param edge
* @return The {@link AlertPatch} array that belongs to the {@link Edge}
*/
public AlertPatch[] getAlertPatches(Edge edge) {
if (edge != null) {
synchronized (this.alertPatches) {
Set<AlertPatch> alertPatches = this.alertPatches.get(edge);
if (alertPatches != null) { return alertPatches.toArray(new AlertPatch[alertPatches.size()]); }
}
}
return new AlertPatch[0];
}
/**
* Return only the StreetEdges in the graph.
*
* @return
*/
public Collection<StreetEdge> getStreetEdges() {
Collection<Edge> allEdges = this.getEdges();
return Lists.newArrayList(IterableLibrary.filter(allEdges, StreetEdge.class));
}
public boolean containsVertex(Vertex v) {
return (v != null) && (this.vertices.get(v.getLabel()) == v);
}
@SuppressWarnings("unchecked")
public <T> T putService(Class<T> serviceType, T service) {
return (T) this._services.put(serviceType, service);
}
public boolean hasService(Class<?> serviceType) {
return this._services.containsKey(serviceType);
}
@SuppressWarnings("unchecked")
public <T> T getService(Class<T> serviceType) {
return (T) this._services.get(serviceType);
}
public <T> T getService(Class<T> serviceType, boolean autoCreate) {
@SuppressWarnings("unchecked")
T t = (T) this._services.get(serviceType);
if (t == null) {
try {
t = serviceType.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
this._services.put(serviceType, t);
}
return t;
}
public void remove(Vertex vertex) {
this.vertices.remove(vertex.getLabel());
}
public void removeVertexAndEdges(Vertex vertex) {
if (!containsVertex(vertex)) { throw new IllegalStateException("attempting to remove vertex that is not in graph."); }
for (Edge e : vertex.getIncoming()) {
this.temporaryEdges.remove(e);
}
for (Edge e : vertex.getOutgoing()) {
this.temporaryEdges.remove(e);
}
vertex.removeAllEdges();
this.remove(vertex);
}
public Envelope getExtent() {
Envelope env = new Envelope();
for (Vertex v : getVertices()) {
env.expandToInclude(v.getCoordinate());
}
return env;
}
public TransferTable getTransferTable() {
return this.transferTable;
}
// Infer the time period covered by the transit feed
public void updateTransitFeedValidity(CalendarServiceData data) {
long now = new Date().getTime() / 1000;
final long SEC_IN_DAY = 24 * 60 * 60;
HashSet<String> agenciesWithFutureDates = new HashSet<String>();
HashSet<String> agencies = new HashSet<String>();
for (AgencyAndId sid : data.getServiceIds()) {
agencies.add(sid.getAgencyId());
for (ServiceDate sd : data.getServiceDatesForServiceId(sid)) {
// Adjust for timezone, assuming there is only one per graph.
long t = sd.getAsDate(getTimeZone()).getTime() / 1000;
if (t > now) {
agenciesWithFutureDates.add(sid.getAgencyId());
}
// assume feed is unreliable after midnight on last service day
long u = t + SEC_IN_DAY;
if (t < this.transitServiceStarts) {
this.transitServiceStarts = t;
}
if (u > this.transitServiceEnds) {
this.transitServiceEnds = u;
}
}
}
for (String agency : agencies) {
if (!agenciesWithFutureDates.contains(agency)) {
LOG.warn(this.addBuilderAnnotation(new NoFutureDates(agency)));
}
}
}
// Check to see if we have transit information for a given date
public boolean transitFeedCovers(long t) {
return (t >= this.transitServiceStarts) && (t < this.transitServiceEnds);
}
public GraphBundle getBundle() {
return this.bundle;
}
public void setBundle(GraphBundle bundle) {
this.bundle = bundle;
}
public int countVertices() {
return this.vertices.size();
}
/**
* Find the total number of edges in this Graph. There are assumed to be no Edges in an incoming
* edge list that are not in an outgoing edge list.
*
* @return number of outgoing edges in the graph
*/
public int countEdges() {
int ne = 0;
for (Vertex v : getVertices()) {
ne += v.getDegreeOut();
}
return ne;
}
/**
* Add a collection of edges from the edgesById index.
*
* @param es
*/
private void addEdgesToIndex(Collection<Edge> es) {
for (Edge e : es) {
this.edgeById.put(e.getId(), e);
}
}
/**
* Rebuilds any indices on the basis of current vertex and edge IDs. If you want the index to be
* accurate, you must run this every time the vertex or edge set changes. TODO(flamholz): keep
* the indices up to date with changes to the graph. This is not simple because the Vertex
* constructor may add itself to the graph before the Vertex has any edges, so updating indices
* on addVertex is insufficient.
*/
public void rebuildVertexAndEdgeIndices() {
this.vertexById = new HashMap<Integer, Vertex>(Vertex.getMaxIndex());
Collection<Vertex> vertices = getVertices();
for (Vertex v : vertices) {
this.vertexById.put(v.getIndex(), v);
}
// Create map from edge ids to edges.
this.edgeById = new HashMap<Integer, Edge>();
for (Vertex v : vertices) {
// TODO(flamholz): this check seems superfluous.
if (v == null) {
continue;
}
// Assumes that all the edges appear in at least one outgoing edge list.
addEdgesToIndex(v.getOutgoing());
}
}
private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException {
inputStream.defaultReadObject();
}
/**
* Add a graph builder annotation to this graph's list of graph builder annotations. The return
* value of this method is the annotation's message, which allows for a single-line idiom that
* creates, registers, and logs a new graph builder annotation:
* log.warning(graph.addBuilderAnnotation(new SomeKindOfAnnotation(param1, param2))); If the
* graphBuilderAnnotations field of this graph is null, the annotation is not actually saved,
* but the message is still returned. This allows annotation registration to be turned off,
* saving memory and disk space when the user is not interested in annotations.
*/
public String addBuilderAnnotation(GraphBuilderAnnotation gba) {
String ret = gba.getMessage();
if (this.graphBuilderAnnotations != null) {
this.graphBuilderAnnotations.add(gba);
}
return ret;
}
public List<GraphBuilderAnnotation> getBuilderAnnotations() {
return this.graphBuilderAnnotations;
}
/* (de) serialization */
public enum LoadLevel {
BASIC, FULL, DEBUG;
}
public static Graph load(File file, LoadLevel level) throws IOException, ClassNotFoundException {
LOG.info("Reading graph " + file.getAbsolutePath() + " ...");
// cannot use getClassLoader() in static context
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
return load(in, level);
}
public static Graph load(ClassLoader classLoader, File file, LoadLevel level) throws IOException, ClassNotFoundException {
LOG.info("Reading graph " + file.getAbsolutePath() + " with alternate classloader ...");
ObjectInputStream in = new GraphObjectInputStream(new BufferedInputStream(new FileInputStream(file)), classLoader);
return load(in, level);
}
public static Graph load(InputStream is, LoadLevel level) throws ClassNotFoundException, IOException {
return load(new ObjectInputStream(is), level);
}
/**
* Default load. Uses DefaultStreetVertexIndexFactory.
*
* @param in
* @param level
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public static Graph load(ObjectInputStream in, LoadLevel level) throws IOException, ClassNotFoundException {
return load(in, level, new DefaultStreetVertexIndexFactory());
}
/**
* Perform indexing on vertices, edges, and timetables, and create transient data structures.
* This used to be done in readObject methods upon deserialization, but stand-alone mode now
* allows passing graphs from graphbuilder to server in memory, without a round trip through
* serialization. TODO: do we really need a factory for different street vertex indexes?
*/
public void index(StreetVertexIndexFactory indexFactory) {
this.temporaryEdges = Collections.newSetFromMap(new ConcurrentHashMap<Edge, Boolean>());
this.streetIndex = indexFactory.newIndex(this);
LOG.debug("street index built.");
LOG.debug("Rebuilding edge and vertex indices.");
rebuildVertexAndEdgeIndices();
Set<TripPattern> tableTripPatterns = Sets.newHashSet();
for (PatternArriveVertex pav : IterableLibrary.filter(this.getVertices(), PatternArriveVertex.class)) {
tableTripPatterns.add(pav.getTripPattern());
}
for (TripPattern ttp : tableTripPatterns) {
if (ttp != null) {
ttp.scheduledTimetable.finish(); // skip frequency-based patterns with no table
// (null)
}
}
// TODO: Move this ^ stuff into the graph index
this.index = new GraphIndex(this);
}
/**
* Loading which allows you to specify StreetVertexIndexFactory and inject other implementation.
*
* @param in
* @param level
* @param indexFactory
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
@SuppressWarnings("unchecked")
public static Graph load(ObjectInputStream in, LoadLevel level, StreetVertexIndexFactory indexFactory) throws IOException,
ClassNotFoundException {
try {
Graph graph = (Graph) in.readObject();
LOG.debug("Basic graph info read.");
if (graph.graphVersionMismatch()) { throw new RuntimeException("Graph version mismatch detected."); }
if (level == LoadLevel.BASIC) { return graph; }
// vertex edge lists are transient to avoid excessive recursion depth
// vertex list is transient because it can be reconstructed from edges
LOG.debug("Loading edges...");
List<Edge> edges = (ArrayList<Edge>) in.readObject();
graph.vertices = new HashMap<String, Vertex>();
for (Edge e : edges) {
graph.vertices.put(e.getFromVertex().getLabel(), e.getFromVertex());
graph.vertices.put(e.getToVertex().getLabel(), e.getToVertex());
}
LOG.info("Main graph read. |V|={} |E|={}", graph.countVertices(), graph.countEdges());
graph.index(indexFactory);
if (level == LoadLevel.FULL) { return graph; }
if (graph.debugData) {
graph.graphBuilderAnnotations = (List<GraphBuilderAnnotation>) in.readObject();
LOG.debug("Debug info read.");
} else {
LOG.warn("Graph file does not contain debug data.");
}
return graph;
} catch (InvalidClassException ex) {
LOG.error("Stored graph is incompatible with this version of OTP, please rebuild it.");
throw new IllegalStateException("Stored Graph version error", ex);
}
}
/**
* Compares the OTP version number stored in the graph with that of the currently running
* instance. Logs warnings explaining that mismatched versions can cause problems.
*
* @return false if Maven versions match (even if commit ids do not match), true if Maven
* version of graph does not match this version of OTP or graphs are otherwise obviously
* incompatible.
*/
private boolean graphVersionMismatch() {
MavenVersion v = MavenVersion.VERSION;
MavenVersion gv = this.mavenVersion;
LOG.info("Graph version: {}", gv);
LOG.info("OTP version: {}", v);
if (!v.equals(gv)) {
LOG.error("This graph was built with a different version of OTP. Please rebuild it.");
return true; // do not allow graph use
} else if (!v.commit.equals(gv.commit)) {
if (v.qualifier.equals("SNAPSHOT")) {
LOG.warn("This graph was built with the same SNAPSHOT version of OTP, but a "
+ "different commit. Please rebuild the graph if you experience incorrect " + "behavior. ");
return false; // graph might still work
} else {
LOG.error("Commit mismatch in non-SNAPSHOT version. This implies a problem with "
+ "the build or release process.");
return true; // major problem
}
} else {
// no version mismatch, no commit mismatch
LOG.info("This graph was built with the currently running version and commit of OTP.");
return false;
}
}
public void save(File file) throws IOException {
LOG.info("Main graph size: |V|={} |E|={}", this.countVertices(), this.countEdges());
LOG.info("Writing graph " + file.getAbsolutePath() + " ...");
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
try {
save(out);
out.close();
} catch (RuntimeException e) {
out.close();
file.delete(); // remove half-written file
throw e;
}
}
public void save(ObjectOutputStream out) throws IOException {
LOG.debug("Consolidating edges...");
// this is not space efficient
List<Edge> edges = new ArrayList<Edge>(this.countEdges());
for (Vertex v : getVertices()) {
// there are assumed to be no edges in an incoming list that are not
// in an outgoing list
edges.addAll(v.getOutgoing());
if ((v.getDegreeOut() + v.getDegreeIn()) == 0) {
LOG.debug("vertex {} has no edges, it will not survive serialization.", v);
}
}
LOG.debug("Assigning vertex/edge ID numbers...");
this.rebuildVertexAndEdgeIndices();
LOG.debug("Writing edges...");
out.writeObject(this);
out.writeObject(edges);
if (this.debugData) {
// should we make debug info generation conditional?
LOG.debug("Writing debug data...");
out.writeObject(this.graphBuilderAnnotations);
out.writeObject(this.vertexById);
out.writeObject(this.edgeById);
} else {
LOG.debug("Skipping debug data.");
}
LOG.info("Graph written.");
}
/* deserialization for org.opentripplanner.customize */
private static class GraphObjectInputStream extends ObjectInputStream {
ClassLoader classLoader;
public GraphObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException {
super(in);
this.classLoader = classLoader;
}
@Override
public Class<?> resolveClass(ObjectStreamClass osc) {
try {
return Class.forName(osc.getName(), false, this.classLoader);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
public Integer getIdForEdge(Edge edge) {
return edge.getId();
}
public CalendarService getCalendarService() {
if (this.calendarService == null) {
CalendarServiceData data = this.getService(CalendarServiceData.class);
if (data != null) {
CalendarServiceImpl calendarService = new CalendarServiceImpl();
calendarService.setData(data);
this.calendarService = calendarService;
}
}
return this.calendarService;
}
public int removeEdgelessVertices() {
int removed = 0;
List<Vertex> toRemove = new LinkedList<Vertex>();
for (Vertex v : this.getVertices()) {
if ((v.getDegreeOut() + v.getDegreeIn()) == 0) {
toRemove.add(v);
}
}
// avoid concurrent vertex map modification
for (Vertex v : toRemove) {
this.remove(v);
removed += 1;
LOG.trace("removed edgeless vertex {}", v);
}
return removed;
}
public Collection<String> getAgencyIds() {
return this.agenciesIds;
}
public Collection<Agency> getAgencies() {
return this.agencies;
}
public void addAgency(Agency agency) {
this.agencies.add(agency);
this.agenciesIds.add(agency.getId());
}
public void addTemporaryEdge(Edge edge) {
this.temporaryEdges.add(edge);
}
public void removeTemporaryEdge(Edge edge) {
if ((edge.getFromVertex() == null) || (edge.getToVertex() == null)) { return; }
this.temporaryEdges.remove(edge);
}
public Collection<Edge> getTemporaryEdges() {
return this.temporaryEdges;
}
public VertexComparatorFactory getVertexComparatorFactory() {
return this.vertexComparatorFactory;
}
public void setVertexComparatorFactory(VertexComparatorFactory vertexComparatorFactory) {
this.vertexComparatorFactory = vertexComparatorFactory;
}
/**
* Returns the time zone for the first agency in this graph. This is used to interpret times in
* API requests. The JVM default time zone cannot be used because we support multiple graphs on
* one server via the routerId. Ideally we would want to interpret times in the time zone of the
* geographic location where the origin/destination vertex or board/alight event is located.
* This may become necessary when we start making graphs with long distance train, boat, or air
* services.
*/
public TimeZone getTimeZone() {
if (this.timeZone == null) {
Collection<String> agencyIds = this.getAgencyIds();
if (agencyIds.size() == 0) {
this.timeZone = TimeZone.getTimeZone("GMT");
LOG.warn("graph contains no agencies; API request times will be interpreted as GMT.");
} else {
CalendarService cs = this.getCalendarService();
for (String agencyId : agencyIds) {
TimeZone tz = cs.getTimeZoneForAgencyId(agencyId);
if (this.timeZone == null) {
LOG.debug("graph time zone set to {}", tz);
this.timeZone = tz;
} else if (!this.timeZone.equals(tz)) {
LOG.error("agency time zone differs from graph time zone: {}", tz);
}
}
}
}
return this.timeZone;
}
public void summarizeBuilderAnnotations() {
List<GraphBuilderAnnotation> gbas = this.graphBuilderAnnotations;
Multiset<Class<? extends GraphBuilderAnnotation>> classes = HashMultiset.create();
LOG.info("Summary (number of each type of annotation):");
for (GraphBuilderAnnotation gba : gbas) {
classes.add(gba.getClass());
}
for (Multiset.Entry<Class<? extends GraphBuilderAnnotation>> e : classes.entrySet()) {
String name = e.getElement().getSimpleName();
int count = e.getCount();
LOG.info(" {} - {}", name, count);
}
}
public GraphMetadata getMetadata() {
// Lazy-initialize the graph metadata since it is not serialized.
if (this.graphMetadata == null) {
this.graphMetadata = new GraphMetadata(this);
}
return this.graphMetadata;
}
public Geometry getHull() {
// Lazy-initialize the graph hull since it is not serialized.
if (this.hull == null) {
this.hull = GraphUtils.makeConvexHull(this);
}
return this.hull;
}
// lazy-init geom index on an as needed basis
public GeometryIndex getGeomIndex() {
if (this.geomIndex == null) {
this.geomIndex = new GeometryIndex(this);
}
return this.geomIndex;
}
// lazy-init sample factor on an as needed basis
public SampleFactory getSampleFactory() {
if (this.sampleFactory == null) {
this.sampleFactory = new SampleFactory(this.getGeomIndex());
}
return this.sampleFactory;
}
}
| mit |
shashanksingh28/code-similarity | data/Big Java 6th Edition/ch14/section_4/MergeSortDemo.java | 425 | import java.util.Arrays;
/**
This program demonstrates the merge sort algorithm by
sorting an array that is filled with random numbers.
*/
public class MergeSortDemo
{
public static void main(String[] args)
{
int[] a = ArrayUtil.randomIntArray(20, 100);
System.out.println(Arrays.toString(a));
MergeSorter.sort(a);
System.out.println(Arrays.toString(a));
}
}
| mit |
sarmadali20/bitparse | app/src/main/java/com/pxlim/bitparse/ParseFragment.java | 3723 | package com.pxlim.bitparse;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ParseFragment extends Fragment {
@BindView(R.id.editTextInput)
EditText editTextInput;
@BindView(R.id.parse)
Button buttonParse;
@BindView(R.id.textViewResult)
TextView textViewResult;
private Set<String> english_dict;
public ParseFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment ParseFragment.
*/
public static ParseFragment newInstance() {
ParseFragment fragment = new ParseFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parse, container, false);
ButterKnife.bind(this, view);
return view;
}
@OnClick(R.id.parse)
public void parse(View view) {
if(editTextInput.getText().toString().trim().equals("")) {
editTextInput.setError("Please provide input text");
}
buttonParse.setEnabled(false);
textViewResult.setText("");
if(english_dict == null) {
DictionaryMaker task = new DictionaryMaker(editTextInput.getText().toString());
task.execute();
return;
}
parseAndUpdateResults(editTextInput.getText().toString());
}
public void parseAndUpdateResults(String input) {
LinkedHashSet<String> words = new LinkedHashSet<>();
ParseUtils.search(input,english_dict,words);
StringBuilder sb = new StringBuilder();
for (String word : words) {
sb.append(word);
sb.append("\n");
}
textViewResult.setText(sb.toString());
buttonParse.setEnabled(true);
}
public class DictionaryMaker extends AsyncTask<Void, Void, Set<String>> {
private String input;
public DictionaryMaker(String input) {
this.input = input;
}
@Override
protected Set<String> doInBackground(Void... params) {
Set<String> result = new HashSet<>();
try{
InputStream file = ParseFragment.this.getResources().openRawResource(R.raw.english_dict);
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line;
while ((line = reader.readLine()) != null) {
result.add(line);
}
reader.close();
} catch(IOException ioe){
Log.e(ParseFragment.class.toString(), ioe.getMessage());
}
return result;
}
@Override
protected void onPostExecute(Set<String> result) {
ParseFragment.this.english_dict = result;
ParseFragment.this.parseAndUpdateResults(input);
}
}
}
| mit |
vingd/vingd-api-java | examples/PurchaseConsoleExample.java | 1267 | import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
import com.vingd.client.VingdClient;
import com.vingd.client.VingdOrder;
import com.vingd.client.VingdPurchase;
import com.vingd.client.exception.VingdOperationException;
import com.vingd.client.exception.VingdTransportException;
public class PurchaseConsoleExample {
public static void main(String[] args) throws VingdTransportException, VingdOperationException, IOException, NoSuchAlgorithmException {
VingdClient vingd = new VingdClient("test@vingd.com", VingdClient.SHA1("123"), VingdClient.sandboxEndpointURL, VingdClient.sandboxFrontendURL);
long oid = vingd.createObject("A test object", "http://localhost:888");
System.out.println("OID = " + oid);
VingdOrder order = vingd.createOrder(oid, 200, "ctx", 15*60*1000);
System.out.println(order);
System.out.println("Purchase link: "+order.getRedirectURL());
System.out.println("Input tid: ");
Scanner input = new Scanner(System.in);
String tid = input.nextLine();
VingdPurchase purchase = vingd.verifyPurchase(oid, tid);
System.out.println("Purchase verified. Buyer HUID = "+purchase.getHUID());
vingd.commitPurchase(purchase);
System.out.println("Purchase committed.");
}
}
| mit |
arnaudroger/SimpleFlatMapper | sfm-csv/src/main/java/org/simpleflatmapper/csv/getter/CsvLongGetter.java | 1128 | package org.simpleflatmapper.csv.getter;
import org.simpleflatmapper.converter.Context;
import org.simpleflatmapper.csv.CsvRow;
import org.simpleflatmapper.csv.mapper.CsvRowGetterFactory;
import org.simpleflatmapper.map.getter.ContextualGetter;
import org.simpleflatmapper.map.getter.LongContextualGetter;
import org.simpleflatmapper.map.getter.OptimizableIndexedContextualGetter;
public class CsvLongGetter implements ContextualGetter<CsvRow, Long>, LongContextualGetter<CsvRow>, OptimizableIndexedContextualGetter {
public final int index;
public CsvLongGetter(int index) {
this.index = index;
}
@Override
public Long get(CsvRow target, Context context) {
return CsvLongGetter.this.get(target, context, index);
}
public static Long get(CsvRow target, Context context, int index) {
return target.getLong(index);
}
@Override
public long getLong(CsvRow target, Context context) {
return getLong(target, context, index);
}
public static long getLong(CsvRow target, Context context, int index) {
return target.getLong(index);
}
}
| mit |
markwest1/yamato | src/java/net/markwest/battleship/ImageMovePanel.java | 1980 | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class ImageMovePanel extends JPanel
{
// To make this class serializable
private static final long serialVersionUID = 1L;
private BufferedImage img;
private Rectangle selection;
private double rotationAngle;
public ImageMovePanel()
{
setOpaque(false);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
setRotationAngle(0);
}
public void setImage(Point p, BufferedImage i)
{
img = i;
int w = 0;
int h = 0;
if (img != null)
{
w = img.getWidth();
h = img.getHeight();
}
selection = new Rectangle(p.x, p.y, w, h);
repaint();
}
public void setRotationAngle(double angle)
{
rotationAngle = angle;
}
public void setSelectionBounds(Rectangle rect)
{
selection = rect;
repaint();
}
public void paintComponent(Graphics gr)
{
// Convert the Graphics object to a Graphics2D object
Graphics2D g2d = (Graphics2D)gr;
// Rotate the image
g2d.rotate(Math.toRadians(rotationAngle),
img.getWidth()/2, img.getHeight()/2);
if ((img != null) && (selection != null))
{
// Declare variables
int dx1 = selection.x;
int dy1 = selection.y;
int dx2 = selection.x + selection.width;
int dy2 = selection.y + selection.height;
// Draw the image
g2d.drawImage(img,
dx1, //dx1
dy1, //dy1
dx2, //dx2
dy2, //dy2
0, //sx1
0, //sy1
img.getWidth(), //sx2
img.getHeight(), //sy2
this);
}
}
}
| mit |
Nowdone/fanxin | src/com/fanxin/app/fx/ChatSingleSettingActivity.java | 11550 | package com.fanxin.app.fx;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.fanxin.app.DemoApplication;
import com.fanxin.app.R;
import com.fanxin.app.activity.BaseActivity;
import com.fanxin.app.domain.User;
import com.fanxin.app.fx.others.LoadUserAvatar;
import com.fanxin.app.fx.others.TopUser;
import com.fanxin.app.fx.others.TopUserDao;
import com.fanxin.app.fx.others.LoadUserAvatar.ImageDownloadedCallBack;
import com.easemob.exceptions.EaseMobException;
@SuppressLint({ "SimpleDateFormat", "SdCardPath" })
public class ChatSingleSettingActivity extends BaseActivity implements
OnClickListener {
// 、置顶、、、、
private RelativeLayout rl_switch_chattotop;
private RelativeLayout rl_switch_block_groupmsg;
private RelativeLayout re_clear;
// 状态变化
private ImageView iv_switch_chattotop;
private ImageView iv_switch_unchattotop;
private ImageView iv_switch_block_groupmsg;
private ImageView iv_switch_unblock_groupmsg;
private String userId;
private String userNick;
private String avatar;
String sex;
private LoadUserAvatar avatarLoader;
private List<String> blackList;
// 置顶列表
Map<String, TopUser> topMap = new HashMap<String, TopUser>();
private ProgressDialog progressDialog;
public static ChatSingleSettingActivity instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singlechat_setting);
avatarLoader = new LoadUserAvatar(this, "/sdcard/fanxin/");
instance = this;
// 获取传过来的userId
userId = getIntent().getStringExtra("userId");
User user = DemoApplication.getInstance().getContactList().get(userId);
// 资料错误则不显示
if (user == null) {
return;
}
userNick = user.getNick();
avatar = user.getAvatar();
sex = user.getSex();
// 黑名单列表
blackList = EMContactManager.getInstance().getBlackListUsernames();
// 置顶列表
topMap = DemoApplication.getInstance().getTopUserList();
//
progressDialog = new ProgressDialog(this);
initView();
initData();
}
private void initView() {
rl_switch_chattotop = (RelativeLayout) findViewById(R.id.rl_switch_chattotop);
rl_switch_block_groupmsg = (RelativeLayout) findViewById(R.id.rl_switch_block_groupmsg);
re_clear = (RelativeLayout) findViewById(R.id.re_clear);
iv_switch_chattotop = (ImageView) findViewById(R.id.iv_switch_chattotop);
iv_switch_unchattotop = (ImageView) findViewById(R.id.iv_switch_unchattotop);
iv_switch_block_groupmsg = (ImageView) findViewById(R.id.iv_switch_block_groupmsg);
iv_switch_unblock_groupmsg = (ImageView) findViewById(R.id.iv_switch_unblock_groupmsg);
// 初始化置顶和免打扰的状态
if (!blackList.contains(userId)) {
iv_switch_block_groupmsg.setVisibility(View.INVISIBLE);
iv_switch_unblock_groupmsg.setVisibility(View.VISIBLE);
} else {
iv_switch_block_groupmsg.setVisibility(View.VISIBLE);
iv_switch_unblock_groupmsg.setVisibility(View.INVISIBLE);
}
if (!topMap.containsKey(userId)) {
// 当前状态是w未置顶
iv_switch_chattotop.setVisibility(View.INVISIBLE);
iv_switch_unchattotop.setVisibility(View.VISIBLE);
} else {
// 当前状态是置顶
iv_switch_chattotop.setVisibility(View.VISIBLE);
iv_switch_unchattotop.setVisibility(View.INVISIBLE);
}
}
private void initData() {
rl_switch_chattotop.setOnClickListener(this);
rl_switch_block_groupmsg.setOnClickListener(this);
re_clear.setOnClickListener(this);
ImageView iv_avatar = (ImageView) this.findViewById(R.id.iv_avatar);
TextView tv_username = (TextView) this.findViewById(R.id.tv_username);
tv_username.setText(userNick);
iv_avatar.setImageResource(R.drawable.default_useravatar);
iv_avatar.setTag(avatar);
if (avatar != null && !avatar.equals("")) {
Bitmap bitmap = avatarLoader.loadImage(iv_avatar, avatar,
new ImageDownloadedCallBack() {
@Override
public void onImageDownloaded(ImageView imageView,
Bitmap bitmap) {
if (imageView.getTag() == avatar) {
imageView.setImageBitmap(bitmap);
}
}
});
if (bitmap != null) {
iv_avatar.setImageBitmap(bitmap);
}
}
iv_avatar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ChatSingleSettingActivity.this,
UserInfoActivity.class).putExtra("hxid", userId)
.putExtra("nick", userNick).putExtra("avatar", avatar)
.putExtra("sex", sex));
}
});
ImageView iv_avatar2 = (ImageView) this.findViewById(R.id.iv_avatar2);
iv_avatar2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ChatSingleSettingActivity.this,
CreatChatRoomActivity.class).putExtra("userId", userId));
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rl_switch_block_groupmsg: // 设置免打扰
progressDialog.setMessage("正在设置免打扰...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
if (iv_switch_block_groupmsg.getVisibility() == View.VISIBLE) {
new Handler().postDelayed(new Runnable() {
public void run() {
removeOutBlacklist(userId);
progressDialog.dismiss();
}
}, 2000);
} else {
moveToBlacklist(userId);
}
break;
case R.id.re_clear: // 清空聊天记录
progressDialog.setMessage("正在清空消息...");
progressDialog.show();
// 按照你们要求必须有个提示,防止记录太少,删得太快,不提示
new Handler().postDelayed(new Runnable() {
public void run() {
EMChatManager.getInstance().clearConversation(userId);
progressDialog.dismiss();
}
}, 2000);
break;
case R.id.rl_switch_chattotop:
// 当前状态是已经置顶,点击后取消置顶
if (iv_switch_chattotop.getVisibility() == View.VISIBLE) {
iv_switch_chattotop.setVisibility(View.INVISIBLE);
iv_switch_unchattotop.setVisibility(View.VISIBLE);
if (topMap.containsKey(userId)) {
topMap.remove(userId);
TopUserDao topUserDao = new TopUserDao(
ChatSingleSettingActivity.this);
topUserDao.deleteTopUser(userId);
}
} else {
// 当前状态是未置顶点击后置顶
iv_switch_chattotop.setVisibility(View.VISIBLE);
iv_switch_unchattotop.setVisibility(View.INVISIBLE);
if (!topMap.containsKey(userId)) {
TopUser topUser = new TopUser();
topUser.setTime(System.currentTimeMillis());
// 1---表示是群组0----个人
topUser.setType(0);
topUser.setUserName(userId);
Map<String, TopUser> map = new HashMap<String, TopUser>();
map.put(userId, topUser);
topMap.putAll(map);
TopUserDao topUserDao = new TopUserDao(
ChatSingleSettingActivity.this);
topUserDao.saveTopUser(topUser);
}
}
break;
default:
break;
}
}
/**
* 把user移入到免打扰
*/
private void moveToBlacklist(final String username) {
new Thread(new Runnable() {
public void run() {
try {
// 加入到黑名单
EMContactManager.getInstance().addUserToBlackList(username,
false);
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
iv_switch_block_groupmsg
.setVisibility(View.VISIBLE);
iv_switch_unblock_groupmsg
.setVisibility(View.INVISIBLE);
}
});
} catch (final EaseMobException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),
"设置失败,原因:" + e.toString(),
Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
/**
* 移出免打扰
*
* @param tobeRemoveUser
*/
private void removeOutBlacklist(final String tobeRemoveUser) {
try {
// 移出黑民单
EMContactManager.getInstance().deleteUserFromBlackList(
tobeRemoveUser);
iv_switch_block_groupmsg.setVisibility(View.INVISIBLE);
iv_switch_unblock_groupmsg.setVisibility(View.VISIBLE);
} catch (EaseMobException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "设置失败",
Toast.LENGTH_SHORT).show();
}
});
}
}
public void back(View v) {
finish();
}
}
| mit |
rnicoll/payment_protocol_example | src/main/java/uk/me/jrn/payment_protocol/servlet/HttpThrowable.java | 1623 | package uk.me.jrn.payment_protocol.servlet;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* Throwable for returning HTTP statuses outwith the normal flow of execution
* for code. Used as a way of ensuring execution of a servlet stops immediately,
* rather than risking typos causing status code to be set and execution to then
* continue.
*/
public class HttpThrowable extends Throwable {
private final int statusCode;
public HttpThrowable(final int statusCode) {
super();
if (statusCode < HttpServletResponse.SC_CONTINUE
|| statusCode >= 600) {
throw new IllegalArgumentException("HTTP status codes must be in the range 100-599 inclusive.");
}
this.statusCode = statusCode;
}
public HttpThrowable(final int statusCode, final String message) {
super(message);
if (statusCode < HttpServletResponse.SC_CONTINUE
|| statusCode >= 600) {
throw new IllegalArgumentException("HTTP status codes must be in the range 100-599 inclusive.");
}
this.statusCode = statusCode;
}
public void send(final HttpServletResponse response)
throws IllegalStateException, IOException {
response.reset();
if (null != this.getMessage()) {
response.sendError(this.getStatusCode(), this.getMessage());
} else {
response.setStatus(this.getStatusCode());
}
}
public int getStatusCode() {
return statusCode;
}
}
| mit |
Darth-Igi/BudgetBook | app/src/main/java/mediajs/budgetbook/utilities/DateUtility.java | 1389 | package mediajs.budgetbook.utilities;
import android.content.Context;
import android.text.format.DateUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* Created by Juergen on 27.01.2016.
*/
public class DateUtility
{
private static SimpleDateFormat iso8601Format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
public static String convertDateToString( Date pDate )
{
String finalDate = "";
if( pDate != null )
{
TimeZone timeZone = TimeZone.getDefault();
iso8601Format.setTimeZone( timeZone );
finalDate = iso8601Format.format( pDate );
}
return finalDate;
}
public static String formatDateTime( Context pContext, Date pDate )
{
String finalDateTime = "";
if( pDate != null )
{
long when = pDate.getTime();
int flags = 0;
flags |= DateUtils.FORMAT_SHOW_TIME;
flags |= DateUtils.FORMAT_SHOW_DATE;
flags |= DateUtils.FORMAT_ABBREV_MONTH;
flags |= DateUtils.FORMAT_SHOW_YEAR;
finalDateTime = DateUtils.formatDateTime( pContext, when, flags );
}
return finalDateTime;
}
public static Date convertStringToIsoDate( String pTimeToFormat )
{
Date date = null;
if( pTimeToFormat != null )
{
try
{
date = iso8601Format.parse( pTimeToFormat );
}
catch( ParseException e )
{
date = null;
}
}
return date;
}
}
| mit |
3203317/ppp | framework-core3/src/main/java/com/transilink/framework/core/filter/PagerFilter.java | 2751 | package com.transilink.framework.core.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import com.transilink.framework.core.utils.fileUtils.SysConfigUtil;
import com.transilink.framework.core.utils.pagesUtils.PageContext;
/**
*
* @author huangxin (3203317@qq.com)
*
*/
@SuppressWarnings("all")
public class PagerFilter implements Filter {
public static final String PAGE_SIZE_NAME = "ps";
private static String ROOT_PATH = "";
private static String WEBROOT_PATH = "";
private static int framework_default_pagesize = 10;
public void destroy() {
// TODO
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
PageContext.setOffset(getOffset(httpRequest));
PageContext.setPageSize(getPageSize(httpRequest));
try {
chain.doFilter(request, response);
} finally {
PageContext.removeOffset();
PageContext.removePageSize();
}
}
private int getOffset(HttpServletRequest request) {
int offset = 0;
try {
offset = Integer.parseInt(request.getParameter("offset"));
} catch (Exception ignore) {
}
return offset;
}
private int getPageSize(HttpServletRequest httpRequest) {
String psvalue = httpRequest.getParameter("limit");
if (null != psvalue && !"".equals(psvalue.trim())) {
Integer ps = 0;
try {
ps = Integer.parseInt(psvalue);
} catch (Exception e) {
}
if (0 != ps) {
httpRequest.getSession().setAttribute(PAGE_SIZE_NAME, ps);
}
}
Integer pagesize = (Integer) httpRequest.getSession().getAttribute(
PAGE_SIZE_NAME);
if (null == pagesize) {
if (StringUtils.isNotBlank(SysConfigUtil
.get("framework.default.pagesize"))) {
framework_default_pagesize = NumberUtils.toInt(SysConfigUtil
.get("framework_default_pagesize"));
}
httpRequest.getSession().setAttribute(PAGE_SIZE_NAME, 10);
return 10;
}
return pagesize;
}
@Override
public void init(FilterConfig arg0) throws ServletException {
String realPath = arg0.getServletContext().getRealPath("/");
WEBROOT_PATH = realPath;
String rootPath = arg0.getServletContext().getContextPath();
if (null == rootPath) {
rootPath = "";
}
ROOT_PATH = rootPath;
}
public static String getRootPath() {
return ROOT_PATH;
}
public static String getWebRootPath() {
return WEBROOT_PATH;
}
}
| mit |
binig/Matching-Trees | src/main/java/org/bin2/matching/tree/QuadtreeBuilder.java | 1771 | package org.bin2.matching.tree;
import java.util.function.Function;
/**
* Created by benoitroger on 10/02/15.
*/
public class QuadtreeBuilder<V> {
private IndexConfiguration indexConfiguration;
private CoordinateTransform<V> coordinateTransform;
public static <T> Function<T, QuadtreeIndex> quadTreeIndex(IndexConfiguration indexConfiguration, CoordinateTransform<T> coordinateTransform) {
return new QuadtreeIndexFunction<>(indexConfiguration, coordinateTransform);
}
public static <V> QuadtreeBuilder<V> newBuilder() {
return new QuadtreeBuilder();
}
private static class QuadtreeIndexFunction<T> implements Function<T, QuadtreeIndex> {
private final CoordinateTransform<T> coordinateTransform;
private final IndexConfiguration indexConfiguration;
public QuadtreeIndexFunction(IndexConfiguration indexConfiguration, CoordinateTransform<T> coordinateTransform) {
this.coordinateTransform = coordinateTransform;
this.indexConfiguration = indexConfiguration;
}
@Override
public QuadtreeIndex apply(T t) {
double[] coords = coordinateTransform.toCoordinate(t);
return new QuadtreeIndex(indexConfiguration, coords);
}
}
public QuadtreeBuilder<V> withCoordinateTransform(CoordinateTransform<V> coordinateTransform) {
this.coordinateTransform=coordinateTransform;
return this;
}
public QuadtreeBuilder<V> withConfiguration(IndexConfiguration indexConfiguration) {
this.indexConfiguration=indexConfiguration;
return this;
}
public RTree<QuadtreeIndex, V> build() {
return new RTree<>(quadTreeIndex(indexConfiguration,coordinateTransform) );
}
}
| mit |
sebastienhouzet/nabaztag-source-code | server/OS/net/violet/platform/api/actions/applications/GetConfigurationInterface.java | 2377 | package net.violet.platform.api.actions.applications;
import java.util.Collections;
import java.util.List;
import net.violet.platform.api.actions.AbstractAction;
import net.violet.platform.api.actions.ActionParam;
import net.violet.platform.api.config.WidgetConfig;
import net.violet.platform.api.exceptions.InvalidParameterException;
import net.violet.platform.api.exceptions.NoSuchApplicationException;
import net.violet.platform.datamodel.Application;
import net.violet.platform.datamodel.Application.ApplicationClass;
import net.violet.platform.dataobjects.ApplicationData;
import net.violet.platform.dataobjects.FilesData;
import net.violet.platform.util.Constantes;
import org.apache.log4j.Logger;
/**
* Return the abstract configuration interface that must be displayed in HTML to
* define the application configuration
*/
public class GetConfigurationInterface extends AbstractApplicationAction {
static final Logger LOGGER = Logger.getLogger(AbstractAction.class);
/**
* Input param : the unique id of an application Return a list of
* ConfigurationWidget
*
* @see net.violet.platform.api.actions.AbstractAction#doProcessRequest(net.violet.platform.api.actions.ActionParam)
*/
@Override
protected Object doProcessRequest(ActionParam inParam) throws NoSuchApplicationException, InvalidParameterException {
final ApplicationData app = getRequestedApplication(inParam, null);
final FilesData settingFile = app.getProfile().getSettingFile();
if (settingFile != null) {
GetConfigurationInterface.LOGGER.debug("Found setting file + " + settingFile.getId());
}
if ((settingFile == null) || settingFile.isEmpty()) {
return Collections.emptyList();
}
return WidgetConfig.loadConfig(settingFile, app.hasExtendedConfigurationFile());
}
/**
* Read Only action
*
* @see net.violet.platform.api.actions.Action#getType()
*/
public ActionType getType() {
return ActionType.GET;
}
/**
* Application Configuration can be cached
*
* @see net.violet.platform.api.actions.Action#isCacheable()
*/
public boolean isCacheable() {
return true;
}
/**
* @see net.violet.platform.api.actions.Action#getExpirationTime()
*/
public long getExpirationTime() {
return Constantes.ONE_DAY_IN_S;
}
@Override
public List<ApplicationClass> getAuthorizedApplicationClasses() {
return Application.CLASSES_UI;
}
}
| mit |
MrNakaan/Seltzer | seltzer-parent/seltzer-cr/src/main/java/tech/seltzer/enums/CommandType.java | 5380 | package tech.seltzer.enums;
import tech.seltzer.objects.command.ChainCommandData;
import tech.seltzer.objects.command.CommandData;
import tech.seltzer.objects.command.GetCookieCommandData;
import tech.seltzer.objects.command.GetCookiesCommandData;
import tech.seltzer.objects.command.GoToCommandData;
import tech.seltzer.objects.command.RunJavascriptCommandData;
import tech.seltzer.objects.command.selector.FillFieldCommandData;
import tech.seltzer.objects.command.selector.SelectorCommandData;
import tech.seltzer.objects.command.selector.SendKeyCommandData;
import tech.seltzer.objects.command.selector.SendKeysCommandData;
import tech.seltzer.objects.command.selector.multiresult.MultiResultSelectorCommandData;
import tech.seltzer.objects.command.selector.multiresult.ReadAttributeCommandData;
import tech.seltzer.objects.command.wait.CountWaitCommandData;
import tech.seltzer.objects.command.wait.JavaScriptWaitCommandData;
import tech.seltzer.objects.command.wait.RefreshedWaitCommandData;
import tech.seltzer.objects.command.wait.SelectionStateWaitCommandData;
import tech.seltzer.objects.command.wait.WaitCommandData;
import tech.seltzer.objects.command.wait.existence.ExistenceWaitCommandData;
import tech.seltzer.objects.command.wait.existence.NestedExistenceWaitCommandData;
import tech.seltzer.objects.command.wait.logical.LogicalAndOrWaitCommandData;
import tech.seltzer.objects.command.wait.logical.LogicalNotWaitCommandData;
import tech.seltzer.objects.command.wait.textmatch.TextMatchAttributeSelectorWaitCommandData;
import tech.seltzer.objects.command.wait.textmatch.TextMatchSelectorWaitCommandData;
import tech.seltzer.objects.command.wait.textmatch.TextMatchWaitCommandData;
import tech.seltzer.objects.command.wait.visibility.InvisibilityWaitCommandData;
import tech.seltzer.objects.command.wait.visibility.NestedVisibilityWaitCommandData;
import tech.seltzer.objects.command.wait.visibility.VisibilityWaitCommandData;
/**
* A list of command data types that Seltzer can handle.
*/
public enum CommandType implements CrType {
NONE(CommandData.class),
BACK(CommandData.class),
CHAIN(ChainCommandData.class),
CLICK(SelectorCommandData.class),
COUNT(SelectorCommandData.class),
DELETE(SelectorCommandData.class),
EXIT(CommandData.class),
FILL_FIELD(FillFieldCommandData.class),
FORM_SUBMIT(SelectorCommandData.class),
FORWARD(CommandData.class),
GET_COOKIE(GetCookieCommandData.class),
GET_COOKIE_FILE(CommandData.class),
GET_COOKIES(GetCookiesCommandData.class),
GET_URL(CommandData.class),
GO_TO(GoToCommandData.class),
READ_ATTRIBUTE(ReadAttributeCommandData.class),
READ_TEXT(MultiResultSelectorCommandData.class),
SEND_KEY(SendKeyCommandData.class),
SEND_KEYS(SendKeysCommandData.class),
START(CommandData.class),
SCREENSHOT_PAGE(CommandData.class),
RUN_JAVASCRIPT(RunJavascriptCommandData.class),
// SCREENSHOT_ELEMENT(SelectorCommandData.class),
WAIT(WaitCommandData.class),
ALERT_PRESENT_WAIT(WaitCommandData.class),
AND_WAIT(LogicalAndOrWaitCommandData.class),
ATTRIBUTE_CONTAINS_WAIT(TextMatchAttributeSelectorWaitCommandData.class),
ATTRIBUTE_IS_WAIT(TextMatchAttributeSelectorWaitCommandData.class),
ATTRIBUTE_IS_NOT_EMPTY_WAIT(TextMatchAttributeSelectorWaitCommandData.class),
ELEMENT_SELECTION_STATE_IS_WAIT(SelectionStateWaitCommandData.class),
ELEMENT_CLICKABLE_WAIT(ExistenceWaitCommandData.class),
SWITCH_TO_FRAME_WHEN_AVAILABLE_WAIT(ExistenceWaitCommandData.class),
ELEMENT_INVISIBLE_WAIT(InvisibilityWaitCommandData.class),
ALL_ELEMENTS_INVISBLE_WAIT(InvisibilityWaitCommandData.class),
ELEMENT_WITH_TEXT_INVISIBLE_WAIT(InvisibilityWaitCommandData.class),
JAVASCRIPT_THROWS_NO_EXCEPTIONS_WAIT(JavaScriptWaitCommandData.class),
JAVASCRIPT_RETURNS_STRING_WAIT(JavaScriptWaitCommandData.class),
NOT_WAIT(LogicalNotWaitCommandData.class),
ELEMENT_COUNT_IS_WAIT(CountWaitCommandData.class),
ELEMENT_COUNT_LESS_THAN_WAIT(CountWaitCommandData.class),
ELEMENT_COUNT_GREATER_THAN_WAIT(CountWaitCommandData.class),
WINDOW_COUNT_IS_WAIT(CountWaitCommandData.class),
OR_WAIT(LogicalAndOrWaitCommandData.class),
ALL_ELEMENTS_PRESENT_WAIT(ExistenceWaitCommandData.class),
ELEMENT_PRESENT_WAIT(ExistenceWaitCommandData.class),
NESTED_ELEMENT_PRESENT_WAIT(NestedExistenceWaitCommandData.class),
NESTED_ELEMENTS_PRESENT_WAIT(NestedExistenceWaitCommandData.class),
REFRESHED_WAIT(RefreshedWaitCommandData.class),
IS_STALE_WAIT(ExistenceWaitCommandData.class),
TEXT_MATCHES_WAIT(TextMatchSelectorWaitCommandData.class),
TEXT_IS_WAIT(TextMatchSelectorWaitCommandData.class),
TEXT_PRESENT_IN_ELEMENT_WAIT(TextMatchSelectorWaitCommandData.class),
TEXT_IN_ELEMENT_VALUE_WAIT(TextMatchSelectorWaitCommandData.class),
TITLE_CONTAINS_WAIT(TextMatchWaitCommandData.class),
TITLE_IS_WAIT(TextMatchWaitCommandData.class),
URL_CONTAINS_WAIT(TextMatchWaitCommandData.class),
URL_MATCHES_WAIT(TextMatchWaitCommandData.class),
URL_IS_WAIT(TextMatchWaitCommandData.class),
ELEMENT_VISIBLE_WAIT(VisibilityWaitCommandData.class),
ALL_ELEMENTS_VISIBLE_WAIT(VisibilityWaitCommandData.class),
NESTED_ELEMENTS_VISIBLE_WAIT(NestedVisibilityWaitCommandData.class);
private Class<? extends CommandData> commandClass;
private CommandType(Class<? extends CommandData> commandClass) {
this.commandClass = commandClass;
}
@Override
public Class<? extends CommandData> getCrClass() {
return commandClass;
}
}
| mit |
paradoxical-io/cassieq | core/src/main/java/io/paradoxical/cassieq/workers/DefaultMessagePublisher.java | 2050 | package io.paradoxical.cassieq.workers;
import com.godaddy.logging.Logger;
import com.google.inject.Inject;
import io.paradoxical.cassieq.dataAccess.exceptions.ExistingMonotonFoundException;
import io.paradoxical.cassieq.factories.MessageRepoFactory;
import io.paradoxical.cassieq.factories.MonotonicRepoFactory;
import io.paradoxical.cassieq.model.Message;
import io.paradoxical.cassieq.model.QueueDefinition;
import org.joda.time.Duration;
import static com.godaddy.logging.LoggerFactory.getLogger;
public class DefaultMessagePublisher implements MessagePublisher {
private static final Logger logger = getLogger(DefaultMessagePublisher.class);
private final MonotonicRepoFactory monotonicRepository;
private final MessageRepoFactory messageRepoFactory;
@Inject
public DefaultMessagePublisher(
MonotonicRepoFactory monotonicRepository,
MessageRepoFactory messageRepoFactory) {
this.monotonicRepository = monotonicRepository;
this.messageRepoFactory = messageRepoFactory;
}
@Override
public void put(final QueueDefinition queueDefinition, final String message, final Long initialInvisibilityTimeSeconds) throws ExistingMonotonFoundException {
final Message messageToInsert = Message.builder()
.blob(message)
.index(monotonicRepository.forQueue(queueDefinition.getId())
.nextMonotonic())
.build();
final Duration initialInvisibility = Duration.standardSeconds(initialInvisibilityTimeSeconds);
messageRepoFactory.forQueue(queueDefinition)
.putMessage(messageToInsert, initialInvisibility);
logger.with("index", messageToInsert.getIndex())
.with("tag", messageToInsert.getTag())
.with("queue-id", queueDefinition.getId())
.debug("Adding message");
}
}
| mit |
chebykinn/university | webservices/lab1/client/src/lab1/ObjectFactory.java | 3895 |
package lab1;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the lab1 package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _GetPersonsResponse_QNAME = new QName("http://lab1.webservices.chebykin.org/", "getPersonsResponse");
private final static QName _GetPersons_QNAME = new QName("http://lab1.webservices.chebykin.org/", "getPersons");
private final static QName _InvalidFilterException_QNAME = new QName("http://lab1.webservices.chebykin.org/", "InvalidFilterException");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: lab1
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link PersonFilter }
*
*/
public PersonFilter createPersonFilter() {
return new PersonFilter();
}
/**
* Create an instance of {@link PersonFilter.Parameters }
*
*/
public PersonFilter.Parameters createPersonFilterParameters() {
return new PersonFilter.Parameters();
}
/**
* Create an instance of {@link PersonServiceFault }
*
*/
public PersonServiceFault createPersonServiceFault() {
return new PersonServiceFault();
}
/**
* Create an instance of {@link GetPersons }
*
*/
public GetPersons createGetPersons() {
return new GetPersons();
}
/**
* Create an instance of {@link GetPersonsResponse }
*
*/
public GetPersonsResponse createGetPersonsResponse() {
return new GetPersonsResponse();
}
/**
* Create an instance of {@link Person }
*
*/
public Person createPerson() {
return new Person();
}
/**
* Create an instance of {@link PersonFilter.Parameters.Entry }
*
*/
public PersonFilter.Parameters.Entry createPersonFilterParametersEntry() {
return new PersonFilter.Parameters.Entry();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetPersonsResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://lab1.webservices.chebykin.org/", name = "getPersonsResponse")
public JAXBElement<GetPersonsResponse> createGetPersonsResponse(GetPersonsResponse value) {
return new JAXBElement<GetPersonsResponse>(_GetPersonsResponse_QNAME, GetPersonsResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetPersons }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://lab1.webservices.chebykin.org/", name = "getPersons")
public JAXBElement<GetPersons> createGetPersons(GetPersons value) {
return new JAXBElement<GetPersons>(_GetPersons_QNAME, GetPersons.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link PersonServiceFault }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://lab1.webservices.chebykin.org/", name = "InvalidFilterException")
public JAXBElement<PersonServiceFault> createInvalidFilterException(PersonServiceFault value) {
return new JAXBElement<PersonServiceFault>(_InvalidFilterException_QNAME, PersonServiceFault.class, null, value);
}
}
| mit |
alketola/popmovies | app/src/main/java/com/mobilitio/popmovies/data/PopMoviesDbContract.java | 2406 | package com.mobilitio.popmovies.data;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Created by Antti on 2017-02-22.
*/
public class PopMoviesDbContract {
public static final String AUTHORITY = "com.mobilitio.popmovies";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
public static final String MOVIE_PATH = "movie";
public static final String ALL_MOVIES_PATH = "allmovies";
public static final String TRAILERS_PATH = "trailers";
public static final class MovieEntry implements BaseColumns {
public static final String TABLE = "movies";
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon()
.appendPath(MOVIE_PATH)
.build();
// CONVENTION: DB column names are the same as TMDB json object names
public static final String COLUMN_ORIGINAL_LANGUAGE = "original_language"; //tmdb_res_original_language
public static final String COLUMN_GENRE_IDS = "genre_ids"; // INT ARRAY: [12,16,35,10751], // tmdb_res_genre_ids_int_array
public static final String COLUMN_BACKDROP_PATH = "backdrop_path"; // "/lubzBMQLLmG88CLQ4F3TxZr2Q7N.jpg", //tmdb_res_backdrop
public static final String COLUMN_OVERVIEW = "overview"; // "The lorem.", // tmdb_res_overview
public static final String COLUMN_VIDEO = "video"; // boolean: INT 0=false, //tmdb_res_video_boolean
public static final String COLUMN_POPULARITY = "popularity"; // FLOAT 308.180118, // tmdb_res_popularity_decimal
public static final String COLUMN_VOTE_COUNT = "vote_count";//INT 1854, //
public static final String COLUMN_VOTE_AVERAGE = "vote_average"; // FLOAT: 5.8
public static final String COLUMN_RELEASE_DATE = "release_date"; // DATE FORMAT "2016-06-18"
public static final String COLUMN_MOVIE_ID = "movie_id"; // INT 328111, PRIMARY KEY // "tmdb_res_id_int">id< !!!!
public static final String COLUMN_POSTER_PATH = "poster_path"; // tmdb_res_poster
public static final String COLUMN_TITLE = "title"; // tmdb_res_title
public static final String COLUMN_ADULT = "adult"; // boolean: INT 0=false,
public static final String COLUMN_ORIGINAL_TITLE = "original_title"; // tmdb_res_original_title
public static final String COLUMN_FAVOURITE = "favourite"; // boolean: INT 0=false,
}
}
| mit |
Shingyx/tictactoe | src/main/java/CmdMain.java | 2916 | import ai.MiniMaxTree;
import game.Game;
import game.GameState;
import game.Player;
import java.util.Scanner;
/**
* Main application for no GUI version.
*/
public class CmdMain {
private Game game;
private Player player;
private Scanner scanner;
public static void main(String[] args) {
CmdMain main = new CmdMain();
Player player = Player.NONE;
if (args.length > 0) {
switch (args[0].trim().toUpperCase()) {
case "X":
player = Player.X;
break;
case "O":
player = Player.O;
break;
default:
System.err.println("Invalid argument");
return;
}
}
main.initialise(player);
}
private void initialise(Player player) {
scanner = new Scanner(System.in);
if (player != Player.NONE) {
this.player = player;
} else {
System.out.println("Choose a player to be: X or O");
String input = scanner.next();
input = input.trim().toUpperCase();
switch (input) {
case "X":
this.player = Player.X;
break;
case "O":
this.player = Player.O;
break;
default:
System.err.println("Invalid input");
return;
}
}
System.out.println("You are player " + this.player.name());
System.out.println("To play, type in row and column, e.g. '0 2' for top right corner, when prompted to do so");
newGame();
gameLoop();
}
private void gameLoop() {
System.out.println(game);
GameState state = game.calculateState();
while (state == GameState.IN_PROGRESS) {
Player currentTurn = game.getTurn();
if (currentTurn == Player.X && player == Player.O ||
currentTurn == Player.O && player == Player.X) {
System.out.println("AI turn");
game.makeAiMove();
} else {
System.out.println("Your turn");
int row = scanner.nextInt();
int col = scanner.nextInt();
boolean move = game.makeMove(row, col);
while (!move) {
System.out.println("Invalid move");
System.out.println("Your turn");
row = scanner.nextInt();
col = scanner.nextInt();
move = game.makeMove(row, col);
}
}
System.out.println(game);
state = game.calculateState();
}
System.out.println(state.toString());
}
private void newGame() {
game = new Game();
}
}
| mit |
archimatetool/archi | org.eclipse.zest.layouts/src/org/eclipse/zest/layouts/dataStructures/DisplayIndependentPoint.java | 3014 | /*******************************************************************************
* Copyright 2005, CHISEL Group, University of Victoria, Victoria, BC, Canada.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: The Chisel Group, University of Victoria
*******************************************************************************/
package org.eclipse.zest.layouts.dataStructures;
/**
* This is a point that isn't dependent on awt, swt, or any other library,
* except layout.
*
* @author Casey Best
*/
public class DisplayIndependentPoint {
public double x, y;
@Override
public boolean equals(Object o) {
DisplayIndependentPoint that = (DisplayIndependentPoint) o;
if (this.x == that.x && this.y == that.y)
return true;
else
return false;
}
public DisplayIndependentPoint(double x, double y) {
this.x = x;
this.y = y;
}
public DisplayIndependentPoint(DisplayIndependentPoint point) {
this.x = point.x;
this.y = point.y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
/**
* Create a new point based on the current point but in a new coordinate system
* @param currentBounds
* @param targetBounds
* @return
*/
public DisplayIndependentPoint convert(DisplayIndependentRectangle currentBounds, DisplayIndependentRectangle targetBounds) {
double currentWidth = currentBounds.width;
double currentHeight = currentBounds.height;
double newX = (currentBounds.width == 0) ? 0 : (x / currentWidth) * targetBounds.width + targetBounds.x;
double newY = (currentBounds.height == 0) ? 0 : (y / currentHeight) * targetBounds.height + targetBounds.y;
return new DisplayIndependentPoint(newX, newY);
}
/**
* Converts this point based on the current x, y values to a percentage
* of the specified coordinate system
* @param bounds
* @return
*/
public DisplayIndependentPoint convertToPercent(DisplayIndependentRectangle bounds) {
double newX = (bounds.width == 0) ? 0 : (x - bounds.x) / bounds.width;
double newY = (bounds.height == 0) ? 0 : (y - bounds.y) / bounds.height;
return new DisplayIndependentPoint(newX, newY);
}
/**
* Converts this point based on the current x, y values from a percentage
* of the specified coordinate system
* @param bounds
* @return
*/
public DisplayIndependentPoint convertFromPercent(DisplayIndependentRectangle bounds) {
double newX = bounds.x + x * bounds.width;
double newY = bounds.y + y * bounds.height;
return new DisplayIndependentPoint(newX, newY);
}
}
| mit |
HerrB92/obp | OpenBeaconPackage/libraries/jadira.parent-3.1.0.CR8/jadira/bindings/src/main/java/org/jadira/bindings/core/utils/reflection/TypeHelper.java | 4375 | /*
* Copyright 2010, 2011 Christopher Pheby
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jadira.bindings.core.utils.reflection;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Originally based on http://www.artima.com/weblogs/viewpost.jsp?thread=208860
*/
public final class TypeHelper {
private TypeHelper() {
}
/**
* Get the underlying class for a type, or null if the type is a variable type.
* @param type the type
* @return the underlying class
*/
public static Class<?> getClass(Type type) {
if (type instanceof Class<?>) {
return (Class<?>) type;
} else if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
Class<?> componentClass = getClass(componentType);
if (componentClass != null) {
return Array.newInstance(componentClass, 0).getClass();
} else {
return null;
}
} else {
return null;
}
}
/**
* Get the actual type arguments a child class has used to extend a generic base class.
* @param baseClass the base class
* @param childClass the child class
* @return a list of the raw classes for the actual type arguments.
*/
public static <T> List<Class<?>> getTypeArguments(Class<T> baseClass, Class<? extends T> childClass) {
Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
Type type = childClass;
// start walking up the inheritance hierarchy until we hit baseClass
while (!getClass(type).equals(baseClass)) {
if (type instanceof Class<?>) {
// there is no useful information for us in raw types, so just keep going.
type = ((Class<?>) type).getGenericSuperclass();
} else {
ParameterizedType parameterizedType = (ParameterizedType) type;
Class<?> rawType = (Class<?>) parameterizedType.getRawType();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
for (int i = 0; i < actualTypeArguments.length; i++) {
resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
}
if (!rawType.equals(baseClass)) {
type = rawType.getGenericSuperclass();
}
}
}
// finally, for each actual type argument provided to baseClass, determine (if possible)
// the raw class for that type argument.
Type[] actualTypeArguments;
if (type instanceof Class<?>) {
actualTypeArguments = ((Class<?>) type).getTypeParameters();
} else {
actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
}
List<Class<?>> typeArgumentsAsClasses = new ArrayList<Class<?>>();
// resolve types by chasing down type variables.
for (Type baseType : actualTypeArguments) {
while (resolvedTypes.containsKey(baseType)) {
baseType = resolvedTypes.get(baseType);
}
typeArgumentsAsClasses.add(getClass(baseType));
}
return typeArgumentsAsClasses;
}
} | mit |
SebastianCarroll/AlgorithmsForJava | src/Graphs/graphs/BFSTest.java | 2134 | package Graphs.graphs;
import static org.junit.Assert.*;
import Misc.base.Colour;
import org.junit.Test;
public class BFSTest {
@Test
public void checkBFS() {
Integer[][] graph = new Integer[][]{
{0,1,0,0},
{0,0,0,1},
{0,1,0,0},
{0,0,1,0}
};
Graph G = new Graph(graph);
GraphNode[] nodes = G.BFS(0);
assertEquals(nodes[0].parent, null);
assertEquals(nodes[1].parent.value, new Integer(0));
assertEquals(nodes[2].parent.value, new Integer(3));
assertEquals(nodes[3].parent.value, new Integer(1));
}
@Test
public void checkBFS_SelfPointingNode() {
Integer[][] graph = new Integer[][]{
{0,1,0,0},
{0,1,0,1},
{0,1,1,0},
{0,0,1,0}
};
Graph G = new Graph(graph);
GraphNode[] nodes = G.BFS(0);
assertEquals(nodes[0].parent, null);
assertEquals(nodes[1].parent.value, new Integer(0));
assertEquals(nodes[2].parent.value, new Integer(3));
assertEquals(nodes[3].parent.value, new Integer(1));
}
@Test
public void checkBFS_UnreachableNode() {
Integer[][] graph = new Integer[][]{
{0,1,0,0},
{0,1,0,1},
{0,1,1,0},
{0,0,1,0}
};
Graph G = new Graph(graph);
GraphNode[] nodes = G.BFS(1);
assertNull(nodes[0].parent);
assertEquals(nodes[0].colour, Colour.WHITE);
assertNull(nodes[1].parent);
assertEquals(nodes[2].parent.value, new Integer(3));
assertEquals(nodes[3].parent.value, new Integer(1));
}
@Test
public void checkBFS_SingleNode() {
Integer[][] graph = new Integer[][]{
{1}
};
Graph G = new Graph(graph);
GraphNode[] nodes = G.BFS(0);
assertNull(nodes[0].parent);
assertEquals(nodes[0].colour, Colour.BLACK);
}
@Test(expected=IllegalArgumentException.class)
public void checkBFS_InvalidInput() {
Integer[][] graph = new Integer[][]{
{1, 0, 0}
};
new Graph(graph);
}
@Test(expected=IllegalArgumentException.class)
public void checkBFS_StartNodeOutOfBounds() {
Integer[][] graph = new Integer[][]{
{1}
};
Graph G = new Graph(graph);
G.BFS(1);
}
}
| mit |
CS2103AUG2016-T09-C2/main | src/test/java/seedu/jimi/logic/JimiParserTest.java | 907 | package seedu.jimi.logic;
import java.lang.reflect.Field;
import org.junit.Test;
import seedu.jimi.logic.commands.AddCommand;
import seedu.jimi.logic.commands.Command;
import seedu.jimi.logic.parser.JimiParser;
import seedu.jimi.model.task.DeadlineTask;
public class JimiParserTest {
@Test
public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
JimiParser parser = new JimiParser();
String userInput = "add \"chore\" due 12-31-2017";
Command c = parser.parseCommand(userInput);
assert c instanceof AddCommand;
Field field = AddCommand.class.getDeclaredField("toAdd");
field.setAccessible(true);
Object o = field.get(c);
assert o instanceof DeadlineTask;
String output = ((DeadlineTask)o).getDeadline().toString();
System.out.println(output);
}
}
| mit |
nnest/sparrow | sparrow-rest/src/main/java/com/github/nnest/sparrow/rest/command/RestCommandEndpointBuilder.java | 6761 | /**
*
*/
package com.github.nnest.sparrow.rest.command;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.github.nnest.sparrow.ElasticDocumentDescriptor;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
/**
* rest command uri helper
*
* @author brad.wu
* @since 0.0.1
* @version 0.0.1
*/
public final class RestCommandEndpointBuilder {
/**
* build endpoint by given document descriptor and id
*
* @param documentDescriptor
* document descriptor
* @param idValue
* id
* @return endpoint
*/
public static String buildEndpoint(ElasticDocumentDescriptor documentDescriptor, String idValue) {
return buildEndpoint(documentDescriptor, idValue, null);
}
/**
* build endpoint by given parameters<br>
* index name and type name are get from {@code documentDescriptor},<br>
* other parameters are optional.
*
* @param documentDescriptor
* document descriptor
* @param idValue
* id value
* @param endpointCommand
* endpoint command
* @return endpoint
*/
public static String buildEndpoint(ElasticDocumentDescriptor documentDescriptor, String idValue,
String endpointCommand) {
return buildEndpoint(documentDescriptor.getIndex(), documentDescriptor.getType(), idValue, endpointCommand);
}
/**
* build endpoint by given parameters.
*
* @param index
* index name
* @param type
* type name
* @param idValue
* id value
* @param endpointCommand
* endpoint command
* @return endpoint
*/
public static String buildEndpoint(String index, String type, String idValue, String endpointCommand) {
return buildEndpoint(Sets.newHashSet(index), Sets.newHashSet(type), idValue, endpointCommand);
}
/**
* build endpoint by given parameters
*
* @param indices
* index names
* @param types
* type names
* @param idValue
* id value
* @param endpointCommand
* endpoint command
* @return endpoint
*/
public static String buildEndpoint(Set<String> indices, Set<String> types, String idValue, String endpointCommand) {
List<String> parts = new LinkedList<String>();
if (indices != null && indices.size() > 0) {
Joiner joiner = Joiner.on(",").skipNulls();
String indicesString = joiner.join(indices);
if (Strings.nullToEmpty(indicesString).trim().length() != 0) {
parts.add(indicesString);
if (types != null && types.size() > 0) {
String typesString = joiner.join(types);
if (Strings.nullToEmpty(typesString).trim().length() != 0) {
parts.add(typesString);
}
}
}
}
if (idValue != null) {
parts.add(idValue);
}
parts.add(endpointCommand);
return Joiner.on('/').skipNulls().join(parts);
}
/**
* transform query parameters to string map
*
* @param params
* parameters
* @return map
*/
@SuppressWarnings("rawtypes")
public static Map<String, String> transformQueryParameters(Set<QueryParam> params) {
if (params == null || params.size() == 0) {
return null;
} else {
Map<String, String> map = new HashMap<>();
for (QueryParam param : params) {
map.put(param.getKey(), param.getValueAsString());
}
return map;
}
}
/**
* transform query parameters to string map
*
* @param params
* parameters
* @return map
*/
@SuppressWarnings("rawtypes")
public static Map<String, String> transformQueryParameters(QueryParam... params) {
if (params == null || params.length == 0) {
return null;
} else {
Map<String, String> map = new HashMap<>();
for (QueryParam param : params) {
map.put(param.getKey(), param.getValueAsString());
}
return map;
}
}
/**
* query parameter of endpoint
*
* @author brad.wu
* @since 0.0.1
* @version 0.0.1
*/
public static interface QueryParam<V> {
/**
* get value as string
*
* @return string value
*/
String getValueAsString();
/**
* get key of param
*
* @return key
*/
String getKey();
}
/**
* abstract query parameter
*
* @author brad.wu
* @since 0.0.1
* @version 0.0.1
*/
public static abstract class AbstractQueryParam<V> implements QueryParam<V> {
private String key = null;
private V value = null;
public AbstractQueryParam(String key, V value) {
assert Strings.nullToEmpty(key).trim().length() != 0 : "Key of query parameter cannot be null or blank.";
this.setKey(key);
this.setValue(value);
}
/**
* (non-Javadoc)
*
* @see com.github.nnest.sparrow.rest.command.RestCommandEndpointBuilder.QueryParam#getKey()
*/
@Override
public String getKey() {
return key;
}
/**
* @param key
* the key to set
*/
protected void setKey(String key) {
this.key = key;
}
/**
* @return the value
*/
public V getValue() {
return value;
}
/**
* @param value
* the value to set
*/
protected void setValue(V value) {
this.value = value;
}
}
/**
* simple query parameter
*
* @author brad.wu
* @since 0.0.1
* @version 0.0.1
*/
public static class SimpleQueryParam extends AbstractQueryParam<String> {
public SimpleQueryParam(String key, String value) {
super(key, value);
}
/**
* (non-Javadoc)
*
* @see com.github.nnest.sparrow.rest.command.RestCommandEndpointBuilder.QueryParam#getValueAsString()
*/
@Override
public String getValueAsString() {
return this.getValue();
}
}
/**
* version query parameter
*
* @author brad.wu
* @since 0.0.1
* @version 0.0.1
*/
public static class VersionQueryParam extends SimpleQueryParam {
public VersionQueryParam(String value) {
super("version", value);
}
/**
* with version
*
* @param value
* value
* @return new VersionQueryParam
*/
public static VersionQueryParam withVersion(String value) {
return new VersionQueryParam(value);
}
}
/**
* query parameter of set values.
*
* @author brad.wu
* @since 0.0.1
* @version 0.0.1
*/
public static class SetQueryParam extends AbstractQueryParam<Set<String>> {
public SetQueryParam(String key, Set<String> value) {
super(key, value);
}
/**
* (non-Javadoc)
*
* @see com.github.nnest.sparrow.rest.command.RestCommandEndpointBuilder.QueryParam#getValueAsString()
*/
@Override
public String getValueAsString() {
Set<String> values = this.getValue();
if (values == null || values.size() == 0) {
return null;
} else {
return Joiner.on(",").skipNulls().join(values);
}
}
}
}
| mit |
alicexinyun/CS2110 | hw3/q2/FullQException.java | 111 | public class FullQException extends Exception {
public FullQException(String string) {
super (string);
}
} | mit |
xiaoyu830411/abtesting_dsl | src/main/java/com/yanglinkui/ab/dsl/condition/Statements.java | 638 | package com.yanglinkui.ab.dsl.condition;
import com.yanglinkui.ab.dsl.Context;
import com.yanglinkui.ab.dsl.Expression;
/**
* Created by jonas on 2017/1/4.
*/
public class Statements implements Expression {
private Expression expression;
public Statements() {}
public Expression getExpression() {
return expression;
}
public void setExpression(Expression expression) {
this.expression = expression;
}
public boolean interpret(Context context) {
return this.expression.interpret(context);
}
public String toString() {
return this.expression.toString();
}
}
| mit |
Azure/azure-sdk-for-java | sdk/securityinsights/azure-resourcemanager-securityinsights/src/main/java/com/azure/resourcemanager/securityinsights/fluent/BookmarkRelationsClient.java | 8187 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.securityinsights.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.securityinsights.fluent.models.RelationInner;
/** An instance of this class provides access to all the operations defined in BookmarkRelationsClient. */
public interface BookmarkRelationsClient {
/**
* Gets all bookmark relations.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param bookmarkId Bookmark ID.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all bookmark relations.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<RelationInner> list(String resourceGroupName, String workspaceName, String bookmarkId);
/**
* Gets all bookmark relations.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param bookmarkId Bookmark ID.
* @param filter Filters the results, based on a Boolean condition. Optional.
* @param orderby Sorts the results. Optional.
* @param top Returns only the first n results. Optional.
* @param skipToken Skiptoken is only used if a previous operation returned a partial result. If a previous response
* contains a nextLink element, the value of the nextLink element will include a skiptoken parameter that
* specifies a starting point to use for subsequent calls. Optional.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all bookmark relations.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<RelationInner> list(
String resourceGroupName,
String workspaceName,
String bookmarkId,
String filter,
String orderby,
Integer top,
String skipToken,
Context context);
/**
* Gets a bookmark relation.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param bookmarkId Bookmark ID.
* @param relationName Relation Name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a bookmark relation.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
RelationInner get(String resourceGroupName, String workspaceName, String bookmarkId, String relationName);
/**
* Gets a bookmark relation.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param bookmarkId Bookmark ID.
* @param relationName Relation Name.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a bookmark relation along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<RelationInner> getWithResponse(
String resourceGroupName, String workspaceName, String bookmarkId, String relationName, Context context);
/**
* Creates the bookmark relation.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param bookmarkId Bookmark ID.
* @param relationName Relation Name.
* @param relation The relation model.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return represents a relation between two resources.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
RelationInner createOrUpdate(
String resourceGroupName, String workspaceName, String bookmarkId, String relationName, RelationInner relation);
/**
* Creates the bookmark relation.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param bookmarkId Bookmark ID.
* @param relationName Relation Name.
* @param relation The relation model.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return represents a relation between two resources along with {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<RelationInner> createOrUpdateWithResponse(
String resourceGroupName,
String workspaceName,
String bookmarkId,
String relationName,
RelationInner relation,
Context context);
/**
* Delete the bookmark relation.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param bookmarkId Bookmark ID.
* @param relationName Relation Name.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String workspaceName, String bookmarkId, String relationName);
/**
* Delete the bookmark relation.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param bookmarkId Bookmark ID.
* @param relationName Relation Name.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the {@link Response}.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> deleteWithResponse(
String resourceGroupName, String workspaceName, String bookmarkId, String relationName, Context context);
}
| mit |
tejen/codepath-android-twitter | app/src/main/java/org/tejen/codepathandroid/twitter/data/User.java | 2726 | package org.tejen.codepathandroid.twitter.data;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcel;
import org.tejen.codepathandroid.twitter.TwitterApp;
import cz.msebera.android.httpclient.Header;
/**
* Created by tejen on 6/6/17.
*/
@Parcel
public class User {
// list the attributes
private String name;
private long uid;
private String screenName;
private String profileImageUrl;
private boolean isVerified;
public String getName(){ return name; }
public long getUid(){ return uid; }
public String getScreenName(){ return screenName; }
public String getProfileImageUrl(){ return profileImageUrl; }
public boolean isVerified(){ return isVerified; }
// deserialize JSON
public static User fromJSON(JSONObject jsonObject) throws JSONException {
User user = new User();
// extract and fill the values
user.name = jsonObject.getString("name");
user.uid = jsonObject.getLong("id");
user.screenName = jsonObject.getString("screen_name");
user.profileImageUrl = jsonObject.getString("profile_image_url");
user.isVerified = jsonObject.getBoolean("verified");
return user;
}
public interface UserCallbackInterface {
void onUserAvailable(User currentUser);
}
public static void getCurrentUser(final UserCallbackInterface handler) {
TwitterClient client = TwitterApp.getRestClient();
client.verifyCredentials(new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
try {
handler.onUserAvailable(User.fromJSON(response));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
}
});
}
}
| mit |
jbocharov/voicebase-java-samples | v3-upload-transcribe/src/main/java/com/voicebase/sample/v3client/model/VbPriorityEnum.java | 1013 | /*
* Voicebase V3 API
* APIs for speech recognition and speech analytics, powering insights every business needs.
*
* OpenAPI spec version: 3.0.1
* Contact: support@voicebase.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.voicebase.sample.v3client.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
/**
* Gets or Sets VbPriorityEnum
*/
public enum VbPriorityEnum {
HIGH("high"),
NORMAL("normal"),
LOW("low");
private String value;
VbPriorityEnum(String value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static VbPriorityEnum fromValue(String text) {
for (VbPriorityEnum b : VbPriorityEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
| mit |
iontorrent/Torrent-Variant-Caller-stable | public/java/src/org/broadinstitute/sting/utils/exceptions/DynamicClassResolutionException.java | 2375 | /*
* Copyright (c) 2010, The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.utils.exceptions;
import java.lang.reflect.InvocationTargetException;
/**
* Class for handling common failures of dynamic class resolution
*
* User: depristo
* Date: Sep 3, 2010
* Time: 2:24:09 PM
*/
public class DynamicClassResolutionException extends UserException {
public DynamicClassResolutionException(Class c, Exception ex) {
super(String.format("Could not create module %s because %s caused by exception %s",
c.getSimpleName(), moreInfo(ex), ex.getMessage()));
}
private static String moreInfo(Exception ex) {
try {
throw ex;
} catch (InstantiationException e) {
return "BUG: cannot instantiate class: must be concrete class";
} catch (NoSuchMethodException e) {
return "BUG: Cannot find expected constructor for class";
} catch (IllegalAccessException e) {
return "Cannot instantiate class (Illegal Access)";
} catch (InvocationTargetException e) {
return "Cannot instantiate class (Invocation failure)";
} catch ( Exception e ) {
return String.format("an exception of type %s occurred",e.getClass().getSimpleName());
}
}
}
| mit |
Wurmcraft/WurmTweaks | src/main/java/wurmcraft/wurmatron/common/utils/thermalexpansion/TEHelper.java | 32267 | package wurmcraft.wurmatron.common.utils.thermalexpansion;
import cofh.api.modhelpers.ThermalExpansionHelper;
import cofh.thermalexpansion.block.TEBlocks;
import cofh.thermalexpansion.util.crafting.CrucibleManager;
import cofh.thermalexpansion.util.crafting.PulverizerManager;
import cofh.thermalexpansion.util.crafting.TransposerManager;
import cpw.mods.fml.common.Optional;
import cpw.mods.fml.common.event.FMLInterModComms;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
public class TEHelper {
public static ItemStack Furnace = new ItemStack(TEBlocks.blockMachine, 1, 0);
public static ItemStack Pulversier = new ItemStack(TEBlocks.blockMachine, 1, 1);
public static ItemStack Sawmill = new ItemStack(TEBlocks.blockMachine, 1, 2);
public static ItemStack Smelter = new ItemStack(TEBlocks.blockMachine, 1, 3);
public static ItemStack Magma = new ItemStack(TEBlocks.blockMachine, 1, 4);
public static ItemStack Fluid = new ItemStack(TEBlocks.blockMachine, 1, 5);
public static ItemStack Glacial = new ItemStack(TEBlocks.blockMachine, 1, 6);
public static ItemStack Cobble = new ItemStack(TEBlocks.blockMachine, 1, 7);
public static ItemStack Aqua = new ItemStack(TEBlocks.blockMachine, 1, 8);
public static ItemStack Assembler = new ItemStack(TEBlocks.blockMachine, 1, 9);
public static ItemStack Power = new ItemStack(TEBlocks.blockMachine, 1, 10);
private static final byte[] SideCache = new byte[] {(byte) 1, 1, (byte) 2, 2, (byte) 2, 2, 2,};
private static NBTTagCompound Augments = new NBTTagCompound();
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getPulveriser (String name) {
if (name == "Basic") {
// Set Basic NBT
Pulversier.stackTagCompound = new NBTTagCompound();
Pulversier.stackTagCompound.setByte("Facing", (byte) 3);
Pulversier.stackTagCompound.setByte("Level", (byte) 0);
Pulversier.stackTagCompound.setByte("RSControl", (byte) 0);
Pulversier.stackTagCompound.setByte("Energy", (byte) 0);
Pulversier.stackTagCompound.setByte("Secure", (byte) 1);
Pulversier.stackTagCompound.setByteArray("SideCache", SideCache);
Pulversier.stackTagCompound.setTag("Augments", Augments);
return Pulversier;
}
if (name == "Hardened") {
// Set Basic NBT
Pulversier.stackTagCompound = new NBTTagCompound();
Pulversier.stackTagCompound.setByte("Facing", (byte) 3);
Pulversier.stackTagCompound.setByte("Level", (byte) 1);
Pulversier.stackTagCompound.setByte("RSControl", (byte) 0);
Pulversier.stackTagCompound.setByte("Energy", (byte) 0);
Pulversier.stackTagCompound.setByte("Secure", (byte) 1);
Pulversier.stackTagCompound.setByteArray("SideCache", SideCache);
Pulversier.stackTagCompound.setTag("Augments", Augments);
return Pulversier;
}
if (name == "Reinforced") {
// Set Basic NBT
Pulversier.stackTagCompound = new NBTTagCompound();
Pulversier.stackTagCompound.setByte("Facing", (byte) 3);
Pulversier.stackTagCompound.setByte("Level", (byte) 2);
Pulversier.stackTagCompound.setByte("RSControl", (byte) 0);
Pulversier.stackTagCompound.setByte("Energy", (byte) 0);
Pulversier.stackTagCompound.setByte("Secure", (byte) 1);
Pulversier.stackTagCompound.setByteArray("SideCache", SideCache);
Pulversier.stackTagCompound.setTag("Augments", Augments);
return Pulversier;
}
if (name == "Resonant") {
// Set Basic NBT
Pulversier.stackTagCompound = new NBTTagCompound();
Pulversier.stackTagCompound.setByte("Facing", (byte) 3);
Pulversier.stackTagCompound.setByte("Level", (byte) 3);
Pulversier.stackTagCompound.setByte("RSControl", (byte) 0);
Pulversier.stackTagCompound.setByte("Energy", (byte) 0);
Pulversier.stackTagCompound.setByte("Secure", (byte) 1);
Pulversier.stackTagCompound.setByteArray("SideCache", SideCache);
Pulversier.stackTagCompound.setTag("Augments", Augments);
return Pulversier;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getFurnace (String name) {
if (name == "Basic") {
// Set Basic NBT
Furnace.stackTagCompound = new NBTTagCompound();
Furnace.stackTagCompound.setByte("Facing", (byte) 3);
Furnace.stackTagCompound.setByte("Level", (byte) 0);
Furnace.stackTagCompound.setByte("RSControl", (byte) 0);
Furnace.stackTagCompound.setByte("Energy", (byte) 0);
Furnace.stackTagCompound.setByte("Secure", (byte) 1);
Furnace.stackTagCompound.setByteArray("SideCache", SideCache);
Furnace.stackTagCompound.setTag("Augments", Augments);
return Furnace;
}
if (name == "Hardened") {
// Set Basic NBT
Furnace.stackTagCompound = new NBTTagCompound();
Furnace.stackTagCompound.setByte("Facing", (byte) 3);
Furnace.stackTagCompound.setByte("Level", (byte) 1);
Furnace.stackTagCompound.setByte("RSControl", (byte) 0);
Furnace.stackTagCompound.setByte("Energy", (byte) 0);
Furnace.stackTagCompound.setByte("Secure", (byte) 1);
Furnace.stackTagCompound.setByteArray("SideCache", SideCache);
Furnace.stackTagCompound.setTag("Augments", Augments);
return Furnace;
}
if (name == "Reinforced") {
// Set Basic NBT
Furnace.stackTagCompound = new NBTTagCompound();
Furnace.stackTagCompound.setByte("Facing", (byte) 3);
Furnace.stackTagCompound.setByte("Level", (byte) 2);
Furnace.stackTagCompound.setByte("RSControl", (byte) 0);
Furnace.stackTagCompound.setByte("Energy", (byte) 0);
Furnace.stackTagCompound.setByte("Secure", (byte) 1);
Furnace.stackTagCompound.setByteArray("SideCache", SideCache);
Furnace.stackTagCompound.setTag("Augments", Augments);
return Furnace;
}
if (name == "Resonant") {
// Set Basic NBT
Furnace.stackTagCompound = new NBTTagCompound();
Furnace.stackTagCompound.setByte("Facing", (byte) 3);
Furnace.stackTagCompound.setByte("Level", (byte) 3);
Furnace.stackTagCompound.setByte("RSControl", (byte) 0);
Furnace.stackTagCompound.setByte("Energy", (byte) 0);
Furnace.stackTagCompound.setByte("Secure", (byte) 1);
Furnace.stackTagCompound.setByteArray("SideCache", SideCache);
Furnace.stackTagCompound.setTag("Augments", Augments);
return Furnace;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getSawmill (String name) {
if (name == "Basic") {
// Set Basic NBT
Sawmill.stackTagCompound = new NBTTagCompound();
Sawmill.stackTagCompound.setByte("Facing", (byte) 3);
Sawmill.stackTagCompound.setByte("Level", (byte) 0);
Sawmill.stackTagCompound.setByte("RSControl", (byte) 0);
Sawmill.stackTagCompound.setByte("Energy", (byte) 0);
Sawmill.stackTagCompound.setByte("Secure", (byte) 1);
Sawmill.stackTagCompound.setByteArray("SideCache", SideCache);
Sawmill.stackTagCompound.setTag("Augments", Augments);
return Sawmill;
}
if (name == "Hardened") {
// Set Basic NBT
Sawmill.stackTagCompound = new NBTTagCompound();
Sawmill.stackTagCompound.setByte("Facing", (byte) 3);
Sawmill.stackTagCompound.setByte("Level", (byte) 1);
Sawmill.stackTagCompound.setByte("RSControl", (byte) 0);
Sawmill.stackTagCompound.setByte("Energy", (byte) 0);
Sawmill.stackTagCompound.setByte("Secure", (byte) 1);
Sawmill.stackTagCompound.setByteArray("SideCache", SideCache);
Sawmill.stackTagCompound.setTag("Augments", Augments);
return Sawmill;
}
if (name == "Reinforced") {
// Set Basic NBT
Sawmill.stackTagCompound = new NBTTagCompound();
Sawmill.stackTagCompound.setByte("Facing", (byte) 3);
Sawmill.stackTagCompound.setByte("Level", (byte) 2);
Sawmill.stackTagCompound.setByte("Secure", (byte) 1);
Sawmill.stackTagCompound.setByte("RSControl", (byte) 0);
Sawmill.stackTagCompound.setByte("Energy", (byte) 0);
Sawmill.stackTagCompound.setByteArray("SideCache", SideCache);
Sawmill.stackTagCompound.setTag("Augments", Augments);
return Sawmill;
}
if (name == "Resonant") {
// Set Basic NBT
Sawmill.stackTagCompound = new NBTTagCompound();
Sawmill.stackTagCompound.setByte("Facing", (byte) 3);
Sawmill.stackTagCompound.setByte("Level", (byte) 3);
Sawmill.stackTagCompound.setByte("RSControl", (byte) 0);
Sawmill.stackTagCompound.setByte("Energy", (byte) 0);
Sawmill.stackTagCompound.setByte("Secure", (byte) 1);
Sawmill.stackTagCompound.setByteArray("SideCache", SideCache);
Sawmill.stackTagCompound.setTag("Augments", Augments);
return Sawmill;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getSmelter (String name) {
if (name == "Basic") {
// Set Basic NBT
Smelter.stackTagCompound = new NBTTagCompound();
Smelter.stackTagCompound.setByte("Facing", (byte) 3);
Smelter.stackTagCompound.setByte("Level", (byte) 0);
Smelter.stackTagCompound.setByte("RSControl", (byte) 0);
Smelter.stackTagCompound.setByte("Energy", (byte) 0);
Smelter.stackTagCompound.setByte("Secure", (byte) 1);
Smelter.stackTagCompound.setByteArray("SideCache", SideCache);
Smelter.stackTagCompound.setTag("Augments", Augments);
return Smelter;
}
if (name == "Hardened") {
// Set Basic NBT
Smelter.stackTagCompound = new NBTTagCompound();
Smelter.stackTagCompound.setByte("Facing", (byte) 3);
Smelter.stackTagCompound.setByte("Level", (byte) 1);
Smelter.stackTagCompound.setByte("RSControl", (byte) 0);
Smelter.stackTagCompound.setByte("Energy", (byte) 0);
Smelter.stackTagCompound.setByte("Secure", (byte) 1);
Smelter.stackTagCompound.setByteArray("SideCache", SideCache);
Smelter.stackTagCompound.setTag("Augments", Augments);
return Smelter;
}
if (name == "Reinforced") {
// Set Basic NBT
Smelter.stackTagCompound = new NBTTagCompound();
Smelter.stackTagCompound.setByte("Facing", (byte) 3);
Smelter.stackTagCompound.setByte("Level", (byte) 2);
Smelter.stackTagCompound.setByte("RSControl", (byte) 0);
Smelter.stackTagCompound.setByte("Energy", (byte) 0);
Smelter.stackTagCompound.setByte("Secure", (byte) 1);
Smelter.stackTagCompound.setByteArray("SideCache", SideCache);
Smelter.stackTagCompound.setTag("Augments", Augments);
return Smelter;
}
if (name == "Resonant") {
// Set Basic NBT
Smelter.stackTagCompound = new NBTTagCompound();
Smelter.stackTagCompound.setByte("Facing", (byte) 3);
Smelter.stackTagCompound.setByte("Level", (byte) 3);
Smelter.stackTagCompound.setByte("RSControl", (byte) 0);
Smelter.stackTagCompound.setByte("Energy", (byte) 0);
Smelter.stackTagCompound.setByte("Secure", (byte) 1);
Smelter.stackTagCompound.setByteArray("SideCache", SideCache);
Smelter.stackTagCompound.setTag("Augments", Augments);
return Smelter;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getMagma (String name) {
if (name == "Basic") {
// Set Basic NBT
Magma.stackTagCompound = new NBTTagCompound();
Magma.stackTagCompound.setByte("Facing", (byte) 3);
Magma.stackTagCompound.setByte("Level", (byte) 0);
Magma.stackTagCompound.setByte("RSControl", (byte) 0);
Magma.stackTagCompound.setByte("Energy", (byte) 0);
Magma.stackTagCompound.setByte("Secure", (byte) 1);
Magma.stackTagCompound.setByteArray("SideCache", SideCache);
Magma.stackTagCompound.setTag("Augments", Augments);
return Magma;
}
if (name == "Hardened") {
// Set Basic NBT
Magma.stackTagCompound = new NBTTagCompound();
Magma.stackTagCompound.setByte("Facing", (byte) 3);
Magma.stackTagCompound.setByte("Level", (byte) 1);
Magma.stackTagCompound.setByte("RSControl", (byte) 0);
Magma.stackTagCompound.setByte("Energy", (byte) 0);
Magma.stackTagCompound.setByte("Secure", (byte) 1);
Magma.stackTagCompound.setByteArray("SideCache", SideCache);
Magma.stackTagCompound.setTag("Augments", Augments);
return Smelter;
}
if (name == "Reinforced") {
// Set Basic NBT
Magma.stackTagCompound = new NBTTagCompound();
Magma.stackTagCompound.setByte("Facing", (byte) 3);
Magma.stackTagCompound.setByte("Level", (byte) 2);
Magma.stackTagCompound.setByte("RSControl", (byte) 0);
Magma.stackTagCompound.setByte("Energy", (byte) 0);
Magma.stackTagCompound.setByte("Secure", (byte) 1);
Magma.stackTagCompound.setByteArray("SideCache", SideCache);
Magma.stackTagCompound.setTag("Augments", Augments);
return Magma;
}
if (name == "Resonant") {
// Set Basic NBT
Magma.stackTagCompound = new NBTTagCompound();
Magma.stackTagCompound.setByte("Facing", (byte) 3);
Magma.stackTagCompound.setByte("Level", (byte) 3);
Magma.stackTagCompound.setByte("RSControl", (byte) 0);
Magma.stackTagCompound.setByte("Energy", (byte) 0);
Magma.stackTagCompound.setByte("Secure", (byte) 1);
Magma.stackTagCompound.setByteArray("SideCache", SideCache);
Magma.stackTagCompound.setTag("Augments", Augments);
return Magma;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getFluid (String name) {
if (name == "Basic") {
// Set Basic NBT
Fluid.stackTagCompound = new NBTTagCompound();
Fluid.stackTagCompound.setByte("Facing", (byte) 3);
Fluid.stackTagCompound.setByte("Level", (byte) 0);
Fluid.stackTagCompound.setByte("RSControl", (byte) 0);
Fluid.stackTagCompound.setByte("Energy", (byte) 0);
Fluid.stackTagCompound.setByte("Secure", (byte) 1);
Fluid.stackTagCompound.setByteArray("SideCache", SideCache);
Fluid.stackTagCompound.setTag("Augments", Augments);
return Fluid;
}
if (name == "Hardened") {
// Set Basic NBT
Fluid.stackTagCompound = new NBTTagCompound();
Fluid.stackTagCompound.setByte("Facing", (byte) 3);
Fluid.stackTagCompound.setByte("Level", (byte) 1);
Fluid.stackTagCompound.setByte("RSControl", (byte) 0);
Fluid.stackTagCompound.setByte("Energy", (byte) 0);
Fluid.stackTagCompound.setByte("Secure", (byte) 1);
Fluid.stackTagCompound.setByteArray("SideCache", SideCache);
Fluid.stackTagCompound.setTag("Augments", Augments);
return Fluid;
}
if (name == "Reinforced") {
// Set Basic NBT
Fluid.stackTagCompound = new NBTTagCompound();
Fluid.stackTagCompound.setByte("Facing", (byte) 3);
Fluid.stackTagCompound.setByte("Level", (byte) 2);
Fluid.stackTagCompound.setByte("RSControl", (byte) 0);
Fluid.stackTagCompound.setByte("Energy", (byte) 0);
Fluid.stackTagCompound.setByte("Secure", (byte) 1);
Fluid.stackTagCompound.setByteArray("SideCache", SideCache);
Fluid.stackTagCompound.setTag("Augments", Augments);
return Fluid;
}
if (name == "Resonant") {
// Set Basic NBT
Fluid.stackTagCompound = new NBTTagCompound();
Fluid.stackTagCompound.setByte("Facing", (byte) 3);
Fluid.stackTagCompound.setByte("Level", (byte) 3);
Fluid.stackTagCompound.setByte("RSControl", (byte) 0);
Fluid.stackTagCompound.setByte("Energy", (byte) 0);
Fluid.stackTagCompound.setByte("Secure", (byte) 1);
Fluid.stackTagCompound.setByteArray("SideCache", SideCache);
Fluid.stackTagCompound.setTag("Augments", Augments);
return Fluid;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getGlacial (String name) {
if (name == "Basic") {
// Set Basic NBT
Glacial.stackTagCompound = new NBTTagCompound();
Glacial.stackTagCompound.setByte("Facing", (byte) 3);
Glacial.stackTagCompound.setByte("Level", (byte) 0);
Glacial.stackTagCompound.setByte("RSControl", (byte) 0);
Glacial.stackTagCompound.setByte("Energy", (byte) 0);
Glacial.stackTagCompound.setByte("Secure", (byte) 1);
Glacial.stackTagCompound.setByteArray("SideCache", SideCache);
Glacial.stackTagCompound.setTag("Augments", Augments);
return Glacial;
}
if (name == "Hardened") {
// Set Basic NBT
Glacial.stackTagCompound = new NBTTagCompound();
Glacial.stackTagCompound.setByte("Facing", (byte) 3);
Glacial.stackTagCompound.setByte("Level", (byte) 1);
Glacial.stackTagCompound.setByte("RSControl", (byte) 0);
Glacial.stackTagCompound.setByte("Energy", (byte) 0);
Glacial.stackTagCompound.setByte("Secure", (byte) 1);
Glacial.stackTagCompound.setByteArray("SideCache", SideCache);
Glacial.stackTagCompound.setTag("Augments", Augments);
return Glacial;
}
if (name == "Reinforced") {
// Set Basic NBT
Glacial.stackTagCompound = new NBTTagCompound();
Glacial.stackTagCompound.setByte("Facing", (byte) 3);
Glacial.stackTagCompound.setByte("Level", (byte) 2);
Glacial.stackTagCompound.setByte("RSControl", (byte) 0);
Glacial.stackTagCompound.setByte("Energy", (byte) 0);
Glacial.stackTagCompound.setByte("Secure", (byte) 1);
Glacial.stackTagCompound.setByteArray("SideCache", SideCache);
Glacial.stackTagCompound.setTag("Augments", Augments);
return Glacial;
}
if (name == "Resonant") {
// Set Basic NBT
Glacial.stackTagCompound = new NBTTagCompound();
Glacial.stackTagCompound.setByte("Facing", (byte) 3);
Glacial.stackTagCompound.setByte("Level", (byte) 3);
Glacial.stackTagCompound.setByte("RSControl", (byte) 0);
Glacial.stackTagCompound.setByte("Energy", (byte) 0);
Glacial.stackTagCompound.setByte("Secure", (byte) 1);
Glacial.stackTagCompound.setByteArray("SideCache", SideCache);
Glacial.stackTagCompound.setTag("Augments", Augments);
return Glacial;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getCobble (String name) {
if (name == "Basic") {
// Set Basic NBT
Cobble.stackTagCompound = new NBTTagCompound();
Cobble.stackTagCompound.setByte("Facing", (byte) 3);
Cobble.stackTagCompound.setByte("Level", (byte) 0);
Cobble.stackTagCompound.setByte("RSControl", (byte) 0);
Cobble.stackTagCompound.setByte("Energy", (byte) 0);
Cobble.stackTagCompound.setByte("Secure", (byte) 1);
Cobble.stackTagCompound.setByteArray("SideCache", SideCache);
Cobble.stackTagCompound.setTag("Augments", Augments);
return Cobble;
}
if (name == "Hardened") {
// Set Basic NBT
Cobble.stackTagCompound = new NBTTagCompound();
Cobble.stackTagCompound.setByte("Facing", (byte) 3);
Cobble.stackTagCompound.setByte("Level", (byte) 1);
Cobble.stackTagCompound.setByte("RSControl", (byte) 0);
Cobble.stackTagCompound.setByte("Energy", (byte) 0);
Cobble.stackTagCompound.setByte("Secure", (byte) 1);
Cobble.stackTagCompound.setByteArray("SideCache", SideCache);
Cobble.stackTagCompound.setTag("Augments", Augments);
return Cobble;
}
if (name == "Reinforced") {
// Set Basic NBT
Cobble.stackTagCompound = new NBTTagCompound();
Cobble.stackTagCompound.setByte("Facing", (byte) 3);
Cobble.stackTagCompound.setByte("Level", (byte) 2);
Cobble.stackTagCompound.setByte("RSControl", (byte) 0);
Cobble.stackTagCompound.setByte("Energy", (byte) 0);
Cobble.stackTagCompound.setByte("Secure", (byte) 1);
Cobble.stackTagCompound.setByteArray("SideCache", SideCache);
Cobble.stackTagCompound.setTag("Augments", Augments);
return Cobble;
}
if (name == "Resonant") {
// Set Basic NBT
Cobble.stackTagCompound = new NBTTagCompound();
Cobble.stackTagCompound.setByte("Facing", (byte) 3);
Cobble.stackTagCompound.setByte("Level", (byte) 3);
Cobble.stackTagCompound.setByte("RSControl", (byte) 0);
Cobble.stackTagCompound.setByte("Energy", (byte) 0);
Cobble.stackTagCompound.setByte("Secure", (byte) 1);
Cobble.stackTagCompound.setByteArray("SideCache", SideCache);
Cobble.stackTagCompound.setTag("Augments", Augments);
return Cobble;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getAqua (String name) {
if (name == "Basic") {
// Set Basic NBT
Aqua.stackTagCompound = new NBTTagCompound();
Aqua.stackTagCompound.setByte("Facing", (byte) 3);
Aqua.stackTagCompound.setByte("Level", (byte) 0);
Aqua.stackTagCompound.setByte("RSControl", (byte) 0);
Aqua.stackTagCompound.setByte("Energy", (byte) 0);
Aqua.stackTagCompound.setByte("Secure", (byte) 1);
Aqua.stackTagCompound.setByteArray("SideCache", SideCache);
Aqua.stackTagCompound.setTag("Augments", Augments);
return Aqua;
}
if (name == "Hardened") {
// Set Basic NBT
Aqua.stackTagCompound = new NBTTagCompound();
Aqua.stackTagCompound.setByte("Facing", (byte) 3);
Aqua.stackTagCompound.setByte("Level", (byte) 1);
Aqua.stackTagCompound.setByte("RSControl", (byte) 0);
Aqua.stackTagCompound.setByte("Energy", (byte) 0);
Aqua.stackTagCompound.setByte("Secure", (byte) 1);
Aqua.stackTagCompound.setByteArray("SideCache", SideCache);
Aqua.stackTagCompound.setTag("Augments", Augments);
return Aqua;
}
if (name == "Reinforced") {
// Set Basic NBT
Aqua.stackTagCompound = new NBTTagCompound();
Aqua.stackTagCompound.setByte("Facing", (byte) 3);
Aqua.stackTagCompound.setByte("Level", (byte) 2);
Aqua.stackTagCompound.setByte("RSControl", (byte) 0);
Aqua.stackTagCompound.setByte("Energy", (byte) 0);
Aqua.stackTagCompound.setByte("Secure", (byte) 1);
Aqua.stackTagCompound.setByteArray("SideCache", SideCache);
Aqua.stackTagCompound.setTag("Augments", Augments);
return Aqua;
}
if (name == "Resonant") {
// Set Basic NBT
Aqua.stackTagCompound = new NBTTagCompound();
Aqua.stackTagCompound.setByte("Facing", (byte) 3);
Aqua.stackTagCompound.setByte("Level", (byte) 3);
Aqua.stackTagCompound.setByte("RSControl", (byte) 0);
Aqua.stackTagCompound.setByte("Energy", (byte) 0);
Aqua.stackTagCompound.setByte("Secure", (byte) 1);
Aqua.stackTagCompound.setByteArray("SideCache", SideCache);
Aqua.stackTagCompound.setTag("Augments", Augments);
return Aqua;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getAssembler (String name) {
if (name == "Basic") {
// Set Basic NBT
Assembler.stackTagCompound = new NBTTagCompound();
Assembler.stackTagCompound.setByte("Facing", (byte) 3);
Assembler.stackTagCompound.setByte("Level", (byte) 0);
Assembler.stackTagCompound.setByte("RSControl", (byte) 0);
Assembler.stackTagCompound.setByte("Energy", (byte) 0);
Assembler.stackTagCompound.setByte("Secure", (byte) 1);
Assembler.stackTagCompound.setByteArray("SideCache", SideCache);
Assembler.stackTagCompound.setTag("Augments", Augments);
return Assembler;
}
if (name == "Hardened") {
// Set Basic NBT
Assembler.stackTagCompound = new NBTTagCompound();
Assembler.stackTagCompound.setByte("Facing", (byte) 3);
Assembler.stackTagCompound.setByte("Level", (byte) 1);
Assembler.stackTagCompound.setByte("RSControl", (byte) 0);
Assembler.stackTagCompound.setByte("Energy", (byte) 0);
Assembler.stackTagCompound.setByte("Secure", (byte) 1);
Assembler.stackTagCompound.setByteArray("SideCache", SideCache);
Assembler.stackTagCompound.setTag("Augments", Augments);
return Assembler;
}
if (name == "Reinforced") {
// Set Basic NBT
Assembler.stackTagCompound = new NBTTagCompound();
Assembler.stackTagCompound.setByte("Facing", (byte) 3);
Assembler.stackTagCompound.setByte("Level", (byte) 2);
Assembler.stackTagCompound.setByte("RSControl", (byte) 0);
Assembler.stackTagCompound.setByte("Energy", (byte) 0);
Assembler.stackTagCompound.setByte("Secure", (byte) 1);
Assembler.stackTagCompound.setByteArray("SideCache", SideCache);
Assembler.stackTagCompound.setTag("Augments", Augments);
return Assembler;
}
if (name == "Resonant") {
// Set Basic NBT
Assembler.stackTagCompound = new NBTTagCompound();
Assembler.stackTagCompound.setByte("Facing", (byte) 3);
Assembler.stackTagCompound.setByte("Level", (byte) 3);
Assembler.stackTagCompound.setByte("RSControl", (byte) 0);
Assembler.stackTagCompound.setByte("Energy", (byte) 0);
Assembler.stackTagCompound.setByte("Secure", (byte) 1);
Assembler.stackTagCompound.setByteArray("SideCache", SideCache);
Assembler.stackTagCompound.setTag("Augments", Augments);
return Assembler;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static ItemStack getPower (String name) {
if (name == "Basic") {
// Set Basic NBT
Power.stackTagCompound = new NBTTagCompound();
Power.stackTagCompound.setByte("Facing", (byte) 3);
Power.stackTagCompound.setByte("Level", (byte) 0);
Power.stackTagCompound.setByte("RSControl", (byte) 0);
Power.stackTagCompound.setByte("Energy", (byte) 0);
Power.stackTagCompound.setByte("Secure", (byte) 1);
Power.stackTagCompound.setByteArray("SideCache", SideCache);
Power.stackTagCompound.setTag("Augments", Augments);
return Power;
}
if (name == "Hardened") {
// Set Basic NBT
Power.stackTagCompound = new NBTTagCompound();
Power.stackTagCompound.setByte("Facing", (byte) 3);
Power.stackTagCompound.setByte("Level", (byte) 1);
Power.stackTagCompound.setByte("RSControl", (byte) 0);
Power.stackTagCompound.setByte("Energy", (byte) 0);
Power.stackTagCompound.setByte("Secure", (byte) 1);
Power.stackTagCompound.setByteArray("SideCache", SideCache);
Power.stackTagCompound.setTag("Augments", Augments);
return Power;
}
if (name == "Reinforced") {
// Set Basic NBT
Power.stackTagCompound = new NBTTagCompound();
Power.stackTagCompound.setByte("Facing", (byte) 3);
Power.stackTagCompound.setByte("Level", (byte) 2);
Power.stackTagCompound.setByte("RSControl", (byte) 0);
Power.stackTagCompound.setByte("Energy", (byte) 0);
Power.stackTagCompound.setByte("Secure", (byte) 1);
Power.stackTagCompound.setByteArray("SideCache", SideCache);
Power.stackTagCompound.setTag("Augments", Augments);
return Power;
}
if (name == "Resonant") {
// Set Basic NBT
Power.stackTagCompound = new NBTTagCompound();
Power.stackTagCompound.setByte("Facing", (byte) 3);
Power.stackTagCompound.setByte("Level", (byte) 3);
Power.stackTagCompound.setByte("RSControl", (byte) 0);
Power.stackTagCompound.setByte("Energy", (byte) 0);
Power.stackTagCompound.setByte("Secure", (byte) 1);
Power.stackTagCompound.setByteArray("SideCache", SideCache);
Power.stackTagCompound.setTag("Augments", Augments);
return Power;
}
return null;
}
@Optional.Method (modid = "ThermalExpansion")
public static void addFurnaceRecipe (int energy, ItemStack input, ItemStack output) {
if (input == null || output == null) {
return;
}
ThermalExpansionHelper.addFurnaceRecipe(energy, input, output);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addPulverizerRecipe (int power, ItemStack in, ItemStack out, ItemStack secondary, int chance) {
PulverizerManager.addRecipe(power, in, out, secondary, chance);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addPulverizerRecipe (int power, ItemStack in, ItemStack out) {
PulverizerManager.addRecipe(power, in, out);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addSawmillRecipe (int energy, ItemStack input, ItemStack primaryOutput) {
addSawmillRecipe(energy, input, primaryOutput, null, 0);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addSawmillRecipe (int energy, ItemStack input, ItemStack primaryOutput, ItemStack secondaryOutput) {
addSawmillRecipe(energy, input, primaryOutput, secondaryOutput, 100);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addSawmillRecipe (int energy, ItemStack input, ItemStack primaryOutput, ItemStack secondaryOutput, int secondaryChance) {
ThermalExpansionHelper.addSawmillRecipe(energy, input, primaryOutput, secondaryOutput, secondaryChance);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addSmelterRecipe (int energy, ItemStack primaryInput, ItemStack secondaryInput, ItemStack primaryOutput) {
addSmelterRecipe(energy, primaryInput, secondaryInput, primaryOutput, null, 0);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addSmelterRecipe (int energy, ItemStack primaryInput, ItemStack secondaryInput, ItemStack primaryOutput, ItemStack secondaryOutput) {
addSmelterRecipe(energy, primaryInput, secondaryInput, primaryOutput, secondaryOutput, 100);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addSmelterRecipe (int energy, ItemStack primaryInput, ItemStack secondaryInput, ItemStack primaryOutput, ItemStack secondaryOutput, int secondaryChance) {
ThermalExpansionHelper.addSmelterRecipe(energy, primaryInput, secondaryInput, primaryOutput, secondaryOutput, secondaryChance);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addCrucibleRecipe (int energy, ItemStack input, FluidStack output) {
CrucibleManager.addRecipe(energy, input, output);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addTransposerFill (int energy, ItemStack input, ItemStack output, FluidStack fluid, boolean reversible) {
TransposerManager.addFillRecipe(energy, input, output, fluid, reversible);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addTransposerExtract (int energy, ItemStack input, ItemStack output, FluidStack fluid, int chance, boolean reversible) {
ThermalExpansionHelper.addTransposerExtract(energy, input, output, fluid, chance, reversible);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addMagmaticFuel (String fluidName, int energy) {
NBTTagCompound toSend = new NBTTagCompound();
toSend.setString("fluidName", fluidName);
toSend.setInteger("energy", energy);
FMLInterModComms.sendMessage("ThermalExpansion", "MagmaticFuel", toSend);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addCompressionFuel (String fluidName, int energy) {
NBTTagCompound toSend = new NBTTagCompound();
toSend.setString("fluidName", fluidName);
toSend.setInteger("energy", energy);
FMLInterModComms.sendMessage("ThermalExpansion", "CompressionFuel", toSend);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addReactantFuel (String fluidName, int energy) {
NBTTagCompound toSend = new NBTTagCompound();
toSend.setString("fluidName", fluidName);
toSend.setInteger("energy", energy);
FMLInterModComms.sendMessage("ThermalExpansion", "ReactantFuel", toSend);
}
@Optional.Method (modid = "ThermalExpansion")
public static void addCoolant (String fluidName, int energy) {
NBTTagCompound toSend = new NBTTagCompound();
toSend.setString("fluidName", fluidName);
toSend.setInteger("energy", energy);
FMLInterModComms.sendMessage("ThermalExpansion", "Coolant", toSend);
}
}
| mit |
microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/models/OnenoteResource.java | 1541 | // Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.models.OnenoteEntityBaseModel;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Onenote Resource.
*/
public class OnenoteResource extends OnenoteEntityBaseModel implements IJsonBackedObject {
/**
* The Content Url.
* The URL for downloading the content
*/
@SerializedName(value = "contentUrl", alternate = {"ContentUrl"})
@Expose
@Nullable
public String contentUrl;
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2019_11_01/src/main/java/com/microsoft/azure/management/network/v2019_11_01/implementation/FirewallPolicyImpl.java | 3147 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_11_01.implementation;
import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl;
import com.microsoft.azure.management.network.v2019_11_01.FirewallPolicy;
import rx.Observable;
import java.util.List;
import com.microsoft.azure.SubResource;
import com.microsoft.azure.management.network.v2019_11_01.ProvisioningState;
import com.microsoft.azure.management.network.v2019_11_01.AzureFirewallThreatIntelMode;
class FirewallPolicyImpl extends GroupableResourceCoreImpl<FirewallPolicy, FirewallPolicyInner, FirewallPolicyImpl, NetworkManager> implements FirewallPolicy, FirewallPolicy.Definition, FirewallPolicy.Update {
FirewallPolicyImpl(String name, FirewallPolicyInner inner, NetworkManager manager) {
super(name, inner, manager);
}
@Override
public Observable<FirewallPolicy> createResourceAsync() {
FirewallPoliciesInner client = this.manager().inner().firewallPolicies();
return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner())
.map(innerToFluentMap(this));
}
@Override
public Observable<FirewallPolicy> updateResourceAsync() {
FirewallPoliciesInner client = this.manager().inner().firewallPolicies();
return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner())
.map(innerToFluentMap(this));
}
@Override
protected Observable<FirewallPolicyInner> getInnerAsync() {
FirewallPoliciesInner client = this.manager().inner().firewallPolicies();
return client.getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
@Override
public boolean isInCreateMode() {
return this.inner().id() == null;
}
@Override
public SubResource basePolicy() {
return this.inner().basePolicy();
}
@Override
public List<SubResource> childPolicies() {
return this.inner().childPolicies();
}
@Override
public String etag() {
return this.inner().etag();
}
@Override
public List<SubResource> firewalls() {
return this.inner().firewalls();
}
@Override
public ProvisioningState provisioningState() {
return this.inner().provisioningState();
}
@Override
public List<SubResource> ruleGroups() {
return this.inner().ruleGroups();
}
@Override
public AzureFirewallThreatIntelMode threatIntelMode() {
return this.inner().threatIntelMode();
}
@Override
public FirewallPolicyImpl withBasePolicy(SubResource basePolicy) {
this.inner().withBasePolicy(basePolicy);
return this;
}
@Override
public FirewallPolicyImpl withThreatIntelMode(AzureFirewallThreatIntelMode threatIntelMode) {
this.inner().withThreatIntelMode(threatIntelMode);
return this;
}
}
| mit |
raoulvdberge/refinedstorage | src/main/java/com/refinedmods/refinedstorage/container/slot/grid/ResultCraftingGridSlot.java | 1268 | package com.refinedmods.refinedstorage.container.slot.grid;
import com.refinedmods.refinedstorage.api.network.grid.IGrid;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.ResultSlot;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.event.ForgeEventFactory;
import javax.annotation.Nonnull;
public class ResultCraftingGridSlot extends ResultSlot {
private final IGrid grid;
public ResultCraftingGridSlot(Player player, IGrid grid, int inventoryIndex, int x, int y) {
super(player, grid.getCraftingMatrix(), grid.getCraftingResult(), inventoryIndex, x, y);
this.grid = grid;
}
// @Volatile: Overriding logic from the super onTake method for Grid behaviors like refilling stacks from the network
@Override
public void onTake(Player player, @Nonnull ItemStack stack) {
checkTakeAchievements(stack);
ForgeHooks.setCraftingPlayer(player);
if (!player.getCommandSenderWorld().isClientSide) {
grid.onCrafted(player, null, null);
}
ForgeEventFactory.firePlayerCraftingEvent(player, stack.copy(), grid.getCraftingMatrix());
ForgeHooks.setCraftingPlayer(null);
}
}
| mit |
georghinkel/ttc2017smartGrids | solutions/ModelJoin/src/main/java/CIM/IEC61970/Informative/MarketOperations/UnitInitialConditions.java | 10786 | /**
*/
package CIM.IEC61970.Informative.MarketOperations;
import CIM.IEC61970.Core.IdentifiedObject;
import java.util.Date;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Unit Initial Conditions</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getResourceStatus <em>Resource Status</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getTimeInStatus <em>Time In Status</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getResourceMW <em>Resource MW</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getGeneratingUnit <em>Generating Unit</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getCumEnergy <em>Cum Energy</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getStatusDate <em>Status Date</em>}</li>
* <li>{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getCumStatusChanges <em>Cum Status Changes</em>}</li>
* </ul>
*
* @see CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage#getUnitInitialConditions()
* @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Resource status at the end of a given clearing period.'"
* annotation="http://langdale.com.au/2005/UML Profile\040documentation='Resource status at the end of a given clearing period.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Resource status at the end of a given clearing period.' Profile\040documentation='Resource status at the end of a given clearing period.'"
* @generated
*/
public interface UnitInitialConditions extends IdentifiedObject {
/**
* Returns the value of the '<em><b>Resource Status</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Resource Status</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Resource Status</em>' attribute.
* @see #setResourceStatus(int)
* @see CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage#getUnitInitialConditions_ResourceStatus()
* @model required="true"
* annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Resource status at the end of previous clearing period:\n 0 - off-line\n 1 - on-line production\n 2 - in shutdown process\n 3 - in startup process'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Resource status at the end of previous clearing period:\n 0 - off-line\n 1 - on-line production\n 2 - in shutdown process\n 3 - in startup process'"
* @generated
*/
int getResourceStatus();
/**
* Sets the value of the '{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getResourceStatus <em>Resource Status</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Resource Status</em>' attribute.
* @see #getResourceStatus()
* @generated
*/
void setResourceStatus(int value);
/**
* Returns the value of the '<em><b>Time In Status</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Time In Status</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Time In Status</em>' attribute.
* @see #setTimeInStatus(float)
* @see CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage#getUnitInitialConditions_TimeInStatus()
* @model dataType="CIM.IEC61970.Domain.Minutes" required="true"
* annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Time in market trading intervals the resource is in the state as of the end of the previous clearing period.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Time in market trading intervals the resource is in the state as of the end of the previous clearing period.'"
* @generated
*/
float getTimeInStatus();
/**
* Sets the value of the '{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getTimeInStatus <em>Time In Status</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Time In Status</em>' attribute.
* @see #getTimeInStatus()
* @generated
*/
void setTimeInStatus(float value);
/**
* Returns the value of the '<em><b>Resource MW</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Resource MW</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Resource MW</em>' attribute.
* @see #setResourceMW(float)
* @see CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage#getUnitInitialConditions_ResourceMW()
* @model dataType="CIM.IEC61970.Domain.ActivePower" required="true"
* annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Resource MW output at the end of previous clearing period.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Resource MW output at the end of previous clearing period.'"
* @generated
*/
float getResourceMW();
/**
* Sets the value of the '{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getResourceMW <em>Resource MW</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Resource MW</em>' attribute.
* @see #getResourceMW()
* @generated
*/
void setResourceMW(float value);
/**
* Returns the value of the '<em><b>Generating Unit</b></em>' reference.
* It is bidirectional and its opposite is '{@link CIM.IEC61970.Informative.MarketOperations.RegisteredGenerator#getUnitInitialConditions <em>Unit Initial Conditions</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Generating Unit</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Generating Unit</em>' reference.
* @see #setGeneratingUnit(RegisteredGenerator)
* @see CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage#getUnitInitialConditions_GeneratingUnit()
* @see CIM.IEC61970.Informative.MarketOperations.RegisteredGenerator#getUnitInitialConditions
* @model opposite="UnitInitialConditions"
* @generated
*/
RegisteredGenerator getGeneratingUnit();
/**
* Sets the value of the '{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getGeneratingUnit <em>Generating Unit</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Generating Unit</em>' reference.
* @see #getGeneratingUnit()
* @generated
*/
void setGeneratingUnit(RegisteredGenerator value);
/**
* Returns the value of the '<em><b>Cum Energy</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Cum Energy</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Cum Energy</em>' attribute.
* @see #setCumEnergy(Object)
* @see CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage#getUnitInitialConditions_CumEnergy()
* @model dataType="CIM.EnergyAsMWh" required="true"
* annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Cumulative energy production over trading period.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Cumulative energy production over trading period.'"
* @generated
*/
Object getCumEnergy();
/**
* Sets the value of the '{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getCumEnergy <em>Cum Energy</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Cum Energy</em>' attribute.
* @see #getCumEnergy()
* @generated
*/
void setCumEnergy(Object value);
/**
* Returns the value of the '<em><b>Status Date</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Status Date</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Status Date</em>' attribute.
* @see #setStatusDate(Date)
* @see CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage#getUnitInitialConditions_StatusDate()
* @model required="true"
* annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Time and date for resourceStatus'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Time and date for resourceStatus'"
* @generated
*/
Date getStatusDate();
/**
* Sets the value of the '{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getStatusDate <em>Status Date</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Status Date</em>' attribute.
* @see #getStatusDate()
* @generated
*/
void setStatusDate(Date value);
/**
* Returns the value of the '<em><b>Cum Status Changes</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Cum Status Changes</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Cum Status Changes</em>' attribute.
* @see #setCumStatusChanges(int)
* @see CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage#getUnitInitialConditions_CumStatusChanges()
* @model required="true"
* annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Cumulative number of status changes of the resource.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Cumulative number of status changes of the resource.'"
* @generated
*/
int getCumStatusChanges();
/**
* Sets the value of the '{@link CIM.IEC61970.Informative.MarketOperations.UnitInitialConditions#getCumStatusChanges <em>Cum Status Changes</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Cum Status Changes</em>' attribute.
* @see #getCumStatusChanges()
* @generated
*/
void setCumStatusChanges(int value);
} // UnitInitialConditions
| mit |
TorchPowered/CraftBloom | src/net/minecraft/entity/monster/EntityCreeper.java | 9564 | package net.minecraft.entity.monster;
import net.minecraft.entity.Entity;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIAttackOnCollide;
import net.minecraft.entity.ai.EntityAIAvoidEntity;
import net.minecraft.entity.ai.EntityAICreeperSwell;
import net.minecraft.entity.ai.EntityAIHurtByTarget;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAINearestAttackableTarget;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAIWander;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.passive.EntityOcelot;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
public class EntityCreeper extends EntityMob
{
/**
* Time when this creeper was last in an active state (Messed up code here, probably causes creeper animation to go
* weird)
*/
private int lastActiveTime;
/**
* The amount of time since the creeper was close enough to the player to ignite
*/
private int timeSinceIgnited;
private int fuseTime = 30;
/** Explosion radius for this creeper. */
private int explosionRadius = 3;
private int field_175494_bm = 0;
public EntityCreeper(World worldIn)
{
super(worldIn);
this.tasks.addTask(1, new EntityAISwimming(this));
this.tasks.addTask(2, new EntityAICreeperSwell(this));
this.tasks.addTask(3, new EntityAIAvoidEntity(this, EntityOcelot.class, 6.0F, 1.0D, 1.2D));
this.tasks.addTask(4, new EntityAIAttackOnCollide(this, 1.0D, false));
this.tasks.addTask(5, new EntityAIWander(this, 0.8D));
this.tasks.addTask(6, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F));
this.tasks.addTask(6, new EntityAILookIdle(this));
this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true));
this.targetTasks.addTask(2, new EntityAIHurtByTarget(this, false, new Class[0]));
}
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D);
}
/**
* The maximum height from where the entity is alowed to jump (used in pathfinder)
*/
public int getMaxFallHeight()
{
return this.getAttackTarget() == null ? 3 : 3 + (int)(this.getHealth() - 1.0F);
}
public void fall(float distance, float damageMultiplier)
{
super.fall(distance, damageMultiplier);
this.timeSinceIgnited = (int)((float)this.timeSinceIgnited + distance * 1.5F);
if (this.timeSinceIgnited > this.fuseTime - 5)
{
this.timeSinceIgnited = this.fuseTime - 5;
}
}
protected void entityInit()
{
super.entityInit();
this.dataWatcher.addObject(16, Byte.valueOf((byte) - 1));
this.dataWatcher.addObject(17, Byte.valueOf((byte)0));
this.dataWatcher.addObject(18, Byte.valueOf((byte)0));
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound tagCompound)
{
super.writeEntityToNBT(tagCompound);
if (this.dataWatcher.getWatchableObjectByte(17) == 1)
{
tagCompound.setBoolean("powered", true);
}
tagCompound.setShort("Fuse", (short)this.fuseTime);
tagCompound.setByte("ExplosionRadius", (byte)this.explosionRadius);
tagCompound.setBoolean("ignited", this.hasIgnited());
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound tagCompund)
{
super.readEntityFromNBT(tagCompund);
this.dataWatcher.updateObject(17, Byte.valueOf((byte)(tagCompund.getBoolean("powered") ? 1 : 0)));
if (tagCompund.hasKey("Fuse", 99))
{
this.fuseTime = tagCompund.getShort("Fuse");
}
if (tagCompund.hasKey("ExplosionRadius", 99))
{
this.explosionRadius = tagCompund.getByte("ExplosionRadius");
}
if (tagCompund.getBoolean("ignited"))
{
this.ignite();
}
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate()
{
if (this.isEntityAlive())
{
this.lastActiveTime = this.timeSinceIgnited;
if (this.hasIgnited())
{
this.setCreeperState(1);
}
int i = this.getCreeperState();
if (i > 0 && this.timeSinceIgnited == 0)
{
this.playSound("creeper.primed", 1.0F, 0.5F);
}
this.timeSinceIgnited += i;
if (this.timeSinceIgnited < 0)
{
this.timeSinceIgnited = 0;
}
if (this.timeSinceIgnited >= this.fuseTime)
{
this.timeSinceIgnited = this.fuseTime;
this.explode();
}
}
super.onUpdate();
}
/**
* Returns the sound this mob makes when it is hurt.
*/
protected String getHurtSound()
{
return "mob.creeper.say";
}
/**
* Returns the sound this mob makes on death.
*/
protected String getDeathSound()
{
return "mob.creeper.death";
}
/**
* Called when the mob's health reaches 0.
*/
public void onDeath(DamageSource cause)
{
super.onDeath(cause);
if (cause.getEntity() instanceof EntitySkeleton)
{
int i = Item.getIdFromItem(Items.record_13);
int j = Item.getIdFromItem(Items.record_wait);
int k = i + this.rand.nextInt(j - i + 1);
this.dropItem(Item.getItemById(k), 1);
}
else if (cause.getEntity() instanceof EntityCreeper && cause.getEntity() != this && ((EntityCreeper)cause.getEntity()).getPowered() && ((EntityCreeper)cause.getEntity()).isAIEnabled())
{
((EntityCreeper)cause.getEntity()).func_175493_co();
this.entityDropItem(new ItemStack(Items.skull, 1, 4), 0.0F);
}
}
public boolean attackEntityAsMob(Entity entityIn)
{
return true;
}
/**
* Returns true if the creeper is powered by a lightning bolt.
*/
public boolean getPowered()
{
return this.dataWatcher.getWatchableObjectByte(17) == 1;
}
public void setPowered(boolean powered) {
if (!powered) {
this.dataWatcher.updateObject(17, Byte.valueOf((byte) 0));
} else {
this.dataWatcher.updateObject(17, Byte.valueOf((byte) 1));
}
}
protected Item getDropItem()
{
return Items.gunpowder;
}
/**
* Returns the current state of creeper, -1 is idle, 1 is 'in fuse'
*/
public int getCreeperState()
{
return this.dataWatcher.getWatchableObjectByte(16);
}
/**
* Sets the state of creeper, -1 to idle and 1 to be 'in fuse'
*/
public void setCreeperState(int state)
{
this.dataWatcher.updateObject(16, Byte.valueOf((byte)state));
}
/**
* Called when a lightning bolt hits the entity.
*/
public void onStruckByLightning(EntityLightningBolt lightningBolt)
{
super.onStruckByLightning(lightningBolt);
this.dataWatcher.updateObject(17, Byte.valueOf((byte)1));
}
/**
* Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a pig.
*/
protected boolean interact(EntityPlayer player)
{
ItemStack itemstack = player.inventory.getCurrentItem();
if (itemstack != null && itemstack.getItem() == Items.flint_and_steel)
{
this.worldObj.playSoundEffect(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "fire.ignite", 1.0F, this.rand.nextFloat() * 0.4F + 0.8F);
player.swingItem();
if (!this.worldObj.isRemote)
{
this.ignite();
itemstack.damageItem(1, player);
return true;
}
}
return super.interact(player);
}
/**
* Creates an explosion as determined by this creeper's power and explosion radius.
*/
private void explode()
{
if (!this.worldObj.isRemote)
{
boolean flag = this.worldObj.getGameRules().getBoolean("mobGriefing");
float f = this.getPowered() ? 2.0F : 1.0F;
this.worldObj.createExplosion(this, this.posX, this.posY, this.posZ, (float)this.explosionRadius * f, flag);
this.setDead();
}
}
public boolean hasIgnited()
{
return this.dataWatcher.getWatchableObjectByte(18) != 0;
}
public void ignite()
{
this.dataWatcher.updateObject(18, Byte.valueOf((byte)1));
}
/**
* Returns true if the newer Entity AI code should be run
*/
public boolean isAIEnabled()
{
return this.field_175494_bm < 1 && this.worldObj.getGameRules().getBoolean("doMobLoot");
}
public void func_175493_co()
{
++this.field_175494_bm;
}
}
| mit |
RealTwo-Space/Neumann | neumann/src/org/real2space/neumann/congraph/core/operation/SubtractOperation.java | 681 | package org.real2space.neumann.congraph.core.operation;
import org.real2space.neumann.congraph.core.data.Data;
import org.real2space.neumann.congraph.core.graph.Node;
import org.real2space.neumann.congraph.core.graph.Operation;
import org.real2space.neumann.congraph.core.graph.BinomialArgument;
/**
* Project Neumann
*
* @author RealTwo-Space
* @version 0
*
* created 12/18/16
*/
public class SubtractOperation extends Operation {
private BinomialArgument arg;
public SubtractOperation(Node a, Node b) {
this.arg = new BinomialArgument(a, b);
}
public Data execute() {
return arg.getDataAt(0).subtract(arg.getDataAt(1));
}
} | mit |
Simego/ChatWA-Server | src/main/java/com/thesimego/senacrs/sistemasdistribuidos/waserver/dao/FriendDAO.java | 1107 | package com.thesimego.senacrs.sistemasdistribuidos.waserver.dao;
import com.thesimego.senacrs.sistemasdistribuidos.waserver.entity.AccountEN;
import com.thesimego.senacrs.sistemasdistribuidos.waserver.entity.FriendEN;
import java.io.Serializable;
import java.util.List;
import org.springframework.stereotype.Repository;
/**
*
* @author drafaelli
*/
@Repository
public class FriendDAO extends GenericDAO<FriendEN> implements Serializable {
public List<FriendEN> findByAccount(AccountEN account) {
return findByAccountId(account.getId());
}
public List<FriendEN> findByAccountId(Integer id) {
return list(new DBField("account", id));
}
public void create(AccountEN account, String friend) {
insert(
new DBField("friend", friend),
new DBField("account", account.getId())
);
}
public FriendEN findByAccountAndFriend(AccountEN account, AccountEN friend) {
return find(
new DBField("account", account.getId()),
new DBField("friend", friend.getLogin())
);
}
}
| mit |
quyenlm/pokersu | poker-business/src/main/java/com/mrmq/poker/business/impl/PokerBusiness.java | 6274 | package com.mrmq.poker.business.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.mrmq.poker.business.AbstractBusiness;
import com.mrmq.poker.business.wraper.impl.PkCashflowWrapper;
import com.mrmq.poker.business.wraper.impl.PkUserWrapper;
import com.mrmq.poker.common.bean.Player;
import com.mrmq.poker.common.glossary.MsgCode;
import com.mrmq.poker.common.proto.AdminModelProto.DepositInfo;
import com.mrmq.poker.db.DbAction;
import com.mrmq.poker.db.entity.PkCashflow;
import com.mrmq.poker.db.entity.PkCashflow.PkCashflowSourceType;
import com.mrmq.poker.db.entity.PkCashflow.PkCashflowStatus;
import com.mrmq.poker.db.entity.PkCashflow.PkCashflowType;
import com.mrmq.poker.db.entity.PkGame;
import com.mrmq.poker.db.entity.PkGameHistory;
import com.mrmq.poker.db.entity.PkGameHistory.PkGameHistoryStatus;
import com.mrmq.poker.db.entity.PkUser;
import com.mrmq.poker.gateway.Gateway;
import com.mrmq.poker.gateway.GatewayFactory;
import com.mrmq.poker.gateway.GatewayFactory.GateWayType;
import com.mrmq.poker.gateway.bean.DepositResult;
public class PokerBusiness extends AbstractBusiness {
/**
* Update User info exclude Balance, PreBalance, Credit
* @param
**/
public boolean updateUser(PkUser user) throws Exception {
if(user == null)
throw new Exception("User can not be null");
boolean result = false;
synchronized (user) {
long eventId = getEventId();
//Update User info
userSyncer.put(new PkUserWrapper(DbAction.UPDATE, user.clone(), eventId));
result = true;
}
return result;
}
public MsgCode deposit(PkUser user, DepositInfo depositInfo, PkCashflowSourceType sourceType) throws Exception {
MsgCode msgCode = null;
Gateway gateway = GatewayFactory.createGateway(GateWayType.BAO_KIM_VALUE);
DepositResult depositResult = gateway.deposit(depositInfo.getBillType(), depositInfo.getBillSeri(), depositInfo.getBillNumber());
if(MsgCode.SUCCESS == depositResult.getMsgCode()) {
//Success
msgCode = changeCashBalance(user, depositResult.getAmount().longValue(), PkCashflowType.DEPOSIT, sourceType, 1, PkCashflowStatus.ACTIVE.getNumber());
} else {
msgCode = MsgCode.FAIL;
msgCode.setMsg(depositResult.getMsgCode().getMsg());
changeCashBalance(user, depositResult.getAmount().longValue(), PkCashflowType.DEPOSIT, sourceType, 1, PkCashflowStatus.INACTIVE.getNumber());
}
return msgCode;
}
public MsgCode changeCashBalance(PkUser user, Long cash, PkCashflowType type, PkCashflowSourceType sourceType, Integer source, Integer status) throws Exception {
if(user == null)
throw new Exception("User can not be null");
if(cash == null || cash <= 0)
throw new Exception("Invalid cash: " + cash);
MsgCode result = MsgCode.UNKNOWN;
synchronized (user) {
long eventId = getEventId();
if(PkCashflowType.BET == type || PkCashflowType.WITHDRAW == type || PkCashflowType.TAX == type)
cash = -cash;
//Update balance in DB
PkUser tempUser = userManager.addBalance(cash, user.getUserId());
if(tempUser == null) {
result = MsgCode.FAIL;
} else {
user.setBalance(tempUser.getBalance());
user.setPrevBalance(tempUser.getPrevBalance());
log.info("EventId={}, User {} {} {}, current balance: {}", eventId, user.getLogin(), type, cash, user.getBalance());
//Insert cashflow
PkCashflow pkCashflow = new PkCashflow();
pkCashflow.setUserId(user.getUserId());
pkCashflow.setAmount(new BigDecimal(cash));
pkCashflow.setCashBalance(user.getBalance());
pkCashflow.setPreBalance(user.getPrevBalance());
pkCashflow.setCurrency(user.getCurrency());
pkCashflow.setSource(source);
pkCashflow.setSourceType(sourceType.getNumber());
pkCashflow.setPromo(new BigDecimal("0"));
pkCashflow.setTaxes(new BigDecimal("0"));
pkCashflow.setType(type.getNumber());
pkCashflow.setStatus(status);
pkCashflow.setInputDate(new Date(System.currentTimeMillis()));
pkCashflow.setUpdateDate(pkCashflow.getInputDate());
cashflowSyncer.put(new PkCashflowWrapper(DbAction.INSERT, pkCashflow, eventId));
result = MsgCode.SUCCESS;
}
}
return result;
}
public PkGameHistory createPkGameHistory(PkGame pkGame, List<Player> players) throws Exception {
if(players == null || players.size() <= 0)
throw new Exception("Invalid players: " + players);
Iterator<String> it = Iterables.transform(players, new Function<Player, String>() {
public String apply(Player player) {
return player.getLoginId();
}
}).iterator();
String playerIds = Joiner.on(',').join(it);
PkGameHistory pkGameHistory = new PkGameHistory();
pkGameHistory.setCurrency(pkGame.getCurrency());
pkGameHistory.setGameId(pkGame.getGameId());
pkGameHistory.setPlayers(playerIds);
pkGameHistory.setCreater(0); //SYSTEM
pkGameHistory.setJoinPlayer(players.size());
pkGameHistory.setMaxBet(pkGame.getMaxBet());
pkGameHistory.setMinBet(pkGame.getMinBet());
pkGameHistory.setStatus(PkGameHistoryStatus.PLAYING.getNumber());
pkGameHistory.setTotalBet(new BigDecimal("0"));
pkGameHistory.setMaxPlayer(pkGame.getMaxPlayer());
pkGameHistory.setStartTime(new Date(System.currentTimeMillis()));
pkGameHistory.setEndTime(new Date(System.currentTimeMillis() + pkGame.getTimePergame()));
pkGameHistory.setUpdateDate(pkGameHistory.getStartTime());
gameHistoryManager.insert(pkGameHistory);
log.info("Created GameHistory: {}", pkGameHistory);
return pkGameHistory;
}
public PkGameHistory updatePkGameHistory(Integer gameId, BigDecimal totalBet, String comment) throws Exception {
PkGameHistory pkGameHistory = getGameHistoryManager().getPkGameHistoryById(gameId);
if(pkGameHistory != null) {
pkGameHistory.setEndTime(new Date(System.currentTimeMillis()));
pkGameHistory.setTotalBet(totalBet);
pkGameHistory.setComment(comment);
pkGameHistory.setStatus(PkGameHistoryStatus.FINISHED.getNumber());
getGameHistoryManager().update(pkGameHistory);
}
return pkGameHistory;
}
}
| mit |
Harmonicahappy/mltoolbox4j | mltoolbox4j-data/com/mltoolbox4j/data/ContinuousRecord.java | 1067 | /**
* Copyright (c) 2017 Terence Wu
*/
package com.mltoolbox4j.data;
import java.io.Serializable;
import com.mltoolbox4j.num4j.structure.Tensor;
/**
* <tt>ContinuousRecord.java</tt><br>
*
* @author TerenceWu
* @time 2017年10月30日 上午11:13:48
* @version 1.0
*/
public class ContinuousRecord implements Serializable {
private static final long serialVersionUID = 1L;
private Tensor attrValues;
public ContinuousRecord(Tensor attrValues) {
this.attrValues = attrValues;
}
public ContinuousRecord(float[] attrValues) {
this.attrValues = new Tensor(attrValues);
}
public int attrSize() {
return attrValues.count();
}
public float[] attrValuesArray() {
return attrValues.get();
}
public float attrValueAt(int index) {
return attrValues.get(index);
}
public String info() {
int size = attrSize();
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < size ; i++) {
builder.append(attrValues.get(i));
if (i != size - 1) {
builder.append(", ");
}
}
return builder.toString();
}
}
| mit |
VeryGame/gdx-surface | gdx-surface/src/main/java/de/verygame/surface/util/FileUtils.java | 1484 | package de.verygame.surface.util;
import com.badlogic.gdx.files.FileHandle;
import java.io.File;
/**
* @author Rico Schrage
*
* Utility methods regarding {@link File} and {@link FileHandle}.
*/
public class FileUtils {
/** AssetManager uses always this separator */
public static final String SEPARATOR = "/";
private FileUtils() {
// utility class
}
/**
* Convenience method to determine if a given path (have to exist!) is directory.
*
* @param path path as string
* @return true if it's describes a directory.
*/
public static boolean isDirectory(String path) {
return new FileHandle(path).isDirectory();
}
/**
* Provides an easy and efficient way to create a system independent path string.
* <br>
* Will only work for relative paths as absolute path are highly system dependent,
* for absolute paths you should consider to use {@link File#getAbsolutePath()}.
*
* @param folders folders
* @return system independent relative path using given folders
*/
public static String toPath(String... folders) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < folders.length; ++i) {
final String folder = folders[i];
builder.append(folder);
if (i != folders.length - 1) {
builder.append(FileUtils.SEPARATOR);
}
}
return builder.toString();
}
}
| mit |
elpsycongroo/national_tax | src/jp/yuudachi/core/exception/ActionException.java | 245 | package jp.yuudachi.core.exception;
public class ActionException extends SysException {
public ActionException() {
super("【业务逻辑出现异常】");
}
public ActionException(String message) {
super(message);
}
}
| mit |
mmirhoseini/marvel | core-lib/src/main/java/com/mirhoseini/marvel/character/search/SearchPresenterImpl.java | 4335 | package com.mirhoseini.marvel.character.search;
import com.mirhoseini.marvel.database.DatabaseHelper;
import com.mirhoseini.marvel.database.mapper.Mapper;
import com.mirhoseini.marvel.util.Constants;
import com.mirhoseini.marvel.util.SchedulerProvider;
import java.sql.SQLException;
import javax.inject.Inject;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
/**
* Created by Mohsen on 20/10/2016.
*/
class SearchPresenterImpl implements SearchPresenter {
@Inject
SearchInteractor interactor;
@Inject
DatabaseHelper databaseHelper;
private SearchView view;
private Disposable disposable;
private SchedulerProvider scheduler;
@Inject
public SearchPresenterImpl(SchedulerProvider scheduler) {
this.scheduler = scheduler;
}
@Override
public void bind(SearchView view) {
this.view = view;
}
@Override
public void doSearch(boolean isConnected, String query, long timestamp) {
if (null != view) {
view.showProgress();
}
disposable = interactor.loadCharacter(query, Constants.PRIVATE_KEY, Constants.PUBLIC_KEY, timestamp)
// check if result code is OK
.map(charactersResponse -> {
if (Constants.CODE_OK == charactersResponse.getCode())
return charactersResponse;
else
throw Exceptions.propagate(new ApiResponseCodeException(charactersResponse.getCode(), charactersResponse.getStatus()));
})
// check if is there any result
.map(charactersResponse -> {
if (charactersResponse.getData().getCount() > 0)
return charactersResponse;
else
throw Exceptions.propagate(new NoSuchCharacterException());
})
// map CharacterResponse to CharacterModel
.map(Mapper::mapCharacterResponseToCharacter)
// cache data on database
.map(character -> {
try {
databaseHelper.addCharacter(character);
} catch (SQLException e) {
throw Exceptions.propagate(e);
}
return character;
})
.observeOn(scheduler.mainThread())
.subscribe(character -> {
if (null != view) {
view.hideProgress();
view.showCharacter(character);
if (!isConnected)
view.showOfflineMessage(false);
}
},
// handle exceptions
throwable -> {
if (null != view) {
view.hideProgress();
if (isConnected) {
if (throwable instanceof ApiResponseCodeException)
view.showServiceError((ApiResponseCodeException) throwable);
else if (throwable instanceof NoSuchCharacterException)
view.showQueryNoResult();
else
view.showRetryMessage(throwable);
} else {
view.showOfflineMessage(true);
}
}
});
}
@Override
public boolean isQueryValid(String query) {
return null != query && !query.isEmpty();
}
@Override
public void loadCharactersCachedData() {
if (null != view)
try {
view.setCharactersCachedData(databaseHelper.selectAllCharacters());
} catch (SQLException e) {
view.showError(e);
}
}
@Override
public void unbind() {
if (disposable != null && !disposable.isDisposed())
disposable.dispose();
interactor.unbind();
view = null;
}
}
| mit |
merinhunter/SecureApp | rsa/MGF1.java | 763 | package rsa;
import java.security.MessageDigest;
import org.bouncycastle.pqc.math.linearalgebra.BigEndianConversions;
import common.Bytes;
public class MGF1 {
private final MessageDigest digest;
public MGF1(MessageDigest digest) {
this.digest = digest;
}
public byte[] generateMask(byte[] mgfSeed, int maskLen) {
int hashCount = (int) Math.ceil((float) maskLen / this.digest.getDigestLength());
byte[] mask = new byte[0];
for (int i = 0; i < hashCount; i++) {
this.digest.update(mgfSeed);
this.digest.update(BigEndianConversions.I2OSP(i, 4));
byte[] hash = this.digest.digest();
mask = Bytes.concat(mask, hash);
}
byte[] output = new byte[maskLen];
System.arraycopy(mask, 0, output, 0, output.length);
return output;
}
}
| mit |
RogueLogic/Parallel | src/main/java/net/roguelogic/mods/parallel/internal/Parallel.java | 409 | package net.roguelogic.mods.parallel.internal;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
@Mod(modid = "parallel")
public final class Parallel {
@Mod.EventHandler
public void onPreInit(FMLPreInitializationEvent event) {
// To quote a well known mod.
// The start of something Great
new Updater();
}
}
| mit |
oldpond/SportsBoards2D-TimeTrials | src/com/sportsboards2d/timetrials/PlayerDb.java | 1850 | package com.sportsboards2d.timetrials;
/*
* DEPRECATED, This class has been replaced by DbHelper
*/
//@DEPRECATED
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
//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 SportsBoards2D. If not, see <http://www.gnu.org/licenses/>.
/**
* Copyright 2011 5807400 Manitoba Inc.
*/
public class PlayerDb extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "appdata";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table players " +
"(_id integer primary key autoincrement, name text not null, team integer not null);";
public PlayerDb(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TimeDb.class.getName(),"Upgrading database from version " + oldVersion +" to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS players");
onCreate(db);
}
}
| mit |
lionking422/random_stuff | RemoteDesktop/RemoteDesktop/src/remotedesktop/RemoteDesktop.java | 347 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package remotedesktop;
/**
*
* @author arghasarkar
*/
public class RemoteDesktop {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
| mit |
Institute-Web-Science-and-Technologies/LiveGovWP1 | shared/liveandgov-commons/src/main/java/eu/liveandgov/wp1/data/impl/Velocity.java | 1100 | package eu.liveandgov.wp1.data.impl;
import eu.liveandgov.wp1.data.AbstractItem;
import eu.liveandgov.wp1.data.DataCommons;
import eu.liveandgov.wp1.serialization.impl.VelocitySerialization;
/**
* Created by Lukas Härtel on 16.07.2014.
*/
public class Velocity extends AbstractItem {
public final float velocity;
public Velocity(long timestamp, String device, float velocity) {
super(timestamp, device);
this.velocity = velocity;
}
@Override
public String getType() {
return DataCommons.TYPE_VELOCITY;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Velocity velocity1 = (Velocity) o;
return Float.compare(velocity1.velocity, velocity) == 0;
}
@Override
public int hashCode() {
return (velocity != +0.0f ? Float.floatToIntBits(velocity) : 0);
}
@Override
protected String createSerializedForm() {
return VelocitySerialization.VELOCITY_SERIALIZATION.serialize(this);
}
}
| mit |
Azure/azure-sdk-for-java | sdk/mariadb/azure-resourcemanager-mariadb/src/main/java/com/azure/resourcemanager/mariadb/implementation/ResourceProvidersImpl.java | 3307 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.mariadb.implementation;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.mariadb.fluent.ResourceProvidersClient;
import com.azure.resourcemanager.mariadb.fluent.models.QueryPerformanceInsightResetDataResultInner;
import com.azure.resourcemanager.mariadb.models.QueryPerformanceInsightResetDataResult;
import com.azure.resourcemanager.mariadb.models.ResourceProviders;
import com.fasterxml.jackson.annotation.JsonIgnore;
public final class ResourceProvidersImpl implements ResourceProviders {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ResourceProvidersImpl.class);
private final ResourceProvidersClient innerClient;
private final com.azure.resourcemanager.mariadb.MariaDBManager serviceManager;
public ResourceProvidersImpl(
ResourceProvidersClient innerClient, com.azure.resourcemanager.mariadb.MariaDBManager serviceManager) {
this.innerClient = innerClient;
this.serviceManager = serviceManager;
}
public QueryPerformanceInsightResetDataResult resetQueryPerformanceInsightData(
String resourceGroupName, String serverName) {
QueryPerformanceInsightResetDataResultInner inner =
this.serviceClient().resetQueryPerformanceInsightData(resourceGroupName, serverName);
if (inner != null) {
return new QueryPerformanceInsightResetDataResultImpl(inner, this.manager());
} else {
return null;
}
}
public Response<QueryPerformanceInsightResetDataResult> resetQueryPerformanceInsightDataWithResponse(
String resourceGroupName, String serverName, Context context) {
Response<QueryPerformanceInsightResetDataResultInner> inner =
this.serviceClient().resetQueryPerformanceInsightDataWithResponse(resourceGroupName, serverName, context);
if (inner != null) {
return new SimpleResponse<>(
inner.getRequest(),
inner.getStatusCode(),
inner.getHeaders(),
new QueryPerformanceInsightResetDataResultImpl(inner.getValue(), this.manager()));
} else {
return null;
}
}
public void createRecommendedActionSession(
String resourceGroupName, String serverName, String advisorName, String databaseName) {
this.serviceClient().createRecommendedActionSession(resourceGroupName, serverName, advisorName, databaseName);
}
public void createRecommendedActionSession(
String resourceGroupName, String serverName, String advisorName, String databaseName, Context context) {
this
.serviceClient()
.createRecommendedActionSession(resourceGroupName, serverName, advisorName, databaseName, context);
}
private ResourceProvidersClient serviceClient() {
return this.innerClient;
}
private com.azure.resourcemanager.mariadb.MariaDBManager manager() {
return this.serviceManager;
}
}
| mit |
farmapromlab/rundeck-mesos-plugin | src/main/java/com/farmaprom/helpers/TaskIdGeneratorHelper.java | 540 | package com.farmaprom.helpers;
import com.dtolabs.rundeck.plugins.step.PluginStepContext;
import org.apache.commons.lang.StringUtils;
import java.util.UUID;
public class TaskIdGeneratorHelper {
public static String getTaskId(PluginStepContext context) {
String taskId = context.getDataContext().get("job").get("project")
+ "-" + context.getDataContext().get("job").get("name")
+ "-" + UUID.randomUUID().toString();
return StringUtils.replace(taskId.toLowerCase(), " ", "-");
}
}
| mit |
tatocaster/BuildNumberOverlay | app/src/androidTest/java/me/tatocaster/buildversionoverlay/ExampleInstrumentedTest.java | 770 | package me.tatocaster.buildversionoverlay;
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("me.tatocaster.buildversionoverlay", appContext.getPackageName());
}
}
| mit |
vvydier/ClaimAcademy | web1/src/web/BookServlet1.java | 2357 | package web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import backend.Book;
import backend.BookCache;
/**
* Servlet implementation class BookServlet
*/
@WebServlet("/BookServlet1")
public class BookServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
private BookCache cache = null;
/**
* @see HttpServlet#HttpServlet()
*/
public BookServlet1() {
super();
// TODO Auto-generated constructor stub
}
@Override
public void init() throws ServletException {
super.init();
cache = new BookCache();
cache.addBook(1, new Book(1, "Practical Clojure", "VV", 10));
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Map<Long, Book> books = cache.getBooks();
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>List of Books</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("<table border=\"1\">");
for (Iterator<Long> iterator = books.keySet().iterator(); iterator.hasNext();) {
Long id = iterator.next();
Book eachBook = books.get(id);
out.println("<tr>");
out.println("<td>"+ eachBook.getId() + "</td>");
out.println("<td>"+ eachBook.getBookTitle() + "</td>");
out.println("<td>"+ eachBook.getPublisher() + "</td>");
out.println("<td>"+ eachBook.getPrice() + "</td>");
out.println("</tr>");
}
out.println("</body>");
out.println("</html>");
// response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| mit |
The-Dream-Team/Tardis | src/main/java/me/dreamteam/tardis/Sprite.java | 410 | package me.dreamteam.tardis;
import java.awt.*;
public class Sprite {
private Image image;
public Sprite(Image image) {
this.image = image;
}
public int getWidth() {
return image.getWidth(null);
}
public int getHeight() {
return image.getHeight(null);
}
public void draw(Graphics g, int x, int y) {
g.drawImage(image, x, y, null);
}
}
| mit |
braunit/WeatherParser | WeatherParser/src/main/java/ca/braunit/weatherparser/taf/util/IcingConditionsDecoder.java | 3107 | /*
* Copyright (c)2014 Braun IT Solutions Ltd, Vancouver, Canada
* http://www.braun-it.ca
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package ca.braunit.weatherparser.taf.util;
import java.util.HashMap;
import java.util.Map;
import ca.braunit.weatherparser.exception.DecoderException;
import ca.braunit.weatherparser.metar.util.CommonDecoder;
import ca.braunit.weatherparser.taf.domain.IcingConditions;
public class IcingConditionsDecoder {
private static final String ICING_CONDITIONS_PATTERN = "6[\\d]{5}( |\\Z)(.)*";
private static final Map<Integer,String> INTENSITY_MAP = new HashMap<Integer,String>();
static {
INTENSITY_MAP.put(0, "no icing / trace of icing");
INTENSITY_MAP.put(1, "light mixed icing");
INTENSITY_MAP.put(2, "light rime icing in cloud");
INTENSITY_MAP.put(3, "light clear icing in precipitation");
INTENSITY_MAP.put(4, "moderate mixed icing");
INTENSITY_MAP.put(5, "moderate rime icing in cloud");
INTENSITY_MAP.put(6, "moderate clear icing in precipitation");
INTENSITY_MAP.put(7, "severe mixed icing");
INTENSITY_MAP.put(8, "severe rime icing in cloud");
INTENSITY_MAP.put(9, "severe clear icing in precipitation");
}
public static IcingConditions decodeObject(StringBuffer tafAsString) throws DecoderException {
IcingConditions icingConditions = null;
if(tafAsString.toString().matches(ICING_CONDITIONS_PATTERN)) {
icingConditions = new IcingConditions();
tafAsString.delete(0, 1);
icingConditions.setIcingIntensityCode(Integer.parseInt(tafAsString.substring(0, 1)));
icingConditions.setIcingIntensity(INTENSITY_MAP.get(icingConditions.getIcingIntensityCode()));
tafAsString.delete(0, 1);
icingConditions.setIcingLayerBase(Integer.parseInt(tafAsString.substring(0, 3)) * 100);
tafAsString.delete(0, 3);
icingConditions.setIcingLayerDepth(Integer.parseInt(tafAsString.substring(0, 1)) * 1000);
CommonDecoder.deleteParsedContent(tafAsString);
}
return icingConditions;
}
}
| mit |
sundxing/LqBookReader | app/src/main/java/com/lqtemple/android/lqbookreader/read/BookLoader.java | 1098 | package com.lqtemple.android.lqbookreader.read;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.lqtemple.android.lqbookreader.FileUtils;
import com.lqtemple.android.lqbookreader.model.Book;
import com.lqtemple.android.lqbookreader.model.RawBook;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by sundxing on 16/12/11.
*/
public class BookLoader {
private static Map<String, Book> cacheBooks = new ConcurrentHashMap<>(1);
// TODO background
public static Book load(String fileName) {
//
Book book = cacheBooks.get(fileName);
if (book == null) {
try {
String result = FileUtils.readFile(fileName, "utf-8").toString();
RawBook rawBook = JSON.parseObject(result, RawBook.class);
book = Book.from(rawBook);
cacheBooks.put(fileName, book);
Log.d("", "book load:" + rawBook.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
return book;
}
}
| mit |
mdamis/galleria | app/src/main/java/com/mdamis/galleria/SubredditActivity.java | 1285 | package com.mdamis.galleria;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.mdamis.galleria.post.Post;
public class SubredditActivity extends AppCompatActivity {
String title;
SubredditFragment subredditFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subreddit);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
title = this.getIntent().getExtras().getString("title");
getSupportActionBar().setTitle(title);
FragmentManager fragmentManager = getFragmentManager();
subredditFragment = (SubredditFragment) fragmentManager.findFragmentById(R.id.subredditFragment);
fragmentManager.beginTransaction().replace(R.id.subredditFragment, subredditFragment).commit();
}
public void onGridItemClick(int position) {
Post post = (Post) subredditFragment.getImageAdapter().getItem(position);
String imageUrl = post.getUrl();
Intent intent = new Intent(this, PostActivity.class);
intent.putExtra("url", imageUrl);
startActivity(intent);
}
}
| mit |
rachitmishra/project-msongo | projectmsongo/src/main/java/in/ceeq/msongo/provider/entity/User.java | 253 | package in.ceeq.msongo.provider.entity;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = -1182387499711122673L;
public long mId;
public String mName;
public String mEmail;
}
| mit |
dkarivalis/SEP_SMIFL | app/models/Portfolio.java | 3091 | package models;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
import play.data.format.*;
import play.data.validation.*;
import play.libs.Json;
import com.avaje.ebean.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* Portfolio entity managed by Ebean
*/
@Entity
@Table(name="portfolio")
public class Portfolio extends Model {
private static final long serialVersionUID = 1L;
@Id
public long id;
@Constraints.Required
public long userId;
@Constraints.Required
public long leagueId;
/**
* Constructor
*/
private Portfolio( final long userId, final long leagueId ) {
this.userId = userId;
this.leagueId = leagueId;
}
/**
* Method to get the JSON for this object.
*/
//TODO add positions
public ObjectNode getJson() {
return Json.newObject()
.put("userId", this.userId)
.put("leagueId", this.leagueId)
.put("id", this.id);
}
/**
* Method for finding a Portfolio in the DB.
* @param userId is the DB id for a user
* @param leagueId is the DB id for a league
* @return Returns a Portfolio if found, null otherwise.
*/
public static Portfolio find( final long userId, final long leagueId ) {
return Ebean.find(Portfolio.class)
.where()
.eq("userId", userId)
.eq("leagueId", leagueId)
.findUnique();
}
/**
* Method for finding a Portfolio in the DB.
* @param portfolioId is the DB id for the portfolio
* @return Returns a Portfolio if found, null otherwise.
*/
public static Portfolio find( final long portfolioId ) {
return Ebean.find(Portfolio.class)
.where()
.eq("id", portfolioId)
.findUnique();
}
/**
* Method for finding a Portfolio in the DB.
* @param portfolioId is the DB id for the portfolio
* @return Returns a Portfolio if found, null otherwise.
*/
public static List<Portfolio> findByLeadgueId( final long leagueId ) {
return Ebean.find(Portfolio.class)
.where()
.eq("leagueId", leagueId)
.findList();
}
/**
* Method sets up a portfolio for a given user in a given league.
*/
public static Portfolio getPortfolio( final long userId, final long leagueId ) {
Portfolio port = Portfolio.find( userId, leagueId );
if ( port != null ) {
//Already in the DB
return port;
}
port = new Portfolio(userId, leagueId);
Ebean.save(port);
return Portfolio.find( userId, leagueId );
}
/**
* Method finds all the portfolios for a user.
*/
//TODO change this to a PagingList
public static List<Portfolio> findAllByUserId ( final long userId ) {
return Ebean.find(Portfolio.class)
.where()
.eq("userId", userId)
.findList();
}
public static Portfolio add ( final long userId, final long leagueId ) {
Portfolio portfolio = Portfolio.find( userId, leagueId );
if ( portfolio != null ) {
return portfolio;
}
portfolio = new Portfolio( userId, leagueId );
Ebean.save(portfolio);
return Portfolio.find( userId, leagueId );
}
}
| mit |
JornC/bitcoin-transaction-explorer | bitcoin-transactions-core/src/main/java/com/yoghurt/crypto/transactions/client/widget/ContextField.java | 4688 | package com.yoghurt.crypto.transactions.client.widget;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.dom.client.HasMouseOutHandlers;
import com.google.gwt.event.dom.client.HasMouseOverHandlers;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.yoghurt.crypto.transactions.client.util.ComputedStyle;
import com.yoghurt.crypto.transactions.client.util.misc.Color;
public class ContextField<T> extends Composite implements HasMouseOutHandlers, HasMouseOverHandlers, HasClickHandlers {
private static final int FIELD_HEIGHT = 24;
interface ContextFieldUiBinder extends UiBinder<Widget, ContextField<?>> {}
private static final ContextFieldUiBinder UI_BINDER = GWT.create(ContextFieldUiBinder.class);
/**
* Needs to correspond to the same value in the UiBinder
*/
private static final int ANIMATION_TIME = 200;
private static final int CLEAN_UP_DELAY = 5 + ANIMATION_TIME;
@UiField CustomStyle style;
@UiField FlowPanel container;
private T value;
private String currentText;
private final Timer cleanupTimer = new Timer() {
@Override
public void run() {
// Make sure we're not animating
container.addStyleName(style.noAnimation());
// Remove all but the last widget
while(container.getWidgetCount() > 1) {
container.remove(0);
}
// Reset the 'top' attribute to 0, and enforce the DOM change
container.getElement().getStyle().setTop(0, Unit.PX);
ComputedStyle.getStyleProperty(container.getElement(), "top");
// Re-enable animation
container.removeStyleName(style.noAnimation());
}
};
public interface CustomStyle extends CssResource {
String fieldSelected();
String fieldActive();
String noAnimation();
}
public ContextField(final T value, final Color color, final String text) {
this.value = value;
initWidget(UI_BINDER.createAndBindUi(this));
setColor(color);
setContent(text, false);
}
public void setColor(final Color color) {
final Color backgroundColor = color.copy();
backgroundColor.setA(0.2);
getElement().getStyle().setBorderColor(color.getValue());
getElement().getStyle().setBackgroundColor(backgroundColor.getValue());
}
public void setContent(final String text) {
setContent(text, true);
}
public void setContent(final String text, final boolean animate) {
// Bug out if the text to display is the same as the current text
if (text != null && text.equals(currentText)) {
return;
}
if(!animate) {
container.clear();
}
final Label lbl = new Label(text);
container.add(lbl);
if(animate) {
container.getElement().getStyle().setTop(- (container.getWidgetCount() - 1) * FIELD_HEIGHT, Unit.PX);
// This is gonna suck if there's more than a couple of these running, so thank god Mr Moore invented that law of his
cleanupTimer.cancel();
cleanupTimer.schedule(CLEAN_UP_DELAY);
} else {
container.getElement().getStyle().setTop(0, Unit.PX);
}
currentText = text;
}
public T getValue() {
return value;
}
public void setValue(final T value) {
this.value = value;
}
public void setSelected(final boolean selected) {
setStyleName(style.fieldSelected(), selected);
}
public void setActive(final boolean active) {
setStyleName(style.fieldActive(), active);
}
@Override
public HandlerRegistration addClickHandler(final ClickHandler handler) {
return addDomHandler(handler, ClickEvent.getType());
}
@Override
public HandlerRegistration addMouseOverHandler(final MouseOverHandler handler) {
return addDomHandler(handler, MouseOverEvent.getType());
}
@Override
public HandlerRegistration addMouseOutHandler(final MouseOutHandler handler) {
return addDomHandler(handler, MouseOutEvent.getType());
}
}
| mit |
gitgabrio/vaadin-spring-archetype | src/main/resources/archetype-resources/src/main/java/server/spring/Config.java | 1575 | #set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.server.spring;
import com.vaadin.spring.annotation.EnableVaadin;
import ${package}.server.service.AuthenticationService;
import ${package}.server.vaadin.eventbus.EventBus;
import ${package}.server.vaadin.view.login.LoginView;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* The type <code>Config</code>.
*/
@Configuration
@EnableVaadin
@PropertySource("classpath:application.properties")
@ComponentScan("${package}.server")
public class Config {
/**
* This is needed for @Value configuration to work properly
*
* @return property sources placeholder configurer
*/
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
/**
* Gets authentication service.
*
* @return the authentication service
*/
@Bean
public AuthenticationService getAuthenticationService() {
return new AuthenticationService();
}
/**
* Gets event bus.
*
* @return the event bus
*/
@Bean
@Scope("prototype")
public EventBus getEventBus() {
return new EventBus();
}
/**
* Gets login view.
*
* @return the login view
*/
@Bean
@Scope("prototype")
public LoginView getLoginView() {
return new LoginView(getAuthenticationService());
}
}
| mit |
pchudzik/springmock | mockito/src/main/java/com/pchudzik/springmock/mockito/spring/MockitoContextCustomizerFactory.java | 1620 | package com.pchudzik.springmock.mockito.spring;
import com.pchudzik.springmock.infrastructure.definition.registry.DoubleRegistry;
import com.pchudzik.springmock.infrastructure.spring.MockContextCustomizer;
import com.pchudzik.springmock.infrastructure.spring.MockContextCustomizerFactory;
import com.pchudzik.springmock.mockito.MockitoDoubleFactory;
import com.pchudzik.springmock.mockito.configuration.MockitoDouble;
import com.pchudzik.springmock.mockito.configuration.MockitoDoubleConfigurationParser;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.test.context.ContextCustomizer;
import java.util.AbstractMap.SimpleEntry;
import java.util.Map;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toMap;
public class MockitoContextCustomizerFactory extends MockContextCustomizerFactory {
public MockitoContextCustomizerFactory() {
super(MockitoDouble.class, new MockitoDoubleConfigurationParser());
}
@Override
protected ContextCustomizer createContextCustomizer(DoubleRegistry doubleRegistry) {
return new MockContextCustomizer(
MockitoDoubleFactory.class,
doubleRegistry,
Stream
.of(new SimpleEntry<>(SkipMockitoBeansPostProcessing.BEAN_NAME, skipMockitoBeansPostProcessing()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
}
private static AbstractBeanDefinition skipMockitoBeansPostProcessing() {
return BeanDefinitionBuilder.genericBeanDefinition(SkipMockitoBeansPostProcessing.class).getBeanDefinition();
}
}
| mit |
tornaia/hr2 | hr2-java-parent/hr2-backend-impl/src/main/java/hu/interconnect/hr/module/reports/receiveditems/ReceivedItemsRowFromReceivedItemCreator.java | 632 | package hu.interconnect.hr.module.reports.receiveditems;
import java.util.Map;
import java.util.function.Function;
import hu.interconnect.hr.domain.AtvettEszkoz;
import hu.interconnect.hr.module.reports.NullValueToEmptyStringMap;
public class ReceivedItemsRowFromReceivedItemCreator implements Function<AtvettEszkoz, Map<String, Object>> {
@Override
public Map<String, Object> apply(AtvettEszkoz atvettEszkozDTO) {
NullValueToEmptyStringMap sor = new NullValueToEmptyStringMap();
sor.put("megnevezes", atvettEszkozDTO.getMegnevezes());
sor.put("megjegyzes", atvettEszkozDTO.getMegjegyzes());
return sor.getMap();
}
}
| mit |
zhangyanwei/overtime-record | code/src/main/java/tools/ctd/dao/impl/ConnectionProvider.java | 2423 | package tools.ctd.dao.impl;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.postgresql.ds.PGPoolingDataSource;
import tools.ctd.dao.IConnectionProvider;
import tools.ctd.env.CoreProperties;
import tools.ctd.exception.CTDException;
public class ConnectionProvider implements IConnectionProvider {
private static final Log LOG = LogFactory.getLog(ConnectionProvider.class);
/** javax.sql.DataSource的PostgreSQL实现 */
private static PGPoolingDataSource source = new PGPoolingDataSource();
static {
init();
}
@Override
public synchronized Connection getConnection() throws CTDException {
Connection conn = null;
try {
conn = source.getConnection();
// 不自动提交
conn.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
LOG.fatal(e);
throw new CTDException(CTDException.DB_CONNECTION_CREATE_ERROR_1, e);
}
return conn;
}
/**
* 初始化数据库连接池,数据库的配置信息请参照{@link DBProperties}类的描述。
*/
private static void init() {
try {
DBProperties initProperties = CoreProperties
.getProperties(DBProperties.class);
String SourceName = "CTD";
String serverName = initProperties.getServerName();
String databaseName = initProperties.getDatabaseName();
String url = initProperties.getUrl();
String userName = initProperties.getUserName();
String password = initProperties.getPassword();
int maxPooledConnections = initProperties.getMaxPooledConnections();
init(SourceName, serverName, databaseName, url, userName, password,
maxPooledConnections);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 初始化数据库连接缓存
*
* @param url
* PostgreSQL数据库连接URL ex.) "jdbc:oracle:oci8:@croccore"
* @param userName
* PostgreSQL数据库用户名
* @param password
* PostgreSQL数据库密码
*/
private static void init(String SourceName, String serverName,
String databaseName, String url, String userName, String password,
int maxPooledConnections) {
source.setDataSourceName(SourceName);
source.setServerName(serverName);
source.setDatabaseName(databaseName);
source.setUser(userName);
source.setPassword(password);
source.setMaxConnections(maxPooledConnections);
}
}
| mit |
BoiseState/CS121-resources | examples/chap04/ArrayListIntegers.java | 1760 |
import java.util.Scanner;
import java.util.ArrayList;
/**
* Demonstrates the use of an ArrayList object with Integer wrapper objects.
*
* @author CS 121 Instructors
*
*/
public class ArrayListIntegers
{
/**
* Prompts the user to enter integers and adds them to an Array List.
* Then removes the even integers.
*
* @param args
*/
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
int intValue;
ArrayList<Integer> myIntList = new ArrayList<Integer>();
/* Store integer values to array list */
do
{
System.out.print("Enter a positive integer (0 to quit): ");
intValue = scan.nextInt();
if(intValue > 0)
{
myIntList.add(intValue);
}
else if(intValue < 0)
{
System.out.println("Invalid input: Your integer must be positive!");
}
} while(intValue != 0);
/* Make sure the list is nonempty */
if(myIntList.size() > 0)
{
/* Print array list contents */
System.out.println("Your initial array list size is " + myIntList.size() + " and contains: ");
for(int i = 0; i < myIntList.size(); i++)
{
System.out.printf("\t[%d] %d\n", i, myIntList.get(i));
}
/* Now remove the even numbers */
System.out.println("Removing even numbers!");
for(int i = myIntList.size() - 1; i >= 0; i--)
{
if(myIntList.get(i) % 2 == 0)
{
myIntList.remove(i);
}
}
/* Print array list contents */
System.out.println("Now your array list size is " + myIntList.size() + " and contains: ");
for(int i = 0; i < myIntList.size(); i++)
{
System.out.printf("\t[%d] %d\n", i, myIntList.get(i));
}
}
else
{
System.out.println("Your array list is empty! Nothing to do!");
}
scan.close();
}
}
| mit |
DavidOpDeBeeck/swamp | swamp-scheduling/src/main/java/de/daxu/swamp/scheduling/command/containerinstance/event/ContainerInstanceCreationEvent.java | 423 | package de.daxu.swamp.scheduling.command.containerinstance.event;
import de.daxu.swamp.scheduling.command.containerinstance.ContainerInstanceStatus;
public interface ContainerInstanceCreationEvent
extends ContainerInstanceDeployEvent, ContainerInstanceStatusChangedEvent {
@Override
default ContainerInstanceStatus getContainerInstanceStatus() {
return ContainerInstanceStatus.CREATION;
}
}
| mit |
dpate90/Mine-Sweeper- | mine_sweeper.java | 264 | import java.io.IOException;
public class mine_sweeper {
// main function
public static void main(String[] args) throws IOException {
// game loop
while (true) {
Game game = new Game();
//if () {
// System.exit(0);
//}
}
}
}
| mit |
vladimir-golovnin/otus-java-2017-04-golovnin | hw10/src/main/java/ru/otus/java_2017_04/golovnin/hw10/DbQueryExecutor.java | 874 | package ru.otus.java_2017_04.golovnin.hw10;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DbQueryExecutor {
private DataSource dataSource;
DbQueryExecutor(DataSource dataSource){
this.dataSource = dataSource;
}
<T> T executeQuery(String query, QueryResultHandler<T> handler){
T result = null;
try(Connection connection = dataSource.getConnection()) {
Statement statement = connection.createStatement();
statement.execute(query);
ResultSet resultSet = statement.getResultSet();
if(handler != null){
result = handler.handle(resultSet);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
| mit |
sevtrust/SCAN | src/ac/BitOutputStream.java | 2606 | package ac;
/*
* Reference arithmetic coding
* Copyright (c) Project Nayuki
*
* https://www.nayuki.io/page/reference-arithmetic-coding
* https://github.com/nayuki/Reference-arithmetic-coding
*/
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
/**
* A stream where bits can be written to. Because they are written to an underlying
* byte stream, the end of the stream is padded with 0's up to a multiple of 8 bits.
* The bits are written in big endian. Mutable and not thread-safe.
* @see BitInputStream
*/
public final class BitOutputStream implements AutoCloseable {
/*---- Fields ----*/
// The underlying byte stream to write to (not null).
private OutputStream output;
// The accumulated bits for the current byte, always in the range [0x00, 0xFF].
private int currentByte;
// Number of accumulated bits in the current byte, always between 0 and 7 (inclusive).
private int numBitsFilled;
private ArrayList<Integer> outputByte;
int i;
/*---- Constructor ----*/
/**
* Constructs a bit output stream based on the specified byte output stream.
* @param in the byte output stream
* @throws NullPointerException if the output stream is {@code null}
*/
public BitOutputStream(OutputStream out) {
if (out == null)
throw new NullPointerException();
outputByte = new ArrayList<Integer>();
output = out;
currentByte = 0;
numBitsFilled = 0;
}
/*---- Methods ----*/
/**
* Writes a bit to the stream. The specified bit must be 0 or 1.
* @param b the bit to write, which must be 0 or 1
* @throws IOException if an I/O exception occurred
*/
public void write(int b) throws IOException {
if (b != 0 && b != 1)
throw new IllegalArgumentException("Argument must be 0 or 1");
currentByte = (currentByte << 1) | b;
numBitsFilled++;
if (numBitsFilled == 8) {
output.write(currentByte);
outputByte.add(currentByte);
currentByte = 0;
numBitsFilled = 0;
}
}
public ArrayList<Integer> getByteStream(){
return outputByte;
}
public void writeByte(int b) throws IOException{
while (numBitsFilled != 0)
write(0);
output.write(b);
}
/**
* Closes this stream and the underlying output stream. If called when this
* bit stream is not at a byte boundary, then the minimum number of "0" bits
* (between 0 and 7 of them) are written as padding to reach the next byte boundary.
* @throws IOException if an I/O exception occurred
*/
public void close() throws IOException {
while (numBitsFilled != 0)
write(0);
if(output != null)
output.close();
}
}
| mit |
Alec-WAM/CrystalMod | src/main/java/alec_wam/CrystalMod/world/crystex/CrystexChunkProvider.java | 20510 | package alec_wam.CrystalMod.world.crystex;
import java.util.List;
import java.util.Random;
import javax.annotation.Nullable;
import alec_wam.CrystalMod.fluids.ModFluids;
import alec_wam.CrystalMod.util.CrystalColors;
import alec_wam.CrystalMod.world.crystex.biomes.ICrystexColorBiome;
import alec_wam.CrystalMod.world.generation.WorldGenLakesFixed;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.WorldEntitySpawner;
import net.minecraft.world.WorldType;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkPrimer;
import net.minecraft.world.chunk.IChunkGenerator;
import net.minecraft.world.gen.MapGenBase;
import net.minecraft.world.gen.MapGenCaves;
import net.minecraft.world.gen.MapGenRavine;
import net.minecraft.world.gen.NoiseGeneratorOctaves;
import net.minecraft.world.gen.NoiseGeneratorPerlin;
public class CrystexChunkProvider implements IChunkGenerator
{
protected static final IBlockState STONE = Blocks.STONE.getDefaultState();
private final Random rand;
private NoiseGeneratorOctaves minLimitPerlinNoise;
private NoiseGeneratorOctaves maxLimitPerlinNoise;
private NoiseGeneratorOctaves mainPerlinNoise;
private NoiseGeneratorPerlin surfaceNoise;
public NoiseGeneratorOctaves scaleNoise;
public NoiseGeneratorOctaves depthNoise;
public NoiseGeneratorOctaves forestNoise;
private final World world;
private final WorldType terrainType;
private final double[] heightMap;
private final float[] biomeWeights;
private IBlockState oceanBlock = Blocks.WATER.getDefaultState();
private double[] depthBuffer = new double[256];
private MapGenBase caveGenerator = new MapGenCaves();
private MapGenBase ravineGenerator = new MapGenRavine();
private Biome[] biomesForGeneration;
double[] mainNoiseRegion;
double[] minLimitRegion;
double[] maxLimitRegion;
double[] depthRegion;
public CrystexChunkProvider(World worldIn, long seed)
{
{
caveGenerator = net.minecraftforge.event.terraingen.TerrainGen.getModdedMapGen(caveGenerator, net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.CAVE);
ravineGenerator = net.minecraftforge.event.terraingen.TerrainGen.getModdedMapGen(ravineGenerator, net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.RAVINE);
}
this.world = worldIn;
this.terrainType = worldIn.getWorldInfo().getTerrainType();
this.rand = new Random(seed);
this.minLimitPerlinNoise = new NoiseGeneratorOctaves(this.rand, 16);
this.maxLimitPerlinNoise = new NoiseGeneratorOctaves(this.rand, 16);
this.mainPerlinNoise = new NoiseGeneratorOctaves(this.rand, 8);
this.surfaceNoise = new NoiseGeneratorPerlin(this.rand, 4);
this.scaleNoise = new NoiseGeneratorOctaves(this.rand, 10);
this.depthNoise = new NoiseGeneratorOctaves(this.rand, 16);
this.forestNoise = new NoiseGeneratorOctaves(this.rand, 8);
this.heightMap = new double[825];
this.biomeWeights = new float[25];
for (int i = -2; i <= 2; ++i)
{
for (int j = -2; j <= 2; ++j)
{
float f = 10.0F / MathHelper.sqrt((float)(i * i + j * j) + 0.2F);
this.biomeWeights[i + 2 + (j + 2) * 5] = f;
}
}
/*if (p_i46668_5_ != null)
{
this.settings = ChunkProviderSettings.Factory.jsonToFactory(p_i46668_5_).build();
this.oceanBlock = this.settings.useLavaOceans ? Blocks.LAVA.getDefaultState() : Blocks.WATER.getDefaultState();
worldIn.setSeaLevel(this.settings.seaLevel);
}*/
net.minecraftforge.event.terraingen.InitNoiseGensEvent.ContextOverworld ctx =
new net.minecraftforge.event.terraingen.InitNoiseGensEvent.ContextOverworld(minLimitPerlinNoise, maxLimitPerlinNoise, mainPerlinNoise, surfaceNoise, scaleNoise, depthNoise, forestNoise);
ctx = net.minecraftforge.event.terraingen.TerrainGen.getModdedNoiseGenerators(worldIn, this.rand, ctx);
this.minLimitPerlinNoise = ctx.getLPerlin1();
this.maxLimitPerlinNoise = ctx.getLPerlin2();
this.mainPerlinNoise = ctx.getPerlin();
this.surfaceNoise = ctx.getHeight();
this.scaleNoise = ctx.getScale();
this.depthNoise = ctx.getDepth();
this.forestNoise = ctx.getForest();
}
public void setBlocksInChunk(int x, int z, ChunkPrimer primer)
{
this.biomesForGeneration = this.world.getBiomeProvider().getBiomesForGeneration(this.biomesForGeneration, x * 4 - 2, z * 4 - 2, 10, 10);
this.generateHeightmap(x * 4, 0, z * 4);
for (int i = 0; i < 4; ++i)
{
int j = i * 5;
int k = (i + 1) * 5;
for (int l = 0; l < 4; ++l)
{
int i1 = (j + l) * 33;
int j1 = (j + l + 1) * 33;
int k1 = (k + l) * 33;
int l1 = (k + l + 1) * 33;
for (int i2 = 0; i2 < 32; ++i2)
{
double d0 = 0.125D;
double d1 = this.heightMap[i1 + i2];
double d2 = this.heightMap[j1 + i2];
double d3 = this.heightMap[k1 + i2];
double d4 = this.heightMap[l1 + i2];
double d5 = (this.heightMap[i1 + i2 + 1] - d1) * 0.125D;
double d6 = (this.heightMap[j1 + i2 + 1] - d2) * 0.125D;
double d7 = (this.heightMap[k1 + i2 + 1] - d3) * 0.125D;
double d8 = (this.heightMap[l1 + i2 + 1] - d4) * 0.125D;
for (int j2 = 0; j2 < 8; ++j2)
{
double d9 = 0.25D;
double d10 = d1;
double d11 = d2;
double d12 = (d3 - d1) * 0.25D;
double d13 = (d4 - d2) * 0.25D;
for (int k2 = 0; k2 < 4; ++k2)
{
double d14 = 0.25D;
double d16 = (d11 - d10) * 0.25D;
double lvt_45_1_ = d10 - d16;
for (int l2 = 0; l2 < 4; ++l2)
{
if ((lvt_45_1_ += d16) > 0.0D)
{
primer.setBlockState(i * 4 + k2, i2 * 8 + j2, l * 4 + l2, STONE);
}
else if (i2 * 8 + j2 < /*this.settings.seaLevel*/64)
{
primer.setBlockState(i * 4 + k2, i2 * 8 + j2, l * 4 + l2, this.oceanBlock);
}
}
d10 += d12;
d11 += d13;
}
d1 += d5;
d2 += d6;
d3 += d7;
d4 += d8;
}
}
}
}
}
public void replaceBiomeBlocks(int x, int z, ChunkPrimer primer, Biome[] biomesIn)
{
if (!net.minecraftforge.event.ForgeEventFactory.onReplaceBiomeBlocks(this, x, z, primer, this.world)) return;
double d0 = 0.03125D;
this.depthBuffer = this.surfaceNoise.getRegion(this.depthBuffer, (double)(x * 16), (double)(z * 16), 16, 16, 0.0625D, 0.0625D, 1.0D);
for (int i = 0; i < 16; ++i)
{
for (int j = 0; j < 16; ++j)
{
Biome biome = biomesIn[j + i * 16];
biome.genTerrainBlocks(this.world, this.rand, primer, x * 16 + i, z * 16 + j, this.depthBuffer[j + i * 16]);
}
}
}
public Chunk provideChunk(int x, int z)
{
this.rand.setSeed((long)x * 341873128712L + (long)z * 132897987541L);
ChunkPrimer chunkprimer = new ChunkPrimer();
this.setBlocksInChunk(x, z, chunkprimer);
this.biomesForGeneration = this.world.getBiomeProvider().getBiomes(this.biomesForGeneration, x * 16, z * 16, 16, 16);
this.replaceBiomeBlocks(x, z, chunkprimer, this.biomesForGeneration);
this.caveGenerator.generate(this.world, x, z, chunkprimer);
this.ravineGenerator.generate(this.world, x, z, chunkprimer);
Chunk chunk = new Chunk(this.world, chunkprimer, x, z);
byte[] abyte = chunk.getBiomeArray();
for (int i = 0; i < abyte.length; ++i)
{
abyte[i] = (byte)Biome.getIdForBiome(this.biomesForGeneration[i]);
}
chunk.generateSkylightMap();
return chunk;
}
public float coordinateScale = 684.412F;
public float heightScale = 684.412F;
public float biomeDepthWeight = 1.0F;
public float biomeDepthOffset;
public float biomeScaleWeight = 1.0F;
public float biomeScaleOffset;
public float baseSize = 8.5F;
public float stretchY = 12.0F;
public float upperLimitScale = 512.0F;
public float lowerLimitScale = 512.0F;
public float depthNoiseScaleX = 200.0F;
public float depthNoiseScaleZ = 200.0F;
public float depthNoiseScaleExponent = 0.5F;
public float mainNoiseScaleX = 80.0F;
public float mainNoiseScaleY = 160.0F;
public float mainNoiseScaleZ = 80.0F;
private void generateHeightmap(int p_185978_1_, int p_185978_2_, int p_185978_3_)
{
this.depthRegion = this.depthNoise.generateNoiseOctaves(this.depthRegion, p_185978_1_, p_185978_3_, 5, 5, (double)depthNoiseScaleX, (double)depthNoiseScaleZ, (double)depthNoiseScaleExponent);
float f = coordinateScale;
float f1 = heightScale;
this.mainNoiseRegion = this.mainPerlinNoise.generateNoiseOctaves(this.mainNoiseRegion, p_185978_1_, p_185978_2_, p_185978_3_, 5, 33, 5, (double)(f / mainNoiseScaleX), (double)(f1 / mainNoiseScaleY), (double)(f / mainNoiseScaleZ));
this.minLimitRegion = this.minLimitPerlinNoise.generateNoiseOctaves(this.minLimitRegion, p_185978_1_, p_185978_2_, p_185978_3_, 5, 33, 5, (double)f, (double)f1, (double)f);
this.maxLimitRegion = this.maxLimitPerlinNoise.generateNoiseOctaves(this.maxLimitRegion, p_185978_1_, p_185978_2_, p_185978_3_, 5, 33, 5, (double)f, (double)f1, (double)f);
int i = 0;
int j = 0;
for (int k = 0; k < 5; ++k)
{
for (int l = 0; l < 5; ++l)
{
float f2 = 0.0F;
float f3 = 0.0F;
float f4 = 0.0F;
int i1 = 2;
Biome biome = this.biomesForGeneration[k + 2 + (l + 2) * 10];
for (int j1 = -2; j1 <= 2; ++j1)
{
for (int k1 = -2; k1 <= 2; ++k1)
{
Biome biome1 = this.biomesForGeneration[k + j1 + 2 + (l + k1 + 2) * 10];
float f5 = biomeDepthOffset + biome1.getBaseHeight() * biomeDepthWeight;
float f6 = biomeScaleOffset + biome1.getHeightVariation() * biomeScaleWeight;
if (this.terrainType == WorldType.AMPLIFIED && f5 > 0.0F)
{
f5 = 1.0F + f5 * 2.0F;
f6 = 1.0F + f6 * 4.0F;
}
float f7 = this.biomeWeights[j1 + 2 + (k1 + 2) * 5] / (f5 + 2.0F);
if (biome1.getBaseHeight() > biome.getBaseHeight())
{
f7 /= 2.0F;
}
f2 += f6 * f7;
f3 += f5 * f7;
f4 += f7;
}
}
f2 = f2 / f4;
f3 = f3 / f4;
f2 = f2 * 0.9F + 0.1F;
f3 = (f3 * 4.0F - 1.0F) / 8.0F;
double d7 = this.depthRegion[j] / 8000.0D;
if (d7 < 0.0D)
{
d7 = -d7 * 0.3D;
}
d7 = d7 * 3.0D - 2.0D;
if (d7 < 0.0D)
{
d7 = d7 / 2.0D;
if (d7 < -1.0D)
{
d7 = -1.0D;
}
d7 = d7 / 1.4D;
d7 = d7 / 2.0D;
}
else
{
if (d7 > 1.0D)
{
d7 = 1.0D;
}
d7 = d7 / 8.0D;
}
++j;
double d8 = (double)f3;
double d9 = (double)f2;
d8 = d8 + d7 * 0.2D;
d8 = d8 * (double)baseSize / 8.0D;
double d0 = (double)baseSize + d8 * 4.0D;
for (int l1 = 0; l1 < 33; ++l1)
{
double d1 = ((double)l1 - d0) * (double)stretchY * 128.0D / 256.0D / d9;
if (d1 < 0.0D)
{
d1 *= 4.0D;
}
double d2 = this.minLimitRegion[i] / (double)lowerLimitScale;
double d3 = this.maxLimitRegion[i] / (double)upperLimitScale;
double d4 = (this.mainNoiseRegion[i] / 10.0D + 1.0D) / 2.0D;
double d5 = MathHelper.clampedLerp(d2, d3, d4) - d1;
if (l1 > 29)
{
double d6 = (double)((float)(l1 - 29) / 3.0F);
d5 = d5 * (1.0D - d6) + -10.0D * d6;
}
this.heightMap[i] = d5;
++i;
}
}
}
}
public void populate(int x, int z)
{
BlockFalling.fallInstantly = true;
int i = x * 16;
int j = z * 16;
BlockPos blockpos = new BlockPos(i, 0, j);
Biome biome = this.world.getBiome(blockpos.add(16, 0, 16));
this.rand.setSeed(this.world.getSeed());
long k = this.rand.nextLong() / 2L * 2L + 1L;
long l = this.rand.nextLong() / 2L * 2L + 1L;
this.rand.setSeed((long)x * k + (long)z * l ^ this.world.getSeed());
boolean flag = false;
ChunkPos chunkpos = new ChunkPos(x, z);
net.minecraftforge.event.ForgeEventFactory.onChunkPopulate(true, this, this.world, this.rand, x, z, flag);
boolean lakes = this.rand.nextInt(4) == 0;
boolean crystal_lakes = this.rand.nextInt(8) == 0;
if (lakes && net.minecraftforge.event.terraingen.TerrainGen.populate(this, this.world, this.rand, x, z, flag, net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType.LAKE))
{
int i1 = this.rand.nextInt(16) + 8;
int j1 = this.rand.nextInt(256);
int k1 = this.rand.nextInt(16) + 8;
(new WorldGenLakesFixed(Blocks.WATER)).generate(this.world, this.rand, blockpos.add(i1, j1, k1));
}
if (crystal_lakes && biome instanceof ICrystexColorBiome && net.minecraftforge.event.terraingen.TerrainGen.populate(this, this.world, this.rand, x, z, flag, net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType.LAKE))
{
int i1 = this.rand.nextInt(16) + 8;
int j1 = this.rand.nextInt(256);
int k1 = this.rand.nextInt(16) + 8;
CrystalColors.SuperSpecial color = ((ICrystexColorBiome)biome).getColor();
Block liquid = null;
if(color == CrystalColors.SuperSpecial.BLUE)liquid = ModFluids.fluidBlueCrystal.getBlock();
if(color == CrystalColors.SuperSpecial.RED)liquid = ModFluids.fluidRedCrystal.getBlock();
if(color == CrystalColors.SuperSpecial.GREEN)liquid = ModFluids.fluidGreenCrystal.getBlock();
if(color == CrystalColors.SuperSpecial.DARK)liquid = ModFluids.fluidDarkCrystal.getBlock();
if(color == CrystalColors.SuperSpecial.PURE)liquid = ModFluids.fluidPureCrystal.getBlock();
if(liquid !=null)new WorldGenLakesFixed(liquid).generate(this.world, this.rand, blockpos.add(i1, j1, k1));
}
/*if (!flag && this.rand.nextInt(this.settings.lavaLakeChance / 10) == 0 && this.settings.useLavaLakes)
if (net.minecraftforge.event.terraingen.TerrainGen.populate(this, this.world, this.rand, x, z, flag, net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType.LAVA))
{
int i2 = this.rand.nextInt(16) + 8;
int l2 = this.rand.nextInt(this.rand.nextInt(248) + 8);
int k3 = this.rand.nextInt(16) + 8;
if (l2 < this.world.getSeaLevel() || this.rand.nextInt(this.settings.lavaLakeChance / 8) == 0)
{
(new WorldGenLakes(Blocks.LAVA)).generate(this.world, this.rand, blockpos.add(i2, l2, k3));
}
}*/
/*if (this.settings.useDungeons)
if (net.minecraftforge.event.terraingen.TerrainGen.populate(this, this.world, this.rand, x, z, flag, net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType.DUNGEON))
{
for (int j2 = 0; j2 < this.settings.dungeonChance; ++j2)
{
int i3 = this.rand.nextInt(16) + 8;
int l3 = this.rand.nextInt(256);
int l1 = this.rand.nextInt(16) + 8;
(new WorldGenDungeons()).generate(this.world, this.rand, blockpos.add(i3, l3, l1));
}
}*/
biome.decorate(this.world, this.rand, new BlockPos(i, 0, j));
if (net.minecraftforge.event.terraingen.TerrainGen.populate(this, this.world, this.rand, x, z, flag, net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType.ANIMALS))
WorldEntitySpawner.performWorldGenSpawning(this.world, biome, i + 8, j + 8, 16, 16, this.rand);
blockpos = blockpos.add(8, 0, 8);
if (net.minecraftforge.event.terraingen.TerrainGen.populate(this, this.world, this.rand, x, z, flag, net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType.ICE))
{
for (int k2 = 0; k2 < 16; ++k2)
{
for (int j3 = 0; j3 < 16; ++j3)
{
BlockPos blockpos1 = this.world.getPrecipitationHeight(blockpos.add(k2, 0, j3));
BlockPos blockpos2 = blockpos1.down();
if (this.world.canBlockFreezeWater(blockpos2))
{
this.world.setBlockState(blockpos2, Blocks.ICE.getDefaultState(), 2);
}
if (this.world.canSnowAt(blockpos1, true))
{
this.world.setBlockState(blockpos1, Blocks.SNOW_LAYER.getDefaultState(), 2);
}
}
}
}//Forge: End ICE
net.minecraftforge.event.ForgeEventFactory.onChunkPopulate(false, this, this.world, this.rand, x, z, flag);
BlockFalling.fallInstantly = false;
}
public boolean generateStructures(Chunk chunkIn, int x, int z)
{
boolean flag = false;
return flag;
}
public List<Biome.SpawnListEntry> getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos)
{
Biome biome = this.world.getBiome(pos);
return biome.getSpawnableList(creatureType);
}
@Nullable
public BlockPos getStrongholdGen(World worldIn, String structureName, BlockPos position, boolean p_180513_4_)
{
return null;
}
public void recreateStructures(Chunk chunkIn, int x, int z)
{
}
} | mit |
woshiwpa/CoreMathImgProc | src/com/cyzapps/uptloadersprint/UPTJavaLoader91.java | 246 | package com.cyzapps.uptloadersprint;
import com.cyzapps.mathrecog.UnitPrototypeMgr;
import com.cyzapps.mathrecog.UnitPrototypeMgr.UnitProtoType;
public class UPTJavaLoader91 {
public static void load(UnitPrototypeMgr uptMgr) {
}
}
| mit |
dextto/AlgorithmStudy | src/main/java/leetcode/No300_LIS_LongestIncreasingSubsequence.java | 1158 | // https://leetcode.com/problems/longest-increasing-subsequence
package leetcode;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class No300_LIS_LongestIncreasingSubsequence {
@Test
public void test() throws Exception {
No300_LIS_LongestIncreasingSubsequence instance = new No300_LIS_LongestIncreasingSubsequence();
assertEquals(4, instance.lengthOfLIS(new int[] { 10, 9, 2, 5, 3, 7, 101, 18 }));
}
public int lengthOfLIS(int[] nums) {
int n = nums.length;
if (n == 0) return 0;
int[] lis = new int[n];
int ret = 1;
for (int i = 0; i < n; i++) {
ret = Math.max(ret, lengthOfLIS(lis, nums, i));
}
return ret;
}
private int lengthOfLIS(int[] lis, int[] nums, int start) {
if (lis[start] != 0) return lis[start];
int ret = 1;
lis[start] = 1;
for (int i = start + 1; i < lis.length; i++) {
if (nums[start] < nums[i]) {
ret = Math.max(ret, lengthOfLIS(lis, nums, i) + 1);
lis[start] = ret;
}
}
return ret;
}
}
| mit |
QVDev/BlendleSDK | Android/SDK/app/src/main/java/com/qvdev/apps/readerkid/utils/BaseBlendleCompatActivity.java | 4190 | package com.qvdev.apps.readerkid.utils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.qvdev.apps.readerkid.R;
import com.qvdev.apps.readerkid.facebook.FacebookSSOHelper;
import com.sdk.SupportedCountries;
import com.sdk.blendle.models.generated.facebook.FacebookMe;
import com.sdk.blendle.models.generated.login.Login;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
public class BaseBlendleCompatActivity extends AppCompatActivity {
protected BlendleCredentialsApi mBlendleApi;
protected BlendleSharedPreferences mBlendleSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initBlendleApi();
initBlendleSharedPrefs();
initTracking();
}
private void initTracking() {
FirebaseAnalytics firebaseAnalytics;
firebaseAnalytics = FirebaseAnalytics.getInstance(this);
firebaseAnalytics.setCurrentScreen(this, getClass().getSimpleName(), getClass().getName());
}
private void initBlendleApi() {
mBlendleApi = new BlendleCredentialsApi(this);
}
private void initBlendleSharedPrefs() {
mBlendleSharedPreferences = new BlendleSharedPreferences(this);
}
protected void showSnackbarWithAction(int viewId, int stringId, int actionStringId, View.OnClickListener actionListener) {
Snackbar.make(findViewById(viewId), getString(stringId), Snackbar.LENGTH_LONG)
.setAction(getString(actionStringId), actionListener).show();
}
protected void showSnackbar(int viewId, int stringId) {
Snackbar.make(findViewById(viewId), getString(stringId), Snackbar.LENGTH_LONG).show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FacebookSSOHelper.ACTIVITY_START_CODE) {
if (resultCode == Activity.RESULT_OK) {
//TODO move this to the Helper class?
FacebookSSOHelper facebookSSOHelper = new FacebookSSOHelper();
final String token = facebookSSOHelper.onActivityResult(requestCode, resultCode, data);
if (token != null) {
mBlendleApi.getFacebookUser(new Callback<FacebookMe>() {
@Override
public void onResponse(Response<FacebookMe> response, Retrofit retrofit) {
FacebookMe facebookResponse = response.body();
mBlendleApi.loginUserWithFacebook(new Callback<Login>() {
@Override
public void onResponse(Response<Login> response, Retrofit retrofit) {
Login loggedInUser = response.body();
mBlendleApi.onUserLoggedIn(loggedInUser);
mBlendleSharedPreferences.storeLoggedInUser(loggedInUser);
showSnackbar(R.id.blendle_content, R.string.login_facebook_succes);
}
@Override
public void onFailure(Throwable t) {
showSnackbar(R.id.blendle_content, R.string.login_facebook_failure);
}
}, facebookResponse.getId(), token);
}
@Override
public void onFailure(Throwable t) {
showSnackbar(R.id.blendle_content, R.string.login_facebook_failure);
}
}, token);
} else {
showSnackbar(R.id.blendle_content, R.string.login_facebook_failure);
}
} else {
showSnackbar(R.id.blendle_content, R.string.login_facebook_failure);
}
}
}
}
| mit |
KoMyoThant/AndroidTutorial | LoginMaterialSample/app/src/main/java/com/mt/loginmaterialsample/MainActivity.java | 373 | package com.mt.loginmaterialsample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import mt.loginmaterialsample.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| mit |
jimmyblylee/EZ.JWAF-Rule | src/rule/src/test/java/com/lee/jwaf/rule/cases/ComponentBadController.java | 626 | /**
* Project Name : jwaf-rule <br>
* File Name : ComponentBadController.java <br>
* Package Name : com.lee.jwaf.rule.cases <br>
* Create Time : 2016-09-19 <br>
* Create by : jimmyblylee@126.com <br>
* Copyright © 2006, 2016, Jimmybly Lee. All rights reserved.
*/
package com.lee.jwaf.rule.cases;
import org.springframework.stereotype.Component;
/**
* ClassName : ComponentBadController <br>
* Description : bean named end with "Controller" should not annotated with {@link Component} <br>
* Create Time : 2016-09-19 <br>
* Create by : jimmyblylee@126.com
*/
@Component
public class ComponentBadController {
}
| mit |
jgrillo/wordcount-service | src/main/java/com/jgrillo/wordcount/api/CountsDeserializer.java | 2247 | package com.jgrillo.wordcount.api;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
public final class CountsDeserializer extends StdDeserializer<Counts> {
public CountsDeserializer() {
this(Counts.class);
}
private CountsDeserializer(Class<Counts> t) {
super(t);
}
@Override
public Counts deserialize(
JsonParser jsonParser, DeserializationContext deserializationContext
) throws IOException {
final ImmutableMap.Builder<String, Long> mapBuilder = ImmutableMap.builder();
JsonToken token;
boolean started = false;
boolean stopped = false;
while ((token = jsonParser.nextToken()) != null) {
if (stopped) {
break;
}
switch (token) {
case START_OBJECT:
break;
case FIELD_NAME:
if (started) {
break;
}
final String name = jsonParser.getCurrentName();
if (name.equals(Counts.COUNTS_PROP)) {
started = true;
break;
} else {
throw new CountsProcessingException(
String.format("Encountered unknown field: \"%s\"", name),
jsonParser.getCurrentLocation()
);
}
case VALUE_NUMBER_INT:
if (started) {
mapBuilder.put(jsonParser.getCurrentName(), jsonParser.getLongValue());
}
break;
case END_OBJECT:
stopped = true;
break;
default:
throw new CountsProcessingException("Encountered unknown state", jsonParser.getCurrentLocation());
}
}
return new Counts(mapBuilder.build());
}
}
| mit |
stevesoltys/telegram-irc | src/main/java/com/stevesoltys/telegramirc/protocol/irc/IRCProtocol.java | 3655 | package com.stevesoltys.telegramirc.protocol.irc;
import com.stevesoltys.telegramirc.configuration.irc.IRCConfiguration;
import com.stevesoltys.telegramirc.protocol.telegram.channel.TelegramChannel;
import com.stevesoltys.telegramirc.protocol.telegram.channel.TelegramChannelRepository;
import org.pircbotx.Configuration;
import org.pircbotx.PircBotX;
import org.pircbotx.exception.IrcException;
import org.pircbotx.hooks.managers.ThreadedListenerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Steve Soltys
*/
@Service
public class IRCProtocol {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final IRCConfiguration serverConfiguration;
private final OperatorBot operatorBotListener;
private final UserBot userBotListener;
private final TelegramChannelRepository telegramChannelRepository;
private final ExecutorService executorService;
private PircBotX operatorBot;
@Autowired
public IRCProtocol(IRCConfiguration serverConfiguration, OperatorBot operatorBotListener,
UserBot userBotListener, TelegramChannelRepository telegramChannelRepository) {
this.serverConfiguration = serverConfiguration;
this.operatorBotListener = operatorBotListener;
this.userBotListener = userBotListener;
this.telegramChannelRepository = telegramChannelRepository;
executorService = Executors.newCachedThreadPool();
}
public void start() {
operatorBot = createBot(serverConfiguration.getOperatorNick(), true);
}
public PircBotX createBot(String username) {
return createBot(username, false);
}
private PircBotX createBot(String username, boolean operator) {
Configuration.Builder configurationBuilder = new Configuration.Builder()
.setName(username)
.setLogin(username)
.setRealName(username)
.setListenerManager(new ThreadedListenerManager(Executors.newSingleThreadExecutor()))
.addListener(operator ? operatorBotListener : userBotListener)
.setAutoNickChange(true)
.setAutoReconnect(true)
.addServer(serverConfiguration.getAddress(), serverConfiguration.getPort())
.setServerPassword(serverConfiguration.getPassword());
if (serverConfiguration.isSsl()) {
configurationBuilder.setSocketFactory(SSLSocketFactory.getDefault());
}
PircBotX bot = new PircBotX(configurationBuilder.buildConfiguration());
executorService.submit(() -> {
try {
bot.startBot();
} catch (IOException | IrcException e) {
logger.error("Error while starting IRC bot: {}", e.toString());
}
});
return bot;
}
public void registerChannel(String telegramChannelIdentifier, String ircChannelIdentifier) {
Optional<TelegramChannel> targetOptional = telegramChannelRepository.
findByTelegramIdentifier(telegramChannelIdentifier);
if (!targetOptional.isPresent()) {
telegramChannelRepository.register(new TelegramChannel(ircChannelIdentifier, telegramChannelIdentifier));
operatorBot.sendIRC().joinChannel(ircChannelIdentifier);
}
}
}
| mit |
SpongeHistory/SpongeAPI-History | src/main/java/org/spongepowered/api/util/event/callback/AbstractEventCallback.java | 1681 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.util.event.callback;
/**
* An abstract implement of {@link EventCallback}.
*/
public abstract class AbstractEventCallback implements EventCallback {
@Override
public boolean isBaseGame() {
return false;
}
/**
* Checks if this is a flowerpot.
*
* @return Whether this is a flowerpot
*/
public boolean isFlowerPot() {
return false;
}
}
| mit |
ccnovoa11/iteracion2 | java-server-master/java-server-master/src/vos/ReservaMsg.java | 1295 | package vos;
import org.codehaus.jackson.annotate.JsonProperty;
public class ReservaMsg {
@JsonProperty(value="id")
private String id;
@JsonProperty(value="idUsuario")
private int idUsuario;
@JsonProperty(value="silla")
private String silla;
@JsonProperty(value="peso")
private Double peso;
@JsonProperty(value="idVuelo")
private String idVuelo;
public ReservaMsg(@JsonProperty(value="id")String id, @JsonProperty(value="idUsuario")int idUsuario,@JsonProperty(value="silla")String silla,
@JsonProperty(value="peso") Double peso,@JsonProperty(value="idVuelo")String idVuelo){
super();
this.id = id;
this.idUsuario=idUsuario;
this.silla=silla;
this.peso=peso;
this.idVuelo=idVuelo;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(int idUsuario) {
this.idUsuario = idUsuario;
}
public String getSilla() {
return silla;
}
public void setSilla(String silla) {
this.silla = silla;
}
public Double getPeso() {
return peso;
}
public void setPeso(Double peso) {
this.peso = peso;
}
public String getIdVuelo() {
return idVuelo;
}
public void setIdVuelo(String idVuelo) {
this.idVuelo = idVuelo;
}
}
| mit |
badoualy/kotlogram | tl/src/main/java/com/github/badoualy/telegram/tl/api/request/TLRequestMessagesGetMessageEditData.java | 3262 | package com.github.badoualy.telegram.tl.api.request;
import com.github.badoualy.telegram.tl.TLContext;
import com.github.badoualy.telegram.tl.api.TLAbsInputPeer;
import com.github.badoualy.telegram.tl.api.messages.TLMessageEditData;
import com.github.badoualy.telegram.tl.core.TLMethod;
import com.github.badoualy.telegram.tl.core.TLObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static com.github.badoualy.telegram.tl.StreamUtils.readInt;
import static com.github.badoualy.telegram.tl.StreamUtils.readTLObject;
import static com.github.badoualy.telegram.tl.StreamUtils.writeInt;
import static com.github.badoualy.telegram.tl.StreamUtils.writeTLObject;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32;
/**
* @author Yannick Badoual yann.badoual@gmail.com
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
public class TLRequestMessagesGetMessageEditData extends TLMethod<TLMessageEditData> {
public static final int CONSTRUCTOR_ID = 0xfda68d36;
protected TLAbsInputPeer peer;
protected int id;
private final String _constructor = "messages.getMessageEditData#fda68d36";
public TLRequestMessagesGetMessageEditData() {
}
public TLRequestMessagesGetMessageEditData(TLAbsInputPeer peer, int id) {
this.peer = peer;
this.id = id;
}
@Override
@SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
public TLMessageEditData deserializeResponse(InputStream stream, TLContext context) throws IOException {
final TLObject response = readTLObject(stream, context);
if (response == null) {
throw new IOException("Unable to parse response");
}
if (!(response instanceof TLMessageEditData)) {
throw new IOException(
"Incorrect response type, expected " + getClass().getCanonicalName() + ", found " + response
.getClass().getCanonicalName());
}
return (TLMessageEditData) response;
}
@Override
public void serializeBody(OutputStream stream) throws IOException {
writeTLObject(peer, stream);
writeInt(id, stream);
}
@Override
@SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
public void deserializeBody(InputStream stream, TLContext context) throws IOException {
peer = readTLObject(stream, context, TLAbsInputPeer.class, -1);
id = readInt(stream);
}
@Override
public int computeSerializedSize() {
int size = SIZE_CONSTRUCTOR_ID;
size += peer.computeSerializedSize();
size += SIZE_INT32;
return size;
}
@Override
public String toString() {
return _constructor;
}
@Override
public int getConstructorId() {
return CONSTRUCTOR_ID;
}
public TLAbsInputPeer getPeer() {
return peer;
}
public void setPeer(TLAbsInputPeer peer) {
this.peer = peer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| mit |
AluminatiFRC/Programming-Challenges | src/ArraySum.java | 917 |
public class ArraySum {
/**
* Run tests on the method we wrote.
*/
public void test(){
//It's a good idea to add more tests.
//Feel free to change the way the tests are performed.
System.out.println("Testing ArraySum");
int result;
result = sumArray(new int[] {1,2});
System.out.println("Expecting 3 got: " + result);
result = sumArray(new int[] {1,2,3,4,5,6,7,8,9});
System.out.println("Expecting 45 got: " + result);
result = sumArray(new int[] {4,4,-9});
System.out.println("Expecting -1 got: " + result);
result = sumArray(new int[] {});
System.out.println("Expecting 0 got: " + result);
}
//Complete the following method
//I've given them a value to return by default, it will need to change.
/**
* Computes the sum of all values in the array. Empty arrays sum to 0.
*/
public int sumArray(int[] array){
return 0;
}
}
| mit |
CyberdyneCC/SimplyJetpacks-2 | src/main/java/tonius/simplyjetpacks/item/rewrite/ItemJetpack.java | 18970 | package tonius.simplyjetpacks.item.rewrite;
import tonius.simplyjetpacks.SimplyJetpacks;
import tonius.simplyjetpacks.client.model.PackModelType;
import tonius.simplyjetpacks.client.util.RenderUtils;
import tonius.simplyjetpacks.config.Config;
import tonius.simplyjetpacks.handler.SyncHandler;
import tonius.simplyjetpacks.item.IHUDInfoProvider;
import tonius.simplyjetpacks.setup.*;
import tonius.simplyjetpacks.util.NBTHelper;
import tonius.simplyjetpacks.util.SJStringHelper;
import tonius.simplyjetpacks.util.StackUtil;
import tonius.simplyjetpacks.util.StringHelper;
import cofh.api.energy.IEnergyContainerItem;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.common.ISpecialArmor;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
import static tonius.simplyjetpacks.handler.LivingTickHandler.floatingTickCount;
public class ItemJetpack extends ItemArmor implements ISpecialArmor, IEnergyContainerItem, IHUDInfoProvider {
public static final String TAG_ENERGY = "Energy";
public static final String TAG_ON = "PackOn";
public static final String TAG_HOVERMODE_ON = "JetpackHoverModeOn";
public static final String TAG_EHOVER_ON = "JetpackEHoverOn";
public String name;
public boolean showTier = true;
public boolean hasFuelIndicator = true;
public boolean hasStateIndicators = true;
public FuelType fuelType = FuelType.ENERGY;
public boolean isFluxBased = false;
private final int numItems;
public ItemJetpack(String name) {
super(ArmorMaterial.IRON, 2, EntityEquipmentSlot.CHEST);
this.name = name;
this.setUnlocalizedName(SimplyJetpacks.PREFIX + name);
this.setHasSubtypes(true);
this.setMaxDamage(0);
this.setCreativeTab(ModCreativeTab.instance);
this.setRegistryName(name);
numItems = Jetpack.values().length;
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs creativeTabs, List<ItemStack> List) {
if (ModItems.integrateEIO) {
for (Jetpack pack : Jetpack.PACKS_EIO) {
ItemStack stack;
if (pack.usesFuel) {
List.add(new ItemStack(item, 1, pack.ordinal()));
} else {
stack = new ItemStack(item, 1, pack.ordinal());
if (item instanceof ItemJetpack) {
((ItemJetpack) item).addFuel(stack, ((ItemJetpack) item).getMaxEnergyStored(stack), false);
}
List.add(stack);
}
}
}
if (ModItems.integrateVanilla) {
for (Jetpack pack : Jetpack.PACKS_VANILLA) {
ItemStack stack;
stack = new ItemStack(item, 1, pack.ordinal());
List.add(stack);
}
}
for (Jetpack pack : Jetpack.PACKS_SJ) {
ItemStack stack;
if (pack.usesFuel) {
List.add(new ItemStack(item, 1, pack.ordinal()));
} else {
stack = new ItemStack(item, 1, pack.ordinal());
if (item instanceof ItemJetpack) {
((ItemJetpack) item).addFuel(stack, ((ItemJetpack) item).getMaxEnergyStored(stack), false);
}
List.add(stack);
}
}
}
@Override
public void onUpdate(ItemStack stack, World world, Entity entity, int par4, boolean par5) {
}
@Override
public void onArmorTick(World world, EntityPlayer player, ItemStack stack) {
flyUser(player, stack, this, false);
}
public void toggleState(boolean on, ItemStack stack, String type, String tag, EntityPlayer player, boolean showInChat) {
NBTHelper.setBoolean(stack, tag, !on);
if (player != null && showInChat) {
String color = on ? TextFormatting.RED.toString() : TextFormatting.GREEN.toString();
type = type != null && !type.equals("") ? "chat." + this.name + "." + type + ".on" : "chat." + this.name + ".on";
String msg = SJStringHelper.localize(type) + " " + color + SJStringHelper.localize("chat." + (on ? "disabled" : "enabled"));
player.addChatMessage(new TextComponentString(msg));
}
}
public void setParticleType(ItemStack stack, ParticleType particle) {
NBTHelper.setInt(stack, Jetpack.TAG_PARTICLE, particle.ordinal());
}
@Override
public EnumRarity getRarity(ItemStack stack) {
int i = MathHelper.clamp_int(stack.getItemDamage(), 0, numItems - 1);
if (Jetpack.values()[i].getRarity() != null) {
return Jetpack.values()[i].getRarity();
}
return super.getRarity(stack);
}
@Override
public boolean showDurabilityBar(ItemStack stack) {
int i = MathHelper.clamp_int(stack.getItemDamage(), 0, numItems - 1);
if (!Jetpack.values()[i].usesFuel) {
return false;
}
return this.hasFuelIndicator;
}
@Override
public double getDurabilityForDisplay(ItemStack stack) {
double stored = this.getMaxFuelStored(stack) - this.getFuelStored(stack) + 1;
double max = this.getMaxFuelStored(stack) + 1;
return stored / max;
}
@Override
public String getUnlocalizedName(ItemStack itemStack) {
int i = MathHelper.clamp_int(itemStack.getItemDamage(), 0, numItems - 1);
return Jetpack.values()[i].unlocalisedName;
}
@Override
public void addInformation(ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced) {
information(stack, this, tooltip);
if (SJStringHelper.canShowDetails()) {
shiftInformation(stack, tooltip);
} else {
tooltip.add(SJStringHelper.getShiftText());
}
}
@SideOnly(Side.CLIENT)
@SuppressWarnings("unchecked")
public void information(ItemStack stack, ItemJetpack item, List list) {
int i = MathHelper.clamp_int(stack.getItemDamage(), 0, numItems - 1);
if (this.showTier) {
list.add(SJStringHelper.getTierText(Jetpack.values()[i].getTier()));
}
list.add(SJStringHelper.getFuelText(this.fuelType, item.getFuelStored(stack), Jetpack.values()[i].getFuelCapacity(), !Jetpack.values()[i].usesFuel));
}
@SideOnly(Side.CLIENT)
@SuppressWarnings("unchecked")
public void shiftInformation(ItemStack stack, List list) {
int i = MathHelper.clamp_int(stack.getItemDamage(), 0, numItems - 1);
list.add(SJStringHelper.getStateText(this.isOn(stack)));
list.add(SJStringHelper.getHoverModeText(this.isHoverModeOn(stack)));
if (Jetpack.values()[i].getFuelUsage() > 0) {
list.add(SJStringHelper.getFuelUsageText(this.fuelType, Jetpack.values()[i].getFuelUsage()));
}
list.add(SJStringHelper.getParticlesText(Jetpack.values()[i].getParticleType(stack)));
SJStringHelper.addDescriptionLines(list, "jetpack", TextFormatting.GREEN.toString());
}
public boolean isOn(ItemStack stack) {
return NBTHelper.getBooleanFallback(stack, TAG_ON, true);
}
// fuel
public int getFuelStored(ItemStack stack) {
return this.getEnergyStored(stack);
}
public int getMaxFuelStored(ItemStack stack) {
return this.getMaxEnergyStored(stack);
}
protected int getFuelUsage(ItemStack stack) {
int i = MathHelper.clamp_int(stack.getItemDamage(), 0, numItems - 1);
//if(ModEnchantments.fuelEffeciency == null) {
return Jetpack.values()[i].getFuelUsage();
//}
//int fuelEfficiencyLevel = tonius.simplyjetpacks.util.math.MathHelper.clampI(EnchantmentHelper.getEnchantmentLevel(ModEnchantments.fuelEffeciency, stack), 0, 4);
//return (int) Math.round(this.fuelUsage * (20 - fuelEfficiencyLevel) / 20.0D);
}
public int addFuel(ItemStack stack, int maxAdd, boolean simulate) {
int energy = this.getEnergyStored(stack);
int energyReceived = Math.min(this.getMaxEnergyStored(stack) - energy, maxAdd);
if (!simulate) {
energy += energyReceived;
NBTHelper.setInt(stack, TAG_ENERGY, energy);
}
return energyReceived;
}
public int useFuel(ItemStack stack, int maxUse, boolean simulate) {
int energy = this.getEnergyStored(stack);
int energyExtracted = Math.min(energy, maxUse);
if (!simulate) {
energy -= energyExtracted;
NBTHelper.setInt(stack, TAG_ENERGY, energy);
}
return energyExtracted;
}
@Override
public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) {
int i = MathHelper.clamp_int(container.getItemDamage(), 0, numItems - 1);
int energy = this.getEnergyStored(container);
int energyReceived = Math.min(this.getMaxEnergyStored(container) - energy, Math.min(maxReceive, Jetpack.values()[i].getFuelPerTickIn()));
if (!simulate) {
energy += energyReceived;
NBTHelper.setInt(container, TAG_ENERGY, energy);
}
return energyReceived;
}
@Override
public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) {
int i = MathHelper.clamp_int(container.getItemDamage(), 0, numItems - 1);
int energy = this.getEnergyStored(container);
int energyExtracted = Math.min(energy, Math.min(maxExtract, Jetpack.values()[i].getFuelPerTickOut()));
if (!simulate) {
energy -= energyExtracted;
NBTHelper.setInt(container, TAG_ENERGY, energy);
}
return energyExtracted;
}
@Override
public int getEnergyStored(ItemStack container) {
return NBTHelper.getInt(container, TAG_ENERGY);
}
@Override
public int getMaxEnergyStored(ItemStack container) {
int i = MathHelper.clamp_int(container.getItemDamage(), 0, numItems - 1);
return Jetpack.values()[i].getFuelCapacity();
}
// HUD info
@Override
@SideOnly(Side.CLIENT)
public void addHUDInfo(List<String> list, ItemStack stack, boolean showFuel, boolean showState) {
if (showFuel && this.hasFuelIndicator) {
list.add(this.getHUDFuelInfo(stack, this));
}
if (showState && this.hasStateIndicators) {
list.add(this.getHUDStatesInfo(stack));
}
}
@SideOnly(Side.CLIENT)
public String getHUDFuelInfo(ItemStack stack, ItemJetpack item) {
int fuel = item.getFuelStored(stack);
int maxFuel = item.getMaxFuelStored(stack);
int percent = (int) Math.ceil((double) fuel / (double) maxFuel * 100D);
return SJStringHelper.getHUDFuelText(this.name, percent, this.fuelType, fuel);
}
public boolean isHoverModeOn(ItemStack stack) {
return NBTHelper.getBoolean(stack, TAG_HOVERMODE_ON);
}
public boolean isEHoverModeOn(ItemStack stack) {
return NBTHelper.getBooleanFallback(stack, TAG_EHOVER_ON, true);
}
public void doEHover(ItemStack armor, EntityLivingBase user) {
NBTHelper.setBoolean(armor, TAG_ON, true);
NBTHelper.setBoolean(armor, TAG_HOVERMODE_ON, true);
if (user instanceof EntityPlayer) {
((EntityPlayer) user).addChatMessage(new TextComponentString(StringHelper.LIGHT_RED + SJStringHelper.localize("chat.jetpack.emergencyHoverMode.msg")));
}
}
@SideOnly(Side.CLIENT)
public String getHUDStatesInfo(ItemStack stack) {
Boolean engine = this.isOn(stack);
Boolean hover = this.isHoverModeOn(stack);
return SJStringHelper.getHUDStateText(engine, hover, null);
}
@Override
public ArmorProperties getProperties(EntityLivingBase player, ItemStack armor, DamageSource source, double damage, int slot) {
int i = MathHelper.clamp_int(armor.getItemDamage(), 0, numItems - 1);
if (Jetpack.values()[i].getIsArmored() && !source.isUnblockable()) {
if (this.isFluxBased && source.damageType.equals("flux")) {
return new ArmorProperties(0, 0.5D, Integer.MAX_VALUE);
}
int energyPerDamage = this.getFuelPerDamage(armor);
int maxAbsorbed = energyPerDamage > 0 ? 25 * (this.getFuelStored(armor) / energyPerDamage) : 0;
return new ArmorProperties(0, 0.85D * (Jetpack.values()[i].getArmorReduction() / 20.0D), maxAbsorbed);
}
return new ArmorProperties(0, 1, 0);
}
@Override
public int getArmorDisplay(EntityPlayer player, ItemStack armor, int slot) {
int i = MathHelper.clamp_int(armor.getItemDamage(), 0, numItems - 1);
if (Jetpack.values()[i].getIsArmored()) {
if (this.getFuelStored(armor) >= Jetpack.values()[i].getArmorFuelPerHit()) {
return Jetpack.values()[i].getArmorReduction();
}
}
return 0;
}
@Override
public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, EntityEquipmentSlot armorSlot, ModelBiped _default) {
int i = MathHelper.clamp_int(itemStack.getItemDamage(), 0, numItems - 1);
if (Config.enableArmor3DModels) {
ModelBiped model = RenderUtils.getArmorModel(Jetpack.values()[i], entityLiving);
if (model != null) {
return model;
}
}
return super.getArmorModel(entityLiving, itemStack, armorSlot, _default);
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, EntityEquipmentSlot slot, String type) {
int i = MathHelper.clamp_int(stack.getItemDamage(), 0, numItems - 1);
String flat = Config.enableArmor3DModels || Jetpack.values()[i].armorModel == PackModelType.FLAT ? "" : ".flat";
return SimplyJetpacks.RESOURCE_PREFIX + "textures/armor/" + Jetpack.values()[i].getBaseName() + flat + ".png";
}
@Override
public void damageArmor(EntityLivingBase entity, ItemStack armor, DamageSource source, int damage, int slot) {
int i = MathHelper.clamp_int(armor.getItemDamage(), 0, numItems - 1);
if (Jetpack.values()[i].getIsArmored() && Jetpack.values()[i].usesFuel) {
if (this.fuelType == FuelType.ENERGY && this.isFluxBased && source.damageType.equals("flux")) {
this.addFuel(armor, damage * (source.getEntity() == null ? Jetpack.values()[i].getArmorFuelPerHit() / 2 : this.getFuelPerDamage(armor)), false);
} else {
this.useFuel(armor, damage * this.getFuelPerDamage(armor), false);
}
}
}
// armor
protected int getFuelPerDamage(ItemStack stack) {
int i = MathHelper.clamp_int(stack.getItemDamage(), 0, numItems - 1);
if (ModEnchantments.fuelEffeciency == null) {
return Jetpack.values()[i].getArmorFuelPerHit();
}
int fuelEfficiencyLevel = MathHelper.clamp_int(EnchantmentHelper.getEnchantmentLevel(ModEnchantments.fuelEffeciency, stack), 0, 4);
return (int) Math.round(Jetpack.values()[i].getArmorFuelPerHit() * (5 - fuelEfficiencyLevel) / 5.0D);
}
public void flyUser(EntityPlayer user, ItemStack stack, ItemJetpack item, boolean force) {
int i = MathHelper.clamp_int(stack.getItemDamage(), 0, numItems - 1);
Item chestItem = StackUtil.getItem(stack);
ItemJetpack jetpack = (ItemJetpack) chestItem;
if (jetpack.isOn(stack)) {
boolean hoverMode = jetpack.isHoverModeOn(stack);
double hoverSpeed = Config.invertHoverSneakingBehavior == SyncHandler.isDescendKeyDown(user) ? Jetpack.values()[i].speedVerticalHoverSlow : Jetpack.values()[i].speedVerticalHover;
boolean flyKeyDown = force || SyncHandler.isFlyKeyDown(user);
boolean descendKeyDown = SyncHandler.isDescendKeyDown(user);
double currentAccel = Jetpack.values()[i].accelVertical * (user.motionY < 0.3D ? 2.5D : 1.0D);
double currentSpeedVertical = Jetpack.values()[i].speedVertical * (user.isInWater() ? 0.4D : 1.0D);
if (flyKeyDown || hoverMode && !user.onGround) {
if (Jetpack.values()[i].usesFuel) {
item.useFuel(stack, (int) (user.isSprinting() ? Math.round(this.getFuelUsage(stack) * Jetpack.values()[i].sprintFuelModifier) : this.getFuelUsage(stack)), false);
}
if (item.getFuelStored(stack) > 0) {
if (flyKeyDown) {
if (!hoverMode) {
user.motionY = Math.min(user.motionY + currentAccel, currentSpeedVertical);
} else {
if (descendKeyDown) {
user.motionY = Math.min(user.motionY + currentAccel, -Jetpack.values()[i].speedVerticalHoverSlow);
} else {
user.motionY = Math.min(user.motionY + currentAccel, Jetpack.values()[i].speedVerticalHover);
}
}
} else {
user.motionY = Math.min(user.motionY + currentAccel, -hoverSpeed);
}
float speedSideways = (float) (user.isSneaking() ? Jetpack.values()[i].speedSideways * 0.5F : Jetpack.values()[i].speedSideways);
float speedForward = (float) (user.isSprinting() ? speedSideways * Jetpack.values()[i].sprintSpeedModifier : speedSideways);
if (SyncHandler.isForwardKeyDown(user)) {
user.moveRelative(0, speedForward, speedForward);
}
if (SyncHandler.isBackwardKeyDown(user)) {
user.moveRelative(0, -speedSideways, speedSideways * 0.8F);
}
if (SyncHandler.isLeftKeyDown(user)) {
user.moveRelative(speedSideways, 0, speedSideways);
}
if (SyncHandler.isRightKeyDown(user)) {
user.moveRelative(-speedSideways, 0, speedSideways);
}
if (!user.worldObj.isRemote) {
user.fallDistance = 0.0F;
if (user instanceof EntityPlayerMP) {
try {
floatingTickCount.setInt(((EntityPlayerMP) user).connection, 0);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/*
TODO: Reimplement explosions
if (Config.flammableFluidsExplode) {
if (!(user instanceof EntityPlayer) || !((EntityPlayer) user).capabilities.isCreativeMode) {
int x = Math.round((float) user.posX - 0.5F);
int y = Math.round((float) user.posY);
int z = Math.round((float) user.posZ - 0.5F);
Block fluidBlock = user.worldObj.getBlock(x, y, z);
if (fluidBlock instanceof IFluidBlock && fluidBlock.isFlammable(user.worldObj, x, y, z, ForgeDirection.UNKNOWN)) {
user.worldObj.playSoundAtEntity(user, "mob.ghast.fireball", 2.0F, 1.0F);
user.worldObj.createExplosion(user, user.posX, user.posY, user.posZ, 3.5F, false);
user.attackEntityFrom(new EntityDamageSource("jetpackexplode", user), 100.0F);
}
}
}*/
}
}
}
}
//Emergency Hover
if (!user.worldObj.isRemote && Jetpack.values()[i].emergencyHoverMode && this.isEHoverModeOn(stack)) {
if (item.getEnergyStored(stack) > 0 && (!this.isHoverModeOn(stack) || !this.isOn(stack))) {
if (user.posY < -5) {
this.doEHover(stack, user);
} else {
if (!user.capabilities.isCreativeMode && user.fallDistance - 1.2F >= user.getHealth()) {
for (int j = 0; j <= 16; j++) {
int x = Math.round((float) user.posX - 0.5F);
int y = Math.round((float) user.posY) - j;
int z = Math.round((float) user.posZ - 0.5F);
if (!user.worldObj.isAirBlock(new BlockPos(x, y, z))) {
this.doEHover(stack, user);
break;
}
}
}
}
}
}
}
public void registerItemModel() {
for (int i = 0; i < numItems; i++) {
SimplyJetpacks.proxy.registerItemRenderer(this, i, Jetpack.getTypeFromMeta(i).getBaseName());
}
}
}
| mit |
MrLoNee/C3 | 01_src/org/capcaval/ccoutils/data/_test/DataTest.java | 875 | package org.capcaval.ccoutils.data._test;
import org.capcaval.ccoutils.converter.ConverterAbstract;
import org.capcaval.ccoutils.data.Data;
import org.capcaval.ccoutils.data.DataEvent;
import org.capcaval.ccoutils.data.DataReadOnly;
import org.capcaval.ccoutils.data._impl.DataImpl;
public class DataTest {
/**
* @param args
*/
public static void main(String[] args) {
Data<Integer> d = new DataImpl<Integer>();
DataReadOnly<Integer> dro = d;
d.subscribeToData(new DataEvent<Integer>() {
@Override
public void notifyDataUpdated(Integer data) {
System.out.println(data);
}
});
d.setValue(5);
d.addDataConverter(new ConverterAbstract<String, Integer>(){
@Override
public Integer convert(String inobj) {
return Integer.getInteger(inobj);
}
});
d.feed("12");
d.feed(20.0);
}
}
| mit |
chrrasmussen/NTNU-Master-Project | no.ntnu.assignmentsystem.editor/src/no/ntnu/assignmentsystem/editor/akka/messages/PluginCodeCompletion.java | 461 | package no.ntnu.assignmentsystem.editor.akka.messages;
import java.io.Serializable;
public class PluginCodeCompletion implements Serializable {
private static final long serialVersionUID = 1L;
public final String packageName;
public final String fileName;
public final int offset;
public PluginCodeCompletion(String packageName, String fileName, int offset) {
this.packageName = packageName;
this.fileName = fileName;
this.offset = offset;
}
}
| mit |
pnhepw/java-lessons-kirylka | homework/lesson_9/src/com/maksim/Main.java | 3217 | package com.maksim;
import java.util.*;
/* homework lesson9 */
public class Main {
public static void main(String[] args) {
/* task #1 */
try {
IO.print("Enter size of the list...");
int size = IO.getIntValue();
List<String> list = new ArrayList<>();
// Loop filling of list
for (int i = 0; i < size; i++) {
IO.print("Enter " + i + " element of the list...");
String value = IO.getStringValue();
/* If command "stop" -> break */
if (value.equals("stop")) {
break;
}
list.add(value);
}
IO.print("", true);
//Loop
for (int i = 0; i < list.size(); i++) {
String value = list.get(i);
// Remove 'a'
value = value.replace("a", "");
list.set(i, value);
IO.print("" + list.get(i) + " | ", false);
}
/* task #2 */
/* Create new tree set */
TreeSet<String> ts = new TreeSet<String>(list);
Iterator<String> b = ts.iterator();
IO.print("Set without duplicate: ");
while (b.hasNext()) {
String value = b.next();
IO.print(value + " | ", false);
}
IO.print("");
/* task #3 */
/* Create new lists*/
int j = 0, k = 0;
List<People> menList = new LinkedList<>();
List<People> womenList = new LinkedList<>();
while ((j + k) < 5) {
IO.print("Enter people...");
String value = IO.getStringValue().trim();
if (value.equals("stop")) {
break;
}
String[] p = new String[3];
p = value.split(" ");
IO.print("Enter sex...");
int sex = IO.getIntValue();
if (sex == 0) {
menList.add(new People(p[0], (p[1] != null)? p[1]:"", (p[2] != null)? p[2]:"", 0));
j++;
} else {
womenList.add(new People(p[0], (p[1] != null)? p[1]:"", (p[2] != null)? p[2]:"", 1));
k++;
}
}
/* Create HashMap instance */
HashMap<String, List> hm = new HashMap<>();
hm.put("man", menList);
hm.put("woman", womenList);
IO.print("Print sex: 0 - man, 1 - woman");
int sex = IO.getIntValue();
String key = "man";
int s = menList.size();
if (sex == 1) {
key = "woman";
s = womenList.size();
}
List<People> people = hm.get(key);
/* Search max size */
int randomInt = (int)(Math.random()*s);
People pp = people.get(randomInt);
/* Print random human */
IO.print(pp.getFirstname() + " " + pp.getLastname() + " " + pp.getPatronymic());
} catch (Exception e) {
IO.print("Incorrect input...");
}
}
}
| mit |
shootboss/goja | goja-jfinal/src/main/java/com/jfinal/render/NullRender.java | 793 | /**
* Copyright (c) 2011-2015, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jfinal.render;
/**
* NullRender.
*/
public class NullRender extends Render {
/**
* Render nothing
*/
public final void render() {
}
}
| mit |
Mazdallier/Mariculture | src/main/java/joshie/mariculture/api/fishery/interfaces/IFishHelper.java | 2299 | package joshie.mariculture.api.fishery.interfaces;
import java.util.Random;
import joshie.mariculture.api.fishery.fish.FishSpecies;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public interface IFishHelper {
/** Registers a fish, with a default id, You must register your fish in PreInit, as Fish IDs are assigned in Init, So do not do any recipes on them until init, or to be extra safe postinit **/
public FishSpecies registerFish(String modid, Class<? extends FishSpecies> species);
public FishSpecies registerFish(String modid, Class<? extends FishSpecies> species, int default_id);
/**
* @param The input fish stack
* @param The fish type you want to make a pure bred of
* @return Returns a pure bred fish */
public ItemStack makePureFish(FishSpecies fish);
/** Makes a bred fish, using the mutation chance modifier, from an egg, returns a fish **/
public ItemStack makeBredFish(ItemStack egg, Random rand, double modifier);
/** Creates an egg from two fish passed in */
public ItemStack generateEgg(ItemStack fish1, ItemStack fish2);
/** Returns the egg, with 1 attempt at hatching it **/
public ItemStack attemptToHatchEgg(ItemStack egg, Random rand, double mutation, IIncubator tile);
/** Whether this fish can live at the current coordinates or not **/
public boolean canLive(World world, int x, int y, int z, ItemStack fish);
/** Returns whether a fish is pure bred or not **/
public boolean isPure(ItemStack stack);
/** Returns whether a fish is male or nnot **/
public boolean isMale(ItemStack stack);
/** Returns whether a fish is female or not **/
public boolean isFemale(ItemStack stack);
/** Checks whether the item stack is a fish egg **/
public boolean isEgg(ItemStack stack);
/** Returns the species of the fish, from either the item, the string or the id **/
public FishSpecies getSpecies(ItemStack stack);
public FishSpecies getSpecies(String species);
public FishSpecies getSpecies(int id);
/** Retrieves the dna you wish to retrieve **/
public Integer getDNA(String dna, ItemStack stack);
public Integer getLowerDNA(String dna, ItemStack stack);
/** IGNORE **/
public void registerFishies();
}
| mit |
jrbeaumont/workcraft | WorkcraftCore/src/org/workcraft/dom/visual/VisualGroup.java | 8089 | package org.workcraft.dom.visual;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.workcraft.dom.Container;
import org.workcraft.dom.DefaultGroupImpl;
import org.workcraft.dom.Node;
import org.workcraft.dom.visual.connections.VisualConnection;
import org.workcraft.gui.Coloriser;
import org.workcraft.gui.graph.tools.ContainerDecoration;
import org.workcraft.gui.graph.tools.Decoration;
import org.workcraft.gui.propertyeditor.PropertyDeclaration;
import org.workcraft.observation.HierarchyObserver;
import org.workcraft.observation.ObservableHierarchy;
import org.workcraft.observation.TransformChangedEvent;
import org.workcraft.observation.TransformChangingEvent;
import org.workcraft.plugins.shared.CommonVisualSettings;
import org.workcraft.util.Hierarchy;
public class VisualGroup extends VisualTransformableNode implements Drawable, Collapsible, Container, ObservableHierarchy {
public static final String PROPERTY_IS_COLLAPSED = "Is collapsed";
protected double size = CommonVisualSettings.getNodeSize();
protected static final double margin = 0.20;
private boolean isCurrentLevelInside = false;
private boolean isCollapsed = false;
private boolean isExcited = false;
DefaultGroupImpl groupImpl = new DefaultGroupImpl(this);
public VisualGroup() {
super();
addPropertyDeclarations();
}
private void addPropertyDeclarations() {
addPropertyDeclaration(new PropertyDeclaration<VisualGroup, Boolean>(
this, PROPERTY_IS_COLLAPSED, Boolean.class, true, true, true) {
@Override
protected void setter(VisualGroup object, Boolean value) {
object.setIsCollapsed(value);
}
@Override
protected Boolean getter(VisualGroup object) {
return object.getIsCollapsed();
}
});
}
@Override
public void setIsCurrentLevelInside(boolean value) {
if (isCurrentLevelInside != value) {
sendNotification(new TransformChangingEvent(this));
this.isCurrentLevelInside = value;
sendNotification(new TransformChangedEvent(this));
}
}
public boolean isCurrentLevelInside() {
return isCurrentLevelInside;
}
@Override
public void setIsCollapsed(boolean value) {
if (isCollapsed != value) {
sendNotification(new TransformChangingEvent(this));
isCollapsed = value;
sendNotification(new TransformChangedEvent(this));
}
}
@Override
public boolean getIsCollapsed() {
return isCollapsed && !isExcited;
}
@Override
public void setIsExcited(boolean value) {
if (isExcited != value) {
sendNotification(new TransformChangingEvent(this));
isExcited = value;
sendNotification(new TransformChangedEvent(this));
}
}
@Override
public void draw(DrawRequest r) {
Decoration dec = r.getDecoration();
if (dec instanceof ContainerDecoration) {
setIsExcited(((ContainerDecoration) dec).isContainerExcited());
}
// This is to update the rendered text for names (and labels) of group children,
// which is necessary to calculate the bounding box before children have been drawn
for (VisualComponent component: Hierarchy.getChildrenOfType(this, VisualComponent.class)) {
component.cacheRenderedText(r);
}
if (getParent() != null) {
drawOutline(r);
drawPivot(r);
}
}
public void drawOutline(DrawRequest r) {
Decoration d = r.getDecoration();
Graphics2D g = r.getGraphics();
Rectangle2D bb = getBoundingBoxInLocalSpace();
if (bb != null) {
g.setColor(Coloriser.colorise(Color.GRAY, d.getColorisation()));
float[] pattern = {0.2f, 0.2f};
g.setStroke(new BasicStroke(0.05f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, pattern, 0.0f));
g.draw(bb);
}
}
public void drawPivot(DrawRequest r) {
Decoration d = r.getDecoration();
Graphics2D g = r.getGraphics();
if (d.getColorisation() != null) {
float s2 = (float) CommonVisualSettings.getPivotSize() / 2;
Path2D p = new Path2D.Double();
p.moveTo(-s2, 0);
p.lineTo(s2, 0);
p.moveTo(0, -s2);
p.lineTo(0, s2);
g.setStroke(new BasicStroke((float) CommonVisualSettings.getPivotWidth()));
g.draw(p);
}
}
@Override
public Rectangle2D getBoundingBoxInLocalSpace() {
Rectangle2D bb = null;
if (!getIsCollapsed() || isCurrentLevelInside()) {
Collection<Touchable> children = Hierarchy.getChildrenOfType(this, Touchable.class);
bb = BoundingBoxHelper.mergeBoundingBoxes(children);
}
if (bb == null) {
bb = new Rectangle2D.Double(-size / 2, -size / 2, size, size);
}
return BoundingBoxHelper.expand(bb, margin, margin);
}
public final Collection<VisualComponent> getComponents() {
return Hierarchy.getChildrenOfType(this, VisualComponent.class);
}
public final Collection<VisualConnection> getnections() {
return Hierarchy.getChildrenOfType(this, VisualConnection.class);
}
public List<Node> unGroup() {
ArrayList<Node> nodesToReparent = new ArrayList<>(groupImpl.getChildren());
Container newParent = Hierarchy.getNearestAncestor(getParent(), Container.class);
groupImpl.reparent(nodesToReparent, newParent);
double tx = localToParentTransform.getTranslateX();
double ty = localToParentTransform.getTranslateY();
VisualModelTransformer.translateNodes(nodesToReparent, -tx, -ty);
return nodesToReparent;
}
@Override
public boolean hitTestInLocalSpace(Point2D pointInLocalSpace) {
Rectangle2D bb = getBoundingBoxInLocalSpace();
if ((bb != null) && (getParent() != null)) {
return bb.contains(pointInLocalSpace);
}
return false;
}
@Override
public void add(Node node) {
groupImpl.add(node);
}
@Override
public void addObserver(HierarchyObserver obs) {
groupImpl.addObserver(obs);
}
@Override
public Collection<Node> getChildren() {
return groupImpl.getChildren();
}
@Override
public Node getParent() {
return groupImpl.getParent();
}
@Override
public void remove(Node node) {
groupImpl.remove(node);
}
public void removeWithoutNotify(Node node) {
groupImpl.removeWithoutNotify(node);
}
@Override
public void removeObserver(HierarchyObserver obs) {
groupImpl.removeObserver(obs);
}
@Override
public void removeAllObservers() {
groupImpl.removeAllObservers();
}
@Override
public void setParent(Node parent) {
groupImpl.setParent(parent);
}
@Override
public void add(Collection<Node> nodes) {
groupImpl.add(nodes);
}
@Override
public void remove(Collection<Node> nodes) {
groupImpl.remove(nodes);
}
@Override
public void reparent(Collection<Node> nodes, Container newParent) {
groupImpl.reparent(nodes, newParent);
}
@Override
public void reparent(Collection<Node> nodes) {
groupImpl.reparent(nodes);
}
@Override
public Point2D getCenterInLocalSpace() {
return new Point2D.Double(0, 0);
}
@Override
public void copyStyle(Stylable src) {
super.copyStyle(src);
if (src instanceof VisualGroup) {
VisualGroup srcGroup = (VisualGroup) src;
setIsCollapsed(srcGroup.getIsCollapsed());
}
}
}
| mit |
arosini/spring-boot-starter-app | src/integration-test/java/ar/integration/actuator/ActuatorHealthEndpointTests.java | 2573 | package ar.integration.actuator;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import ar.integration.AbstractIntegrationTests;
import com.jayway.restassured.http.ContentType;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the health endpoint provided by the Spring Boot Actuator (/admin/health).
*
* @author adam
*
*/
public class ActuatorHealthEndpointTests extends AbstractIntegrationTests {
////////////////////
// Initialization //
////////////////////
/** The path of the Actuator's health endpoint. */
private String healthPath;
/** The full URL of the Actuator's health endpoint. */
private String healthUrl;
/** The String value representing a service is up in the Actuator's health endpoint. */
private String up;
@Override
@Before
public void before() {
super.before();
healthPath = "/admin/health";
healthUrl = rootUrl + healthPath;
up = "UP";
}
////////////////////////////////////
// Actuator Health Endpoint Tests //
////////////////////////////////////
@Test
public void health_DELETE() {
lastResponse = given().delete(healthUrl);
assertHealthOkResponse();
}
@Test
public void health_GET() {
lastResponse = given().get(healthUrl);
assertHealthOkResponse();
}
@Test
public void health_GET_notAcceptable() {
lastResponse = given().accept(ContentType.XML).get(healthUrl);
assertNotAcceptableResponse();
}
@Test
public void health_HEAD() {
lastResponse = given().head(healthUrl);
assertNoContentResponse();
}
@Test
public void health_PATCH() {
lastResponse = given().patch(healthUrl);
assertHealthOkResponse();
}
@Test
public void health_POST() {
lastResponse = given().post(healthUrl);
assertHealthOkResponse();
}
@Test
public void health_PUT() {
lastResponse = given().put(healthUrl);
assertHealthOkResponse();
}
///////////////////////
// Assertion Helpers //
///////////////////////
private void assertHealthOkResponse() {
assertOkResponse();
lastResponse.then()
.body("status", equalTo(up))
.body("diskSpace.status", equalTo(up))
.body("diskSpace.total", notNullValue())
.body("diskSpace.free", notNullValue())
.body("diskSpace.threshold", notNullValue())
.body("mongo.status", equalTo(up))
.body("mongo.version", notNullValue())
.body("_links.self.href", equalTo(healthUrl));
}
}
| mit |
walkingdevs/sdk | src/walkingdevs/http/ReqBuilderImpl.java | 1948 | package walkingdevs.http;
import walkingdevs.val.Val;
class ReqBuilderImpl implements ReqBuilder {
public int readTimeout() {
return readTimeout;
}
public ReqBuilder readTimeout(int readTimeout) {
this.readTimeout = Val.Negative("readTimeout", readTimeout).get();
return this;
}
public int connectTimeout() {
return connectTimeout;
}
public ReqBuilder connectTimeout(int connectTimeout) {
this.connectTimeout = Val.Negative("connectTimeout", connectTimeout).get();
return this;
}
public Url uri() {
return uri;
}
public Method method() {
return method;
}
public ReqBuilder method(Method method) {
this.method = Val.NULL("method", method).get();
return this;
}
public Headers headers() {
return headers;
}
public ReqBuilder headers(Headers headers) {
this.headers = Val.NULL("headers", headers).get();
return this;
}
public ReqBuilder header(String name, String value) {
headers().add(name, value);
return this;
}
public Body body() {
return body;
}
public ReqBuilder body(Body body) {
this.body = Val.NULL("body", body).get();
return this;
}
public ReqBuilder body(Form form) {
return body(Body.mk(form));
}
public Req build() {
return Req.mk(
uri(),
method(),
headers(),
body(),
readTimeout(),
connectTimeout()
);
}
ReqBuilderImpl(Url uri) {
this.uri = uri;
}
// 10 minutes
private static final int Timeout = 60 * 60 * 10;
private final Url uri;
private int readTimeout = Timeout;
private int connectTimeout = Timeout;
private Method method = Method.GET;
private Headers headers = Headers.mk();
private Body body = Body.mk();
} | mit |
gontsekekana/enigmamachine | app/gui/Encode.java | 805 | package gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import circuit.*;
public class Encode extends JPanel implements ActionListener {
private JTextField tf = new JTextField();
private JButton encode = new JButton("Encode");
private InternalCircuitry ic = null;
private String out =null;
private Boolean locked = false;
public Encode() {
setLayout( new GridLayout(1,2));
encode.addActionListener(this);
add(tf);
add(encode);
ic = new InternalCircuitry();
ic.setRings('M','C','K');
}
public void actionPerformed( ActionEvent e) {
if( !locked) {
String s = tf.getText();
out = ic.run(s);
locked = true;
}
}
public String getOutput() {
String o = null;
if(locked) {
locked = false;
o = out;
out = null;
}
return o;
}
}
| mit |
thombergs/coderadar | server/coderadar-webapp/src/main/java/org/wickedsource/coderadar/module/rest/ModuleController.java | 5546 | package org.wickedsource.coderadar.module.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.ExposesResourceFor;
import org.springframework.hateoas.PagedResources;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.wickedsource.coderadar.core.rest.validation.ResourceNotFoundException;
import org.wickedsource.coderadar.core.rest.validation.UserException;
import org.wickedsource.coderadar.module.domain.Module;
import org.wickedsource.coderadar.module.domain.ModuleRepository;
import org.wickedsource.coderadar.project.domain.Project;
import org.wickedsource.coderadar.project.rest.ProjectVerifier;
import javax.validation.Valid;
@Controller
@ExposesResourceFor(Module.class)
@Transactional
@RequestMapping(path = "/projects/{projectId}/modules")
public class ModuleController {
private ProjectVerifier projectVerifier;
private ModuleRepository moduleRepository;
private ModuleAssociationService moduleAssociationService;
@Autowired
public ModuleController(ProjectVerifier projectVerifier, ModuleRepository moduleRepository, ModuleAssociationService moduleAssociationService) {
this.projectVerifier = projectVerifier;
this.moduleRepository = moduleRepository;
this.moduleAssociationService = moduleAssociationService;
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<ModuleResource> createModule(@Valid @RequestBody ModuleResource moduleResource, @PathVariable Long projectId) {
Project project = projectVerifier.loadProjectOrThrowException(projectId);
if (moduleRepository.countByProjectIdAndPath(projectId, moduleResource.getModulePath()) > 0) {
throw new UserException(String.format("Module with path '%s' already exists for this project!", moduleResource.getModulePath()));
}
ModuleResourceAssembler assembler = new ModuleResourceAssembler(project);
Module module = new Module();
assembler.updateEntity(module, moduleResource);
module = moduleRepository.save(module);
moduleAssociationService.associate(module);
return new ResponseEntity<>(assembler.toResource(module), HttpStatus.CREATED);
}
@RequestMapping(method = RequestMethod.GET, path = "/{moduleId}")
public ResponseEntity<ModuleResource> getModule(@PathVariable Long moduleId, @PathVariable Long projectId) {
Project project = projectVerifier.loadProjectOrThrowException(projectId);
Module module = moduleRepository.findByIdAndProjectId(moduleId, projectId);
if (module == null) {
throw new ResourceNotFoundException();
}
ModuleResourceAssembler assembler = new ModuleResourceAssembler(project);
ModuleResource resource = assembler.toResource(module);
return new ResponseEntity<>(resource, HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.POST, path = "/{moduleId}")
public ResponseEntity<ModuleResource> updateModule(@Valid @RequestBody ModuleResource moduleResource, @PathVariable Long moduleId, @PathVariable Long projectId) {
Project project = projectVerifier.loadProjectOrThrowException(projectId);
Module module = moduleRepository.findByIdAndProjectId(moduleId, projectId);
if (module == null) {
throw new ResourceNotFoundException();
}
ModuleResourceAssembler assembler = new ModuleResourceAssembler(project);
module = assembler.updateEntity(module, moduleResource);
moduleAssociationService.reassociate(module);
return new ResponseEntity<>(assembler.toResource(module), HttpStatus.OK);
}
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<PagedResources<ModuleResource>> listModules(@PageableDefault Pageable pageable, PagedResourcesAssembler pagedResourcesAssembler, @PathVariable long projectId) {
Project project = projectVerifier.loadProjectOrThrowException(projectId);
Page<Module> page = moduleRepository.findByProjectId(projectId, pageable);
ModuleResourceAssembler assembler = new ModuleResourceAssembler(project);
PagedResources<ModuleResource> pagedResources = pagedResourcesAssembler.toResource(page, assembler);
return new ResponseEntity<>(pagedResources, HttpStatus.OK);
}
@RequestMapping(path = "/{moduleId}", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteModule(@PathVariable Long moduleId, @PathVariable Long projectId) {
projectVerifier.checkProjectExistsOrThrowException(projectId);
Module module = moduleRepository.findOne(moduleId);
if (module == null) {
throw new ResourceNotFoundException();
}
moduleAssociationService.disassociate(module);
moduleRepository.delete(module);
return new ResponseEntity<>(HttpStatus.OK);
}
}
| mit |
bing-ads-sdk/BingAds-Java-SDK | src/test/java/com/microsoft/bingads/v12/api/test/entities/criterions/campaign/device/write/BulkCampaignDeviceCriterionWriteTargetTest.java | 1605 | package com.microsoft.bingads.v12.api.test.entities.criterions.campaign.device.write;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import com.microsoft.bingads.v12.api.test.entities.criterions.campaign.device.BulkCampaignDeviceCriterionTest;
import com.microsoft.bingads.v12.bulk.entities.BulkCampaignDeviceCriterion;
import com.microsoft.bingads.v12.campaignmanagement.DeviceCriterion;
@RunWith(Parameterized.class)
public class BulkCampaignDeviceCriterionWriteTargetTest extends BulkCampaignDeviceCriterionTest {
@Parameterized.Parameter(value = 1)
public String propertyValue;
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[][]{
{"Computers", "Computers"},
{"Smartphones", "Smartphones"},
{"", ""},
{null, null}
}
);
}
@Test
public void testWrite() {
testWriteProperty(
"Target",
datum,
propertyValue,
new BiConsumer<BulkCampaignDeviceCriterion, String>() {
@Override
public void accept(BulkCampaignDeviceCriterion c, String v) {
((DeviceCriterion)c.getBiddableCampaignCriterion().getCriterion()).setDeviceName(v);
}
}
);
}
}
| mit |
mukilkrishnan/leetcode | array/FindPeakElement.java | 1635 | public class FindPeakElement {
/**
* A peak element is an element that is greater than its neighbors.
* Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
* The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
* You may imagine that num[-1] = num[n] = -∞.
* For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
*/
public int findPeakElement(int[] nums) {
return findPeakOverRange (nums, 0, nums.length - 1, nums.length);
}
private int findPeakOverRange (int[] nums, int low, int high, int capacity) {
/**
* Recursively find peak in the range nums[low] to nums[high] using binary search
*/
// to avoid overflow
int mid = low + (high - low) / 2;
// condition |low|high|low|
if ((mid == 0 || nums[mid - 1] <= nums[mid]) && (mid == capacity - 1 || nums[mid + 1] <= nums[mid])) return mid;
// search left half for a peak
else if (mid > 0 && nums[mid - 1] > nums[mid]) return findPeakOverRange (nums, low, mid - 1, capacity);
// search right half for a peak
else return findPeakOverRange (nums, mid + 1, high, capacity);
}
public static void main (String[] args) {
FindPeakElement test = new FindPeakElement ();
int[] nums1 = {1, 2, 3, 1};
int[] nums2 = {23, 21, 20, 21, 19, 17, 16};
System.out.println (test.findPeakElement (nums1) == 2);
System.out.println (test.findPeakElement (nums2) == 3);
}
} | mit |
sheplu/Checkers | src/com/sheplu/checkers/game/Game.java | 228 | package com.sheplu.checkers.game;
public class Game {
private int Size;
public Game() {
}
public void launch() {
}
public int getSize() {
return Size;
}
public void setSize(int size) {
Size = size;
}
}
| mit |
macmata/projet5001-java | core/src/com/projet5001/game/actors/MyActor.java | 8697 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Alexandre Leblanc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.projet5001.game.actors;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.*;
import com.badlogic.gdx.scenes.scene2d.actions.MoveByAction;
import com.projet5001.game.Ai.BehaviorTree.Ai;
import com.projet5001.game.collisions.WorldCollector;
import com.projet5001.game.controleur.AnimationControleur;
import com.projet5001.game.events.ActorEvent;
import com.projet5001.game.events.MovementEvents;
import com.projet5001.game.listeners.ContainerListener;
import com.projet5001.game.listeners.MovementListener;
public class MyActor extends Actor {
protected int collisionBoxSize;
protected int ZIndex;
protected float speed;
protected Sprite sprite;
protected TextureRegion textureRegion;
protected Rectangle hitbox;
protected Circle visionHitbox;
protected Vector2 old_position;
protected Vector2 futur_position;
protected float visionDistance;
protected AnimationControleur animationControleur;
protected String move;
public MyActor() {
this(null);
}
public MyActor(Texture texture) {
super();
this.speed = 32 / 16;
this.ZIndex = 0;
this.visionDistance = 250;
this.collisionBoxSize = 4;
this.sprite = null;
this.textureRegion = null;
this.animationControleur = null;
this.move = "idle";
this.visionHitbox = new Circle(this.getCenterX(), this.getCenterY(), visionDistance);
this.old_position = new Vector2();
this.futur_position = new Vector2();
this.options(texture);
addListener(new MovementListener() {
public boolean moveLeft(MovementEvents event) {
((MyActor) event.getTarget()).moveLeft();
return false;
}
public boolean moveRight(MovementEvents event) {
((MyActor) event.getTarget()).moveRight();
return false;
}
public boolean moveUp(MovementEvents event) {
((MyActor) event.getTarget()).moveUp();
return false;
}
public boolean moveDown(MovementEvents event) {
((MyActor) event.getTarget()).moveDown();
return false;
}
public boolean idle(MovementEvents event) {
//((MyActor) event.getTarget()).setSpeed(0);
return false;
}
});
addListener(new ContainerListener() {
//todo changer une fois que l'on sait comment les acteur reagise au collision
public boolean collision(ActorEvent actorEvent) {
//((MyActor) containerEvent.getTarget()).collide(containerEvent.getList());
return false;
}
});
//todo menu ou option du personnage ou npc
addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
System.out.println(((MyActor) event.getTarget()).toString());
return false;
}
});
}
public void options(Texture texture) {
if (texture != null) {
this.sprite = new Sprite(texture);
this.setBounds(getX(), getY(), this.sprite.getWidth(), this.sprite.getHeight());
this.hitbox = new Rectangle(this.getX(), this.getY(), this.getWidth(), this.getHeight() / collisionBoxSize);
}
this.setTouchable(Touchable.enabled);
}
public void options(AnimationControleur animationControleur) {
if (animationControleur != null) {
this.animationControleur = animationControleur;
this.textureRegion = animationControleur.getCurrentTexture(this.move);
this.setBounds(getX(), getY(), this.textureRegion.getRegionWidth(), this.textureRegion.getRegionHeight());
this.hitbox = new Rectangle(this.getX(), this.getY(), this.getWidth(), this.getHeight() / collisionBoxSize);
}
this.setTouchable(Touchable.enabled);
}
public Circle getVisionHitbox() {
return visionHitbox;
}
public Rectangle getHitbox() {
return hitbox;
}
public Vector2 getVector() {
return new Vector2(this.getX(), this.getY());
}
public void setMove(String move) {
this.move = move;
}
public void moveLeft() {
setMove("walk_left");
move(-speed, 0);
}
public void moveRight() {
setMove("walk_right");
move(speed, 0);
}
public void moveUp() {
setMove("walk_up");
move(0, speed);
}
public void moveDown() {
setMove("walk_down");
move(0, -speed);
}
public void move(float x, float y) {
savePosition(x, y);
setHitboxPosition(this.futur_position);
if (WorldCollector.collection().hit(this.hitbox)) {
resetPosition();
} else {
MoveByAction moveAction = new MoveByAction();
moveAction.setAmount(x, y);
this.addAction(moveAction);
}
updateHitboxPosition();
}
protected void savePosition(float x, float y) {
this.old_position.set(this.getX(), this.getY());
this.futur_position.set(this.getX() + x, this.getY() + y);
}
public void resetPosition() {
this.setPosition(this.old_position);
this.updateHitboxPosition();
}
public void setPosition(float x, float y) {
super.setPosition(x, y);
this.updateHitboxPosition();
}
public void setPosition(Vector2 vector) {
this.setPosition(vector.x, vector.y);
}
public void updateHitboxPosition() {
this.hitbox.setPosition(this.getX(), this.getY());
}
public void setHitboxPosition(Vector2 vector2) {
this.hitbox.setPosition(vector2.x, vector2.y);
}
@Override
public void act(float delta) {
this.setZIndex((int) this.getY());
this.isIdle();
super.act(delta);
this.visionHitbox.set(this.getX(), this.getY(), this.visionDistance);
this.hitbox.setPosition(this.getX(), this.getY());
//important puisque les actions ne son pas déclenché tjs au meme moment.
}
public int getZIndex() {
return this.ZIndex;
}
public void setZIndex(int index) {
this.ZIndex = index;
}
private boolean isIdle() {
int i = 0;
for (Action action : this.getActions()) {
if (action instanceof Ai) {
continue;
}
i++;
}
if (i == 0) {
setMove("idle");
return true;
}
return false;
}
public boolean isSeeingEnemies() {
return false;
}
public boolean isSafe() {
return true;
}
@Override
public void draw(Batch batch, float parentAlpha) {
if (this.sprite != null) {
this.sprite.setPosition(getX(), getY());
this.sprite.draw(batch);
}
if (this.animationControleur != null) {
this.textureRegion = this.animationControleur.getCurrentTexture(move);
batch.draw(textureRegion, getX(), getY());
}
}
}
| mit |
navalev/azure-sdk-for-java | sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorHandlerProviderTest.java | 7209 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.core.amqp.implementation;
import com.azure.core.amqp.AmqpTransportType;
import com.azure.core.amqp.ProxyAuthenticationType;
import com.azure.core.amqp.ProxyOptions;
import com.azure.core.amqp.implementation.handler.ConnectionHandler;
import com.azure.core.amqp.implementation.handler.WebSocketsConnectionHandler;
import com.azure.core.amqp.implementation.handler.WebSocketsProxyConnectionHandler;
import org.apache.qpid.proton.reactor.Reactor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.Collections;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
public class ReactorHandlerProviderTest {
private static final String CONNECTION_ID = "test-connection-id";
private static final String HOSTNAME = "my-hostname.windows.com";
private static final InetSocketAddress PROXY_ADDRESS = InetSocketAddress.createUnresolved("foo.proxy.com", 3138);
private static final Proxy PROXY = new Proxy(Proxy.Type.HTTP, PROXY_ADDRESS);
private static final String USERNAME = "test-user";
private static final String PASSWORD = "test-password";
private static final String PRODUCT = "test";
private static final String CLIENT_VERSION = "1.0.0-test";
@Mock
private Reactor reactor;
@Mock
private ReactorProvider reactorProvider;
private ReactorHandlerProvider provider;
private ProxySelector originalProxySelector;
private ProxySelector proxySelector;
public static Stream<ProxyOptions> getProxyConfigurations() {
return Stream.of(ProxyOptions.SYSTEM_DEFAULTS,
new ProxyOptions(ProxyAuthenticationType.BASIC, null, "some username", "some password"),
null
);
}
@BeforeEach
public void setup() throws IOException {
MockitoAnnotations.initMocks(this);
when(reactorProvider.createReactor(eq(CONNECTION_ID), anyInt())).thenReturn(reactor);
when(reactorProvider.getReactor()).thenReturn(reactor);
provider = new ReactorHandlerProvider(reactorProvider);
originalProxySelector = ProxySelector.getDefault();
proxySelector = mock(ProxySelector.class, Mockito.CALLS_REAL_METHODS);
ProxySelector.setDefault(proxySelector);
}
@AfterEach
public void teardown() {
Mockito.framework().clearInlineMocks();
ProxySelector.setDefault(originalProxySelector);
}
@Test
public void getsConnectionHandlerAMQP() {
// Act
final ConnectionHandler handler = provider.createConnectionHandler(CONNECTION_ID, HOSTNAME,
AmqpTransportType.AMQP, null, PRODUCT, CLIENT_VERSION);
// Assert
Assertions.assertNotNull(handler);
Assertions.assertEquals(5671, handler.getProtocolPort());
}
/**
* Verify that if the user has not provided a proxy, and asks for websockets, we pass the correct handler.
*/
@ParameterizedTest
@MethodSource("getProxyConfigurations")
public void getsConnectionHandlerWebSockets(ProxyOptions configuration) {
// Act
final ConnectionHandler handler = provider.createConnectionHandler(CONNECTION_ID, HOSTNAME,
AmqpTransportType.AMQP_WEB_SOCKETS, configuration, PRODUCT, CLIENT_VERSION);
// Assert
Assertions.assertNotNull(handler);
Assertions.assertTrue(handler instanceof WebSocketsConnectionHandler);
Assertions.assertEquals(443, handler.getProtocolPort());
}
/**
* Verify if user provides a proxy address, we return the correct proxy properties.
*/
@Test
public void getsConnectionHandlerProxy() {
// Arrange
final InetSocketAddress address = InetSocketAddress.createUnresolved("my-new.proxy.com", 8888);
final Proxy newProxy = new Proxy(Proxy.Type.HTTP, address);
final ProxyOptions configuration = new ProxyOptions(ProxyAuthenticationType.BASIC, newProxy, USERNAME, PASSWORD);
final String hostname = "foo.eventhubs.azure.com";
// Act
final ConnectionHandler handler = provider.createConnectionHandler(CONNECTION_ID, hostname,
AmqpTransportType.AMQP_WEB_SOCKETS, configuration, PRODUCT, CLIENT_VERSION);
// Assert
Assertions.assertNotNull(handler);
Assertions.assertTrue(handler instanceof WebSocketsProxyConnectionHandler);
Assertions.assertEquals(address.getHostName(), handler.getHostname());
Assertions.assertEquals(address.getPort(), handler.getProtocolPort());
verifyZeroInteractions(proxySelector);
}
/**
* Verifies that if no proxy configuration is set, then it will use the system configured proxy.
*/
@ParameterizedTest
@MethodSource("getProxyConfigurations")
public void noProxySelected(ProxyOptions configuration) {
// Arrange
final String hostname = "foo.eventhubs.azure.com";
when(proxySelector.select(argThat(u -> u.getHost().equals(hostname))))
.thenReturn(Collections.singletonList(PROXY));
// Act
final ConnectionHandler handler = provider.createConnectionHandler(CONNECTION_ID, hostname,
AmqpTransportType.AMQP_WEB_SOCKETS, configuration, PRODUCT, CLIENT_VERSION);
// Act and Assert
Assertions.assertEquals(PROXY_ADDRESS.getHostName(), handler.getHostname());
Assertions.assertEquals(PROXY_ADDRESS.getPort(), handler.getProtocolPort());
}
/**
* Verify that when there are no legal proxy addresses, false is returned.
*/
@Test
public void shouldUseProxyNoLegalProxyAddress() {
// Arrange
final String host = "foo.eventhubs.azure.com";
when(proxySelector.select(argThat(u -> u.getHost().equals(host))))
.thenReturn(Collections.emptyList());
// Act and Assert
Assertions.assertFalse(WebSocketsProxyConnectionHandler.shouldUseProxy(host));
}
@Test
public void shouldUseProxyHostNull() {
assertThrows(NullPointerException.class, () -> WebSocketsProxyConnectionHandler.shouldUseProxy(null));
}
@Test
public void shouldUseProxyNullProxySelector() {
// Arrange
final String host = "foo.eventhubs.azure.com";
ProxySelector.setDefault(null);
// Act and Assert
Assertions.assertFalse(WebSocketsProxyConnectionHandler.shouldUseProxy(host));
}
}
| mit |