code
stringlengths
10
749k
repo_name
stringlengths
5
108
path
stringlengths
7
333
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
10
749k
// @(#)$Id: JMLValueBagSpecs.java,v 1.16 2006/02/17 01:21:47 chalin Exp $ // Copyright (C) 2005 Iowa State University // // This file is part of the runtime library of the Java Modeling Language. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2.1, // of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with JML; see the file LesserGPL.txt. If not, write to the Free // Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA // 02110-1301 USA. package org.jmlspecs.models; /** Special behavior for JMLValueBag not shared by JMLObjectBag. * * @version $Revision: 1.16 $ * @author Gary T. Leavens, with help from Clyde Ruby, and others. * @see JMLValueType * @see JMLValueBag */ //-@ immutable public /*@ pure @*/ abstract class JMLValueBagSpecs implements JMLValueType { /** Is the argument ".equals" to one of the values in this bag. * @see #has(Object) * @see #count(JMLType) */ /*@ public normal_behavior @ ensures \result <==> count(elem) > 0; @*/ public abstract boolean has(/*@ nullable @*/ JMLType elem); /** Is the argument ".equals" to one of the values in this bag. * @see #has(JMLType) * @see #count(Object) */ /*@ public normal_behavior @ requires elem != null; @ ensures \result @ <==> elem instanceof JMLType && has((JMLType)elem); @ also @ public normal_behavior @ requires elem == null; @ ensures \result == has(null); @*/ public boolean has(/*@ nullable @*/ Object elem) { if (elem == null) { return has(null); } else { return elem instanceof JMLType && has((JMLType)elem); } } /** Tell many times the argument occurs ".equals" to one of the * values in this bag. * @see #count(Object) * @see #has(JMLType) */ /*@ public normal_behavior @ ensures \result >= 0 @ && (* \result is the number of times elem tests @ as ".equals" to one of the objects in the bag *); @*/ public abstract int count(/*@ nullable @*/ JMLType elem); /** Tell many times the argument occurs ".equals" to one of the * values in this bag. * @see #count(JMLType) * @see #has(Object) */ /*@ public normal_behavior @ requires elem != null; @ ensures \result @ == (elem instanceof JMLType ? count((JMLType)elem) : 0); @ also @ public normal_behavior @ requires elem == null; @ ensures \result == count(null); @*/ public int count(/*@ nullable @*/ Object elem) { if (elem == null) { return count(null); } else { return (elem instanceof JMLType ? count((JMLType)elem) : 0); } } /** Tells the number of elements in the bag. */ /*@ public normal_behavior @ ensures \result >= 0 @ && (* \result is the number of elements in the bag *); @*/ public abstract int int_size(); // Specification inherited from JMLValueType. // Note: not requiring the \result contain "clones" of the elements of // this, allows the implementer latitude to take advantage of the // nature of immutable types. public abstract Object clone(); /** How many times does the argument occur as an objects * representing values in the bag? * @see #count(Object) */ /*@ public normal_behavior @ ensures (* \result is the number of occurences of objects @ in this bag that are "==" to elem *); public model int countObject(JMLType elem); @*/ /** Returns a new bag that contains all the elements of this and * also the given argument. * @see #insert(JMLType, int) */ public abstract /*@ non_null @*/ JMLValueBag insert (/*@ nullable @*/ JMLType elem) /*@ public model_program { @ assume elem != null && int_size() < Integer.MAX_VALUE; @ JMLType copy = (JMLType) elem.clone(); @ JMLValueBag returnVal = null; @ @ behavior @ assignable returnVal; @ ensures returnVal != null @ && (\forall JMLType e; !e.equals(copy); @ countObject(e) == returnVal.countObject(e)) @ && returnVal.countObject(copy) == 1 @ && returnVal.int_size() == int_size() + 1; @ @ return returnVal; @ } @*/ ; /** Returns a new bag that contains all the elements of this and * also the given argument. * @see #insert(JMLType) */ /*@ public model_program { @ assume cnt >= 0; @ assume elem != null && int_size() < Integer.MAX_VALUE - cnt; @ JMLType copy = (JMLType) elem.clone(); @ JMLValueBag returnVal = null; @ @ behavior @ assignable returnVal; @ ensures returnVal != null @ && (\forall JMLType e; e != copy; @ countObject(e) @ == returnVal.countObject(e)) @ && returnVal.countObject(copy) == cnt @ && returnVal.int_size() == int_size() + cnt; @ @ return returnVal; @ } @ @ also @ signals (IllegalArgumentException) cnt < 0; @*/ public abstract /*@ non_null @*/ JMLValueBag insert (/*@ nullable @*/ JMLType elem, int cnt) throws IllegalArgumentException; }
GaloisInc/Votail
external_tools/JML/org/jmlspecs/models/JMLValueBagSpecs.java
Java
mit
6,189
package nxt.peer; import nxt.Nxt; import nxt.Transaction; import nxt.TransactionProcessor; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONStreamAware; final class GetUnconfirmedTransactions extends PeerServlet.PeerRequestHandler { static final GetUnconfirmedTransactions instance = new GetUnconfirmedTransactions(); JSONStreamAware processRequest(JSONObject paramJSONObject, Peer paramPeer) { JSONObject localJSONObject = new JSONObject(); JSONArray localJSONArray = new JSONArray(); for (Transaction localTransaction : Nxt.getTransactionProcessor().getAllUnconfirmedTransactions()) { localJSONArray.add(localTransaction.getJSONObject()); } localJSONObject.put("unconfirmedTransactions", localJSONArray); return localJSONObject; } }
stevedoe/nxt-client
src/nxt/peer/GetUnconfirmedTransactions.java
Java
mit
837
<<<<<<< HEAD //package fii.admission.utils; // //import org.springframework.http.HttpStatus; //import org.springframework.http.ResponseEntity; //import org.springframework.web.bind.annotation.PathVariable; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.RequestMethod; //import org.springframework.web.bind.annotation.RestController; // //import java.util.ArrayList; //import java.util.HashMap; //import java.util.List; //import java.util.TreeMap; // ///** // * Created by andy on 07.06.2017. // */ //@RequestMapping(value = "/model") //@RestController //public class UtilsController { // @RequestMapping(value = "/placement/students", method = RequestMethod.GET) // public ResponseEntity<List<StudentsPlacement>> getStudentsPlacement() { // // List<StudentsPlacement> result = UtilsService.getStudentsPlacement(); // // if (result == null) // return new ResponseEntity<List<StudentsPlacement>>(result, HttpStatus.NO_CONTENT); // // return new ResponseEntity<List<StudentsPlacement>>(result, HttpStatus.OK); // } // // @RequestMapping(value = "/placement/students/{filename}", method = RequestMethod.GET) // public ResponseEntity<List<StudentsPlacement>> getStudentsPlacement(@PathVariable String fileName) { // // List<StudentsPlacement> result = UtilsService.getStudentsPlacement(fileName); // // if (result == null) // return new ResponseEntity<List<StudentsPlacement>>(result, HttpStatus.NO_CONTENT); // // return new ResponseEntity<List<StudentsPlacement>>(result, HttpStatus.OK); // } // // @RequestMapping(value = "/placement/profesori", method = RequestMethod.GET) // public void getProfesoriPlacement() { // UtilsService.getProfesoriPlacement(); // } // // @RequestMapping(value = "/export/{fileName}", method = RequestMethod.GET) // public void exportStudents(@PathVariable String fileName) { // UtilsService.exportStudents(fileName ); // } // //} ======= package fii.admission.utils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TreeMap; /** * Created by andy on 07.06.2017. */ @RequestMapping(value = "/model") @RestController public class UtilsController { @RequestMapping(value = "/placement/students", method = RequestMethod.GET) public ResponseEntity<List<StudentsPlacement>> getStudentsPlacement() { List<StudentsPlacement> result = UtilsService.getStudentsPlacement(); if (result == null) return new ResponseEntity<List<StudentsPlacement>>(result, HttpStatus.NO_CONTENT); return new ResponseEntity<List<StudentsPlacement>>(result, HttpStatus.OK); } @RequestMapping(value = "/placement/students/{fileName}", method = RequestMethod.GET) public ResponseEntity<List<StudentsPlacement>> getStudentsPlacement(@PathVariable String fileName) { List<StudentsPlacement> result = UtilsService.getStudentsPlacement(fileName); if (result == null) return new ResponseEntity<List<StudentsPlacement>>(result, HttpStatus.NO_CONTENT); return new ResponseEntity<List<StudentsPlacement>>(result, HttpStatus.OK); } @RequestMapping(value = "/export/{fileName}", method = RequestMethod.GET) public void exportStudents(@PathVariable String fileName) { UtilsService.exportStudents(fileName ); } } >>>>>>> cc4a7bfdbfd76af54c759a32ab1f1d8051ac366c
ip-b1-2017/fii-admission
Integration/Mare_Proiect/spring-boot/src/main/java/fii/admission/utils/UtilsController.java
Java
mit
3,840
package com.eboji.data.server; import java.util.concurrent.Executors; import com.eboji.commons.msg.BaseMsg; import com.eboji.commons.msg.CreateRoomMsg; import com.eboji.commons.msg.JoinRoomMsg; import com.eboji.commons.msg.JoinRoomNoMemMsg; import com.eboji.commons.msg.LoginMsg; import com.eboji.data.server.task.BaseTask; import com.eboji.data.server.task.CreateRoomTask; import com.eboji.data.server.task.GetGameServerInfoTask; import com.eboji.data.server.task.JoinRoomTask; import com.eboji.data.server.task.LoginTask; import com.eboji.data.service.DataService; /** * 数据服务处理核心转发类 * @author zhoucl * */ public class DataServerProcessor { private DataService dataService; public DataServerProcessor(DataService dataService, int poolSize) { this.dataService = dataService; DataServerExecutors.setService(Executors. newFixedThreadPool(poolSize)); } /** * 转发处理方法 * @param msg * @param remoteAddress */ public void process(BaseMsg msg, String remoteAddress) { BaseTask task = null; if(msg instanceof CreateRoomMsg) { task = new CreateRoomTask(remoteAddress, (CreateRoomMsg)msg, dataService); } else if(msg instanceof LoginMsg) { task = new LoginTask(remoteAddress, (LoginMsg)msg, dataService); } else if(msg instanceof JoinRoomMsg) { task = new JoinRoomTask(remoteAddress, (JoinRoomMsg)msg, dataService); } else if(msg instanceof JoinRoomNoMemMsg) { task = new GetGameServerInfoTask(remoteAddress, (JoinRoomNoMemMsg)msg, dataService); } if(task != null) { DataServerExecutors.getService().submit(task); } } }
zhoucl/RootProject
DataServer/src/main/java/com/eboji/data/server/DataServerProcessor.java
Java
mit
1,633
package de.fu_berlin.inf.ag_se.browser.html; import java.util.Map; /** * Abstractions of an HTML tag like &lt;a * href=&quot;http://bkahlert.com&quot;&gt;bkahlert.com&lt;/a&gt;. * * @author bkahlert * */ public interface IElement { /** * Returns the HTML tag's name. * * @return */ public String getName(); public Map<String, String> getAttributes(); /** * Returns the attribute with the given name. * * @param name * @return null if attribute is not set */ public String getAttribute(String name); String getData(String key); /** * Returns the {@link IElement}'s css classes. * * @return */ public String[] getClasses(); /** * Returns the {@link IElement}'s content, which is the portion between the * opening and closing tag. * * @return */ public String getContent(); /** * Returns html that represents this {@link IElement}. * * @return */ public String toHtml(); }
ag-se/swt-browser-improved
src/main/java/de/fu_berlin/inf/ag_se/browser/html/IElement.java
Java
mit
949
/* * Copyright (c) 2013 Red Rainbow IT Solutions GmbH, Germany * * 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.jeecqrs.event.bus.local; /** * Provides the ability to generate a {@code MultiTopicPublisher} topic * for a given event class. * * @param <E> the base event type */ public interface TopicGenerationStrategy<E> { /** * Gets the topic for the given event type. * * @param eventType the event type * @return the topic name */ String topicFor(Class<? extends E> eventType); /** * Gets the name of the wildcard topic containing all events published * on the event bus. * * @return the wildcard topic name */ String wildcardTopic(); }
JEEventStore/JEECQRS
core/src/main/java/org/jeecqrs/event/bus/local/TopicGenerationStrategy.java
Java
mit
1,770
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** Abstraction and classes related to disk cache. */ package com.facebook.cache.disk;
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/cache/disk/package-info.java
Java
mit
278
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * MainAboutBox.java * * Created on 2012-7-25, 8:21:03 */ package com.carpark.view; /** * * @author Zeming */ public class MainAboutBox extends javax.swing.JDialog { /** Creates new form MainAboutBox */ public MainAboutBox(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); setName("Form"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.carpark.view.CarParkApp.class).getContext().getResourceMap(MainAboutBox.class); jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N jButton1.setFont(resourceMap.getFont("jButton1.font")); // NOI18N jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N jButton1.setName("jButton1"); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel3.setIcon(resourceMap.getIcon("jLabel3.icon")); // NOI18N jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N jLabel3.setName("jLabel3"); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(jLabel2) .addContainerGap(184, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(jLabel3) .addContainerGap(66, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(60, 60, 60) .addComponent(jLabel1) .addContainerGap(83, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(153, Short.MAX_VALUE) .addComponent(jButton1) .addGap(43, 43, 43)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addGap(18, 18, 18) .addComponent(jButton1) .addContainerGap(21, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents //关闭按钮 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { MainAboutBox dialog = new MainAboutBox(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; // End of variables declaration//GEN-END:variables }
leoliew/CarPark
src/com/carpark/view/MainAboutBox.java
Java
mit
5,063
package fr.faylixe.ekite.internal; import java.io.IOException; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.custom.CaretEvent; import org.eclipse.swt.custom.CaretListener; import fr.faylixe.ekite.EKitePlugin; /** * {@link SelectionListener} is in charge of monitoring * <tt>selection</tt> event and to dispatch them to Kite. * Such event are triggered by a cursor move, or user selection. * * TODO Consider using dedicated queue * for sending event in a separated * thread in order to avoid blocking * * @author fv */ public final class SelectionListener implements ISelectionChangedListener, CaretListener { /** Event sender used by this listener to send event notification. **/ private final EventSender sender; /** * Default constructor. * * @param sender Event sender instance to use. */ public SelectionListener(final EventSender sender) { this.sender = sender; } /** {@inheritDoc} **/ @Override public void selectionChanged(final SelectionChangedEvent event) { final ISelection selection = event.getSelection(); if (selection instanceof ITextSelection) { final ITextSelection textSelection = (ITextSelection) selection; try { sender.sendSelection( textSelection.getOffset(), textSelection.getOffset() + textSelection.getLength()); if (EKitePlugin.DEBUG) { EKitePlugin.log( "Selection changed " + textSelection.getOffset() + " - " + textSelection.getLength()); } } catch (final IOException | IllegalStateException e) { EKitePlugin.log(e); } } } /** {@inheritDoc }**/ @Override public void caretMoved(final CaretEvent event) { try { sender.sendSelection(event.caretOffset, event.caretOffset); if (EKitePlugin.DEBUG) { EKitePlugin.log("Caret moved to " + event.caretOffset); } } catch (final IOException | IllegalStateException e) { EKitePlugin.log(e); } } }
Faylixe/ekite
plugin/src/fr/faylixe/ekite/internal/SelectionListener.java
Java
mit
2,102
package com.jgb.designpatterns.strategy; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class CapTextFormatter implements TextFormatter { private static final Logger LOG = LogManager.getLogger(CapTextFormatter.class); @Override public void format(String text) { LOG.info("[CapTextFormatter]: " + text.toUpperCase()); } }
jgb11/design-patterns-tutorial
src/main/java/com/jgb/designpatterns/strategy/CapTextFormatter.java
Java
mit
409
package com.wrapper.spotify.requests.data.shows; import com.wrapper.spotify.TestUtil; import com.wrapper.spotify.exceptions.SpotifyWebApiException; import com.wrapper.spotify.model_objects.specification.EpisodeSimplified; import com.wrapper.spotify.model_objects.specification.Paging; import com.wrapper.spotify.requests.data.AbstractDataTest; import org.apache.hc.core5.http.ParseException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.io.IOException; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertEquals; @RunWith(MockitoJUnitRunner.class) public class GetShowsEpisodesRequestTest extends AbstractDataTest<Paging<EpisodeSimplified>> { private final GetShowsEpisodesRequest defaultRequest = SPOTIFY_API.getShowEpisodes(ID_SHOW) .setHttpManager( TestUtil.MockedHttpManager.returningJson( "requests/data/shows/GetShowsEpisodesRequest.json")) .offset(OFFSET) .limit(LIMIT) .market(MARKET) .build(); public GetShowsEpisodesRequestTest() throws Exception { } @Test public void shouldComplyWithReference() { assertHasAuthorizationHeader(defaultRequest); assertEquals( "https://api.spotify.com:443/v1/shows/5AvwZVawapvyhJUIx71pdJ/episodes?offset=0&limit=10&market=SE", defaultRequest.getUri().toString()); } @Test public void shouldReturnDefault_sync() throws IOException, SpotifyWebApiException, ParseException { shouldReturnDefault(defaultRequest.execute()); } @Test public void shouldReturnDefault_async() throws ExecutionException, InterruptedException { shouldReturnDefault(defaultRequest.executeAsync().get()); } public void shouldReturnDefault(final Paging<EpisodeSimplified> episodeSimplifiedPaging) { assertEquals( "https://api.spotify.com/v1/shows/38bS44xjbVVZ3No3ByF1dJ/episodes?offset=1&limit=2", episodeSimplifiedPaging.getHref()); assertEquals( 2, episodeSimplifiedPaging.getItems().length); assertEquals( 2, (int) episodeSimplifiedPaging.getLimit()); assertEquals( "https://api.spotify.com/v1/shows/38bS44xjbVVZ3No3ByF1dJ/episodes?offset=3&limit=2", episodeSimplifiedPaging.getNext()); assertEquals( 1, (int) episodeSimplifiedPaging.getOffset()); assertEquals( "https://api.spotify.com/v1/shows/38bS44xjbVVZ3No3ByF1dJ/episodes?offset=0&limit=2", episodeSimplifiedPaging.getPrevious()); assertEquals( 499, (int) episodeSimplifiedPaging.getTotal()); } }
thelinmichael/spotify-web-api-java
src/test/java/com/wrapper/spotify/requests/data/shows/GetShowsEpisodesRequestTest.java
Java
mit
2,582
package autofixture.publicinterface.generators; import autofixture.publicinterface.InstanceType; public interface EnumCache { <T> void registerIfNotPresent(InstanceType<T> instanceType); <T> T retrieveNextValueOf(InstanceType<T> instanceType); }
ghostsquad/AutoFixtureGenerator
src/main/java/autofixture/publicinterface/generators/EnumCache.java
Java
mit
266
import java.io.Serializable; import java.util.ArrayList; /** * The representation of a tile/block in the game * @author Samy Narrainen * */ public class Tile implements Serializable { /** * Variables */ //The tiles which are connected to this one public boolean north, east, south, west; //Associations with the room //public Monster m; //Is the room null (of type 4) public boolean isNull; //Has the player entered this square at anytime? public boolean found; //The type of room it is, 0 EMPTY, 1 MONSTER, 2 TRAP, 3 TREASURE, 4 NULL public int type; /** * Constructor */ public Tile() { this.north = false; this.east = false; this.south = false; this.west = false; //this.m = null; this.isNull = false; this.found = false; } /** * Methods to set whether or not the tile has an adjacent tile * @param b true if it does */ public void setNorthTile(boolean b) { this.north = b; } public void setEastTile(boolean b) { this.east = b; } public void setSouthTile(boolean b) { this.south = b; } public void setWestTile(boolean b) { this.west = b; } /** * Methods to see if the tile has a tile in an adjacent position */ public boolean hasNorthTile(){ if(this.north) return true; else return false; } public boolean hasEastTile(){ if(this.east) return true; else return false; } public boolean hasSouthTile(){ if(this.south) return true; else return false; } public boolean hasWestTile(){ if(this.west) return true; else return false; } /** * Whether or not the tile is considered null (4) * @return true if the room is null, else false */ public boolean isNull() { if(this.isNull) return true; else return false; } /** * Setter for isNull variable * @param b */ public void setNull(boolean b) { this.isNull = b; } /** * Has the tile been found? * @return true if it has */ public boolean isFound(){ if(this.found) return true; else return false; } /** * Setter for found variable * @param b */ public void setFound(boolean b) { this.found = b; } /** * A list of all adjacent tiles, encoded by integer * @return sides, the the tiles represented with this tile */ public ArrayList<Integer> getAdjacentTiles() { ArrayList<Integer> sides = new ArrayList<Integer>(); if(this.north) sides.add(10); if(this.east) sides.add(20); if(this.south) sides.add(30); if(this.west) sides.add(40); return sides; } /** * Setter for the room type * @param t: 0 EMPTY, 1 MONSTER, 2 TRAP, 3 TREASURE */ public void setType(int t) { this.type = t; } /** * Getter for the type of room * @return */ public int getType() { return this.type; } }
SamyNarrainen/Loot-Fight-Survive
src/Tile.java
Java
mit
2,821
package by.triumgroup.recourse.entity.model; import org.hibernate.validator.constraints.SafeHtml; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.sql.Time; import java.sql.Timestamp; import java.util.Objects; @Entity @Table(name = "lesson") public class Lesson extends BaseEntity<Integer> { @NotNull(message = "Start time is not specified") @Column(columnDefinition = "DATETIME", nullable = false) private Timestamp startTime; @NotNull(message = "Duration is not specified") @Column(columnDefinition = "TIME", nullable = false) private Time duration; @NotNull(message = "Course ID is not specified") @Column(columnDefinition = "INT(11)", nullable = false) private Integer courseId; @NotNull(message = "Topic is not specified") @SafeHtml @Size(min = 1, max = 50, message = "Topic length must be in range 1-50") @Column(length = 50) private String topic; @NotNull(message = "Teacher is not specified") @ManyToOne(targetEntity = User.class) @JoinColumn(name = "teacher_id") private User teacher; @Column(columnDefinition = "TEXT", nullable = false) private String task; public Lesson() { } public Lesson(Timestamp startTime, Time duration, Integer courseId, String topic, User teacher) { this.startTime = startTime; this.duration = duration; this.courseId = courseId; this.topic = topic; this.teacher = teacher; } public Lesson(Lesson lesson) { this.startTime = lesson.startTime; this.duration = lesson.duration; this.courseId = lesson.courseId; this.topic = lesson.topic; this.teacher = lesson.teacher; } public Timestamp getStartTime() { return startTime; } public void setStartTime(Timestamp startTime) { this.startTime = startTime; } public Time getDuration() { return duration; } public void setDuration(Time duration) { this.duration = duration; } public Integer getCourseId() { return courseId; } public void setCourseId(Integer courseId) { this.courseId = courseId; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public User getTeacher() { return teacher; } public void setTeacher(User teacher) { this.teacher = teacher; } public String getTask() { return task; } public void setTask(String task) { this.task = task; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Lesson lesson = (Lesson) o; return Objects.equals(startTime, lesson.startTime) && Objects.equals(duration, lesson.duration) && Objects.equals(courseId, lesson.courseId) && Objects.equals(topic, lesson.topic) && Objects.equals(task, lesson.task) && Objects.equals(teacher, lesson.teacher); } @Override public int hashCode() { return Objects.hash(super.hashCode(), startTime, duration, courseId, topic, teacher, task); } }
TriumGroup/ReCourse
src/main/java/by/triumgroup/recourse/entity/model/Lesson.java
Java
mit
3,402
package pl.pwr.hiervis.prefuse.histogram; /* * Adapted for HocusLocus by Ajish George <[email protected]> * from code by * @author <a href="http://jheer.org">jeffrey heer</a> * @author <a href="http://webfoot.com/ducky.home.html">Kaitlin Duck Sherwood</a> * * See HistogramFrame.java for details */ //TODO @@@ How can I prevent people from modifying the table? Can I mark //the columns as read-only? //I'm afraid of doing too much to prevent setting, as the constructor needs //to set things. Can I set things by doing super.set() etc? //TODO @@@ do I want to allow using predicates on this table? Probably... import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import pl.pwr.hiervis.prefuse.TableEx; import prefuse.data.Table; import prefuse.data.column.Column; import prefuse.data.parser.DoubleParser; import prefuse.data.parser.IntParser; import prefuse.data.parser.StringParser; import prefuse.data.tuple.TableTuple; import prefuse.data.tuple.TupleManager; import prefuse.data.util.RowManager; import prefuse.util.collections.CopyOnWriteArrayList; /** * <p> * A HistogramTable is a subclass of (@link prefuse.data.Table), but * that has been histogramized: one column of the original * (@link prefuse.data.Table) gets counted and slotted into a Table. * The first (@link prefuse.data.column.Column) is the ranges of the data, * with the value of the cell corresponding to the minimum value of the range. * The second column holds the number of each element in the original Table * that falls within the data range represented by the cell in column 1. * * NOTE: This only works with numeric and string fields. * It has not been tested with booleans or derived fields. * Booleans will probably be treated as strings. * * Known bug: See the HistogramFrame class comments about an axis bug. * * @author <a href="http://webfoot.com/ducky.home.html">Kaitlin Duck Sherwood</a> * @author <a href="http://jheer.org">jeffrey heer</a> */ public class HistogramTable extends TableEx { static final int DEFAULT_BIN_COUNT = 15; // m_bin{Min, Max} are the min and max of the data column BUT for Strings, min is 1 // and max is the number of unique strings. protected Hashtable<String, Double> m_binMin = new Hashtable<String, Double>(); protected Hashtable<String, Double> m_binMax = new Hashtable<String, Double>(); protected Hashtable<String, Integer> m_countMins = new Hashtable<String, Integer>(); protected Hashtable<String, Integer> m_countMaxes = new Hashtable<String, Integer>(); protected double m_binWidth; protected int m_binCount; public HistogramTable( Table aTable ) { this( aTable, DEFAULT_BIN_COUNT ); } /** * @param aTable * a Prefuse Table with data values (i.e. non-histogrammized) in it * @param aBinCount * how many bins the data's range should be split into */ public HistogramTable( Table aTable, int aBinCount ) { super(); if ( aBinCount <= 0 ) { throw new IllegalArgumentException( "Bin count must be a positive number." ); } String[] fieldNames = getFieldNames( aTable ); m_binCount = aBinCount; initializeHistogramTable( fieldNames, m_binCount ); for ( int fieldIndex = 0; fieldIndex < fieldNames.length; fieldIndex++ ) { String field = fieldNames[fieldIndex]; Column dataColumn = aTable.getColumn( field ); if ( dataColumn == null ) { throw new NullPointerException( "Column not found for field " + field ); } if ( dataColumn.canGetDouble() ) { initializeNumericColumn( field, dataColumn ); } else if ( dataColumn.canGetString() ) { initializeStringColumn( field, dataColumn ); } else { // Can't really histogrammize any other data in a sensible way, ignore it *shrug* continue; } } } /** * @param aTable * a HistogramTable or Prefuse Table * @return fieldNames a list of the names of the columns in the table. * Note that a HistogramTable will have all the same column names as * are in its (Prefuse Table) data table's, but will also have an additional * set of columns that have the counts. See getCountField(). * TODO It might be interesting to have a method getNonCountFieldNames which * strips out the count fields. */ public static String[] getFieldNames( Table aTable ) { int columnCount = aTable.getColumnCount(); String[] fieldNames = new String[columnCount]; for ( int columnIndex = 0; columnIndex < columnCount; columnIndex++ ) { fieldNames[columnIndex] = aTable.getColumnName( columnIndex ); } return fieldNames; } /** * @param field * the name of the dataColumn to histogrammize * @param dataColumn * the dataColumn to histogrammize * Note: I was unable to figure out how to get the name of a column * from a Column object. That seemed odd. -- KDS * Note that I don't actually have to pass in the dataColumn -- * I can get that from the field name -- but the dataColumn happens * to be handy, so why not. */ private void initializeStringColumn( String field, Column dataColumn ) { // create the two columns, one for bins and one for counts addColumn( field, String.class ); Column binColumn = getColumn( field ); binColumn.setParser( new StringParser() ); String countField = getCountField( field ); addColumn( countField, int.class ); Column countColumn = getColumn( countField ); countColumn.setParser( new IntParser() ); // min/max are kept around (i.e. are instance variables) because // they get used a lot when recalculating axes. m_countMins.put( field, 0 ); m_countMaxes.put( field, 0 ); // make a hash with the keys/counts (because that's easy); transfer // into the column later m_binWidth = 1; Hashtable<String, Integer> values = new Hashtable<String, Integer>(); int count = 0; String key; for ( int rowIndex = 0; rowIndex < dataColumn.getRowCount(); rowIndex++ ) { key = dataColumn.getString( rowIndex ); if ( null != values.get( key ) ) { count = values.get( key ); } else { // this is the first one count = 0; } values.put( key, ++count ); } // with all the values (keys) and their counts in a hash, it's easy to // figure out how many unique keys there are m_binMin.put( field, 0.0 ); m_binMax.put( field, (double)values.size() ); // It is quite possible for the number of bins to be different // than the number of unique ordinal values. If there are more // ordinal values than bins, just show the arbitrarily first // m_binCount ones; if there are fewer, pad the ends with null. int rowIndex = 0; Enumeration<String> keys = values.keys(); while ( keys.hasMoreElements() && rowIndex < m_binCount ) { key = (String)keys.nextElement(); { binColumn.setString( key, rowIndex ); countColumn.setInt( values.get( key ), rowIndex++ ); } } // insert dummy values if there are fewer unique strings than bins for ( int i = rowIndex; i < getRowCount(); i++ ) { binColumn.setString( "", i ); countColumn.setInt( 0, i ); } } /** * @param field * the name of the dataColumn to histogrammize * @param dataColumn * the dataColumn to histogrammize */ private void initializeNumericColumn( String field, Column dataColumn ) { addColumn( field, double.class ); getColumn( field ).setParser( new DoubleParser() ); String countField = getCountField( field ); addColumn( countField, int.class ); getColumn( countField ).setParser( new IntParser() ); initializeNumericBinInfo( field, dataColumn ); initializeNumericBinColumn( field ); initializeCountColumn( field, dataColumn ); } /** * @param field * the name of the dataColumn to histogrammize * @param dataColumn * the dataColumn to histogrammize */ private void initializeNumericBinInfo( String field, Column dataColumn ) { double[] minMax = new double[2]; minMax = getNumericColumnMinMax( dataColumn ); double minValue = minMax[0]; double maxValue = minMax[1]; m_binMax.put( field, maxValue ); m_binMin.put( field, minValue ); m_binWidth = ( 1 + maxValue - minValue ) / m_binCount; assert m_binWidth >= 0.0 : "m_binWidth < 0!"; } /** * Fill in the histogram table. * * @param fields * the names of all the fields * @param rowCount * the number of rows */ private void initializeHistogramTable( String[] fields, int rowCount ) { int columnCount = 2 * fields.length; m_listeners = new CopyOnWriteArrayList(); m_columns = new ArrayList( columnCount ); m_names = new ArrayList( columnCount ); m_rows = new RowManager( this ); m_entries = new HashMap( columnCount + 5 ); m_tuples = new TupleManager( this, null, TableTuple.class ); addRows( rowCount ); } /** * Initialize the bin column. The bin columns have information on * the range of values that the count columns have counts for. For * example, you can say "there are 17 elements between the value of * 2 and 14". 17 would be the value in the count field, and 2-14 * would be represented by the bin field. Note that the way that * bin fields are represented, the value in the bin field is the low * end of the range. In the example, the bin field would have a 2 * in it. * * @param field * the name of the dataColumn to histogrammize */ private void initializeNumericBinColumn( String field ) { double dataColumnMin = m_binMin.get( field ); for ( int binIndex = 0; binIndex < m_binCount; binIndex++ ) { set( binIndex, field, dataColumnMin + binIndex * m_binWidth ); } } /** * Initialize the column with the counts of elements in them. * * @param field * the name of the dataColumn to histogrammize * @param dataColumn * the column in the original (@link prefuse.data.Table) * to be histogramized. */ private void initializeCountColumn( String field, Column dataColumn ) { int binSlot; int currentCount; // separate var just for debugging ease String countField = getCountField( field ); // initialize everything to 0 before starting to count for ( int binIndex = 0; binIndex < m_binCount; binIndex++ ) { set( binIndex, countField, 0 ); } double dataColumnMin = m_binMin.get( field ); double cellValue; for ( int dataRowIndex = 0; dataRowIndex < dataColumn.getRowCount(); dataRowIndex++ ) { cellValue = dataColumn.getDouble( dataRowIndex ); binSlot = (int)( ( cellValue - dataColumnMin ) / m_binWidth ); currentCount = getInt( binSlot, countField ); setInt( binSlot, countField, currentCount + 1 ); } } public double getBinMin( String field ) { return m_binMin.get( field ); } public double getBinMax( String field ) { return m_binMax.get( field ); } public double getBinCount() { return m_binCount; } /** * @param aColumn * the column to get min/max of * @return min and max (in an array) of aColumn */ private double[] getNumericColumnMinMax( Column aColumn ) { double oldMin = aColumn.getDouble( 0 ); double oldMax = oldMin; double[] minMax = new double[2]; if ( aColumn.canGetDouble() ) { double currentValue; for ( int rowIndex = 1; rowIndex < aColumn.getRowCount(); rowIndex++ ) { currentValue = aColumn.getDouble( rowIndex ); oldMin = Math.min( oldMin, currentValue ); oldMax = Math.max( oldMax, currentValue ); } } minMax[0] = oldMin; minMax[1] = oldMax; return minMax; } /** * @param field * the name of the histogramColumn * @return the minimum and maximum values of the associated * count column in an array. */ private double[] getNumericColumnMinMax( String field ) { return getNumericColumnMinMax( getColumn( field ) ); } /** * @param field * the name of the histogramColumn * @return the minimum value of the associated count column * (In other words, if you ask for getCountMin("A"), you * will get the min of the column "A counts".) */ public double getCountMin( String field ) { String countField = getCountField( field ); double[] minMax = new double[2]; if ( null == m_countMaxes.get( countField ) ) { minMax = getNumericColumnMinMax( countField ); m_countMins.put( countField, (int)minMax[0] ); m_countMaxes.put( countField, (int)minMax[1] ); } return m_countMins.get( countField ); } /** * @param field * the name of the histogramColumn * @return the max value of the associated count column * (In other words, if you ask for getCountMin("A"), you * will get the max of the column "A counts".) */ public double getCountMax( String field ) { String countField = getCountField( field ); if ( null == m_countMaxes.get( countField ) ) { getCountMin( field ); // sets both } return m_countMaxes.get( countField ); } public static String getCountField( String field ) { return field + " count"; } @Override public void dispose() { super.dispose(); m_binMin.clear(); m_binMax.clear(); m_countMins.clear(); m_countMaxes.clear(); } }
kartoFlane/hiervis
src/pl/pwr/hiervis/prefuse/histogram/HistogramTable.java
Java
mit
13,306
/* * The MIT License (MIT) * * Copyright (c) 2011-2016 CraftyCreeper, minebot.net, oneill011990 * * 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 de.germanspacebuild.plugins.fasttravel.events; import de.germanspacebuild.plugins.fasttravel.data.FastTravelSign; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; /** * Created by oneill011990 on 04.03.2016 * for FastTravelReborn * * @author oneill011990 */ public class FastTravelEvent extends Event implements Cancellable { private static final HandlerList HANDLER_LIST = new HandlerList(); private boolean canceled; private Player player; private FastTravelSign sign; private int price; public FastTravelEvent(Player player, FastTravelSign sign) { this.player = player; this.sign = sign; } public FastTravelEvent(Player player, FastTravelSign sign, int price) { this.player = player; this.sign = sign; this.price = price; } public static HandlerList getHandlerList() { return HANDLER_LIST; } public Player getPlayer() { return player; } public FastTravelSign getSign() { return sign; } @Override public boolean isCancelled() { return canceled; } @Override public void setCancelled(boolean b) { this.canceled = b; } @Override public HandlerList getHandlers() { return HANDLER_LIST; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
oneill011990/FastTravelReborn
src/main/java/de/germanspacebuild/plugins/fasttravel/events/FastTravelEvent.java
Java
mit
2,687
/* * The MIT License (MIT) * * Copyright (c) 2016-2020, Hamdi Douss * * 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. */ /** * Points definitions. */ package com.jeometry.twod.point;
HDouss/jeometry
jeometry-api/src/main/java/com/jeometry/twod/point/package-info.java
Java
mit
1,214
package com.smcpartners.shape.shared.dto.common; import com.smcpartners.shape.shared.constants.UseCaseConstants; /** * Responsible:<br/> * 1. Returned from a use case * <p> * Created by johndestefano on 10/7/15. * <p> * Changes:<b/> */ public class UsecaseResponse extends RequestResponse { /** * Any exception thrown in the use case */ private Exception error; /** * Custom error message from a use case */ private String errMsg; private String responseCode; /** * Return object from a use case invocation */ private Object response; public UsecaseResponse() { } public Exception getError() { return error; } public void setError(Exception error) { this.error = error; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public boolean isErr() { if (error != null || errMsg != null || (this.getResponseCode() != null && UseCaseConstants.valueOf(this.getResponseCode()) != UseCaseConstants.OK_RESPONSE)) { return true; } return false; } public boolean isOk() { if (this.getResponseCode() != null && this.getResponseCode() != UseCaseConstants.OK_RESPONSE.getVal()) { return false; } else { return true; } } public String getResponseCode() { return responseCode; } public void setResponseCode(String responseCode) { this.responseCode = responseCode; } public Object getResponse() { return response; } public void setResponse(Object response) { this.response = response; } }
SMCPartners/shape-server
src/main/java/com/smcpartners/shape/shared/dto/common/UsecaseResponse.java
Java
mit
1,779
package tie.hackathon.travelguide; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.dd.processbutton.FlatButton; import com.fourmob.datetimepicker.date.DatePickerDialog; import com.sleepbot.datetimepicker.time.RadialPickerLayout; import com.sleepbot.datetimepicker.time.TimePickerDialog; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Objects; import Util.Constants; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnTextChanged; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Activity to add new trip */ public class AddNewTrip extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener,View.OnClickListener { private static final String DATEPICKER_TAG1 = "datepicker1"; private static final String DATEPICKER_TAG2 = "datepicker2"; private String nameyet; private String cityid = "2"; private String startdate; private String enddate; private String tripname; private String userid; private MaterialDialog dialog; private Handler mHandler; private SharedPreferences sharedPreferences; private DatePickerDialog datePickerDialog; @BindView(R.id.cityname) AutoCompleteTextView cityname; @BindView(R.id.sdate) FlatButton sdate; @BindView(R.id.edate) FlatButton edate; @BindView(R.id.ok) FlatButton ok; @BindView(R.id.tname) EditText tname; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_new_trip); ButterKnife.bind(this); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); userid = sharedPreferences.getString(Constants.USER_ID, "1"); mHandler = new Handler(Looper.getMainLooper()); cityname.setThreshold(1); final Calendar calendar = Calendar.getInstance(); datePickerDialog = DatePickerDialog.newInstance(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), isVibrate()); sdate.setOnClickListener(this); edate.setOnClickListener(this); ok.setOnClickListener(this); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @OnTextChanged(R.id.cityname) void onTextChanged(){ nameyet = cityname.getText().toString(); if (!nameyet.contains(" ")) { Log.e("name", nameyet + " "); tripAutoComplete(); // Calls API to autocomplete cityname } } @Override public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) { if (Objects.equals(datePickerDialog.getTag(), DATEPICKER_TAG1)) { Calendar calendar = new GregorianCalendar(year, month, day); startdate = Long.toString(calendar.getTimeInMillis() / 1000); } if (Objects.equals(datePickerDialog.getTag(), DATEPICKER_TAG2)) { Calendar calendar = new GregorianCalendar(year, month, day); enddate = Long.toString(calendar.getTimeInMillis() / 1000); } } @Override public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {} /** * Calls city name autocomplete API */ private void tripAutoComplete() { // to fetch city names String uri = Constants.apilink + "city/autocomplete.php?search=" + nameyet.trim(); Log.e("executing", uri + " "); //Set up client OkHttpClient client = new OkHttpClient(); //Execute request Request request = new Request.Builder() .url(uri) .build(); //Setup callback client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e("Request Failed", "Message : " + e.getMessage()); } @Override public void onResponse(Call call, final Response response) throws IOException { final String res = response.body().string(); mHandler.post(new Runnable() { @Override public void run() { JSONArray arr; final ArrayList names, ids; try { arr = new JSONArray(res); Log.e("RESPONSE : ", arr + " "); names = new ArrayList<>(); ids = new ArrayList<>(); for (int i = 0; i < arr.length(); i++) { try { names.add(arr.getJSONObject(i).getString("name")); ids.add(arr.getJSONObject(i).getString("id")); } catch (JSONException e) { e.printStackTrace(); Log.e("error ", " " + e.getMessage()); } } ArrayAdapter<String> dataAdapter = new ArrayAdapter<> (getApplicationContext(), R.layout.spinner_layout, names); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); cityname.setThreshold(1); cityname.setAdapter(dataAdapter); cityname.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { cityid = ids.get(arg2).toString(); } }); } catch (JSONException e) { e.printStackTrace(); Log.e("EXCEPTION : ", e.getMessage() + " "); } } }); } }); } /** * Calls API to add new trip */ private void addTrip() { // Show a dialog box dialog = new MaterialDialog.Builder(AddNewTrip.this) .title(R.string.app_name) .content("Please wait...") .progress(true, 0) .show(); String uri = Constants.apilink + "trip/add-trip.php?user=" + userid + "&title=" + tripname + "&start_time=" + startdate + "&city=" + cityid; Log.e("CALLING : ", uri); //Set up client OkHttpClient client = new OkHttpClient(); //Execute request Request request = new Request.Builder() .url(uri) .build(); //Setup callback client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e("Request Failed", "Message : " + e.getMessage()); } @Override public void onResponse(Call call, final Response response) throws IOException { mHandler.post(new Runnable() { @Override public void run() { Log.e("RESPONSE : ", "Done"); Toast.makeText(AddNewTrip.this, "Trip added", Toast.LENGTH_LONG).show(); dialog.dismiss(); } }); } }); } private boolean isVibrate() { return false; } private boolean isCloseOnSingleTapDay() { return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) finish(); return super.onOptionsItemSelected(item); } @Override public void onClick(View view) { switch (view.getId()){ // Set Start date case R.id.sdate : datePickerDialog.setVibrate(isVibrate()); datePickerDialog.setYearRange(1985, 2028); datePickerDialog.setCloseOnSingleTapDay(isCloseOnSingleTapDay()); datePickerDialog.show(getSupportFragmentManager(), DATEPICKER_TAG1); break; // Set end date case R.id.edate : datePickerDialog.setVibrate(isVibrate()); datePickerDialog.setYearRange(1985, 2028); datePickerDialog.setCloseOnSingleTapDay(isCloseOnSingleTapDay()); datePickerDialog.show(getSupportFragmentManager(), DATEPICKER_TAG2); break; // Add a new trip case R.id.ok : tripname = tname.getText().toString(); addTrip(); break; } } }
gugakatsi/Travel-Mate
Android/app/src/main/java/tie/hackathon/travelguide/AddNewTrip.java
Java
mit
9,982
// This is a generated file. Not intended for manual editing. package com.smcplugin.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.smcplugin.psi.SmcTypes.*; import com.smcplugin.psi.*; public class SmcPushStateNameElementImpl extends SmcNamedElementImpl implements SmcPushStateNameElement { public SmcPushStateNameElementImpl(ASTNode node) { super(node); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof SmcVisitor) ((SmcVisitor)visitor).visitPushStateNameElement(this); else super.accept(visitor); } @Override @NotNull public List<SmcComment> getCommentList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, SmcComment.class); } public PsiElement getNameIdentifier() { return SmcPsiImplUtil.getNameIdentifier(this); } }
menshele/smcplugin
gen/com/smcplugin/psi/impl/SmcPushStateNameElementImpl.java
Java
mit
999
package com.smcplugin.validation; import com.intellij.lang.annotation.Annotation; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.psi.PsiElement; import com.smcplugin.psi.SmcParameterType; import com.smcplugin.psi.SmcPsiUtil; import org.jetbrains.annotations.NotNull; import java.text.MessageFormat; /** * scmplugin * Created by lemen on 27.03.2016. */ public class SmcTypeIsAvailableAnnotator implements Annotator { private static final String TYPE_NOT_RESOLVED_MESSAGE = "Cannot resolve \"{0}\" type."; @Override public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { if (element instanceof SmcParameterType) { SmcParameterType type = (SmcParameterType) element; String name = type.getName(); PsiElement nameIdentifier = type.getNameIdentifier(); if (name == null || nameIdentifier == null) return; if (!SmcPsiUtil.isTypeAvailableFromSmc(type)) { Annotation errorAnnotation = holder.createErrorAnnotation(nameIdentifier, getMessage(name)); errorAnnotation.setTextAttributes(CodeInsightColors.WRONG_REFERENCES_ATTRIBUTES); } } } @NotNull private String getMessage(String name) { return MessageFormat.format(TYPE_NOT_RESOLVED_MESSAGE, name); } }
menshele/smcplugin
src/com/smcplugin/validation/SmcTypeIsAvailableAnnotator.java
Java
mit
1,475
package com.salil.futureapp.base.util; import java.util.List; public class FutureUtil { public static boolean isEmptyOrBlank(final String str) { return str == null || str.trim().isEmpty(); } @SuppressWarnings("rawtypes") public static boolean isListEmptyOrBlank(final List list) { return list == null || list.isEmpty(); } }
salilwalavalkar/futureapp-parent
futureapp-base/src/main/java/com/salil/futureapp/base/util/FutureUtil.java
Java
mit
338
package io.iansoft.blockchain.repository.search; import io.iansoft.blockchain.domain.Quote; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Spring Data Elasticsearch repository for the {@link Quote} entity. */ public interface QuoteSearchRepository extends ElasticsearchRepository<Quote, Long> { }
iansoftdev/all-blockchain
src/main/java/io/iansoft/blockchain/repository/search/QuoteSearchRepository.java
Java
mit
342
package gardncl.whobrokeitlast.services; import gardncl.whobrokeitlast.dao.DeveloperDao; import gardncl.whobrokeitlast.dao.ProjectDao; import gardncl.whobrokeitlast.models.Developer; import gardncl.whobrokeitlast.models.Project; import org.eclipse.egit.github.core.Repository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.NoSuchElementException; import java.util.Optional; @Service public class ProjectService { @Autowired private ProjectDao projectDao; @Autowired private DeveloperDao developerDao; @Autowired private GithubService githubService; public Project insertProject(String projectTitle, String owner) throws IOException { Optional<Long> id = githubService.getRepos(owner) .stream() .filter(x -> x.getName().equals(projectTitle)) .map(Repository::getId) .findFirst(); if (!id.isPresent()) throw new NoSuchElementException("Project "+projectTitle+" does not exist for user "+owner+"."); Developer projectOwner = developerDao.getByUserName(owner); if (projectOwner == null) throw new NoSuchElementException("User "+owner+" does not exist."); Project project = new Project(id.get(), projectTitle, projectOwner); return projectDao.save(project); } }
gardncl/whobrokeitlast
backend/src/main/java/gardncl/whobrokeitlast/services/ProjectService.java
Java
mit
1,447
/* * Copyright (c) 2011-2016, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.abst.sfm; import boofcv.alg.sfm.DepthSparse3D; import boofcv.struct.image.ImageGray; /** * Wrapper around {@link DepthSparse3D} for {@link ImagePixelTo3D}. * * @author Peter Abeles */ public class DepthSparse3D_to_PixelTo3D<T extends ImageGray> implements ImagePixelTo3D { DepthSparse3D<T> alg; public DepthSparse3D_to_PixelTo3D(DepthSparse3D<T> alg) { this.alg = alg; } @Override public boolean process(double x, double y) { return alg.process((int)x,(int)y); } @Override public double getX() { return alg.getWorldPt().x; } @Override public double getY() { return alg.getWorldPt().y; } @Override public double getZ() { return alg.getWorldPt().z; } @Override public double getW() { return 1; } }
bladestery/Sapphire
example_apps/AndroidStudioMinnie/sapphire/src/main/java/boofcv/abst/sfm/DepthSparse3D_to_PixelTo3D.java
Java
mit
1,436
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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.metamolecular.mx.test; import com.metamolecular.mx.io.Molecules; import com.metamolecular.mx.model.DefaultMolecule; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.query.DefaultAtomMatcher; import junit.framework.TestCase; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class DefaultAtomMatcherTest extends TestCase { private DefaultAtomMatcher matcher; private Molecule phenol; public DefaultAtomMatcherTest() { phenol = Molecules.createPhenol(); } @Override protected void setUp() throws Exception { matcher = new DefaultAtomMatcher(); } public void testItMatchesBasedOnAtomLabel() { matcher.setSymbol("O"); assertTrue(matcher.matches(phenol.getAtom(6))); } public void testItFailsMatchBasedOnAtomLabel() { matcher.setSymbol("O"); assertFalse(matcher.matches(phenol.getAtom(0))); } public void testItMatchesBasedOnMaximumNeighbors() { matcher.setMaximumNeighbors(1); assertTrue(matcher.matches(phenol.getAtom(6))); } public void testItFailsMatchBasedOnMaximumNeighbors() { matcher.setMaximumNeighbors(1); assertFalse(matcher.matches(phenol.getAtom(0))); } public void testItShouldCreateATemplateMatcherThatMatchesPhenolOxygen() { matcher = new DefaultAtomMatcher(phenol.getAtom(6)); assertTrue(matcher.matches(phenol.getAtom(6))); } public void testItShouldCreateATemplateMatcherThatMatchesPhenolQuatCarbon() { matcher = new DefaultAtomMatcher(phenol.getAtom(5)); assertTrue(matcher.matches(phenol.getAtom(5))); } public void testItDoesntMatchDoublyBlockedSecondaryCarbonToQuatCarbon() { Molecule neopentane = Molecules.createNeopentane(); matcher = new DefaultAtomMatcher(Molecules.createPropane().getAtom(1), 2); assertFalse(matcher.matches(neopentane.getAtom(0))); } private Molecule createEthylene() { Molecule result = new DefaultMolecule(); result.connect(result.addAtom("C"), result.addAtom("C"), 2); return result; } private Molecule createAcetylene() { Molecule result = createEthylene(); result.getBond(0).setType(3); return result; } private Molecule createAllene() { Molecule result = createEthylene(); result.connect(result.getAtom(1), result.addAtom("C"), 2); return result; } private Molecule createIsopropanol() { Molecule result = Molecules.createAcetone(); result.getBond(2).setType(1); return result; } }
metamolecular/mx
src/com/metamolecular/mx/test/DefaultAtomMatcherTest.java
Java
mit
3,760
package cz.chovanecm.pascal.truffle.nodes; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * Created by martin on 1/5/17. */ public abstract class ProcedureNode extends StatementNode { @Children final ExpressionNode[] parameters; public ProcedureNode(ExpressionNode[] parameters) { this.parameters = parameters; } public ExpressionNode[] getParameters() { return parameters; } /** * Create a new instance of the same type * * @param parameters * @return */ public ProcedureNode newInstance(ExpressionNode[] parameters) { try { Constructor<? extends ProcedureNode> constructor = getClass().getConstructor(new Class[]{ExpressionNode[].class}); return constructor.newInstance(new Object[]{parameters}); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { System.err.println("Really weird!!!!"); e.printStackTrace(); } return null; } }
chovanecm/pascal-truffle
pascal/src/main/java/cz/chovanecm/pascal/truffle/nodes/ProcedureNode.java
Java
mit
1,104
package cn.rieon.cordova; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; public class LaserScanner extends CordovaPlugin { /** * broadcaster receive */ private String SCANNER_RETURN_DATA = "com.se4500.onDecodeComplete"; /** * broadcaster start scan */ private String SCANNER_START_SCAN = "com.geomobile.se4500barcode"; /** * broadcaster stop scan */ private String SCANNER_STOP_SCAN = "com.geomobile.se4500barcode.poweroff"; private static final String LOG_TAG = "LaserReceiver"; private CallbackContext callbackContext = null; private BroadcastReceiver receiver = null; private String lastBarcode = null; /** * get activity * @return Activity */ private Activity getActivity(){ return this.cordova.getActivity(); } /** * cordova initialize * @param cordova * @param webView */ public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); IntentFilter iFilter = new IntentFilter(); /** * call scanner */ iFilter.addAction(SCANNER_RETURN_DATA); getActivity().registerReceiver(receiver, iFilter); if (receiver == null) { receiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(SCANNER_RETURN_DATA)) { String data = intent.getStringExtra("se4500"); resultHandler(data); } } }; } /** * register receiver */ getActivity().registerReceiver(receiver, iFilter); } /** * execute action * @param action The action to execute. * @param args The exec() arguments. * @param callbackContext The callback context used when calling back into JavaScript. * @return */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { this.callbackContext = callbackContext; if (action.equals("scan")) { startScan(); return true; } if (action.equals("receive")){ sendUpdate(lastBarcode,true); return true; } return false; } /** * stop scan and unregister receiver when destroy */ @Override public void onDestroy() { stopScan(); removeLaserScannerListener(); super.onDestroy(); } @Override public void onReset() { stopScan(); removeLaserScannerListener(); super.onReset(); } /** * start scan */ private void startScan() { Intent intent = new Intent(); intent.setAction(SCANNER_START_SCAN); getActivity().sendBroadcast(intent, null); } private void stopScan(){ Intent intent = new Intent(); intent.setAction(SCANNER_STOP_SCAN); getActivity().sendBroadcast(intent); } /** * Stop the receiver and set it to null. */ private void removeLaserScannerListener() { if (this.receiver != null) { try { getActivity().unregisterReceiver(this.receiver); this.receiver = null; } catch (Exception e) { Log.e(LOG_TAG, "Error unregistering LaserReceiver receiver: " + e.getMessage(), e); } } } private void resultHandler(String data){ sendUpdate(data,true); lastBarcode = data; } private void sendUpdate(String data, boolean keepCallback) { if (callbackContext != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, data); result.setKeepCallback(keepCallback); callbackContext.sendPluginResult(result); } } }
rieonke/cordova-plugin-laser-scanner
src/android/LaserScanner.java
Java
mit
4,458
/* * Copyright (C) 2013-2019 Timothy Baxendale * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ package tbax.baxshops.notification; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.jetbrains.annotations.NotNull; @Deprecated public interface DeprecatedNote extends ConfigurationSerializable { @NotNull Notification getNewNote(); @NotNull Class<? extends Notification> getNewNoteClass(); }
tbaxendale/baxshops
src/main/java/tbax/baxshops/notification/DeprecatedNote.java
Java
mit
1,135
package ui; import javafx.application.Platform; import javafx.scene.layout.Region; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import state.Change; import state.Observer; import state.State; // The rendered view is only interested in Html from the state public class RenderedView extends Region implements Observer { private State state; private State.PureState pureState; final WebView browser = new WebView(); final WebEngine webEngine = browser.getEngine(); /* * WebView objects must be created and accessed solely from the FX thread. */ public RenderedView(){ state = State.getInstance(); pureState = state.getPureState(); state.registerObserver(this); webEngine.load("file:///Users/j/Documents/workspace/react_java/html/start.html"); getChildren().add(browser); } @Override public void update(Change c) { switch(c){ case SELECTED_FILE: webEngine.loadContent(pureState.getHtml()); break; case HTML_GENERATED: { String html = pureState.getHtml(); Platform.runLater(new Runnable() { @Override public void run() { webEngine.loadContent(html); } }); break; } default: break; } } }
JonArnfred/react_component_editor
src/ui/RenderedView.java
Java
mit
1,252
/** * Copyright 2014 www.delight.im <[email protected]> * * 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 edu.cmu.cylab.starslinger.util; import android.content.Context; import android.graphics.Paint; import android.graphics.Typeface; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextPaint; import android.text.style.MetricAffectingSpan; /** * Emoji support for Android down to API level 8 (Android 2.2) * <p> * Usage: CharSequence myCharSequence = AndroidEmoji.ensure(myString); */ public class AndroidEmoji { /** * Span to set on TextView instances in order to have a custom font for * single parts of a text * * <pre> * SpannableStringBuilder ssb = new SpannableStringBuilder(myStringToShow); * ssb.setSpan(new CustomTypefaceSpan(myTypeface), myFromPosition, myToPosition, * Spanned.SPAN_EXCLUSIVE_INCLUSIVE); * myTextView.setText(ssb); * </pre> * * @author Benjamin Dobell */ private static class CustomTypefaceSpan extends MetricAffectingSpan { private final Typeface mTypeface; public CustomTypefaceSpan(final Typeface typeface) { mTypeface = typeface; } @Override public void updateDrawState(final TextPaint drawState) { apply(drawState); } @Override public void updateMeasureState(final TextPaint paint) { apply(paint); } private void apply(final Paint paint) { final Typeface oldTypeface = paint.getTypeface(); final int oldStyle = oldTypeface != null ? oldTypeface.getStyle() : 0; final int fakeStyle = oldStyle & ~mTypeface.getStyle(); if ((fakeStyle & Typeface.BOLD) != 0) { paint.setFakeBoldText(true); } if ((fakeStyle & Typeface.ITALIC) != 0) { paint.setTextSkewX(-0.25f); } paint.setTypeface(mTypeface); } } /** * Manages the reference to the emoji font * <p> * Usage: FontProvider.getInstance(context).getFontEmoji() */ private static class FontProvider { private static final String PATH_EMOJI = "fonts/AndroidEmoji.ttf"; private static FontProvider mInstance; private Typeface mFontEmoji; public static FontProvider getInstance(Context context) { if (mInstance == null) { mInstance = new FontProvider(context.getApplicationContext()); } return mInstance; } private FontProvider(Context context) { mFontEmoji = Typeface.createFromAsset(context.getAssets(), PATH_EMOJI); } public Typeface getFontEmoji() { return mFontEmoji; } } /** * Compares the given code point against 722 emoji code points from Unicode * 6.3 * <p> * Reference: EmojiSources.txt by Unicode, Inc. * (http://www.unicode.org/Public/UNIDATA/EmojiSources.txt) * * @param codePoint the code point to check * @return whether the code point represents an emoji or not */ private static boolean isEmoji(int codePoint) { return // Digits and number sign on keys (actually defined in concatenated // form) // codePoint == 0x0023 0x20E3 || // codePoint == 0x0030 0x20E3 || // codePoint == 0x0031 0x20E3 || // codePoint == 0x0032 0x20E3 || // codePoint == 0x0033 0x20E3 || // codePoint == 0x0034 0x20E3 || // codePoint == 0x0035 0x20E3 || // codePoint == 0x0036 0x20E3 || // codePoint == 0x0037 0x20E3 || // codePoint == 0x0038 0x20E3 || // codePoint == 0x0039 0x20E3 || codePoint == 0x00A9 || codePoint == 0x00AE || codePoint == 0x2002 || codePoint == 0x2003 || codePoint == 0x2005 || codePoint == 0x203C || codePoint == 0x2049 || codePoint == 0x2122 || codePoint == 0x2139 || codePoint == 0x2194 || codePoint == 0x2195 || codePoint == 0x2196 || codePoint == 0x2197 || codePoint == 0x2198 || codePoint == 0x2199 || codePoint == 0x21A9 || codePoint == 0x21AA || codePoint == 0x231A || codePoint == 0x231B || codePoint == 0x23E9 || codePoint == 0x23EA || codePoint == 0x23EB || codePoint == 0x23EC || codePoint == 0x23F0 || codePoint == 0x23F3 || codePoint == 0x24C2 || codePoint == 0x25AA || codePoint == 0x25AB || codePoint == 0x25B6 || codePoint == 0x25C0 || codePoint == 0x25FB || codePoint == 0x25FC || codePoint == 0x25FD || codePoint == 0x25FE || codePoint == 0x2600 || codePoint == 0x2601 || codePoint == 0x260E || codePoint == 0x2611 || codePoint == 0x2614 || codePoint == 0x2615 || codePoint == 0x261D || codePoint == 0x263A || codePoint == 0x2648 || codePoint == 0x2649 || codePoint == 0x264A || codePoint == 0x264B || codePoint == 0x264C || codePoint == 0x264D || codePoint == 0x264E || codePoint == 0x264F || codePoint == 0x2650 || codePoint == 0x2651 || codePoint == 0x2652 || codePoint == 0x2653 || codePoint == 0x2660 || codePoint == 0x2663 || codePoint == 0x2665 || codePoint == 0x2666 || codePoint == 0x2668 || codePoint == 0x267B || codePoint == 0x267F || codePoint == 0x2693 || codePoint == 0x26A0 || codePoint == 0x26A1 || codePoint == 0x26AA || codePoint == 0x26AB || codePoint == 0x26BD || codePoint == 0x26BE || codePoint == 0x26C4 || codePoint == 0x26C5 || codePoint == 0x26CE || codePoint == 0x26D4 || codePoint == 0x26EA || codePoint == 0x26F2 || codePoint == 0x26F3 || codePoint == 0x26F5 || codePoint == 0x26FA || codePoint == 0x26FD || codePoint == 0x2702 || codePoint == 0x2705 || codePoint == 0x2708 || codePoint == 0x2709 || codePoint == 0x270A || codePoint == 0x270B || codePoint == 0x270C || codePoint == 0x270F || codePoint == 0x2712 || codePoint == 0x2714 || codePoint == 0x2716 || codePoint == 0x2728 || codePoint == 0x2733 || codePoint == 0x2734 || codePoint == 0x2744 || codePoint == 0x2747 || codePoint == 0x274C || codePoint == 0x274E || codePoint == 0x2753 || codePoint == 0x2754 || codePoint == 0x2755 || codePoint == 0x2757 || codePoint == 0x2764 || codePoint == 0x2795 || codePoint == 0x2796 || codePoint == 0x2797 || codePoint == 0x27A1 || codePoint == 0x27B0 || codePoint == 0x2934 || codePoint == 0x2935 || codePoint == 0x2B05 || codePoint == 0x2B06 || codePoint == 0x2B07 || codePoint == 0x2B1B || codePoint == 0x2B1C || codePoint == 0x2B50 || codePoint == 0x2B55 || codePoint == 0x3030 || codePoint == 0x303D || codePoint == 0x3297 || codePoint == 0x3299 || codePoint == 0x1F004 || codePoint == 0x1F0CF || codePoint == 0x1F170 || codePoint == 0x1F171 || codePoint == 0x1F17E || codePoint == 0x1F17F || codePoint == 0x1F18E || codePoint == 0x1F191 || codePoint == 0x1F192 || codePoint == 0x1F193 || codePoint == 0x1F194 || codePoint == 0x1F195 || codePoint == 0x1F196 || codePoint == 0x1F197 || codePoint == 0x1F198 || codePoint == 0x1F199 || codePoint == 0x1F19A || // Regional Indicator Symbols (actually defined in concatenated // form) (codePoint == 0x1F1E8 || codePoint == 0x1F1F3) || (codePoint == 0x1F1E9 || codePoint == 0x1F1EA) || (codePoint == 0x1F1EA || codePoint == 0x1F1F8) || (codePoint == 0x1F1EB || codePoint == 0x1F1F7) || (codePoint == 0x1F1EC || codePoint == 0x1F1E7) || (codePoint == 0x1F1EE || codePoint == 0x1F1F9) || (codePoint == 0x1F1EF || codePoint == 0x1F1F5) || (codePoint == 0x1F1F0 || codePoint == 0x1F1F7) || (codePoint == 0x1F1F7 || codePoint == 0x1F1FA) || (codePoint == 0x1F1FA || codePoint == 0x1F1F8) || codePoint == 0x1F201 || codePoint == 0x1F202 || codePoint == 0x1F21A || codePoint == 0x1F22F || codePoint == 0x1F232 || codePoint == 0x1F233 || codePoint == 0x1F234 || codePoint == 0x1F235 || codePoint == 0x1F236 || codePoint == 0x1F237 || codePoint == 0x1F238 || codePoint == 0x1F239 || codePoint == 0x1F23A || codePoint == 0x1F250 || codePoint == 0x1F251 || codePoint == 0x1F300 || codePoint == 0x1F301 || codePoint == 0x1F302 || codePoint == 0x1F303 || codePoint == 0x1F304 || codePoint == 0x1F305 || codePoint == 0x1F306 || codePoint == 0x1F307 || codePoint == 0x1F308 || codePoint == 0x1F309 || codePoint == 0x1F30A || codePoint == 0x1F30B || codePoint == 0x1F30C || codePoint == 0x1F30F || codePoint == 0x1F311 || codePoint == 0x1F313 || codePoint == 0x1F314 || codePoint == 0x1F315 || codePoint == 0x1F319 || codePoint == 0x1F31B || codePoint == 0x1F31F || codePoint == 0x1F320 || codePoint == 0x1F330 || codePoint == 0x1F331 || codePoint == 0x1F334 || codePoint == 0x1F335 || codePoint == 0x1F337 || codePoint == 0x1F338 || codePoint == 0x1F339 || codePoint == 0x1F33A || codePoint == 0x1F33B || codePoint == 0x1F33C || codePoint == 0x1F33D || codePoint == 0x1F33E || codePoint == 0x1F33F || codePoint == 0x1F340 || codePoint == 0x1F341 || codePoint == 0x1F342 || codePoint == 0x1F343 || codePoint == 0x1F344 || codePoint == 0x1F345 || codePoint == 0x1F346 || codePoint == 0x1F347 || codePoint == 0x1F348 || codePoint == 0x1F349 || codePoint == 0x1F34A || codePoint == 0x1F34C || codePoint == 0x1F34D || codePoint == 0x1F34E || codePoint == 0x1F34F || codePoint == 0x1F351 || codePoint == 0x1F352 || codePoint == 0x1F353 || codePoint == 0x1F354 || codePoint == 0x1F355 || codePoint == 0x1F356 || codePoint == 0x1F357 || codePoint == 0x1F358 || codePoint == 0x1F359 || codePoint == 0x1F35A || codePoint == 0x1F35B || codePoint == 0x1F35C || codePoint == 0x1F35D || codePoint == 0x1F35E || codePoint == 0x1F35F || codePoint == 0x1F360 || codePoint == 0x1F361 || codePoint == 0x1F362 || codePoint == 0x1F363 || codePoint == 0x1F364 || codePoint == 0x1F365 || codePoint == 0x1F366 || codePoint == 0x1F367 || codePoint == 0x1F368 || codePoint == 0x1F369 || codePoint == 0x1F36A || codePoint == 0x1F36B || codePoint == 0x1F36C || codePoint == 0x1F36D || codePoint == 0x1F36E || codePoint == 0x1F36F || codePoint == 0x1F370 || codePoint == 0x1F371 || codePoint == 0x1F372 || codePoint == 0x1F373 || codePoint == 0x1F374 || codePoint == 0x1F375 || codePoint == 0x1F376 || codePoint == 0x1F377 || codePoint == 0x1F378 || codePoint == 0x1F379 || codePoint == 0x1F37A || codePoint == 0x1F37B || codePoint == 0x1F380 || codePoint == 0x1F381 || codePoint == 0x1F382 || codePoint == 0x1F383 || codePoint == 0x1F384 || codePoint == 0x1F385 || codePoint == 0x1F386 || codePoint == 0x1F387 || codePoint == 0x1F388 || codePoint == 0x1F389 || codePoint == 0x1F38A || codePoint == 0x1F38B || codePoint == 0x1F38C || codePoint == 0x1F38D || codePoint == 0x1F38E || codePoint == 0x1F38F || codePoint == 0x1F390 || codePoint == 0x1F391 || codePoint == 0x1F392 || codePoint == 0x1F393 || codePoint == 0x1F3A0 || codePoint == 0x1F3A1 || codePoint == 0x1F3A2 || codePoint == 0x1F3A3 || codePoint == 0x1F3A4 || codePoint == 0x1F3A5 || codePoint == 0x1F3A6 || codePoint == 0x1F3A7 || codePoint == 0x1F3A8 || codePoint == 0x1F3A9 || codePoint == 0x1F3AA || codePoint == 0x1F3AB || codePoint == 0x1F3AC || codePoint == 0x1F3AD || codePoint == 0x1F3AE || codePoint == 0x1F3AF || codePoint == 0x1F3B0 || codePoint == 0x1F3B1 || codePoint == 0x1F3B2 || codePoint == 0x1F3B3 || codePoint == 0x1F3B4 || codePoint == 0x1F3B5 || codePoint == 0x1F3B6 || codePoint == 0x1F3B7 || codePoint == 0x1F3B8 || codePoint == 0x1F3B9 || codePoint == 0x1F3BA || codePoint == 0x1F3BB || codePoint == 0x1F3BC || codePoint == 0x1F3BD || codePoint == 0x1F3BE || codePoint == 0x1F3BF || codePoint == 0x1F3C0 || codePoint == 0x1F3C1 || codePoint == 0x1F3C2 || codePoint == 0x1F3C3 || codePoint == 0x1F3C4 || codePoint == 0x1F3C6 || codePoint == 0x1F3C8 || codePoint == 0x1F3CA || codePoint == 0x1F3E0 || codePoint == 0x1F3E1 || codePoint == 0x1F3E2 || codePoint == 0x1F3E3 || codePoint == 0x1F3E5 || codePoint == 0x1F3E6 || codePoint == 0x1F3E7 || codePoint == 0x1F3E8 || codePoint == 0x1F3E9 || codePoint == 0x1F3EA || codePoint == 0x1F3EB || codePoint == 0x1F3EC || codePoint == 0x1F3ED || codePoint == 0x1F3EE || codePoint == 0x1F3EF || codePoint == 0x1F3F0 || codePoint == 0x1F40C || codePoint == 0x1F40D || codePoint == 0x1F40E || codePoint == 0x1F411 || codePoint == 0x1F412 || codePoint == 0x1F414 || codePoint == 0x1F417 || codePoint == 0x1F418 || codePoint == 0x1F419 || codePoint == 0x1F41A || codePoint == 0x1F41B || codePoint == 0x1F41C || codePoint == 0x1F41D || codePoint == 0x1F41E || codePoint == 0x1F41F || codePoint == 0x1F420 || codePoint == 0x1F421 || codePoint == 0x1F422 || codePoint == 0x1F423 || codePoint == 0x1F424 || codePoint == 0x1F425 || codePoint == 0x1F426 || codePoint == 0x1F427 || codePoint == 0x1F428 || codePoint == 0x1F429 || codePoint == 0x1F42B || codePoint == 0x1F42C || codePoint == 0x1F42D || codePoint == 0x1F42E || codePoint == 0x1F42F || codePoint == 0x1F430 || codePoint == 0x1F431 || codePoint == 0x1F432 || codePoint == 0x1F433 || codePoint == 0x1F434 || codePoint == 0x1F435 || codePoint == 0x1F436 || codePoint == 0x1F437 || codePoint == 0x1F438 || codePoint == 0x1F439 || codePoint == 0x1F43A || codePoint == 0x1F43B || codePoint == 0x1F43C || codePoint == 0x1F43D || codePoint == 0x1F43E || codePoint == 0x1F440 || codePoint == 0x1F442 || codePoint == 0x1F443 || codePoint == 0x1F444 || codePoint == 0x1F445 || codePoint == 0x1F446 || codePoint == 0x1F447 || codePoint == 0x1F448 || codePoint == 0x1F449 || codePoint == 0x1F44A || codePoint == 0x1F44B || codePoint == 0x1F44C || codePoint == 0x1F44D || codePoint == 0x1F44E || codePoint == 0x1F44F || codePoint == 0x1F450 || codePoint == 0x1F451 || codePoint == 0x1F452 || codePoint == 0x1F453 || codePoint == 0x1F454 || codePoint == 0x1F455 || codePoint == 0x1F456 || codePoint == 0x1F457 || codePoint == 0x1F458 || codePoint == 0x1F459 || codePoint == 0x1F45A || codePoint == 0x1F45B || codePoint == 0x1F45C || codePoint == 0x1F45D || codePoint == 0x1F45E || codePoint == 0x1F45F || codePoint == 0x1F460 || codePoint == 0x1F461 || codePoint == 0x1F462 || codePoint == 0x1F463 || codePoint == 0x1F464 || codePoint == 0x1F466 || codePoint == 0x1F467 || codePoint == 0x1F468 || codePoint == 0x1F469 || codePoint == 0x1F46A || codePoint == 0x1F46B || codePoint == 0x1F46E || codePoint == 0x1F46F || codePoint == 0x1F470 || codePoint == 0x1F471 || codePoint == 0x1F472 || codePoint == 0x1F473 || codePoint == 0x1F474 || codePoint == 0x1F475 || codePoint == 0x1F476 || codePoint == 0x1F477 || codePoint == 0x1F478 || codePoint == 0x1F479 || codePoint == 0x1F47A || codePoint == 0x1F47B || codePoint == 0x1F47C || codePoint == 0x1F47D || codePoint == 0x1F47E || codePoint == 0x1F47F || codePoint == 0x1F480 || codePoint == 0x1F481 || codePoint == 0x1F482 || codePoint == 0x1F483 || codePoint == 0x1F484 || codePoint == 0x1F485 || codePoint == 0x1F486 || codePoint == 0x1F487 || codePoint == 0x1F488 || codePoint == 0x1F489 || codePoint == 0x1F48A || codePoint == 0x1F48B || codePoint == 0x1F48C || codePoint == 0x1F48D || codePoint == 0x1F48E || codePoint == 0x1F48F || codePoint == 0x1F490 || codePoint == 0x1F491 || codePoint == 0x1F492 || codePoint == 0x1F493 || codePoint == 0x1F494 || codePoint == 0x1F495 || codePoint == 0x1F496 || codePoint == 0x1F497 || codePoint == 0x1F498 || codePoint == 0x1F499 || codePoint == 0x1F49A || codePoint == 0x1F49B || codePoint == 0x1F49C || codePoint == 0x1F49D || codePoint == 0x1F49E || codePoint == 0x1F49F || codePoint == 0x1F4A0 || codePoint == 0x1F4A1 || codePoint == 0x1F4A2 || codePoint == 0x1F4A3 || codePoint == 0x1F4A4 || codePoint == 0x1F4A5 || codePoint == 0x1F4A6 || codePoint == 0x1F4A7 || codePoint == 0x1F4A8 || codePoint == 0x1F4A9 || codePoint == 0x1F4AA || codePoint == 0x1F4AB || codePoint == 0x1F4AC || codePoint == 0x1F4AE || codePoint == 0x1F4AF || codePoint == 0x1F4B0 || codePoint == 0x1F4B1 || codePoint == 0x1F4B2 || codePoint == 0x1F4B3 || codePoint == 0x1F4B4 || codePoint == 0x1F4B5 || codePoint == 0x1F4B8 || codePoint == 0x1F4B9 || codePoint == 0x1F4BA || codePoint == 0x1F4BB || codePoint == 0x1F4BC || codePoint == 0x1F4BD || codePoint == 0x1F4BE || codePoint == 0x1F4BF || codePoint == 0x1F4C0 || codePoint == 0x1F4C1 || codePoint == 0x1F4C2 || codePoint == 0x1F4C3 || codePoint == 0x1F4C4 || codePoint == 0x1F4C5 || codePoint == 0x1F4C6 || codePoint == 0x1F4C7 || codePoint == 0x1F4C8 || codePoint == 0x1F4C9 || codePoint == 0x1F4CA || codePoint == 0x1F4CB || codePoint == 0x1F4CC || codePoint == 0x1F4CD || codePoint == 0x1F4CE || codePoint == 0x1F4CF || codePoint == 0x1F4D0 || codePoint == 0x1F4D1 || codePoint == 0x1F4D2 || codePoint == 0x1F4D3 || codePoint == 0x1F4D4 || codePoint == 0x1F4D5 || codePoint == 0x1F4D6 || codePoint == 0x1F4D7 || codePoint == 0x1F4D8 || codePoint == 0x1F4D9 || codePoint == 0x1F4DA || codePoint == 0x1F4DB || codePoint == 0x1F4DC || codePoint == 0x1F4DD || codePoint == 0x1F4DE || codePoint == 0x1F4DF || codePoint == 0x1F4E0 || codePoint == 0x1F4E1 || codePoint == 0x1F4E2 || codePoint == 0x1F4E3 || codePoint == 0x1F4E4 || codePoint == 0x1F4E5 || codePoint == 0x1F4E6 || codePoint == 0x1F4E7 || codePoint == 0x1F4E8 || codePoint == 0x1F4E9 || codePoint == 0x1F4EA || codePoint == 0x1F4EB || codePoint == 0x1F4EE || codePoint == 0x1F4F0 || codePoint == 0x1F4F1 || codePoint == 0x1F4F2 || codePoint == 0x1F4F3 || codePoint == 0x1F4F4 || codePoint == 0x1F4F6 || codePoint == 0x1F4F7 || codePoint == 0x1F4F9 || codePoint == 0x1F4FA || codePoint == 0x1F4FB || codePoint == 0x1F4FC || codePoint == 0x1F503 || codePoint == 0x1F50A || codePoint == 0x1F50B || codePoint == 0x1F50C || codePoint == 0x1F50D || codePoint == 0x1F50E || codePoint == 0x1F50F || codePoint == 0x1F510 || codePoint == 0x1F511 || codePoint == 0x1F512 || codePoint == 0x1F513 || codePoint == 0x1F514 || codePoint == 0x1F516 || codePoint == 0x1F517 || codePoint == 0x1F518 || codePoint == 0x1F519 || codePoint == 0x1F51A || codePoint == 0x1F51B || codePoint == 0x1F51C || codePoint == 0x1F51D || codePoint == 0x1F51E || codePoint == 0x1F51F || codePoint == 0x1F520 || codePoint == 0x1F521 || codePoint == 0x1F522 || codePoint == 0x1F523 || codePoint == 0x1F524 || codePoint == 0x1F525 || codePoint == 0x1F526 || codePoint == 0x1F527 || codePoint == 0x1F528 || codePoint == 0x1F529 || codePoint == 0x1F52A || codePoint == 0x1F52B || codePoint == 0x1F52E || codePoint == 0x1F52F || codePoint == 0x1F530 || codePoint == 0x1F531 || codePoint == 0x1F532 || codePoint == 0x1F533 || codePoint == 0x1F534 || codePoint == 0x1F535 || codePoint == 0x1F536 || codePoint == 0x1F537 || codePoint == 0x1F538 || codePoint == 0x1F539 || codePoint == 0x1F53A || codePoint == 0x1F53B || codePoint == 0x1F53C || codePoint == 0x1F53D || codePoint == 0x1F550 || codePoint == 0x1F551 || codePoint == 0x1F552 || codePoint == 0x1F553 || codePoint == 0x1F554 || codePoint == 0x1F555 || codePoint == 0x1F556 || codePoint == 0x1F557 || codePoint == 0x1F558 || codePoint == 0x1F559 || codePoint == 0x1F55A || codePoint == 0x1F55B || codePoint == 0x1F5FB || codePoint == 0x1F5FC || codePoint == 0x1F5FD || codePoint == 0x1F5FE || codePoint == 0x1F5FF || codePoint == 0x1F601 || codePoint == 0x1F602 || codePoint == 0x1F603 || codePoint == 0x1F604 || codePoint == 0x1F605 || codePoint == 0x1F606 || codePoint == 0x1F609 || codePoint == 0x1F60A || codePoint == 0x1F60B || codePoint == 0x1F60C || codePoint == 0x1F60D || codePoint == 0x1F60F || codePoint == 0x1F612 || codePoint == 0x1F613 || codePoint == 0x1F614 || codePoint == 0x1F616 || codePoint == 0x1F618 || codePoint == 0x1F61A || codePoint == 0x1F61C || codePoint == 0x1F61D || codePoint == 0x1F61E || codePoint == 0x1F620 || codePoint == 0x1F621 || codePoint == 0x1F622 || codePoint == 0x1F623 || codePoint == 0x1F624 || codePoint == 0x1F625 || codePoint == 0x1F628 || codePoint == 0x1F629 || codePoint == 0x1F62A || codePoint == 0x1F62B || codePoint == 0x1F62D || codePoint == 0x1F630 || codePoint == 0x1F631 || codePoint == 0x1F632 || codePoint == 0x1F633 || codePoint == 0x1F635 || codePoint == 0x1F637 || codePoint == 0x1F638 || codePoint == 0x1F639 || codePoint == 0x1F63A || codePoint == 0x1F63B || codePoint == 0x1F63C || codePoint == 0x1F63D || codePoint == 0x1F63E || codePoint == 0x1F63F || codePoint == 0x1F640 || codePoint == 0x1F645 || codePoint == 0x1F646 || codePoint == 0x1F647 || codePoint == 0x1F648 || codePoint == 0x1F649 || codePoint == 0x1F64A || codePoint == 0x1F64B || codePoint == 0x1F64C || codePoint == 0x1F64D || codePoint == 0x1F64E || codePoint == 0x1F64F || codePoint == 0x1F680 || codePoint == 0x1F683 || codePoint == 0x1F684 || codePoint == 0x1F685 || codePoint == 0x1F687 || codePoint == 0x1F689 || codePoint == 0x1F68C || codePoint == 0x1F68F || codePoint == 0x1F691 || codePoint == 0x1F692 || codePoint == 0x1F693 || codePoint == 0x1F695 || codePoint == 0x1F697 || codePoint == 0x1F699 || codePoint == 0x1F69A || codePoint == 0x1F6A2 || codePoint == 0x1F6A4 || codePoint == 0x1F6A5 || codePoint == 0x1F6A7 || codePoint == 0x1F6A8 || codePoint == 0x1F6A9 || codePoint == 0x1F6AA || codePoint == 0x1F6AB || codePoint == 0x1F6AC || codePoint == 0x1F6AD || codePoint == 0x1F6B2 || codePoint == 0x1F6B6 || codePoint == 0x1F6B9 || codePoint == 0x1F6BA || codePoint == 0x1F6BB || codePoint == 0x1F6BC || codePoint == 0x1F6BD || codePoint == 0x1F6BE || codePoint == 0x1F6C0; } /** * Ensures that all emoji in the given string will be displayed correctly by * modifying the font for single symbols * * @param input the string to guarantee displayable emoji for * @param context the context to get the FontProvider instance from * @return the string with adjusted fonts as a CharSequence */ public static CharSequence ensure(String input, final Context context) { // if Android version is above 4.1.1 if (android.os.Build.VERSION.SDK_INT >= 17) { // return the text unchanged as emoji support is built-in already return input; } // if the input is null if (input == null) { // just return the input unchanged as it cannot be processed return input; } // extract the single chars that will be operated on final char[] chars = input.toCharArray(); // create a SpannableStringBuilder instance where the font ranges will // be set for emoji characters final SpannableStringBuilder ssb = new SpannableStringBuilder(input); int codePoint; boolean isSurrogatePair; // check every char in the input text for (int i = 0; i < chars.length; i++) { // if the char is a leading part of a surrogate pair (Unicode) if (Character.isHighSurrogate(chars[i])) { // just ignore it and wait for the trailing part continue; } // if the char is a trailing part of a surrogate pair (Unicode) else if (Character.isLowSurrogate(chars[i])) { // if the char and its predecessor are indeed a valid surrogate // pair if (i > 0 && Character.isSurrogatePair(chars[i - 1], chars[i])) { // get the Unicode code point for the surrogate pair codePoint = Character.toCodePoint(chars[i - 1], chars[i]); // remember that we have a surrogate pair here (which counts // as two characters) isSurrogatePair = true; } // if the char and its predecessor are not actually a valid // surrogate pair else { // just ignore it continue; } } // if the char is not part of a surrogate pair, i.e. a simple char // from the BMP else { // get the Unicode code point by simply casting the char to int codePoint = chars[i]; // remember that we have a BMP symbol here (which counts as a // single character) isSurrogatePair = false; } // if the detected code point is a known emoji if (isEmoji(codePoint)) { // change the font for this symbol (two characters if surrogate // pair) to the emoji font ssb.setSpan( new CustomTypefaceSpan(FontProvider.getInstance(context).getFontEmoji()), isSurrogatePair ? i - 1 : i, i + 1, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } } // return the SpannableStringBuilder with adjusted fonts (implements // CharSequence) return ssb; } }
SafeSlingerProject/SafeSlinger-Android
safeslinger-messenger/src/edu/cmu/cylab/starslinger/util/AndroidEmoji.java
Java
mit
30,418
/* * The MIT License * * Copyright 2016 Isaac Aymerich <[email protected]>. * * 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.github.segator.scaleway.api.entity; /** * * @author Isaac Aymerich <[email protected]> */ public class ScalewayResponseError { private String message; private String type; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return "ScalewayResponseError{" + "message=" + message + ", type=" + type + '}'; } }
segator/scaleway-sdk
src/main/java/com/github/segator/scaleway/api/entity/ScalewayResponseError.java
Java
mit
1,791
package io.github.satoshinm.WebSandboxMC.bridge; import io.github.satoshinm.WebSandboxMC.Settings; import io.github.satoshinm.WebSandboxMC.ws.WebSocketServerThread; import io.netty.buffer.*; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.Sign; import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Directional; import org.bukkit.block.data.Lightable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.zip.DeflaterOutputStream; /** * Bridges blocks in the world, translates between coordinate systems */ public class BlockBridge { public WebSocketServerThread webSocketServerThread; private final int x_center, y_center, z_center, y_offset; public final int radius; public final World world; public Location spawnLocation; private boolean allowBreakPlaceBlocks; private boolean allowSigns; private boolean seeTime; private Map<Material, Integer> blocksToWeb; private int blocksToWebMissing; // unknown/unsupported becomes cloud, if key missing private boolean warnMissing; private List<Material> unbreakableBlocks; private String textureURL; private boolean creativeMode; public BlockBridge(WebSocketServerThread webSocketServerThread, Settings settings) { this.webSocketServerThread = webSocketServerThread; this.radius = settings.radius; this.y_offset = settings.y_offset; if (settings.world == null || "".equals(settings.world)) { this.world = Bukkit.getWorlds().get(0); } else { this.world = Bukkit.getWorld(settings.world); } if (this.world == null) { throw new IllegalArgumentException("World not found: " + settings.world); } if (settings.x_center == 0 && settings.y_center == 0 && settings.z_center == 0) { Location spawn = this.world.getSpawnLocation(); this.x_center = spawn.getBlockX(); this.y_center = spawn.getBlockY(); this.z_center = spawn.getBlockZ(); } else { this.x_center = settings.x_center; this.y_center = settings.y_center; this.z_center = settings.z_center; } // TODO: configurable spawn within range of sandbox, right now, it is the center of the sandbox this.spawnLocation = new Location(this.world, this.x_center, this.y_center, this.z_center); this.allowBreakPlaceBlocks = settings.allowBreakPlaceBlocks; this.allowSigns = settings.allowSigns; this.seeTime = settings.seeTime; this.blocksToWeb = new HashMap<Material, Integer>(); this.blocksToWebMissing = 16; // unknown/unsupported becomes cloud // Overrides from config, if any for (String materialString : settings.blocksToWebOverride.keySet()) { Object object = settings.blocksToWebOverride.get(materialString); int n = 0; if (object instanceof String) { n = Integer.parseInt((String) object); } else if (object instanceof Integer) { n = (Integer) object; } else { webSocketServerThread.log(Level.WARNING, "blocks_to_web_override invalid integer ignored: "+n+", in "+object); continue; } Material material = Material.getMaterial(materialString); if (materialString.equals("missing")) { this.blocksToWebMissing = n; this.webSocketServerThread.log(Level.FINEST, "blocks_to_web_override missing value to set to: "+n); } else { if (material == null) { webSocketServerThread.log(Level.WARNING, "blocks_to_web_override invalid material ignored: " + materialString); continue; } this.blocksToWeb.put(material, n); this.webSocketServerThread.log(Level.FINEST, "blocks_to_web_override: " + material + " = " + n); } } this.warnMissing = settings.warnMissing; this.unbreakableBlocks = new ArrayList<Material>(); for (String materialString : settings.unbreakableBlocks) { Material material = Material.getMaterial(materialString); if (material == null) { webSocketServerThread.log(Level.WARNING, "unbreakable_blocks invalid material ignored: " + materialString); continue; } this.unbreakableBlocks.add(material); } this.textureURL = settings.textureURL; this.creativeMode = settings.creativeMode; } private final ByteBufAllocator allocator = PooledByteBufAllocator.DEFAULT; // Send the client the initial section of the world when they join public void sendWorld(final Channel channel) { if (textureURL != null) { webSocketServerThread.sendLine(channel, "t," + textureURL); } if (creativeMode) { webSocketServerThread.sendLine(channel, "m,1"); } else { webSocketServerThread.sendLine(channel, "m,0"); } String name = webSocketServerThread.webPlayerBridge.channelId2name.get(channel.id()); webSocketServerThread.sendLine(channel, "u," + name); int day_length = 60 * 20; // 20 minutes if (seeTime) { double fraction = world.getTime() / 1000.0 / 24.0; // 0-1 double elapsed = (fraction + 6.0 / 24) * day_length; webSocketServerThread.sendLine(channel, "E," + elapsed + "," + day_length); // TODO: listen for server time change and resend E, command } else { webSocketServerThread.sendLine(channel, "E,0,0"); } // Send a multi-block update message announcement that a binary chunk is coming /* int startx = -radius; int starty = y_offset; int startz = -radius; int endx = radius - 1; int endy = radius * 2 - 1 + y_offset; int endz = radius - 1; */ int startx = 0; int starty = y_offset; int startz = 0; int endx = radius * 2 - 1; int endy = radius * 2 - 1 + y_offset; int endz = radius * 2 - 1; webSocketServerThread.sendLine(channel, "b," + startx + "," + starty + "," + startz + "," + endx + "," + endy + "," + endz); ByteBuf data = allocator.buffer( (radius*2) * (radius*2) * (radius*2) * 2); boolean thereIsAWorld = false; LinkedList<String> blockDataUpdates = new LinkedList<String>(); int offset = 0; // Gather block data for multiblock update compression for (int i = -radius; i < radius; ++i) { for (int j = -radius; j < radius; ++j) { for (int k = -radius; k < radius; ++k) { Block block = world.getBlockAt(j + x_center, i + y_center, k + z_center); Material material = block.getType(); BlockState blockState = block.getState(); int type = toWebBlockType(material, blockState); data.setShortLE(offset, (short) type); offset += 2; // Gather block data updates String blockDataCommand = getDataBlockUpdateCommand(block.getLocation(), material, blockState); if (type != 0) thereIsAWorld = true; if (blockDataCommand != null) blockDataUpdates.add(blockDataCommand); } } } data.writerIndex(data.capacity()); // Send compressed block types try { // Compress with DeflateOutputStream, note _not_ GZIPOutputStream since that adds // gzip headers (see https://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib) // which miniz does not support (https://github.com/richgel999/miniz/blob/ec028ffe66e2da67eed208de3db66fcf72b24dac/miniz.h#L33) ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DeflaterOutputStream gzipOutputStream = new DeflaterOutputStream(byteArrayOutputStream); byte[] bytes = new byte[data.readableBytes()]; data.readBytes(bytes); gzipOutputStream.write(bytes); gzipOutputStream.close(); byte[] gzipBytes = byteArrayOutputStream.toByteArray(); ByteBuf gzipBytesBuffer = Unpooled.wrappedBuffer(gzipBytes); webSocketServerThread.sendBinary(channel, gzipBytesBuffer); } catch (IOException ex) { webSocketServerThread.log(Level.WARNING, "Failed to compress chunk data to send to web client: "+ex); throw new RuntimeException(ex); } finally { data.release(); } // then block data and refresh for (String blockDataCommand : blockDataUpdates) { webSocketServerThread.sendLine(channel, blockDataCommand); } webSocketServerThread.sendLine(channel,"K,0,0,1"); webSocketServerThread.sendLine(channel, "R,0,0"); if (!thereIsAWorld) { webSocketServerThread.sendLine(channel, "T,No blocks sent (server misconfiguration, check x/y/z_center)"); webSocketServerThread.log(Level.WARNING, "No valid blocks were found centered around ("+ x_center + "," + y_center + "," + z_center + ") radius " + radius + ", try changing these values or blocks_to_web in the configuration. All blocks were air or missing!"); } // Move player on top of the new blocks int x_start = radius; int y_start = world.getHighestBlockYAt(x_center, z_center) - radius - y_offset; int z_start = radius; int rotation_x = 0; int rotation_y = 0; webSocketServerThread.sendLine(channel, "U,1," + x_start + "," + y_start + "," + z_start + "," + rotation_x + "," + rotation_y ); } public boolean withinSandboxRange(Location location) { int x = location.getBlockX(); int y = location.getBlockY(); int z = location.getBlockZ(); if (x >= x_center + radius || x < x_center - radius) { return false; } if (y >= y_center + radius || y < y_center - radius) { return false; } if (z >= z_center + radius || z < z_center - radius) { return false; } return true; } public Location toBukkitLocation(int x, int y, int z) { x += -radius + x_center; y += -radius + y_center - y_offset; z += -radius + z_center; Location location = new Location(world, x, y, z); return location; } public Location toBukkitPlayerLocation(double x, double y, double z) { x += -radius + x_center; y += -radius + y_center - y_offset; z += -radius + z_center; Location location = new Location(world, x, y, z); return location; } public int toWebLocationBlockX(Location location) { return location.getBlockX() - (-radius + x_center); } public int toWebLocationBlockY(Location location) { return location.getBlockY() - (-radius + y_center - y_offset); } public int toWebLocationBlockZ(Location location) { return location.getBlockZ() - (-radius + z_center); } public double toWebLocationEntityX(Location location) { return location.getX() - (-radius + x_center); } public double toWebLocationEntityY(Location location) { return location.getY() - (-radius + y_center - y_offset); } public double toWebLocationEntityZ(Location location) { return location.getZ() - (-radius + z_center); } // Handle the web client changing a block, update the bukkit world public void clientBlockUpdate(ChannelHandlerContext ctx, int x, int y, int z, int type) { if (!allowBreakPlaceBlocks) { webSocketServerThread.sendLine(ctx.channel(), "T,Breaking/placing blocks not allowed"); // TODO: set back to original block to revert on client return; } Location location = toBukkitLocation(x, y, z); if (!withinSandboxRange(location)) { webSocketServerThread.log(Level.FINEST, "client tried to modify outside of sandbox! "+location); // not severe, since not prevented client-side webSocketServerThread.sendLine(ctx.channel(), "T,You cannot build at ("+x+","+y+","+z+")"); // TODO: Clear the block, fix this (set to air) /* webSocketServerThread.sendLine(ctx.channel(), "B,0,0,"+ox+","+oy+","+oz+",0"); webSocketServerThread.sendLine(ctx.channel(), "R,0,0"); */ return; } Block previousBlock = location.getBlock(); Material previousMaterial = previousBlock.getType(); if (unbreakableBlocks.contains(previousMaterial)) { webSocketServerThread.log(Level.FINEST, "client tried to change unbreakable block at " + location + " of type previousMaterial="+previousMaterial); webSocketServerThread.sendLine(ctx.channel(), "T,You cannot break blocks of type " + previousMaterial); // Revert on client int previousType = toWebBlockType(previousMaterial, null); webSocketServerThread.sendLine(ctx.channel(), "B,0,0,"+x+","+y+","+z+","+previousType); webSocketServerThread.sendLine(ctx.channel(), "R,0,0"); return; } Block block = world.getBlockAt(location); if (block == null) { webSocketServerThread.log(Level.WARNING, "web client no such block at " + location); // does this happen? return; } webSocketServerThread.log(Level.FINEST, "setting block at "+location); BlockState blockState = block.getState(); toBukkitBlockType(type, blockState); // Notify other web clients - note they will have the benefit of seeing the untranslated block (feature or bug?) webSocketServerThread.broadcastLineExcept(ctx.channel().id(), "B,0,0," + x + "," + y + "," + z + "," + type); webSocketServerThread.broadcastLineExcept(ctx.channel().id(), "R,0,0"); } // Handle the bukkit world changing a block, tell all web clients and refresh public void notifyBlockUpdate(Location location, Material material, BlockState blockState) { webSocketServerThread.log(Level.FINEST, "bukkit block at "+location+" was set to "+material); if (!withinSandboxRange(location)) { // Clients don't need to know about every block change on the server, only within the sandbox return; } setBlockUpdate(location, material, blockState); webSocketServerThread.broadcastLine("R,0,0"); } // Get the command string to send block data besides the type, if needed (signs, lighting) private String getDataBlockUpdateCommand(Location location, Material material, BlockState blockState) { if (material == null || material == Material.AIR) return null; int light_level = toWebLighting(material, blockState); if (light_level != 0) { int x = toWebLocationBlockX(location); int y = toWebLocationBlockY(location); int z = toWebLocationBlockZ(location); return "L,0,0,"+x+","+y+","+z+"," + light_level; } if (blockState instanceof org.bukkit.block.Sign) { Sign sign = (Sign) blockState; return getNotifySignChange(blockState.getLocation(), blockState.getType(), blockState, sign.getLines()); } return null; } private void setBlockUpdate(Location location, Material material, BlockState blockState) { // Send to all web clients to let them know it changed using the "B," command int type = toWebBlockType(material, blockState); if (type == -1) { if (warnMissing) { webSocketServerThread.log(Level.WARNING, "Block type missing from blocks_to_web: " + material + " at " + location); } type = blocksToWebMissing; } int x = toWebLocationBlockX(location); int y = toWebLocationBlockY(location); int z = toWebLocationBlockZ(location); webSocketServerThread.broadcastLine("B,0,0,"+x+","+y+","+z+","+type); String blockDataCommand = this.getDataBlockUpdateCommand(location, material, blockState); if (blockDataCommand != null) { webSocketServerThread.broadcastLine(blockDataCommand); } webSocketServerThread.log(Level.FINEST, "notified block update: ("+x+","+y+","+z+") to "+type); } private int toWebLighting(Material material, BlockState blockState) { BlockData blockData = blockState.getBlockData(); boolean isLit = false; if (blockData instanceof Lightable) { Lightable lightable = (Lightable) blockData; isLit = lightable.isLit(); } // See http://minecraft.gamepedia.com/Light#Blocks // Note not all of these may be fully supported yet switch (material) { case BEACON: case FIRE: case GLOWSTONE: case JACK_O_LANTERN: case LAVA: case REDSTONE_LAMP: // TODO: get notified when toggles on/off if (!isLit) { return 0; } case SEA_LANTERN: case END_ROD: return 15; case TORCH: return 14; case FURNACE: if (blockData instanceof org.bukkit.block.data.type.Furnace) { // TODO: or is Lightable too? org.bukkit.block.data.type.Furnace furnace = (org.bukkit.block.data.type.Furnace) blockData; if (!furnace.isLit()) { return 0; } } return 13; case END_PORTAL: case NETHER_PORTAL: return 11; case REDSTONE_ORE: case DEEPSLATE_REDSTONE_ORE: if (!isLit) { return 0; } return 9; case ENDER_CHEST: case REDSTONE_TORCH: if (!isLit) { return 0; } return 7; case MAGMA_BLOCK: return 3; case BREWING_STAND: case BROWN_MUSHROOM: case DRAGON_EGG: case END_PORTAL_FRAME: return 1; default: return 0; } } // The web client represents directional blocks has four block ids // example: furnaces private int getDirectionalOrthogonalWebBlock(int base, Directional directional) { BlockFace facing = directional.getFacing(); switch (facing) { case NORTH: return base+0; case SOUTH: return base+1; case WEST: return base+2; case EAST: return base+3; default: webSocketServerThread.log(Level.WARNING, "unknown orthogonal directional rotation: "+facing); return base; } } // example: pumpkins, for some reason, fronts are inverted private int getDirectionalOrthogonalWebBlockReversed(int base, Directional directional) { BlockFace facing = directional.getFacing(); switch (facing) { case SOUTH: return base+0; case NORTH: return base+1; case EAST: return base+2; case WEST: return base+3; default: webSocketServerThread.log(Level.WARNING, "unknown orthogonal directional rotation: "+facing); return base; } } // Translate web<->bukkit blocks // TODO: refactor to remove all bukkit dependency in this class (enums strings?), generalize to can support others private int toWebBlockType(Material material, BlockState blockState) { if (blocksToWeb.containsKey(material)) { return blocksToWeb.get(material); } BlockData blockData = blockState != null ? blockState.getBlockData() : null; Directional directional = null; if (blockData instanceof Directional) { directional = (Directional) blockData; } boolean isLit = false; if (blockData instanceof Lightable) { Lightable lightable = (Lightable) blockData; isLit = lightable.isLit(); } switch (material) { case AIR: return 0; case GRASS_BLOCK: return 1; case SAND: return 2; case SMOOTH_STONE: return 3; // TODO: 3 is smooth stone brick, what is this? case MOSSY_STONE_BRICKS: return 76; // mossy stone brick case CRACKED_STONE_BRICKS: return 77; // cracked stone brick case BRICKS: return 4; case OAK_LOG: // log = block found in trees case OAK_WOOD: // wood = bark block case STRIPPED_OAK_LOG: case STRIPPED_OAK_WOOD: case JUNGLE_LOG: case JUNGLE_WOOD: case STRIPPED_JUNGLE_LOG: case STRIPPED_JUNGLE_WOOD: case ACACIA_LOG: case ACACIA_WOOD: case STRIPPED_ACACIA_LOG: case STRIPPED_ACACIA_WOOD: case DARK_OAK_LOG: case DARK_OAK_WOOD: case STRIPPED_DARK_OAK_LOG: case STRIPPED_DARK_OAK_WOOD: return 5; // oak wood log case SPRUCE_LOG: case STRIPPED_SPRUCE_LOG: return 107; // spruce wood log case BIRCH_LOG: case STRIPPED_BIRCH_LOG: return 108; // birch wood log // TODO: tree.getDirection(), faces different case GOLD_ORE: return 70; case IRON_ORE: return 71; case COAL_ORE: return 72; case LAPIS_ORE: return 73; case LAPIS_BLOCK: return 74; case DIAMOND_ORE: return 48; case REDSTONE_ORE: return 49; // TODO: more ores, for now, showing as stone case NETHER_QUARTZ_ORE: return 6; case STONE: return 6; case DIRT: return 7; case OAK_PLANKS: case SPRUCE_PLANKS: case BIRCH_PLANKS: case JUNGLE_PLANKS: case ACACIA_PLANKS: case DARK_OAK_PLANKS: case CRIMSON_PLANKS: return 8; // plank case SNOW: return 9; case GLASS: return 10; case COBBLESTONE: return 11; case CHEST: return 14; case OAK_LEAVES: case DARK_OAK_LEAVES: case ACACIA_LEAVES: case BIRCH_LEAVES: return 15; // leaves case SPRUCE_LEAVES: // "redwood return 109; // spruce leaves // TODO: return cloud (16); case GRASS: case TALL_GRASS: return 17; // TODO: other double plants, but a lot look like longer long grass case FERN: return 29; // fern case DEAD_BUSH: return 23; // deadbush, places on sand case DANDELION: return 18; case POPPY: case ALLIUM: case AZURE_BLUET: case RED_TULIP: case ORANGE_TULIP: case PINK_TULIP: case OXEYE_DAISY: case CORNFLOWER: case LILY_OF_THE_VALLEY: case WITHER_ROSE: case SPORE_BLOSSOM: return 19; // red rose case CHORUS_FLOWER: return 20; case OAK_SAPLING: case DARK_OAK_SAPLING: case ACACIA_SAPLING: case JUNGLE_SAPLING: return 20; // oak sapling case SPRUCE_SAPLING: return 30; // spruce sapling ("darker barked/leaves tree species") case BIRCH_SAPLING: return 31; // birch sapling case SUNFLOWER: return 21; case WHITE_TULIP: return 22; // white flower case BLUE_ORCHID: return 23; // blue flower case WHITE_WOOL: return 32; case ORANGE_WOOL: return 33; case MAGENTA_WOOL: return 34; case LIGHT_BLUE_WOOL: return 35; case YELLOW_WOOL: return 36; case LIME_WOOL: return 37; case PINK_WOOL: return 38; case GRAY_WOOL: return 39; case LIGHT_GRAY_WOOL: return 40; // formerly silver case CYAN_WOOL: return 41; case PURPLE_WOOL: return 42; case BLUE_WOOL: return 43; case BROWN_WOOL: return 44; case GREEN_WOOL: return 45; case BLACK_WOOL: return 47; case OAK_WALL_SIGN: case SPRUCE_WALL_SIGN: case BIRCH_WALL_SIGN: case JUNGLE_WALL_SIGN: case DARK_OAK_WALL_SIGN: case CRIMSON_WALL_SIGN: return 0; // air, since text is written on block behind it case OAK_SIGN: case SPRUCE_SIGN: case BIRCH_SIGN: case JUNGLE_SIGN: case DARK_OAK_SIGN: case CRIMSON_SIGN: return 8; // plank TODO: return sign post model // Light sources (nonzero toWebLighting()) TODO: return different textures? + allow placement, distinct blocks case GLOWSTONE: return 64; // #define GLOWING_STONE case SEA_LANTERN: return 35; // light blue wool case TORCH: return 21; // sunflower, looks kinda like a torch case REDSTONE_TORCH: case REDSTONE_WALL_TORCH: return 19; // red flower, vaguely a torch // Liquids // TODO: flowing, stationary, and different heights of each liquid case WATER: return 12; // water case LAVA: return 13; // lava // TODO: support more blocks by default case BEDROCK: return 65; case GRAVEL: return 66; case IRON_BLOCK: return 67; case GOLD_BLOCK: return 68; case DIAMOND_BLOCK: return 69; case SANDSTONE: return 75; case BOOKSHELF: return 50; case MOSSY_COBBLESTONE: return 51; case OBSIDIAN: return 52; case CRAFTING_TABLE: return 53; case FURNACE: { if (directional != null) { if (!isLit) { return getDirectionalOrthogonalWebBlock(90, directional); // 90, 91, 92, 93 } else { return getDirectionalOrthogonalWebBlock(94, directional); // 94, 95, 96, 97 } } return !isLit ? 90 : 94; //return !isLit ? 54 : 55; // old } case SPAWNER: return 56; case SNOW_BLOCK: return 57; case ICE: return 58; case CLAY: return 59; case JUKEBOX: return 60; case CACTUS: return 61; case MYCELIUM: return 62; case NETHERRACK: return 63; case SPONGE: return 24; case MELON: return 25; case END_STONE: return 26; case TNT: return 27; case EMERALD_BLOCK: return 28; case CARVED_PUMPKIN: { if (directional != null) { return getDirectionalOrthogonalWebBlockReversed(98, directional); // 98, 99, 100, 101 } } case PUMPKIN: return 78; // faceless case JACK_O_LANTERN: { if (directional != null) { return getDirectionalOrthogonalWebBlockReversed(102, directional); // 102, 103, 104, 105 } return 79; // all faces } case BROWN_MUSHROOM_BLOCK: return 80; // brown TODO: data case RED_MUSHROOM_BLOCK: return 81; // red TODO: data case COMMAND_BLOCK: return 82; case EMERALD_ORE: return 83; case SOUL_SAND: return 84; case NETHER_BRICK: return 85; case FARMLAND: return 86; // wet farmland TODO: dry farmland (87) case REDSTONE_LAMP: return !isLit ? 88 : 89; case BARRIER: return 106; default: return this.blocksToWebMissing; } } // Mutate blockState to block of type type private void toBukkitBlockType(int type, BlockState blockState) { Material material = null; BlockData blockData = null; switch (type) { case 0: material = Material.AIR; break; case 1: material = Material.GRASS; break; case 2: material = Material.SAND; break; case 3: material = Material.SMOOTH_STONE; break; // TODO: what is smooth brick? case 4: material = Material.BRICK; break; case 5: material = Material.OAK_LOG; break; case 6: material = Material.STONE; break; case 7: material = Material.DIRT; break; case 8: material = Material.OAK_WOOD; break; // TODO: this was WOOD, is this right? bark? case 9: material = Material.SNOW_BLOCK; break; case 10: material = Material.GLASS; break; case 11: material = Material.COBBLESTONE; break; case 12: material = Material.WATER; break; case 13: material = Material.LAVA; break; case 14: material = Material.CHEST; break; // TODO: doesn't seem to set? case 15: material = Material.OAK_LEAVES; break; //case 16: material = Material.clouds; break; // clouds case 17: material = Material.TALL_GRASS; break; case 18: material = Material.DANDELION; break; case 19: material = Material.RED_TULIP; break; case 20: material = Material.CHORUS_FLOWER; break; case 21: material = Material.RED_MUSHROOM; break; case 22: material = Material.BROWN_MUSHROOM; break; case 23: material = Material.DEAD_BUSH; break; case 24: material = Material.SPONGE; break; case 25: material = Material.MELON; break; case 26: material = Material.END_STONE; break; case 27: material = Material.TNT; break; case 28: material = Material.EMERALD_BLOCK; break; case 29: material = Material.FERN; break; case 30: material = Material.SPRUCE_SAPLING; break; case 31: material = Material.BIRCH_SAPLING; break; case 32: material = Material.WHITE_WOOL; break; case 33: material = Material.ORANGE_WOOL; break; case 34: material = Material.MAGENTA_WOOL; break; case 35: material = Material.LIGHT_BLUE_WOOL; break; case 36: material = Material.YELLOW_WOOL; break; case 37: material = Material.LIME_WOOL; break; case 38: material = Material.PINK_WOOL; break; case 39: material = Material.GRAY_WOOL; break; case 40: material = Material.LIGHT_GRAY_WOOL; break; case 41: material = Material.CYAN_WOOL; break; case 42: material = Material.PURPLE_WOOL; break; case 43: material = Material.BLUE_WOOL; break; case 44: material = Material.BROWN_WOOL; break; case 45: material = Material.GREEN_WOOL; break; case 46: material = Material.RED_WOOL; break; case 47: material = Material.BLACK_WOOL; break; case 48: material = Material.DIAMOND_ORE; break; case 49: material = Material.REDSTONE_ORE; break; case 50: material = Material.BOOKSHELF; break; case 51: material = Material.MOSSY_COBBLESTONE; break; case 52: material = Material.OBSIDIAN; break; case 53: material = Material.CRAFTING_TABLE; break; case 54: // TODO: remove, what was this? case 55: // TODO: remove, what was this? material = Material.FURNACE; break; case 56: material = Material.AIR; break; // not allowing, dangerous Material.MOB_SPAWNER case 57: material = Material.SNOW_BLOCK; break; case 58: material = Material.ICE; break; case 59: material = Material.CLAY; break; case 60: material = Material.JUKEBOX; break; case 61: material = Material.CACTUS; break; case 62: material = Material.MYCELIUM; break; case 63: material = Material.NETHERRACK; break; case 64: material = Material.GLOWSTONE; break; case 65: material = Material.BEDROCK; break; case 66: material = Material.GRAVEL; break; case 67: material = Material.IRON_BLOCK; break; case 68: material = Material.GOLD_BLOCK; break; case 69: material = Material.DIAMOND_BLOCK; break; case 70: material = Material.GOLD_ORE; break; case 71: material = Material.IRON_ORE; break; case 72: material = Material.COAL_ORE; break; case 73: material = Material.LAPIS_ORE; break; case 74: material = Material.LAPIS_BLOCK; break; case 75: material = Material.SANDSTONE; break; case 76: material = Material.MOSSY_COBBLESTONE; break; // TODO: mossy stone brick case 77: material = Material.MOSSY_COBBLESTONE; break; // TODO: cracked stone brick case 78: material = Material.PUMPKIN; break; // TODO: direction case 79: material = Material.JACK_O_LANTERN; break; // TODO: direction case 80: material = Material.BROWN_MUSHROOM_BLOCK; break; // TODO: type case 81: material = Material.RED_MUSHROOM_BLOCK; break; // TODO: type case 82: material = Material.AIR; break; // not ever allowing Material.COMMAND; break; case 83: material = Material.EMERALD_ORE; break; case 84: material = Material.SOUL_SAND; break; case 85: material = Material.NETHER_BRICK; break; case 86: material = Material.FARMLAND; break; //case 87: // TODO: dry farmland case 88: case 89: material = Material.REDSTONE_LAMP; // TODO: set lit //Lightable lit = new Lightable(); //lit.setLit(type == 89); // lamp on break; case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: material = Material.FURNACE; // TODO: direction // TODO: set lit //org.bukkit.block.data.type.Furnace f = new org.bukkit.block.data.type.Furnace(); // TODO: how to construct this? it is an interface, do we have to get after? //f.setLit(type >= 94); // burning // TODO: set direction break; case 98: case 99: case 100: case 101: material = Material.PUMPKIN; break; // TODO: direction case 102: case 103: case 104: case 105: material = Material.JACK_O_LANTERN; break; // TODO: direction case 106: material = Material.AIR; break; // not allowing Material.BARRIER; break; case 107: material = Material.SPRUCE_WOOD; break; // spruce wood log case 108: material = Material.BIRCH_WOOD; break; // birch wood log case 109: material = Material.SPRUCE_LEAVES; break; // TODO: spruce leaves default: webSocketServerThread.log(Level.WARNING, "untranslated web block id "+type); material = Material.DIAMOND_ORE; // placeholder TODO fix } if (unbreakableBlocks.contains(material)) { webSocketServerThread.log(Level.WARNING, "client tried to place unplaceable block type "+type+ " from "+material); return; // ignore, not reverting } if (material != null) { blockState.setType(material); if (blockData != null) { blockState.setBlockData(blockData); } boolean force = true; boolean applyPhysics = false; blockState.update(force, applyPhysics); } } public String getNotifySignChange(Location location, Material material, BlockState blockState, String[] lines) { int x = toWebLocationBlockX(location); int y = toWebLocationBlockY(location); int z = toWebLocationBlockZ(location); BlockFace blockFace = BlockFace.NORTH; BlockData blockData = blockState.getBlockData(); if (blockData instanceof Directional) { //org.bukkit.block.data.type.Sign sign = (org.bukkit.block.data.type.Sign) blockData; Directional directional = (Directional) blockData; try { blockFace = directional.getFacing(); } catch (NullPointerException ex) { // ignore invalid data, https://github.com/GlowstoneMC/Glowstone/issues/484 webSocketServerThread.log(Level.WARNING, "Invalid sign data at " + location); } } int face = 7; if (blockFace == null) { // https://github.com/satoshinm/WebSandboxMC/issues/92 webSocketServerThread.log(Level.WARNING, "Invalid sign face at " + location); } else if (material == Material.OAK_WALL_SIGN || material == Material.SPRUCE_WALL_SIGN || material == Material.BIRCH_WALL_SIGN || material == Material.JUNGLE_WALL_SIGN || material == Material.DARK_OAK_WALL_SIGN || material == Material.CRIMSON_WALL_SIGN) { // wallsigns, attached to block behind switch (blockFace) { default: case NORTH: face = 2; // north z += 1; break; case SOUTH: face = 3; // south z -= 1; break; case WEST: face = 0; // west x += 1; break; case EAST: face = 1; // east x -= 1; break; } } else if (material == Material.OAK_SIGN || material == Material.SPRUCE_SIGN || material == Material.BIRCH_SIGN || material == Material.JUNGLE_SIGN || material == Material.DARK_OAK_SIGN || material == Material.CRIMSON_SIGN) { // standing sign, on the block itself // TODO: support more fine-grained directions, right now Craft only four cardinal switch (blockFace) { case SOUTH: case SOUTH_SOUTH_WEST: case SOUTH_WEST: face = 3; // south break; case WEST_SOUTH_WEST: case WEST: case WEST_NORTH_WEST: case NORTH_WEST: face = 0; // west break; default: case NORTH_NORTH_WEST: case NORTH: case NORTH_NORTH_EAST: case NORTH_EAST: face = 2; // north break; case EAST_NORTH_EAST: case EAST: case EAST_SOUTH_EAST: case SOUTH_EAST: case SOUTH_SOUTH_EAST: face = 1; // east break; } } webSocketServerThread.log(Level.FINEST, "sign change: "+location+", blockFace="+blockFace); String text = ""; for (int i = 0; i < lines.length; ++i) { text += lines[i] + " "; // TODO: support explicit newlines; Craft wraps sign text lines automatically } if (text.contains("\n")) { // \n is used as a command terminator in the Craft protocol (but ',' is acceptable) text = text.replaceAll("\n", " "); } return "S,0,0,"+x+","+y+","+z+","+face+","+text; } public void notifySignChange(Location location, Material material, BlockState blockState, String[] lines) { webSocketServerThread.broadcastLine(this.getNotifySignChange(location, material, blockState, lines)); webSocketServerThread.broadcastLine("R,0,0"); // TODO: refresh correct chunk } public void clientNewSign(ChannelHandlerContext ctx, int x, int y, int z, int face, String text) { if (!allowSigns) { webSocketServerThread.sendLine(ctx.channel(), "T,Writing on signs is not allowed"); // TODO: revert on client return; } BlockFace blockFace; switch (face) { case 0: // west blockFace = BlockFace.WEST; x -= 1; break; case 1: // east blockFace = BlockFace.EAST; x += 1; break; default: case 2: // north blockFace = BlockFace.NORTH; z -= 1; break; case 3: // south blockFace = BlockFace.SOUTH; z += 1; break; } Location location = toBukkitLocation(x, y, z); if (!withinSandboxRange(location)) { webSocketServerThread.log(Level.FINEST, "client tried to write a sign outside sandbox range"); return; } // Create the sign Block block = location.getWorld().getBlockAt(location); webSocketServerThread.log(Level.FINEST, "setting sign at "+location+" text="+text); block.setType(Material.OAK_WALL_SIGN); BlockState blockState = block.getState(); if (!(blockState instanceof Sign)) { webSocketServerThread.log(Level.WARNING, "failed to place sign at "+location); return; } Sign sign = (Sign) blockState; // Set the sign text // TODO: text lines by 15 characters into 5 lines sign.setLine(0, text); webSocketServerThread.log(Level.FINEST, "set sign text="+text+", sign="+sign+", blockFace="+blockFace+", block="+block+", face="+face); // Set sign direction BlockData blockData = blockState.getBlockData(); if (!(blockData instanceof Directional)) { webSocketServerThread.log(Level.WARNING, "failed to get sign directional block data at " + location); } Directional directional = (Directional) blockData; directional.setFacing(blockFace); webSocketServerThread.log(Level.FINEST, "setting sign at "+location+" blockFace="+blockFace); blockState.setBlockData(directional); boolean force = true; boolean applyPhysics = false; sign.update(force, applyPhysics); blockState.update(force, applyPhysics); webSocketServerThread.log(Level.FINEST, "updated sign at "+location); // SignChangeEvent not posted when signs created programmatically; notify web clients ourselves notifySignChange(location, block.getType(), block.getState(), sign.getLines()); } }
satoshinm/WebSandboxMC
src/main/java/io/github/satoshinm/WebSandboxMC/bridge/BlockBridge.java
Java
mit
44,037
package org.hive2hive.core.network.messages.request; import java.io.Serializable; import java.util.Set; import org.hive2hive.core.network.messages.BaseMessage; import org.hive2hive.core.network.messages.direct.BaseDirectMessage; import org.hive2hive.core.network.messages.direct.response.IResponseCallBackHandler; import org.hive2hive.core.network.messages.direct.response.ResponseMessage; /** * An interface which allows a {@link BaseMessage} or {@link BaseDirectMessage} messages to have a * {@link IResponseCallBackHandler} callback handler. The callback handler gets called when a * {@link ResponseMessage} message with a response arrived at the requesting node. * * @author Nendor, Seppi, Christian */ public interface IRequestMessage { /** * Setter * * @param handler * a {@link IResponseCallBackHandler} for handling responses from receiver node */ public void setCallBackHandler(IResponseCallBackHandler handler); /** * Add * * @param handler * a {@link IResponseCallBackHandler} for handling responses from receiver node */ public void addCallBackHandler(IResponseCallBackHandler handler); /** * Getter * * @return the callback handler (if set) */ public Set<IResponseCallBackHandler> getCallBackHandlers(); /** * Configures the {@link ResponseMessage} for this {@link RoutedRequestMessage} with the correct message * ID * and receiver address. * * @param content The content of the response. * @return The configured {@link ResponseMessage}. */ public ResponseMessage createResponse(Serializable content); /** * Sends the {@link ResponseMessage} <b>directly</b> to its requester. * * @param response The {@link ResponseMessage} created with * {@link RoutedRequestMessage#createResponse(Serializable)}. */ public void sendDirectResponse(ResponseMessage response); }
Hive2Hive/Hive2Hive
org.hive2hive.core/src/main/java/org/hive2hive/core/network/messages/request/IRequestMessage.java
Java
mit
1,891
import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonWriter; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.io.StringWriter; import java.util.*; @ServerEndpoint("/chatroomServerEndpoint") public class ChessAnalysisServerEndpoint { private static final String SESSION_ID = "sessionId"; // private static Set<Session> analysisUsers = Collections.synchronizedSet(new HashSet<Session>()); // private static String currentFen; private static Map<Integer, ChessSession> sessions = Collections.synchronizedMap(new HashMap<Integer, ChessSession>()); public ChessAnalysisServerEndpoint() { if (!sessions.containsKey(1)) { sessions.put(1, new ChessSession()); } } @OnOpen public void onOpen(Session userSession) throws IOException { Integer sessionId = (Integer) userSession.getUserProperties().get(SESSION_ID); // ChessSession chessSession = ; if (sessionId == null) { sessionId = Integer.valueOf(1); // all users goes to one analysis board for now userSession.getUserProperties().put(SESSION_ID, sessionId); // chessSession = new ChessSession(); // sessions.put(sessionId, chessSession); } // else { // chessSession = sessions.get(sessionId); // } final ChessSession chessSession = sessions.get(1); chessSession.addUser(userSession); final String currentFen = chessSession.getCurrentFen(); if (currentFen != null) { userSession.getBasicRemote().sendText(buildJsonData(currentFen)); } } @OnMessage public void onMessage(String message, Session userSession) throws IOException { Integer sessionId = (Integer) userSession.getUserProperties().get(SESSION_ID); final ChessSession chessSession = sessions.get(sessionId); synchronized (chessSession) { chessSession.setCurrentFen(message); Iterator<Session> iterator = chessSession.getUsersIterator(); while (iterator.hasNext()) iterator.next().getBasicRemote().sendText(buildJsonData(message)); } } @OnClose public void onClose(Session userSession) { Integer sessionId = (Integer) userSession.getUserProperties().get(SESSION_ID); sessions.get(sessionId).removeUser(userSession); } private String buildJsonData(String message) { JsonObject jsonObject = Json.createObjectBuilder().add("fen", message).build(); StringWriter stringWriter = new StringWriter(); try (JsonWriter jsonWriter = Json.createWriter(stringWriter)) { jsonWriter.write(jsonObject); } return stringWriter.toString(); } }
marekjeszka/ChessAnalysis
src/main/java/ChessAnalysisServerEndpoint.java
Java
mit
2,982
/** */ package COSEM.COSEMObjects; import COSEM.InterfaceClasses.Profilegeneric; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Error Profile Object</b></em>'. * <!-- end-user-doc --> * * * @see COSEM.COSEMObjects.COSEMObjectsPackage#getErrorProfileObject() * @model * @generated */ public interface ErrorProfileObject extends Profilegeneric { } // ErrorProfileObject
georghinkel/ttc2017smartGrids
solutions/ModelJoin/src/main/java/COSEM/COSEMObjects/ErrorProfileObject.java
Java
mit
410
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------- * XYLineAnnotation.java * --------------------- * (C) Copyright 2003-2013, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Peter Kolb (see patch 2809117); * * Changes: * -------- * 02-Apr-2003 : Version 1 (DG); * 19-Aug-2003 : Added equals method, implemented Cloneable, and applied * serialization fixes (DG); * 21-Jan-2004 : Update for renamed method in ValueAxis (DG); * 14-Apr-2004 : Fixed draw() method to handle plot orientation correctly (DG); * 29-Sep-2004 : Added support for tool tips and URLS, now extends * AbstractXYAnnotation (DG); * 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG); * 08-Jun-2005 : Fixed equals() method to handle GradientPaint() (DG); * 05-Nov-2008 : Added workaround for JRE bug 6574155, see JFreeChart bug * 2221495 (DG); * 02-Jul-2013 : Use ParamChecks (DG); * */ package org.jfree.chart.annotations; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.LineUtilities; import org.jfree.chart.util.ParamChecks; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable; import org.jfree.util.ShapeUtilities; /** * A simple line annotation that can be placed on an {@link XYPlot}. */ public class XYLineAnnotation extends AbstractXYAnnotation implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -80535465244091334L; /** The x-coordinate. */ private double x1; /** The y-coordinate. */ private double y1; /** The x-coordinate. */ private double x2; /** The y-coordinate. */ private double y2; /** The line stroke. */ private transient Stroke stroke; /** The line color. */ private transient Paint paint; /** * Creates a new annotation that draws a line from (x1, y1) to (x2, y2) * where the coordinates are measured in data space (that is, against the * plot's axes). * * @param x1 the x-coordinate for the start of the line. * @param y1 the y-coordinate for the start of the line. * @param x2 the x-coordinate for the end of the line. * @param y2 the y-coordinate for the end of the line. */ public XYLineAnnotation(double x1, double y1, double x2, double y2) { this(x1, y1, x2, y2, new BasicStroke(1.0f), Color.black); } /** * Creates a new annotation that draws a line from (x1, y1) to (x2, y2) * where the coordinates are measured in data space (that is, against the * plot's axes). * * @param x1 the x-coordinate for the start of the line. * @param y1 the y-coordinate for the start of the line. * @param x2 the x-coordinate for the end of the line. * @param y2 the y-coordinate for the end of the line. * @param stroke the line stroke (<code>null</code> not permitted). * @param paint the line color (<code>null</code> not permitted). */ public XYLineAnnotation(double x1, double y1, double x2, double y2, Stroke stroke, Paint paint) { super(); ParamChecks.nullNotPermitted(stroke, "stroke"); ParamChecks.nullNotPermitted(paint, "paint"); this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.stroke = stroke; this.paint = paint; } /** * Draws the annotation. This method is called by the {@link XYPlot} * class, you won't normally need to call it yourself. * * @param g2 the graphics device. * @param plot the plot. * @param dataArea the data area. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param rendererIndex the renderer index. * @param info if supplied, this info object will be populated with * entity information. */ public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis, int rendererIndex, PlotRenderingInfo info) { PlotOrientation orientation = plot.getOrientation(); RectangleEdge domainEdge = Plot.resolveDomainAxisLocation( plot.getDomainAxisLocation(), orientation); RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation( plot.getRangeAxisLocation(), orientation); float j2DX1 = 0.0f; float j2DX2 = 0.0f; float j2DY1 = 0.0f; float j2DY2 = 0.0f; if (orientation == PlotOrientation.VERTICAL) { j2DX1 = (float) domainAxis.valueToJava2D(this.x1, dataArea, domainEdge); j2DY1 = (float) rangeAxis.valueToJava2D(this.y1, dataArea, rangeEdge); j2DX2 = (float) domainAxis.valueToJava2D(this.x2, dataArea, domainEdge); j2DY2 = (float) rangeAxis.valueToJava2D(this.y2, dataArea, rangeEdge); } else if (orientation == PlotOrientation.HORIZONTAL) { j2DY1 = (float) domainAxis.valueToJava2D(this.x1, dataArea, domainEdge); j2DX1 = (float) rangeAxis.valueToJava2D(this.y1, dataArea, rangeEdge); j2DY2 = (float) domainAxis.valueToJava2D(this.x2, dataArea, domainEdge); j2DX2 = (float) rangeAxis.valueToJava2D(this.y2, dataArea, rangeEdge); } g2.setPaint(this.paint); g2.setStroke(this.stroke); Line2D line = new Line2D.Float(j2DX1, j2DY1, j2DX2, j2DY2); // line is clipped to avoid JRE bug 6574155, for more info // see JFreeChart bug 2221495 boolean visible = LineUtilities.clipLine(line, dataArea); if (visible) { g2.draw(line); } String toolTip = getToolTipText(); String url = getURL(); if (toolTip != null || url != null) { addEntity(info, ShapeUtilities.createLineRegion(line, 1.0f), rendererIndex, toolTip, url); } } /** * Tests this object for equality with an arbitrary object. * * @param obj the object to test against (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof XYLineAnnotation)) { return false; } XYLineAnnotation that = (XYLineAnnotation) obj; if (this.x1 != that.x1) { return false; } if (this.y1 != that.y1) { return false; } if (this.x2 != that.x2) { return false; } if (this.y2 != that.y2) { return false; } if (!PaintUtilities.equal(this.paint, that.paint)) { return false; } if (!ObjectUtilities.equal(this.stroke, that.stroke)) { return false; } // seems to be the same... return true; } /** * Returns a hash code. * * @return A hash code. */ public int hashCode() { int result; long temp; temp = Double.doubleToLongBits(this.x1); result = (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.x2); result = 29 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.y1); result = 29 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.y2); result = 29 * result + (int) (temp ^ (temp >>> 32)); return result; } /** * Returns a clone of the annotation. * * @return A clone. * * @throws CloneNotSupportedException if the annotation can't be cloned. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.paint, stream); SerialUtilities.writeStroke(this.stroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.paint = SerialUtilities.readPaint(stream); this.stroke = SerialUtilities.readStroke(stream); } }
Epsilon2/Memetic-Algorithm-for-TSP
jfreechart-1.0.16/source/org/jfree/chart/annotations/XYLineAnnotation.java
Java
mit
10,895
package br.inpe.cap.evolution.processor; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileUtils; import org.repodriller.persistence.PersistenceMechanism; import org.repodriller.persistence.csv.CSVFile; import br.inpe.cap.evolution.domain.MavenDependency; import br.inpe.cap.evolution.domain.MavenProject; import br.inpe.cap.evolution.parser.XmlMavenParser; public class AllDependenciesPostProcessor { public XmlMavenParser parser = new XmlMavenParser(); public static void main(String[] args) throws IOException { System.out.println("Starting..."); AllDependenciesPostProcessor postProcessor = new AllDependenciesPostProcessor(); CSVFile csv = new CSVFile("study" + File.separator + "effective_pom.csv", true); postProcessor.writeCsvHeader(csv); File disconfiDir = new File("C:\\Users\\VANT\\workspace\\disconf-poms"); File[] listFiles = disconfiDir.listFiles(); postProcessor.processDirectory(csv, listFiles); System.out.println("Finish!"); } private void processDirectory(CSVFile csv, File[] listFiles) throws IOException { for (File file : listFiles) { if(file.isDirectory()) { this.processDirectory(csv, file.listFiles()); } if(file.getName().startsWith("_")) { this.process(file, csv); } } } public void process(File pomFile, PersistenceMechanism writer) throws IOException { // int totalCommits = hashes.size(); int currentHashPosition = Integer.valueOf(pomFile.getName().substring(pomFile.getName().lastIndexOf(".")+1)); // int currentHashPosition = 1; // float percent = 100 - ((currentHashPosition*100)/(float)totalCommits); String sourceCode = FileUtils.readFileToString(pomFile); MavenProject pom = parser.readPOM(sourceCode); List<MavenDependency> currentDependencies = pom.getDependencies(); List<MavenDependency> dependencyManagedDependencies = pom.getDependencyManagement().getDependencies(); currentDependencies.addAll(dependencyManagedDependencies); currentDependencies.forEach( (dependency) -> writeCsvLine(writer, currentHashPosition, pomFile , dependency) ); dependencyManagedDependencies.forEach( (dependency) -> writeCsvLine(writer, currentHashPosition, pomFile , dependency) ); } private void writeCsvHeader(PersistenceMechanism writer) { writer.write( // "DATE", "FILE", "COMMIT_POSISTION", "IS_DependencyManeged", "GROUP_ID", "ARTIFACT_ID", "VERSION" ); } private void writeCsvLine(PersistenceMechanism writer, int currentHashPosition, File pomFile, MavenDependency mavenDependency) { // try { // Path pomPath = Paths.get(pomFile.toURI()); // BasicFileAttributes attr = Files.readAttributes(pomPath, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); writer.write( // não faz sentido gravar dessa forma a data de criação, pois todos foram "criados" novamento no momento do checkou pelo método FileUtils.writeStringToFile // DATE_FORMAT.format(new Date(attr.creationTime().toMillis())), pomFile.getAbsolutePath(), currentHashPosition, mavenDependency.isDependencyManaged(), mavenDependency.getGroupId(), mavenDependency.getArtifactId(), mavenDependency.getVersion() ); // } catch (IOException e) { // throw new RuntimeException(e); // } } }
nascimentolwtn/ApacheEvolutionStudy
src/br/inpe/cap/evolution/processor/AllDependenciesPostProcessor.java
Java
mit
3,473
package ru.lanbilling.webservice.wsdl; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="ret" type="{http://www.w3.org/2001/XMLSchema}long"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "ret" }) @XmlRootElement(name = "delBsoDocResponse") @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public class DelBsoDocResponse { @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") protected long ret; /** * Gets the value of the ret property. * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public long getRet() { return ret; } /** * Sets the value of the ret property. * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public void setRet(long value) { this.ret = value; } }
kanonirov/lanb-client
src/main/java/ru/lanbilling/webservice/wsdl/DelBsoDocResponse.java
Java
mit
1,709
/* * The MIT License * * Copyright (c) 2010 tap4j team (see AUTHORS) * * 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.tap4j.model; import java.io.Serializable; /** * TAP element for a plan that is skipped. * * @since 1.0 */ public class SkipPlan implements Serializable { /** * Serial Version UID. */ private static final long serialVersionUID = 9108007596777603763L; /** * The reason for the skip. */ private final String reason; /** * Constructor with parameter. * * @param reason Skip reason. */ public SkipPlan(String reason) { super(); this.reason = reason; } /** * @return Skip reason. */ public String getReason() { return this.reason; } }
tupilabs/tap4j
src/main/java/org/tap4j/model/SkipPlan.java
Java
mit
1,817
package rise.http; import rise.Token; import org.json.simple.JSONStreamAware; import javax.servlet.http.HttpServletRequest; import static rise.http.JSONResponses.INCORRECT_WEBSITE; import static rise.http.JSONResponses.MISSING_TOKEN; import static rise.http.JSONResponses.MISSING_WEBSITE; public final class DecodeToken extends APIServlet.APIRequestHandler { static final DecodeToken instance = new DecodeToken(); private DecodeToken() { super(new APITag[] {APITag.TOKENS}, "website", "token"); } @Override public JSONStreamAware processRequest(HttpServletRequest req) { String website = req.getParameter("website"); String tokenString = req.getParameter("token"); if (website == null) { return MISSING_WEBSITE; } else if (tokenString == null) { return MISSING_TOKEN; } try { Token token = Token.parseToken(tokenString, website.trim()); return JSONData.token(token); } catch (RuntimeException e) { return INCORRECT_WEBSITE; } } }
risex/risecoin
src/java/rise/http/DecodeToken.java
Java
mit
1,099
package com.hdavidzhu.chatapp; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; // Declares the class ChatAdapter public class ChatAdapter extends ArrayAdapter<ChatHolder> { // Allows context to be accessed outside of the construction and become a class variable. Context context; int resource; List<ChatHolder> listChats; public class ViewHolder { public TextView message, name, timestamp; } public ChatAdapter(Context context, int resource, List<ChatHolder> listChats) { super(context, resource, listChats); this.context = context; this.resource = resource; this.listChats = listChats; } // [???] Does this mean that we are overriding the method that String already provides with this new one? // @Override // public String toString(){ // StringBuilder sb = new StringBuilder(); // for (ChatHolder chat: this.addedChats) { // sb.append("Chat "); // sb.append(chat.id); // sb.append(" at "); // sb.append(chat.timestamp); // sb.append("\n"); // } // return sb.toString(); // } @Override public int getCount(){ Log.d("Stuff","Is getView working?"); return listChats.size(); } @Override public ChatHolder getItem(int position) { Log.d("Stuff","Is getItem working?"); return listChats.get(position); } // Get a view that displays the data at the specified position in the data set. @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; // If we don't have an initial view, if (convertView == null) { // We will generate it from scratch using the following line. // convertView = activity.getLayoutInflater().inflate(R.layout.chat_item,null); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.chat_item, parent, false); viewHolder = new ViewHolder(); viewHolder.message = (TextView) convertView.findViewById(R.id.chat_message); viewHolder.name = (TextView) convertView.findViewById(R.id.chat_name); viewHolder.timestamp = (TextView) convertView.findViewById(R.id.chat_timestamp); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.name.setText(listChats.get(position).name); Log.d(listChats.get(position).name,listChats.get(position).name); viewHolder.message.setText(listChats.get(position).message); Log.d(listChats.get(position).message,listChats.get(position).message); viewHolder.message.setText(listChats.get(position).timestamp); Log.d(listChats.get(position).timestamp,listChats.get(position).timestamp); return convertView; } }
hdavidzhu/MobileProto2014-Lab2
app/src/main/java/com/hdavidzhu/chatapp/ChatAdapter.java
Java
mit
3,192
package diffcalc.view; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.impl.AdapterImpl; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.dialogs.DialogSettings; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog; import org.eclipse.ui.part.ViewPart; import MatchModel.Hero; import MatchModel.MatchModelFactory; import MatchModel.Player; import MatchModel.PlayerGroup; import diffcalc.controller.GroupSuggestion; import diffcalc.controller.HeroSuggestionController; public class HeroSuggestionView extends ViewPart { private class HeroSelectionDialog extends FilteredItemsSelectionDialog { public HeroSelectionDialog(Shell shell, boolean multi) { super(shell, multi); } protected IStatus validateItem(Object item) { return Status.OK_STATUS; } protected Comparator<Hero> getItemsComparator() { return new Comparator<Hero>() { public int compare(Hero o1, Hero o2) { return o1.getId() - o2.getId(); } }; } public String getElementName(Object item) { Hero h = (Hero) item; return h.getName(); } protected IDialogSettings getDialogSettings() { return new DialogSettings("mydotapicker.herodialog"); } protected void fillContentProvider(AbstractContentProvider contentProvider, ItemsFilter itemsFilter, IProgressMonitor progressMonitor) throws CoreException { Collection<Hero> heroes = controller.getAllHeroes(); progressMonitor.beginTask("Searching", heroes.size()); for (Hero h : heroes) { contentProvider.add(h, itemsFilter); progressMonitor.worked(1); } } protected ItemsFilter createFilter() { return new ItemsFilter() { public boolean matchItem(Object item) { Hero hero = (Hero) item; return matches(hero.getName()) ; } public boolean isConsistentItem(Object item) { return true; } }; } protected Control createExtendedContentArea(Composite parent) { return null; } } private class HeroSelectionAdapter extends SelectionAdapter { private Button sourceButton; private HeroSelectionAdapter(Button sourceButton) { this.sourceButton = sourceButton; } @Override public void widgetSelected(SelectionEvent e) { sourceButton.setData(null); updateSuggestedHeroes(); sourceButton.setImage(images.getDefaultImage()); } } public static final String ID = "mydotapicker.view"; private HeroSuggestionController controller; private Images images = new Images(); private TableViewer suggestionViewer; private Composite composite; private Button[] enemies; private Button[] allies; private Button exactDiff; public HeroSuggestionView() { super(); controller = new HeroSuggestionController(); PlayerGroup selected = controller.getFirstAvailableGroup(); if (selected == null) { NewPartyWizard partyWizard = new NewPartyWizard(); WizardDialog dialog = new WizardDialog(null, partyWizard); dialog.open(); if (dialog.getReturnCode() == WizardDialog.OK) { selected = partyWizard.getGroup(); } } if (selected == null) { selected = MatchModelFactory.eINSTANCE.createPlayerGroup(); } updateControlerSelection(selected); } private void updateControlerSelection(PlayerGroup selected) { Adapter adapter = new AdapterImpl() { @Override public void notifyChanged(Notification msg) { Display.getDefault().asyncExec(new Runnable() { public void run() { updateSuggestedHeroes(); } }); } }; controller.setSelected(selected, adapter); } void updateSelection(PlayerGroup group) { updateControlerSelection(group); clearButtons(controller.getSlected().getPlayers().size()); updateSuggestedHeroes(); } private void updateSuggestedHeroes() { final List<Hero> alliedHeroes = getHeroArray(allies); final List<Hero> enemyHeroes = getHeroArray(enemies); final boolean exact = exactDiff.getSelection(); // TODO Reuse job and cancel at dispose... Job suggestHeroJob = new Job("Parsing matches"){ protected IStatus run(IProgressMonitor monitor) { if (controller.getSlected() == null) { return Status.CANCEL_STATUS; } try { List<GroupSuggestion> suggestions = controller.getSuggestedHeroes(alliedHeroes, enemyHeroes, exact); Display.getDefault().asyncExec(new Runnable(){ public void run() { suggestionViewer.setInput(null); List<Player> players = controller.getSlected().getPlayers(); for (int i = 0; i < 5; i++) { TableColumn column = suggestionViewer.getTable().getColumn(i); if (i < players.size()) { column.setWidth(150); column.setText(players.get(i).getName()); } else { column.setWidth(0); column.setText(""); } } suggestionViewer.setInput(suggestions); composite.pack(); }}); } catch (InterruptedException e) { // TODO Return error e.printStackTrace(); } return Status.OK_STATUS; }}; suggestHeroJob.schedule(); } public void createPartControl(Composite parent) { composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(1, false)); exactDiff = new Button(composite, SWT.CHECK); exactDiff.setText("Exact diff"); exactDiff.setSelection(true); exactDiff.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateSuggestedHeroes(); } }); Composite buttonComposite = new Composite(composite, SWT.NONE); buttonComposite.setLayout(new GridLayout(5, false)); enemies = new Button[5]; for (int i = 0; i < enemies.length; i++) { enemies[i] = createButton(buttonComposite); } allies = new Button[5]; for (int i = 0; i < allies.length; i++) { allies[i] = createButton(buttonComposite); } suggestionViewer = new TableViewer(composite, SWT.NONE); suggestionViewer.setContentProvider(ArrayContentProvider.getInstance()); suggestionViewer.getTable().setLinesVisible(true); suggestionViewer.getTable().setHeaderVisible(true); for (int i = 0; i < allies.length; i++) { TableViewerColumn column = new TableViewerColumn(suggestionViewer, SWT.NONE); column.getColumn().setWidth(0); column.setLabelProvider(new HeroLabelProvider(i)); } if (controller.getSlected() != null) { clearButtons(controller.getSlected().getPlayers().size()); } updateSuggestedHeroes(); } private class HeroLabelProvider extends ColumnLabelProvider { private int colNumber; public HeroLabelProvider(int num) { colNumber = num; } @Override public String getText(Object element) { if (element instanceof GroupSuggestion && controller.getSlected().getPlayers().size() > colNumber) { Player player = controller.getSlected().getPlayers().get(colNumber); GroupSuggestion gs = (GroupSuggestion) element; int suggestionSize = exactDiff.getSelection() ? 0 : getHeroArray(allies).size() + getHeroArray(enemies).size(); return gs.printPlayerSuggestion(player, suggestionSize); } return ""; } } private Button createButton(Composite composite) { Button b = new Button(composite, SWT.NONE); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FilteredItemsSelectionDialog dialog = new HeroSelectionDialog(composite.getShell(), false); dialog.setListLabelProvider(new LabelProvider(){ @Override public String getText(Object element) { if (element instanceof Hero) { return ((Hero)element).getName(); } return ""; } }); if (dialog.open() == InputDialog.OK) { Button b = (Button) e.getSource(); Hero h = (Hero) dialog.getResult()[0]; b.setData(h); updateSuggestedHeroes(); b.setImage(images.getHeroImage(h)); } } }); MenuManager menuManager = new MenuManager(); Menu menu = menuManager.createContextMenu(b); b.setMenu(menu); getSite().registerContextMenu(menuManager, getSite().getSelectionProvider()); MenuItem item = new MenuItem(menu, SWT.PUSH); item.setText("Remove"); item.addSelectionListener(new HeroSelectionAdapter(b)); return b; } protected List<Hero> getHeroArray(Button[] array) { ArrayList<Hero> heroes = new ArrayList<Hero>(); for (int i = 0; i < array.length; i++) { Hero h = (Hero) array[i].getData(); if (h != null) { heroes.add(h); } } return heroes; } @Override public void dispose() { images.dispose(); super.dispose(); } private void clearButtons(int partySize) { for (int i = 0; i < 5; i++) { allies[i].setData(null); allies[i].setImage(images.getDefaultImage()); enemies[i].setData(null); enemies[i].setImage(images.getDefaultImage()); allies[i].setEnabled(i >= partySize); } } public void setFocus() { allies[0].setFocus(); } }
BjornArnelid/diffcalc
diffcalc/src/diffcalc/view/HeroSuggestionView.java
Java
mit
10,142
package com.github.scaronthesky.eternalwinterwars.model.units; import java.util.UUID; import org.andengine.entity.sprite.Sprite; import com.github.scaronthesky.eternalwinterwars.model.entity.FightingEntity; import com.github.scaronthesky.eternalwinterwars.model.players.Player; import com.github.scaronthesky.eternalwinterwars.model.units.costbehaviours.CostBehaviour; import com.github.scaronthesky.eternalwinterwars.model.units.movementbehaviours.UnitMovementBehaviour; public abstract class Unit extends FightingEntity { private UnitMovementBehaviour movementBehaviour; private CostBehaviour costBehaviour; /** * A unit. Use UnitBuilder class to create new units. */ public Unit(UUID uuid, String spriteKey, Player owner) { super(uuid, spriteKey, owner); } /** * Returns the number of fields a unit can move. * * @return number of fields. */ public int getMaxMovementRange() { return this.movementBehaviour.getMaxMovementRange(); } /** * Returns the cost of buying this unit. * * @return the cost of the unit. */ public int buy() { return this.costBehaviour.buy(); } /** * Returns the profit of selling this unit. * * @return the profit of selling this unit. */ public int sell() { return this.costBehaviour.sell(); } /** * @param movementBehaviour * the movementBehaviour to set */ public void setMovementBehaviour(UnitMovementBehaviour movementBehaviour) { this.movementBehaviour = movementBehaviour; } /** * @param costBehaviour * the costBehaviour to set */ public void setCostBehaviour(CostBehaviour costBehaviour) { this.costBehaviour = costBehaviour; } }
hinogi/eternalwinterwars
src/com/github/scaronthesky/eternalwinterwars/model/units/Unit.java
Java
mit
1,679
package black.alias.pixelpie.graphics; import black.alias.pixelpie.PixelPie; import processing.core.PApplet; import processing.core.PGraphics; import processing.opengl.PGraphicsOpenGL; public class Graphics { public int x, y, depth, index; public PGraphics graphic; final PixelPie pie; public Graphics(int PosX, int PosY, int objWidth, int objHeight, int Depth, PixelPie pie) { this.pie = pie; x = PosX; y = PosY; depth = Depth; graphic = pie.app.createGraphics(objWidth, objHeight); pie.graphics.add(this); // Set default transparent bg. graphic.noSmooth(); graphic.beginDraw(); graphic.background(0, 0); graphic.endDraw(); } public void draw(int index) { if ( // If it's not on screen, skip draw method. PixelPie.toInt(pie.testOnScreen(x, y)) + PixelPie.toInt(pie.testOnScreen(x + graphic.width, y)) + PixelPie.toInt(pie.testOnScreen(x , y + graphic.height)) + PixelPie.toInt(pie.testOnScreen(x + graphic.width, y + graphic.height)) == 0) { return; } // Add graphic to render queue. pie.depthBuffer.append(PApplet.nf(depth, 4) + 2 + index); } public void render() { // Draw graphic to screen. int startX = PApplet.max(0, -(x - pie.displayX)); int startY = PApplet.max(0, -(y - pie.displayY)); int drawWidth = graphic.width - PApplet.max(0, x + graphic.width - pie.displayX - pie.matrixWidth) - startX; int drawHeight = graphic.height - PApplet.max(0, y + graphic.height - pie.displayY - pie.matrixHeight) - startY; if (pie.app.g instanceof PGraphicsOpenGL) { pie.app.copy( graphic, startX, startY, drawWidth, drawHeight, (startX > 0) ? 0 : (x - pie.displayX) * pie.pixelSize, (startY > 0) ? 0 : (y - pie.displayY) * pie.pixelSize, drawWidth * pie.pixelSize, drawHeight * pie.pixelSize ); } else { pie.app.copy( graphic.get(), startX, startY, drawWidth, drawHeight, (startX > 0) ? 0 : (x - pie.displayX) * pie.pixelSize, (startY > 0) ? 0 : (y - pie.displayY) * pie.pixelSize, drawWidth * pie.pixelSize, drawHeight * pie.pixelSize ); } } }
AliasBlack/pixelpie
pixelpie/src/main/java/black/alias/pixelpie/graphics/Graphics.java
Java
mit
2,141
/* * Certain versions of software and/or documents ("Material") accessible here may contain branding from * Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017, * the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP * and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE * marks are the property of their respective owners. * __________________________________________________________________ * MIT License * * (c) Copyright 2012-2019 Micro Focus or one of its affiliates. * * The only warranties for products and services of Micro Focus and its affiliates * and licensors ("Micro Focus") are set forth in the express warranty statements * accompanying such products and services. Nothing herein should be construed as * constituting an additional warranty. Micro Focus shall not be liable for technical * or editorial errors or omissions contained herein. * The information contained herein is subject to change without notice. * ___________________________________________________________________ */ package com.microfocus.application.automation.tools.results; import hudson.model.DirectoryBrowserSupport; import hudson.model.ModelObject; import hudson.model.Run; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import java.io.IOException; public class DetailReport implements ModelObject { private String name = ""; private String color = ""; private String duration = ""; private String pass = ""; private String fail = ""; private Run<?, ?> build = null; private DirectoryBrowserSupport _directoryBrowserSupport = null; public DetailReport(Run<?,?> build, String name, DirectoryBrowserSupport directoryBrowserSupport) { this.build = build; this.name = name; _directoryBrowserSupport = directoryBrowserSupport; } @Override public String getDisplayName() { return name; } @SuppressWarnings("squid:S1452") public Run<?, ?> getBuild() { return build; } public String getName() { return name; } public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { if (_directoryBrowserSupport != null) _directoryBrowserSupport.generateResponse(req, rsp, this); } public String getColor() { return color; } public void setColor(String value) { color = value; } public String getDuration() { return duration; } public void setDuration(String value) { duration = value; } public String getPass() { return pass; } public void setPass(String value) { pass = value; } public String getFail() { return fail; } public void setFail(String value) { fail = value; } public void updateReport(String duration, String pass, String fail) { setDuration(duration); setPass(pass); setFail(fail); } }
HPSoftware/hpaa-octane-dev
src/main/java/com/microfocus/application/automation/tools/results/DetailReport.java
Java
mit
3,202
package br.edu.ifba.bru.sistemas.ifbaeventos.controller; import java.io.Serializable; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import br.edu.ifba.bru.sistemas.ifbaeventos.model.Participante; import br.edu.ifba.bru.sistemas.service.CadastroParticipantes; import br.edu.ifba.bru.sistemas.service.NegocioException; //@ManagedBean @Named @javax.faces.view.ViewScoped public class CadastroParticipanteBean implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Inject private CadastroParticipantes cadastro; private Participante participante;// = new Participante(); public void prepararCadastro(){ if (this.participante == null){ this.participante = new Participante(); } } public void salvar() { FacesContext context = FacesContext.getCurrentInstance(); try { this.cadastro.salvar(this.participante); //this.pessoa = new Participante(); context.addMessage(null, new FacesMessage( "Participante salvo com sucesso!")); } catch (NegocioException e) { FacesMessage mensagem = new FacesMessage(e.getMessage()); mensagem.setSeverity(FacesMessage.SEVERITY_ERROR); context.addMessage(null, mensagem); } } public Participante getParticipante() { return participante; } public void setParticipante(Participante participante) { this.participante = participante; } }
israelba/ifbaeventos
src/main/java/br/edu/ifba/bru/sistemas/ifbaeventos/controller/CadastroParticipanteBean.java
Java
mit
1,471
package com.apssouza.controllers; import com.apssouza.monitors.TodoServiceMethodInvokedStore; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.LongSummaryStatistics; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RequestMapping("/todo-statistics") @RestController public class TodoServiceStatisticsController { @Autowired TodoServiceMethodInvokedStore monitor; @GetMapping public ObjectNode get() { LongSummaryStatistics statistics = monitor.getStatistics(); return JsonNodeFactory.instance.objectNode(). put("average-duration", statistics.getAverage()). put("invocation-count", statistics.getCount()). put("min-duration", statistics.getMin()). put("max-duration", statistics.getMax()); } }
apssouza22/java-microservice
remainder-service/src/main/java/com/apssouza/controllers/TodoServiceStatisticsController.java
Java
mit
1,081
package com.zheng.upms.rpc.service.impl; import com.zheng.common.annotation.BaseService; import com.zheng.common.base.BaseServiceImpl; import com.zheng.upms.dao.mapper.UpmsUserOrganizationMapper; import com.zheng.upms.dao.model.UpmsUserOrganization; import com.zheng.upms.dao.model.UpmsUserOrganizationExample; import com.zheng.upms.rpc.api.UpmsUserOrganizationService; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * UpmsUserOrganizationService实现 * Created by shuzheng on 2017/3/20. */ @Service @Transactional @BaseService public class UpmsUserOrganizationServiceImpl extends BaseServiceImpl<UpmsUserOrganizationMapper, UpmsUserOrganization, UpmsUserOrganizationExample> implements UpmsUserOrganizationService { private static final Logger LOGGER = LoggerFactory.getLogger(UpmsUserOrganizationServiceImpl.class); @Autowired UpmsUserOrganizationMapper upmsUserOrganizationMapper; @Override public int organization(String[] organizationIds, int id) { int result = 0; // 删除旧记录 UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample(); upmsUserOrganizationExample.createCriteria() .andUserIdEqualTo(id); upmsUserOrganizationMapper.deleteByExample(upmsUserOrganizationExample); // 增加新记录 if (null != organizationIds) { for (String organizationId : organizationIds) { if (StringUtils.isBlank(organizationId)) { continue; } UpmsUserOrganization upmsUserOrganization = new UpmsUserOrganization(); upmsUserOrganization.setUserId(id); upmsUserOrganization.setOrganizationId(NumberUtils.toInt(organizationId)); result = upmsUserOrganizationMapper.insertSelective(upmsUserOrganization); } } return result; } }
shuzheng/zheng
zheng-upms/zheng-upms-rpc-service/src/main/java/com/zheng/upms/rpc/service/impl/UpmsUserOrganizationServiceImpl.java
Java
mit
2,197
package com.example; import android.app.Application; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); return packages; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } }
ivpusic/react-native-image-crop-picker
example/android/app/src/main/java/com/example/MainApplication.java
Java
mit
1,036
package be.idoneus.hipchat.buildbot.config.modules; import be.idoneus.hipchat.buildbot.bot.DefaultCommandDispatcher; import be.idoneus.hipchat.buildbot.bot.DefaultPluginContextBuilder; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.assistedinject.FactoryModuleBuilder; import lombok.extern.slf4j.Slf4j; import be.idoneus.hipchat.buildbot.api.bot.CommandDispatcher; import be.idoneus.hipchat.buildbot.api.bot.PluginContextBuilder; import be.idoneus.hipchat.buildbot.api.domain.Installation; import be.idoneus.hipchat.buildbot.api.store.Store; import be.idoneus.hipchat.buildbot.api.store.StoreFactory; import be.idoneus.hipchat.buildbot.bot.PluginContextBuilderFactory; @Slf4j public class BotModule extends AbstractModule { @Override protected void configure() { bind(CommandDispatcher.class).to(DefaultCommandDispatcher.class); install(new FactoryModuleBuilder() .implement(PluginContextBuilder.class, DefaultPluginContextBuilder.class) .build(PluginContextBuilderFactory.class)); } @Provides Store<Installation> provideInstallationStore(StoreFactory storeFactory) { return storeFactory.get("installations", Installation.class); } }
Idoneus/buildbot
buildbot-core/src/main/java/be/idoneus/hipchat/buildbot/config/modules/BotModule.java
Java
mit
1,272
package IteratorsAndComperators.Lab.Library; import java.util.Arrays; import java.util.List; public class Book { private String title; private int year; private List<String> authors; public Book(String title, int year, String... authors){ setTitle(title); setAuthors(authors); setYear(year); } private void setTitle(String title) { this.title = title; } private void setYear(int year) { this.year = year; } private void setAuthors(String[] authors) { this.authors = Arrays.asList(authors); } public String getTitle() { return title; } public int getYear() { return year; } public List<String> getAuthors() { return authors; } @Override public String toString() { return String.format("title: %s, year: %d, author/s: %s", this.title, this.year, String.join(", ", this.authors)); } }
lmarinov/Exercise-repo
Java_Advanced_2021/src/IteratorsAndComperators/Lab/Library/Book.java
Java
mit
1,001
package com.example.commontasker; import android.app.ActivityGroup; import android.content.Intent; import android.os.Bundle; import android.widget.TabHost; public class createtask extends ActivityGroup { TabHost tabHost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.createtask); tabHost=(TabHost)findViewById(R.id.tabHost); tabHost.setup(this.getLocalActivityManager()); TabHost.TabSpec tabSpec =tabHost.newTabSpec("Tab One"); tabSpec.setContent(new Intent(this,HomeFrag.class)); tabSpec.setIndicator("ELEMENTS OF TASK"); tabHost.addTab(tabSpec); /* TabHost.TabSpec tabSpec2 =tabHost.newTabSpec("Tab One"); tabSpec2.setContent(new Intent(this,TopPaidFragment.class)); tabSpec2.setIndicator("ΧΑΡΤΗΣ"); tabHost.addTab(tabSpec2);*/ } }
netCommonsEU/CommonTasker
app/src/main/java/com/example/commontasker/createtask.java
Java
mit
935
package test_utils; import android.util.SparseArray; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.HashMap; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; public class MockSparseArray { private SparseArray<Object> mocked = mock(SparseArray.class); private HashMap<Integer, Object> map = new HashMap<>(); public static void powerMockNew() throws Exception { whenNew(SparseArray.class).withAnyArguments().thenAnswer(new Answer<SparseArray>() { @Override public SparseArray answer(InvocationOnMock invocation) throws Throwable { return new MockSparseArray().getMockedSparseArray(); } }); } public MockSparseArray() { Answer<Void> writeValueAnswer = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { int key = (int)invocation.getArguments()[0]; Object value = invocation.getArguments()[1]; map.put(key, value); return null; } }; doAnswer(writeValueAnswer).when(mocked).put(anyInt(), anyObject()); when(mocked.get(anyInt())).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { int key = (int)invocation.getArguments()[0]; return map.get(key); } }); when(mocked.size()).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return map.size(); } }); } private SparseArray getMockedSparseArray() { return mocked; } }
jpalves/solid
solid/src/test/java/test_utils/MockSparseArray.java
Java
mit
2,072
package javasockets; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; /** * Класс реализует Server Socket. * Класс создан на основе класса Thread и для работы с ним необходимо перегрузить * метод run(), который выполняется при запуске потока. */ public class Server extends Thread { private int port; public Server(int port) { this.port = port; } @Override public void run() { BufferedReader in = null; PrintWriter out= null; ServerSocket server = null; Socket fromclient = null; try { server = new ServerSocket(port); fromclient = server.accept(); in = new BufferedReader(new InputStreamReader( fromclient.getInputStream())); out = new PrintWriter(fromclient.getOutputStream(), true); String input; while ((input = in.readLine()) != null) { if (input.equalsIgnoreCase("exit")) { break; } out.println("ECHO: " + input); } } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } finally { try { out.close(); in.close(); fromclient.close(); server.close(); } catch (IOException ex) { // ignore } } } }
meefik/java-examples
JavaSockets/src/javasockets/Server.java
Java
mit
1,764
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com) // Copyright (c) 1997 by David Flanagan // This example is provided WITHOUT ANY WARRANTY either expressed or implied. // You may study, use, modify, and distribute it for non-commercial purposes. // For any commercial use, see http://www.davidflanagan.com/javaexamples import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; /** A program that displays all the event that occur in its window */ public class EventTester2 extends Frame { /** The main method: create an EventTester frame, and pop it up */ public static void main(String[] args) { EventTester2 et = new EventTester2(); et.setSize(500, 400); et.show(); } /** The constructor: register the event types we are interested in */ public EventTester2() { super("Event Tester"); this.enableEvents(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.KEY_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK | AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK); } /** * Display mouse events that don't involve mouse motion. * The mousemods() method prints modifiers, and is defined below. * The other methods return additional information about the mouse event. * showLine() displays a line of text in the window. It is defined * at the end of this class, along with the paint() method. */ public void processMouseEvent(MouseEvent e) { String type = null; switch(e.getID()) { case MouseEvent.MOUSE_PRESSED: type = "MOUSE_PRESSED"; break; case MouseEvent.MOUSE_RELEASED: type = "MOUSE_RELEASED"; break; case MouseEvent.MOUSE_CLICKED: type = "MOUSE_CLICKED"; break; case MouseEvent.MOUSE_ENTERED: type = "MOUSE_ENTERED"; break; case MouseEvent.MOUSE_EXITED: type = "MOUSE_EXITED"; break; } showLine(mousemods(e) + type + ": [" + e.getX() + "," + e.getY() + "] " + "num clicks = " + e.getClickCount() + (e.isPopupTrigger()?"; is popup trigger":"")); } /** * Display mouse moved and dragged mouse event. Note that MouseEvent * is the only event type that has two methods, two EventListener interfaces * and two adapter classes to handle two distinct categories of events. * Also, as seen in init(), mouse motion events must be requested * separately from other mouse event types. */ public void processMouseMotionEvent(MouseEvent e) { String type = null; switch(e.getID()) { case MouseEvent.MOUSE_MOVED: type = "MOUSE_MOVED"; break; case MouseEvent.MOUSE_DRAGGED: type = "MOUSE_DRAGGED"; break; } showLine(mousemods(e) + type + ": [" + e.getX() + "," + e.getY() + "] " + "num clicks = " + e.getClickCount() + (e.isPopupTrigger()?"; is popup trigger":"")); } /** Return a string representation of the modifiers for a MouseEvent. * Note that the methods called here are inherited from InputEvent. */ protected String mousemods(MouseEvent e) { int mods = e.getModifiers(); String s = ""; if (e.isShiftDown()) s += "Shift "; if (e.isControlDown()) s += "Ctrl "; if ((mods & InputEvent.BUTTON1_MASK) != 0) s += "Button 1 "; if ((mods & InputEvent.BUTTON2_MASK) != 0) s += "Button 2 "; if ((mods & InputEvent.BUTTON3_MASK) != 0) s += "Button 3 "; return s; } /** * Display keyboard events. * Note that there are three distinct types of key events, and that * key events are reported by key code and/or Unicode character. * KEY_PRESSED and KEY_RELEASED events are generated for all key strokes. * KEY_TYPED events are only generated when a key stroke produces a * Unicode character; these events do not report a key code. * If isActionKey() returns true, then the key event reports only * a key code, because the key that was pressed or released (such as a * function key) has no corresponding Unicode character. * Key codes can be interpreted by using the many VK_ constants defined * by the KeyEvent class, or they can be converted to strings using * the static getKeyText() method as we do here. */ public void processKeyEvent(KeyEvent e) { String eventtype, modifiers, code, character; switch(e.getID()) { case KeyEvent.KEY_PRESSED: eventtype = "KEY_PRESSED"; break; case KeyEvent.KEY_RELEASED: eventtype = "KEY_RELEASED"; break; case KeyEvent.KEY_TYPED: eventtype = "KEY_TYPED"; break; default: eventtype = "UNKNOWN"; } // Convert the list of modifier keys to a string modifiers = KeyEvent.getKeyModifiersText(e.getModifiers()); // Get string and numeric versions of the key code, if any. if (e.getID() == KeyEvent.KEY_TYPED) code = ""; else code = "Code=" + KeyEvent.getKeyText(e.getKeyCode()) + " (" + e.getKeyCode() + ")"; // Get string and numeric versions of the Unicode character, if any. if (e.isActionKey()) character = ""; else character = "Character=" + e.getKeyChar() + " (Unicode=" + ((int)e.getKeyChar()) + ")"; // Display it all. showLine(eventtype + ": " + modifiers + " " + code + " " + character); } /** Display keyboard focus events. Focus can be permanently * gained or lost, or temporarily transferred to or from a component. */ public void processFocusEvent(FocusEvent e) { if (e.getID() == FocusEvent.FOCUS_GAINED) showLine("FOCUS_GAINED" + (e.isTemporary()?" (temporary)":"")); else showLine("FOCUS_LOST" + (e.isTemporary()?" (temporary)":"")); } /** Display Component events. */ public void processComponentEvent(ComponentEvent e) { switch(e.getID()) { case ComponentEvent.COMPONENT_MOVED: showLine("COMPONENT_MOVED"); break; case ComponentEvent.COMPONENT_RESIZED: showLine("COMPONENT_RESIZED");break; case ComponentEvent.COMPONENT_HIDDEN: showLine("COMPONENT_HIDDEN"); break; case ComponentEvent.COMPONENT_SHOWN: showLine("COMPONENT_SHOWN"); break; } } /** Display Window events. Note the special handling of WINDOW_CLOSING */ public void processWindowEvent(WindowEvent e) { switch(e.getID()) { case WindowEvent.WINDOW_OPENED: showLine("WINDOW_OPENED"); break; case WindowEvent.WINDOW_CLOSED: showLine("WINDOW_CLOSED"); break; case WindowEvent.WINDOW_CLOSING: showLine("WINDOW_CLOSING"); break; case WindowEvent.WINDOW_ICONIFIED: showLine("WINDOW_ICONIFIED"); break; case WindowEvent.WINDOW_DEICONIFIED: showLine("WINDOW_DEICONIFIED"); break; case WindowEvent.WINDOW_ACTIVATED: showLine("WINDOW_ACTIVATED"); break; case WindowEvent.WINDOW_DEACTIVATED: showLine("WINDOW_DEACTIVATED"); break; } // If the user requested a window close, quit the program. // But first display a message, force it to be visible, and make // sure the user has time to read it. if (e.getID() == WindowEvent.WINDOW_CLOSING) { showLine("WINDOW_CLOSING event received."); showLine("Application will exit in 5 seconds"); update(this.getGraphics()); try {Thread.sleep(5000);} catch (InterruptedException ie) { ; } System.exit(0); } } /** The list of lines to display in the window */ protected Vector lines = new Vector(); /** Add a new line to the list of lines, and redisplay */ protected void showLine(String s) { if (lines.size() == 20) lines.removeElementAt(0); lines.addElement(s); repaint(); } /** This method repaints the text in the window */ public void paint(Graphics g) { for(int i = 0; i < lines.size(); i++) g.drawString((String)lines.elementAt(i), 20, i*16 + 50); } }
shashanksingh28/code-similarity
test/Java Examples in a Nutshell/1st Edition/EventTester2.java
Java
mit
7,763
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.containerregistry.implementation; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.Get; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.containerregistry.fluent.OperationsClient; import com.azure.resourcemanager.containerregistry.fluent.models.OperationDefinitionInner; import com.azure.resourcemanager.containerregistry.models.OperationListResult; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in OperationsClient. */ public final class OperationsClientImpl implements OperationsClient { private final ClientLogger logger = new ClientLogger(OperationsClientImpl.class); /** The proxy service used to perform REST calls. */ private final OperationsService service; /** The service client containing this operation class. */ private final ContainerRegistryManagementClientImpl client; /** * Initializes an instance of OperationsClientImpl. * * @param client the instance of the service client containing this operation class. */ OperationsClientImpl(ContainerRegistryManagementClientImpl client) { this.service = RestProxy.create(OperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for ContainerRegistryManagementClientOperations to be used by the proxy * service to perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "ContainerRegistryMan") private interface OperationsService { @Headers({"Content-Type: application/json"}) @Get("/providers/Microsoft.ContainerRegistry/operations") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<OperationListResult>> list( @HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<OperationListResult>> listNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); } /** * Lists all of the available Azure Container Registry REST API operations. * * @throws 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 result of a request to list container registry operations. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationDefinitionInner>> listSinglePageAsync() { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String apiVersion = "2021-09-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.list(this.client.getEndpoint(), apiVersion, accept, context)) .<PagedResponse<OperationDefinitionInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Lists all of the available Azure Container Registry REST API operations. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws 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 result of a request to list container registry operations. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationDefinitionInner>> listSinglePageAsync(Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String apiVersion = "2021-09-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service .list(this.client.getEndpoint(), apiVersion, accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Lists all of the available Azure Container Registry REST API operations. * * @throws 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 result of a request to list container registry operations. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<OperationDefinitionInner> listAsync() { return new PagedFlux<>(() -> listSinglePageAsync(), nextLink -> listNextSinglePageAsync(nextLink)); } /** * Lists all of the available Azure Container Registry REST API operations. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws 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 result of a request to list container registry operations. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<OperationDefinitionInner> listAsync(Context context) { return new PagedFlux<>( () -> listSinglePageAsync(context), nextLink -> listNextSinglePageAsync(nextLink, context)); } /** * Lists all of the available Azure Container Registry REST API operations. * * @throws 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 result of a request to list container registry operations. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<OperationDefinitionInner> list() { return new PagedIterable<>(listAsync()); } /** * Lists all of the available Azure Container Registry REST API operations. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws 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 result of a request to list container registry operations. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<OperationDefinitionInner> list(Context context) { return new PagedIterable<>(listAsync(context)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws 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 result of a request to list container registry operations. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationDefinitionInner>> listNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) .<PagedResponse<OperationDefinitionInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws 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 result of a request to list container registry operations. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<OperationDefinitionInner>> listNextSinglePageAsync(String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .listNext(nextLink, this.client.getEndpoint(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } }
Azure/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/implementation/OperationsClientImpl.java
Java
mit
12,583
package net.minecraft.src; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.PacketDispatcher; import cpw.mods.fml.common.network.Player; import cpw.mods.fml.common.registry.BlockProxy; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.util.Iterator; import java.util.Random; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import static net.minecraftforge.common.ForgeDirection.*; public class YC_BlockCrystalizer extends BlockContainer implements BlockProxy { private Random random = new Random(); protected YC_BlockCrystalizer(int par1) { super(par1, Material.rock); //func_94332_a(YC_ClientProxy.textureMap); this.setCreativeTab(CreativeTabs.tabMisc); setHardness(1); setResistance(5); setTickRandomly(true); } @Override @SideOnly(Side.CLIENT) public void func_94332_a(IconRegister par1IconRegister) { field_94336_cN = par1IconRegister.func_94245_a("blockIron"); } public boolean isOpaqueCube() { return false; } /** * Checks to see if its valid to put this block at the specified coordinates. Args: world, x, y, z */ //public boolean canPlaceBlockAt(World par1World, int par2, int par3, int par4) //{ // return true; //} /** * ejects contained items into the world, and notifies neighbours of an update, as appropriate */ public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6) { YC_TileEntityBlockCrystalizer var7 = (YC_TileEntityBlockCrystalizer)par1World.getBlockTileEntity(par2, par3, par4); if (var7 != null) { for (int var8 = 0; var8 < var7.getSizeInventory(); ++var8) { ItemStack var9 = var7.getStackInSlot(var8); if (var9 != null) { float var10 = this.random.nextFloat() * 0.8F + 0.1F; float var11 = this.random.nextFloat() * 0.8F + 0.1F; EntityItem var14; for (float var12 = this.random.nextFloat() * 0.8F + 0.1F; var9.stackSize > 0; par1World.spawnEntityInWorld(var14)) { int var13 = this.random.nextInt(21) + 10; if (var13 > var9.stackSize) { var13 = var9.stackSize; } var9.stackSize -= var13; var14 = new EntityItem(par1World, (double)((float)par2 + var10), (double)((float)par3 + var11), (double)((float)par4 + var12), new ItemStack(var9.itemID, var13, var9.getItemDamage())); float var15 = 0.05F; var14.motionX = (double)((float)this.random.nextGaussian() * var15); var14.motionY = (double)((float)this.random.nextGaussian() * var15 + 0.2F); var14.motionZ = (double)((float)this.random.nextGaussian() * var15); if (var9.hasTagCompound()) { //func_92014_d() == getitem var14.getEntityItem().setTagCompound((NBTTagCompound)var9.getTagCompound().copy()); } } } } } super.breakBlock(par1World, par2, par3, par4, par5, par6); } @Override public String getUnlocalizedName() { return "Crystalizer"; } public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) { YC_TileEntityBlockCrystalizer w = (YC_TileEntityBlockCrystalizer)world.getBlockTileEntity(x, y, z); PacketDispatcher.sendPacketToPlayer(w.getDescriptionPacket(), (Player) player); //YC_GUIBlockDetector g = new YC_GUIBlockDetector(ModLoader.getMinecraftInstance().thePlayer.inventory, w); player.openGui(YC_Mod.instance, YC_Mod.c_blockCrystalizerGuiID, world, x, y, z); return true; } /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ public TileEntity createNewTileEntity(World par1World) { return new YC_TileEntityBlockCrystalizer(); } @Override public TileEntity createTileEntity(World world, int metadata) { return new YC_TileEntityBlockCrystalizer(); } @Override public int getRenderType() { return YC_Mod.c_crystalizerRenderID; } @Override public boolean renderAsNormalBlock() { return false; } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(World par1World, int par2, int par3, int par4, Random par5Random) { //Minecraft.getMinecraft().effectRenderer.addEffect( // (EntityFX)new YC_EntityFXAstralAura(par1World, par2, par3, par4, 0, 0, 0), // null); } @Override public int tickRate(World par1World) { return 1; } }
XZelnar/AstralCraft
src/YC_BlockCrystalizer.java
Java
mit
5,787
package com.hmkcode.spring.mybatis.mapper; import java.util.List; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import com.hmkcode.spring.mybatis.vo.Child; import com.hmkcode.spring.mybatis.vo.Parent;; public interface Mapper { //if @Select is used table/column name and class/property name should be the same //SQL query in "Mapper.xml" public List<Parent> selectAllParent(); //SQL query in "Mapper.xml" public Parent selectParent(@Param("id") int id); @Insert("INSERT INTO parent (parentName) VALUES (#{parentName})") public int insertParent(Parent parent); @Select("SELECT * FROM child WHERE parentId = #{id}") public List<Child> selectAllChildren(@Param("id") int id); @Select("SELECT * FROM child WHERE childId = #{id}") public Child selectChild(@Param("id") int id); //SQL query in "Mapper.xml" public int insertchild(Child child); }
rchumarin/java-course-ee
Spring/spring-mybatis-junit/src/main/java/com/hmkcode/spring/mybatis/mapper/Mapper.java
Java
mit
963
/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 5.0 */ /* JavaCCOptions: */ package com.infdot.analysis.parser; /** Token Manager Error. */ public class TokenMgrError extends Error { /** * The version identifier for this Serializable class. * Increment only if the <i>serialized</i> form of the * class changes. */ private static final long serialVersionUID = 1L; /* * Ordinals for various reasons why an Error of this type can be thrown. */ /** * Lexical error occurred. */ static final int LEXICAL_ERROR = 0; /** * An attempt was made to create a second instance of a static token manager. */ static final int STATIC_LEXER_ERROR = 1; /** * Tried to change to an invalid lexical state. */ static final int INVALID_LEXICAL_STATE = 2; /** * Detected (and bailed out of) an infinite loop in the token manager. */ static final int LOOP_DETECTED = 3; /** * Indicates the reason why the exception is thrown. It will have * one of the above 4 values. */ int errorCode; /** * Replaces unprintable characters by their escaped (or unicode escaped) * equivalents in the given string */ protected static final String addEscapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } /** * Returns a detailed message for the Error when it is thrown by the * token manager to indicate a lexical error. * Parameters : * EOFSeen : indicates if EOF caused the lexical error * curLexState : lexical state in which this error occurred * errorLine : line number when the error occurred * errorColumn : column number when the error occurred * errorAfter : prefix that was seen before this error occurred * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** * You can also modify the body of this method to customize your error messages. * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not * of end-users concern, so you can return something like : * * "Internal Error : Please file a bug report .... " * * from this method for such cases in the release version of your parser. */ public String getMessage() { return super.getMessage(); } /* * Constructors of various flavors follow. */ /** No arg constructor. */ public TokenMgrError() { } /** Constructor with message and reason. */ public TokenMgrError(String message, int reason) { super(message); errorCode = reason; } /** Full Constructor. */ public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); } } /* JavaCC - OriginalChecksum=41171118c15841b535505e659badd150 (do not edit this line) */
rla/while
parser/src/com/infdot/analysis/parser/TokenMgrError.java
Java
mit
4,436
package io.loefflefarn.bnet.api; import static org.junit.Assert.assertEquals; import io.loefflefarn.bnet.api.domain.BnetRequest; import io.loefflefarn.bnet.api.domain.Region; import java.util.Locale; import org.junit.Test; public class SimpleBnetRequestServiceTest { private final BnetRequestService service = new SimpleBnetRequestService(); @Test public void request() throws Exception { testRequestAndGet(); } @Test public void get() throws Exception { testRequestAndGet(); } private void testRequestAndGet() { BnetRequest request = new BnetRequest(Region.EUROPE, Locale.GERMANY, "XXXXXXXXXX", "d3", "profile"); request.getPathParams().put("battleTag", "gamerXYZ"); String response = (String) service.request(request).get(); assertEquals("{\"code\":403, \"type\":\"Forbidden\", \"detail\":\"Account Inactive\"}", response); } }
loefflefarn/battlenet-api-client
src/test/java/io/loefflefarn/bnet/api/SimpleBnetRequestServiceTest.java
Java
mit
923
/* The MIT License (MIT) Copyright (c) 2008 Kleber Maia de Andrade 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 imanager.ui.entity; import iobjects.*; import iobjects.entity.*; import iobjects.ui.entity.*; import imanager.entity.*; /** * Utilitário para criação de controles para a classe Departamento. */ public class DepartamentoUI { /** * Retorna a representação HTML de um LookupList contendo valores da * entidade Departamento. * @param facade Fachada. * @param param Param cujas propriedades irão gerar o controle de seleção. * @param empresaId Empresa ID. * @param width int Largura do controle de seleção na página ou 0 (zero) para * que ele se ajuste automaticamente ao seu conteiner. * @param style String Estilo de formatação do ParamFormSelect. * @param onChangeScript Código JavaScript para ser executado quando o usuário * alterar o valor do elemento HTML. * @return Retorna a representação HTML de um LookupList contendo valores * da entidade Departamento. * @throws java.lang.Exception */ static public String lookupListForParam(Facade facade, int empresaId, Param param, int width, String style, String onChangeScript) throws Exception { // retorna return LookupList.script(facade, Departamento.CLASS_NAME, "global_departamento", new String[]{Departamento.FIELD_NOME.getFieldName()}, new String[]{Departamento.FIELD_DEPARTAMENTO_ID.getFieldName()}, new String[]{param.getIntValue() + ""}, new String[]{Departamento.FIELD_NOME.getFieldName()}, Departamento.FIELD_EMPRESA_ID.getFieldName() + "=" + empresaId, LookupList.SELECT_TYPE_SINGLE, param.getName(), param.getScriptConstraint(), param.getScriptConstraintErrorMessage(), "width:" + (width > 0 ? width + "px;" : "100%;") + style, onChangeScript, true); } /** * Retorna a representação JavaScript de um LookupList contendo valores da * entidade Departamento. * @param facade Fachada. * @param entityLookup EntityLookup cujas propriedades irão gerar o controle de seleção. * @param entityInfo EntityInfo contendo os valores do registro que está sendo * editado/inserido. * @param empresaId Empreda ID. * @param width int Largura do controle de seleção na página ou 0 (zero) para * que ele se ajuste automaticamente ao seu conteiner. * @param style String Estilo de formatação do ParamFormSelect. * @param onChangeScript Código JavaScript para ser executado quando o usuário * alterar o valor do elemento HTML. * @return Retorna a representação JavaScript de um LookupList contendo * valores da entidade Departamento. * @throws Exception Em caso de exceção na tentativa de acesso ao banco de dados. */ static public String lookupListForLookup(Facade facade, EntityLookup entityLookup, EntityInfo entityInfo, int empresaId, int width, String style, String onChangeScript) throws Exception { // obtém Departamento ID Integer departamentoId = (Integer)entityInfo.getPropertyValue(entityLookup.getKeyFields()[1].getFieldAlias()); // retorna return LookupList.script(facade, Departamento.CLASS_NAME, "global_departamento", new String[]{Departamento.FIELD_NOME.getFieldName()}, new String[]{Departamento.FIELD_DEPARTAMENTO_ID.getFieldName()}, new String[]{departamentoId + ""}, new String[]{Departamento.FIELD_NOME.getFieldName()}, "(" + Departamento.FIELD_EMPRESA_ID.getFieldName() + " = " + empresaId + ")", LookupList.SELECT_TYPE_SINGLE, entityLookup.getKeyFields()[1].getFieldAlias(), entityLookup.getKeyFields()[1].getScriptConstraint(), entityLookup.getKeyFields()[1].getScriptConstraintErrorMessage(), (width > 0 ? "width:" + width + "px;" : "width:100%;") + style, onChangeScript, true); } private DepartamentoUI() { } }
kleber-maia/iobjects-crm
src/java/imanager/ui/entity/DepartamentoUI.java
Java
mit
6,278
package com.nucleus.app; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import helper.AppConstant; /** * Created by Anand.M.P on 1/30/2016. */ public class Camera extends AppCompatActivity { public static final String TAG = Camera.class.getSimpleName(); static final int REQUEST_IMAGE_CAPTURE = 1; private Bitmap mImageBitmap; private String mCurrentPhotoPath; private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.camera_layout); mImageView = (ImageView) findViewById(R.id.mImageView); Button btnCameraCompress = (Button) findViewById(R.id.btnCameraCompress); Button btnCameraCancel = (Button) findViewById(R.id.btnCameraCancel); Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File Log.i(TAG, "IOException"); } // Continue only if the File was successfully created if (photoFile != null) { cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE); } } btnCameraCompress.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { // Log.d("imgpath", _imagePaths.get(position)); Intent compressImage = new Intent(v.getContext(), BitmapActivity.class); compressImage.putExtra("COMPRESS_IMAGE", "101"); compressImage.putExtra("IMAGE_PATH", mCurrentPhotoPath); v.getContext().startActivity(compressImage); } }); btnCameraCancel.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { // Log.d("imgpath", _imagePaths.get(position)); Intent backToMainActivity = new Intent(v.getContext(), MainActivity.class); v.getContext().startActivity(backToMainActivity); } }); } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; // File storageDir = Environment.getExternalStoragePublicDirectory( // Environment.DIRECTORY_PICTURES); File storageDir = new File( android.os.Environment.getExternalStorageDirectory() + File.separator + "DCIM/Camera"); File image = File.createTempFile( imageFileName, // prefix ".jpg", // suffix storageDir // directory ); // Save a file: path for use with ACTION_VIEW intents mCurrentPhotoPath = "file:" + image.getAbsolutePath(); return image; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { try { mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)); mImageView.setImageBitmap(mImageBitmap); } catch (IOException e) { e.printStackTrace(); } } } }
TheAndroidApp/Nucleus
app/src/main/java/com/nucleus/app/Camera.java
Java
mit
4,249
package thahn.java.agui.ide.eclipse.wizard; public class TextUtils { /** * Returns true if the string is null or 0-length. * * @param str * the string to be examined * @return true if str is null or zero length */ public static boolean isNullorEmpty(CharSequence str) { if (str == null || str.length() == 0) return true; else return false; } public static boolean isNullorEmpty(String str) { if (str == null || str.length() == 0 || str.trim().equals("")) return true; else return false; } public static String makeCiphers(int cipers, int digit) { StringBuilder index = new StringBuilder(); index.append(digit); int temp = 0; int unit = 10; int count = 1; while ((temp = digit / unit) > 0) { unit *= 10; ++count; } for (int j = 0; j < 5 - count; ++j) { index.insert(0, "0"); } return index.toString(); } }
thahn0720/agui_eclipse_plugin
src/thahn/java/agui/ide/eclipse/wizard/TextUtils.java
Java
mit
932
package com.orange.lecons; import static org.fest.assertions.api.Assertions.assertThat; import org.junit.Test; public class Lecon5DesComparaisonsTest { private Lecon5DesComparaisons lecon5 = new Lecon5DesComparaisons(); @Test public void je_retourne_le_plus_grand() throws Exception { int lePlusGrand = lecon5.je_retourne_le_plus_grand(4, 10); assertThat(lePlusGrand).isEqualTo(4); } @Test public void je_retourne_le_plus_petit() throws Exception { int lePlusPetit = lecon5.je_retourne_le_plus_petit(4, 10); assertThat(lePlusPetit).isEqualTo(4); } }
bastiendavid/learn-java
src/test/java/com/orange/lecons/Lecon5DesComparaisonsTest.java
Java
mit
573
package net.minecraft.client.gui; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.io.IOException; import java.util.Iterator; import java.util.Map; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.Language; import net.minecraft.client.resources.LanguageManager; import net.minecraft.client.settings.GameSettings; public class GuiLanguage extends GuiScreen { protected GuiScreen field_146453_a; private GuiLanguage.List field_146450_f; /** Reference to the GameSettings object. */ private final GameSettings game_settings_3; private final LanguageManager field_146454_h; private GuiOptionButton field_146455_i; private GuiOptionButton field_146452_r; private static final String __OBFID = "CL_00000698"; public GuiLanguage(GuiScreen p_i1043_1_, GameSettings p_i1043_2_, LanguageManager p_i1043_3_) { this.field_146453_a = p_i1043_1_; this.game_settings_3 = p_i1043_2_; this.field_146454_h = p_i1043_3_; } /** * Adds the buttons (and other controls) to the screen in question. */ public void initGui() { this.buttonList.add(this.field_146455_i = new GuiOptionButton(100, this.width / 2 - 155, this.height - 38, GameSettings.Options.FORCE_UNICODE_FONT, this.game_settings_3.getKeyBinding(GameSettings.Options.FORCE_UNICODE_FONT))); this.buttonList.add(this.field_146452_r = new GuiOptionButton(6, this.width / 2 - 155 + 160, this.height - 38, I18n.format("gui.done", new Object[0]))); this.field_146450_f = new GuiLanguage.List(this.mc); this.field_146450_f.registerScrollButtons(7, 8); } /** * Handles mouse input. */ public void handleMouseInput() throws IOException { super.handleMouseInput(); this.field_146450_f.func_178039_p(); } protected void actionPerformed(GuiButton button) throws IOException { if (button.enabled) { switch (button.id) { case 5: break; case 6: this.mc.displayGuiScreen(this.field_146453_a); break; case 100: if (button instanceof GuiOptionButton) { this.game_settings_3.setOptionValue(((GuiOptionButton)button).returnEnumOptions(), 1); button.displayString = this.game_settings_3.getKeyBinding(GameSettings.Options.FORCE_UNICODE_FONT); ScaledResolution var2 = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight); int var3 = var2.getScaledWidth(); int var4 = var2.getScaledHeight(); this.setWorldAndResolution(this.mc, var3, var4); } break; default: this.field_146450_f.actionPerformed(button); } } } /** * Draws the screen and all the components in it. Args : mouseX, mouseY, renderPartialTicks */ public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.field_146450_f.drawScreen(mouseX, mouseY, partialTicks); this.drawCenteredString(this.fontRendererObj, I18n.format("options.language", new Object[0]), this.width / 2, 16, 16777215); this.drawCenteredString(this.fontRendererObj, "(" + I18n.format("options.languageWarning", new Object[0]) + ")", this.width / 2, this.height - 56, 8421504); super.drawScreen(mouseX, mouseY, partialTicks); } class List extends GuiSlot { private final java.util.List field_148176_l = Lists.newArrayList(); private final Map field_148177_m = Maps.newHashMap(); private static final String __OBFID = "CL_00000699"; public List(Minecraft mcIn) { super(mcIn, GuiLanguage.this.width, GuiLanguage.this.height, 32, GuiLanguage.this.height - 65 + 4, 18); Iterator var3 = GuiLanguage.this.field_146454_h.getLanguages().iterator(); while (var3.hasNext()) { Language var4 = (Language)var3.next(); this.field_148177_m.put(var4.getLanguageCode(), var4); this.field_148176_l.add(var4.getLanguageCode()); } } protected int getSize() { return this.field_148176_l.size(); } protected void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY) { Language var5 = (Language)this.field_148177_m.get(this.field_148176_l.get(slotIndex)); GuiLanguage.this.field_146454_h.setCurrentLanguage(var5); GuiLanguage.this.game_settings_3.language = var5.getLanguageCode(); this.mc.refreshResources(); GuiLanguage.this.fontRendererObj.setUnicodeFlag(GuiLanguage.this.field_146454_h.isCurrentLocaleUnicode() || GuiLanguage.this.game_settings_3.forceUnicodeFont); GuiLanguage.this.fontRendererObj.setBidiFlag(GuiLanguage.this.field_146454_h.isCurrentLanguageBidirectional()); GuiLanguage.this.field_146452_r.displayString = I18n.format("gui.done", new Object[0]); GuiLanguage.this.field_146455_i.displayString = GuiLanguage.this.game_settings_3.getKeyBinding(GameSettings.Options.FORCE_UNICODE_FONT); GuiLanguage.this.game_settings_3.saveOptions(); } protected boolean isSelected(int slotIndex) { return ((String)this.field_148176_l.get(slotIndex)).equals(GuiLanguage.this.field_146454_h.getCurrentLanguage().getLanguageCode()); } protected int getContentHeight() { return this.getSize() * 18; } protected void drawBackground() { GuiLanguage.this.drawDefaultBackground(); } protected void drawSlot(int p_180791_1_, int p_180791_2_, int p_180791_3_, int p_180791_4_, int p_180791_5_, int p_180791_6_) { GuiLanguage.this.fontRendererObj.setBidiFlag(true); GuiLanguage.this.drawCenteredString(GuiLanguage.this.fontRendererObj, ((Language)this.field_148177_m.get(this.field_148176_l.get(p_180791_1_))).toString(), this.width / 2, p_180791_3_ + 1, 16777215); GuiLanguage.this.fontRendererObj.setBidiFlag(GuiLanguage.this.field_146454_h.getCurrentLanguage().isBidirectional()); } } }
Hexeption/Youtube-Hacked-Client-1.8
minecraft/net/minecraft/client/gui/GuiLanguage.java
Java
mit
6,571
package com.java.group34; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.java.group34", appContext.getPackageName()); } }
bennyguo/AssemblyNews
app/src/androidTest/java/com/java/group34/ExampleInstrumentedTest.java
Java
mit
736
package tdc2014.temporal; import java.time.LocalDate; import java.time.temporal.Temporal; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAdjusters; public class DiaPagamentoAdjuster implements TemporalAdjuster { private final DiasUteisAdjuster quintoDiaUtilAdjuster; public DiaPagamentoAdjuster() { this.quintoDiaUtilAdjuster = new DiasUteisAdjuster(5); } @Override public Temporal adjustInto(final Temporal temporal) { final LocalDate date = LocalDate.from(temporal); final LocalDate firtsDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth()); final LocalDate payDay = firtsDayOfMonth.with(quintoDiaUtilAdjuster); if (date.isAfter(payDay)) { return date.with(TemporalAdjusters.firstDayOfNextMonth()).with(this); } return payDay; } }
mgraciano/tdc-2014
date-time/src/main/java/tdc2014/temporal/DiaPagamentoAdjuster.java
Java
mit
870
package com.moerog.util; import java.io.Reader; import org.apache.log4j.Logger; import org.apache.struts.actions.EventDispatchAction; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; import com.moerog.user.UserAction; public class BasicEventDispatchAction extends EventDispatchAction { protected static Logger logger = Logger.getLogger(UserAction.class); protected SqlMapClient client; public BasicEventDispatchAction() { try { String resource = "com/moerog/config/sqlConfig.xml"; Reader reader = Resources.getResourceAsReader(resource); client = SqlMapClientBuilder.buildSqlMapClient(reader); } catch (Exception e) { e.printStackTrace(); } } }
m0er/university-projects
mOerog-struts/src/com/moerog/util/BasicEventDispatchAction.java
Java
mit
796
package uk.gov.dvsa.ui.pages.login; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import uk.gov.dvsa.framework.config.webdriver.MotAppDriver; import uk.gov.dvsa.helper.PageInteractionHelper; import uk.gov.dvsa.ui.interfaces.WarningPage; import uk.gov.dvsa.ui.pages.Page; public class LockOutWarningPage extends Page implements WarningPage { private static final String PAGE_TITLE = "Authentication failed"; private static final String LOCKOUT_WARNING_MESSAGE = "You have tried to sign in 4 times"; @FindBy(linkText = "change your password") private WebElement changePasswordLink; @FindBy(className = "banner--error") private WebElement warningMessage; public LockOutWarningPage(MotAppDriver driver) { super(driver); selfVerify(); } @Override protected boolean selfVerify() { return PageInteractionHelper.verifyTitle(warningMessage.getText(), LOCKOUT_WARNING_MESSAGE); } @Override public boolean isMessageDisplayed() { return warningMessage.getText().contains(LOCKOUT_WARNING_MESSAGE); } }
dvsa/mot
mot-selenium/src/main/java/uk/gov/dvsa/ui/pages/login/LockOutWarningPage.java
Java
mit
1,112
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ package org.ligoj.app.plugin.prov.dao; import java.util.List; import javax.cache.annotation.CacheKey; import javax.cache.annotation.CacheResult; import org.ligoj.app.plugin.prov.model.ProvContainerPrice; import org.ligoj.app.plugin.prov.model.ProvContainerType; import org.ligoj.app.plugin.prov.model.VmOs; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; /** * {@link ProvContainerPrice} repository. */ public interface ProvContainerPriceRepository extends BaseProvTermPriceOsRepository<ProvContainerType, ProvContainerPrice> { @Override @CacheResult(cacheName = "prov-container-license") List<String> findAllLicenses(@CacheKey String node, @CacheKey VmOs os); @Override @CacheResult(cacheName = "prov-container-os") List<String> findAllOs(@CacheKey String node); /** * Return the lowest instance price configuration from the minimal requirements. * * @param types The valid instance type identifiers. * @param terms The valid instance terms identifiers. * @param cpu The required CPU. * @param gpu The required CPU. * @param ram The required RAM in GiB. * @param os The requested OS. * @param location The requested location identifier. * @param rate Usage rate. Positive number. Maximum is <code>1</code>, minimum is <code>0.01</code>. * @param globalRate Usage rate multiplied by the duration. Should be <code>rate * duration</code>. * @param duration The duration in month. Minimum is 1. * @param license Optional license notice. When not <code>null</code> a license constraint is added. * @param initialCost The maximal initial cost. * @param pageable The page control to return few item. * @return The cheapest container price or empty result. */ @Query(""" SELECT ip, ( ip.cost + CEIL(GREATEST(ip.minCpu, :cpu) /ip.incrementCpu) * ip.incrementCpu * ip.costCpu + CASE WHEN (ip.incrementGpu IS NULL OR ip.incrementGpu=0.0) THEN 0.0 ELSE (CEIL(GREATEST(ip.minGpu, :gpu) /ip.incrementGpu) * ip.incrementGpu * ip.costGpu) END + CEIL(GREATEST(GREATEST(ip.minCpu, :cpu) * COALESCE(ip.minRamRatio,0.0), :ram) /ip.incrementRam) * ip.incrementRam * ip.costRam ) * CASE WHEN ip.period = 0 THEN :globalRate ELSE (ip.period * CEIL(:duration/ip.period)) END AS totalCost, ( ip.cost + CEIL(GREATEST(ip.minCpu, :cpu) /ip.incrementCpu) * ip.incrementCpu * ip.costCpu + CASE WHEN (ip.incrementGpu IS NULL OR ip.incrementGpu=0.0) THEN 0.0 ELSE (CEIL(GREATEST(ip.minGpu, :gpu) /ip.incrementGpu) * ip.incrementGpu * ip.costGpu) END + CEIL(GREATEST(GREATEST(ip.minCpu, :cpu) * COALESCE(ip.minRamRatio,0.0), :ram) /ip.incrementRam) * ip.incrementRam * ip.costRam ) * CASE WHEN ip.period = 0 THEN :rate ELSE 1.0 END AS monthlyCost FROM #{#entityName} ip WHERE ip.location.id = :location AND ip.incrementCpu IS NOT NULL AND ip.os=:os AND (ip.maxCpu IS NULL OR ip.maxCpu >=:cpu) AND (ip.maxGpu IS NULL OR ip.maxGpu >=:gpu) AND (ip.maxRam IS NULL OR ip.maxRam >=:ram) AND (ip.license IS NULL OR :license = ip.license) AND (ip.initialCost IS NULL OR :initialCost >= ip.initialCost) AND (ip.type.id IN :types) AND (ip.term.id IN :terms) AND (ip.maxRamRatio IS NULL OR GREATEST(ip.minCpu, :cpu) * ip.maxRamRatio <= :ram) ORDER BY totalCost ASC, ip.type.id DESC, ip.maxCpu ASC """) List<Object[]> findLowestDynamicPrice(List<Integer> types, List<Integer> terms, double cpu, double gpu, double ram, VmOs os, int location, double rate, double globalRate, double duration, String license, double initialCost, Pageable pageable); /** * Return the lowest instance price configuration from the minimal requirements. * * @param types The valid instance type identifiers. * @param terms The valid instance terms identifiers. * @param os The requested OS. * @param location The requested location identifier. * @param rate Usage rate. Positive number. Maximum is <code>1</code>, minimum is <code>0.01</code>. * @param duration The duration in month. Minimum is 1. * @param license Optional license notice. When not <code>null</code> a license constraint is added. * @param initialCost The maximal initial cost. * @param pageable The page control to return few item. * @return The minimum instance price or empty result. */ @Query(""" SELECT ip, CASE WHEN ip.period = 0 THEN (ip.cost * :rate * :duration) ELSE (ip.costPeriod * CEIL(:duration/ip.period)) END AS totalCost, CASE WHEN ip.period = 0 THEN (ip.cost * :rate) ELSE ip.cost END AS monthlyCost FROM #{#entityName} ip WHERE ip.location.id = :location AND ip.incrementCpu IS NULL AND ip.os=:os AND (ip.license IS NULL OR :license = ip.license) AND (ip.initialCost IS NULL OR :initialCost >= ip.initialCost) AND (ip.type.id IN :types) AND (ip.term.id IN :terms) ORDER BY totalCost ASC, ip.type.id DESC """) List<Object[]> findLowestPrice(List<Integer> types, List<Integer> terms, VmOs os, int location, double rate, double duration, String license, double initialCost, Pageable pageable); }
ligoj/plugin-prov
src/main/java/org/ligoj/app/plugin/prov/dao/ProvContainerPriceRepository.java
Java
mit
5,352
package com.giggs.heroquest.models.items.equipments.weapons; import com.giggs.heroquest.models.items.equipments.Equipment; /** * Created by guillaume ON 10/6/14. */ public class Weapon extends Equipment { private final int minDamage; private final int deltaDamage; public Weapon(String identifier, int minDamage, int deltaDamage, int level, int price) { super(identifier, level, (int) (price * (1 + (level * 0.25)))); this.minDamage = minDamage; this.deltaDamage = deltaDamage; } public int getMinDamage() { return (int) Math.max(minDamage * (1 + 0.15 * level), minDamage + level); } public int getDeltaDamage() { return (int) Math.max(deltaDamage * (1 + 0.15 * level), deltaDamage + level); } }
guillaume-gouchon/dungeonquest
android/app/src/main/java/com/giggs/heroquest/models/items/equipments/weapons/Weapon.java
Java
mit
777
package info.jchein.apps.nr.codetest.ingest.segments.logunique; public interface IUniqueMessageTrie { boolean isUnique(int prefix, short suffix); }
jheinnic/reactor-readnums
readnums-app/src/main/java/info/jchein/apps/nr/codetest/ingest/segments/logunique/IUniqueMessageTrie.java
Java
mit
153
package test.ywen; import com.ywen.CryptoManager; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.misc.BASE64Decoder; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Created by wenyun on 15/4/22. */ public class CryptoTest { private static CryptoManager cryptoManager; private final Logger logger = LoggerFactory.getLogger(CryptoTest.class); private String getKeyFromFile(String filePath) { String key = null; try { URL url = this.getClass().getResource(filePath); BufferedReader bufferedReader = new BufferedReader(new FileReader(url.getFile())); List<String> list = new ArrayList<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { list.add(line); } StringBuilder stringBuilder = new StringBuilder(); //去掉第一行和最后一行 for (int i = 1; i < list.size() - 1; i++) { stringBuilder.append(list.get(i)).append("\r"); } key = stringBuilder.toString(); } catch (FileNotFoundException e) { logger.error("{}", e); } catch (IOException e) { logger.error("{}", e); } return key; } @Before public void setCryptoManager() { String pubKeyStr = getKeyFromFile("/rsa_public_key.pem"); Assert.assertNotNull(pubKeyStr); String privateKeyStr = getKeyFromFile("/pkcs8_private_key.pem"); Assert.assertNotNull(privateKeyStr); cryptoManager = new CryptoManager(privateKeyStr, pubKeyStr); } @Test public void testJavaRSA() { try { String plainText = "http://wo.yao.cl"; String encryptStr = cryptoManager.rsaEncrypt(plainText); String decryptStr = cryptoManager.rsaDecrypt(encryptStr); logger.info("encrypt string is " + encryptStr); logger.info("decrypt string is " + decryptStr); Assert.assertEquals(plainText, decryptStr); } catch (Exception e) { logger.error("{}", e); } } @Test public void testRSAWithIos() { //使用的key文件夹下预先生成的密钥文件,把ios那边的结果作为期望结果 String plainText = "1"; String expectStr = "bxFq9YjfFs3l1VbRktfNSb5omvO5SQLxsRhBxNX73Ig9qebOim40VFSRTvmSzhjI" + "sNpreVfg+JQxxxLMPx6bDRf4y5CpZRwk+MsLjbolCO396LpsMT/cS7m7XT/60pWH" + "IZGg2YVZT63UO5aozf9mT8eCVBa1Nk46u4AoJ9BCCfA="; try { String decryptStr = cryptoManager.rsaDecrypt(expectStr); logger.info("decrypt string is " + decryptStr); Assert.assertEquals(plainText, decryptStr); } catch (Exception e) { logger.error("{}", e); } } @Test public void testJavaDES() { try { String plainText = "http://wo.yao.cl"; String key = "12345678"; String encryptStr = CryptoManager.desEncrypt(plainText, key); String decryptStr = CryptoManager.desDecrypt(encryptStr, key); logger.info("encrypt string is " + encryptStr); logger.info("decrypt string is " + decryptStr); Assert.assertEquals(plainText, decryptStr); } catch (Exception e) { logger.error("{}", e); } } @Test public void testDESWithIos() { try { String encryptStr = "zS5Gry+KJqs="; String expectStr = "1"; String key = "12345678"; String decryptStr = CryptoManager.desDecrypt(encryptStr, key); logger.info("decrypt string is " + decryptStr); Assert.assertEquals(expectStr, decryptStr); } catch (Exception e) { logger.error("{}", e); } } }
yaliyingwy/YwenCrypto
java/src/test/java/test/ywen/CryptoTest.java
Java
mit
4,132
package com.delta.utilites; /** * Created by Olavi Kamppari on 10/25/2015. * * Added to Github on 11/16/2015 (https://github.com/OliviliK/FTC_Library/blob/master/Wire.java) * * Revisions: * 151107 by OAK: * 1) in portIsReady fixed problem related to repeated read of same address * 2) in executeCommands added missing line to stop idle polling * 151116 by OAK: * 1) added method requestCount(), to complement the existing responseCount() * 2) added method write() with second parameter as object (for no value) */ import android.util.Log; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.I2cController; import com.qualcomm.robotcore.hardware.I2cDevice; import java.util.concurrent.locks.Lock; public class Wire implements I2cController.I2cPortReadyCallback { // --------------------------------- CONSTANTS ------------------------------------------------- // Cache buffer constant values static final byte READ_MODE = 0x00 - 128, // MSB = 1 WRITE_MODE = 0x00; // MSB = 0 // Cache buffer index values static final int CACHE_MODE = 0, // MSB = 1 when read mode is active DEV_ADDR = 1, // Device address REG_NUMBER = 2, // Register address REG_COUNT = 3, // Register count DATA_OFFSET = 4, // First byte of transferred data LAST_INDEX = 29, // Last index available for data ACTION_FLAG = 31, // 0 = idle, -1 = transfer is active CACHE_SIZE = 32; // dCache fixed size // --------------------------------- CLASS VARIABLES ------------------------------------------- private ArrayQueue<Element> downQueue; // Down stream buffer private ArrayQueue<Element> upQueue; // Up stream buffer private I2cDevice wireDev; // Generic I2C Device Object private byte wireDevAddr; // Generic Device Address private byte[] rCache; // Read Cache private byte[] wCache; // Write Cache private Lock rLock; // Lock for Read Cache private Lock wLock; // Lock for Write Cache & request queue private byte[] dCache; // Buffer for down stream details private int dNext; // Next location for incoming bytes private byte[] uCache; // Buffer for up stream response private int uNext; // Next location for response bytes private int uLimit; // Last location for response bytes private long uMicros; // Time stamp, microseconds since start private long startTime; // Start time in nanoseconds private boolean isIdle; // Mechanism to control polling // --------------------------------- CLASS INIT AND CLOSE --------------------------------------- public Wire(HardwareMap hardwareMap, String deviceName, int devAddr) { downQueue = new ArrayQueue<Element>(); upQueue = new ArrayQueue<Element>(); wireDev = hardwareMap.i2cDevice.get(deviceName); wireDevAddr = (byte) devAddr; rCache = wireDev.getI2cReadCache(); wCache = wireDev.getI2cWriteCache(); rLock = wireDev.getI2cReadCacheLock(); wLock = wireDev.getI2cWriteCacheLock(); dCache = new byte[CACHE_SIZE]; dNext = DATA_OFFSET; uCache = new byte[CACHE_SIZE]; uMicros = 0L; startTime = System.nanoTime(); uNext = DATA_OFFSET; uLimit = uNext; isIdle = true; wireDev.registerForI2cPortReadyCallback(this); } public void close() { wireDev.deregisterForPortReadyCallback(); downQueue.close(); upQueue.close(); wireDev.close(); } //------------------------------------------------- Public Methods ------------------------- public void beginWrite(int regNumber) { dCache[CACHE_MODE] = WRITE_MODE; dCache[DEV_ADDR] = wireDevAddr; dCache[REG_NUMBER] = (byte) regNumber; dNext = DATA_OFFSET; } public void write(int value) { if (dNext >= LAST_INDEX) return; // Max write size has been reached dCache[dNext++] = (byte) value; } public void write(int regNumber, int value) { beginWrite(regNumber); write(value); endWrite(); } public void writeHL(int regNumber, int value) { beginWrite(regNumber); write((byte) (value >> 8)); write((byte) (value)); endWrite(); } public void writeLH(int regNumber, int value) { beginWrite(regNumber); write((byte) (value)); write((byte) (value >> 8)); endWrite(); } public void write(int regNumber, Object x) { if (x == null) { beginWrite(regNumber); endWrite(); } } public void endWrite() { dCache[REG_COUNT] = (byte) (dNext - DATA_OFFSET); addRequest(); } public void requestFrom(int regNumber, int regCount) { dCache[CACHE_MODE] = READ_MODE; dCache[DEV_ADDR] = wireDevAddr; dCache[REG_NUMBER] = (byte) regNumber; dCache[REG_COUNT] = (byte) regCount; addRequest(); } public int responseCount() { int count = 0; try { rLock.lock(); count = upQueue.length(); } finally { rLock.unlock(); } return count; } public int requestCount() { int count = 0; try { wLock.lock(); count = downQueue.length(); } finally { wLock.unlock(); } return count; } public boolean getResponse() { boolean responseReceived = false; uNext = DATA_OFFSET; uLimit = uNext; try { rLock.lock(); // Explicit protection with rLock if (!upQueue.isEmpty()) { responseReceived = true; uMicros = getFromQueue(uCache, upQueue); uLimit = uNext + uCache[REG_COUNT]; } } finally { rLock.unlock(); } return responseReceived; } public boolean isRead() { return (uCache[CACHE_MODE] == READ_MODE); } public boolean isWrite() { return (uCache[CACHE_MODE] == WRITE_MODE); } public int registerNumber() { return uCache[REG_NUMBER] & 0xff; } public int deviceAddress() { return uCache[DEV_ADDR] & 0xff; } public long micros() { return uMicros; } public int available() { return uLimit - uNext; } public int read() { if (uNext >= uLimit) return 0; return uCache[uNext++] & 0xff; } public int readHL() { int high = read(); int low = read(); return 256 * high + low; } public int readLH() { int low = read(); int high = read(); return 256 * high + low; } //------------------------------------------------- Main routine: Device CallBack ------------- public void portIsReady(int port) { boolean isValidReply = false; try { rLock.lock(); if ( rCache[CACHE_MODE] == wCache[CACHE_MODE] && rCache[DEV_ADDR] == wCache[DEV_ADDR] && rCache[REG_NUMBER] == wCache[REG_NUMBER] && rCache[REG_COUNT] == wCache[REG_COUNT]) { storeReceivedData(); // Store read/write data rCache[REG_COUNT] = -1; // Mark the reply used isValidReply = true; } } finally { rLock.unlock(); } if (isValidReply) { executeCommands(); // Start next transmission } else { boolean isPollingRequired = false; try { wLock.lock(); // Protect the testing isPollingRequired = (wCache[DEV_ADDR] == wireDevAddr); } finally { wLock.unlock(); } if (isPollingRequired) { wireDev.readI2cCacheFromController(); // Keep polling active } } } // --------------------------------- Commands to DIM ------------------------------------------- private void executeCommands() { try { wLock.lock(); if (downQueue.isEmpty()) { isIdle = true; wCache[DEV_ADDR] = -1; // No further polling is required } else { getFromQueue(wCache, downQueue); // Ignore timestamp wCache[ACTION_FLAG] = -1; } } finally { wLock.unlock(); } if (!isIdle) { wireDev.writeI2cCacheToController(); } } private void addRequest() { boolean isStarting = false; // logCache('d',"addRequest"); try { wLock.lock(); if (isIdle) { int length = DATA_OFFSET + dCache[REG_COUNT]; for (int i = 0; i < length; i++) wCache[i] = dCache[i]; wCache[ACTION_FLAG] = -1; isIdle = false; isStarting = true; } else { addToQueue(0L, dCache, downQueue); } } finally { wLock.unlock(); } if (isStarting) { wireDev.writeI2cCacheToController(); } } // --------------------------------- PROCESSING OF RECEIVED DATA ------------------------------- private void storeReceivedData() { // rCache has been locked long uMicros = (System.nanoTime() - startTime) / 1000L; addToQueue(uMicros, rCache, upQueue); // logCache('r',"storeReceivedData"); } //------------------------------------------------- Add and Remove from Queue ------------------ private void addToQueue(long timeStamp, byte[] cache, ArrayQueue<Element> queue) { int length = DATA_OFFSET + cache[REG_COUNT]; Element element = new Element(); element.timeStamp = timeStamp; element.cache = new byte[length]; for (int i = 0; i < length; i++) element.cache[i] = cache[i]; queue.add(element); } private long getFromQueue(byte[] cache, ArrayQueue<Element> queue) { Element element = queue.remove(); if (element == null) return 0; int length = element.cache.length; long timeStamp = element.timeStamp; for (int i = 0; i < length; i++) cache[i] = element.cache[i]; return timeStamp; } class Element { public long timeStamp; public byte[] cache; } private void logCache(char cacheLetter, String function) { switch (cacheLetter){ case 'd': logCache(dCache,function,cacheLetter); break; case 'w': logCache(wCache,function,cacheLetter); break; case 'r': logCache(rCache,function,cacheLetter); break; case 'u': logCache(uCache,function,cacheLetter); break; } } private void logCache(byte[] cache, String function, char cacheLetter) { int showCount = cache[3]; boolean isWrite = (cache[0] == WRITE_MODE); switch (cacheLetter){ case 'd': case 'w': if (cache[0] != WRITE_MODE) showCount = 0; break; case 'r': case 'u': if (cache[0] == WRITE_MODE) showCount = 0; break; } if (showCount > 6) showCount = 6; String msg = String.format( "%17s %c[%d][%d], %cCache: mod=0x%02X, dev=0x%02X, reg=0x%02X, cnt=%2d ", function,isIdle?'T':'F',downQueue.length(),upQueue.length(), cacheLetter,cache[0],cache[1],cache[2],cache[3]); for (int i=0;i<showCount;i++) { msg += String.format(" 0x%02X",cache[4+i]); } Log.i("Wire",msg); } }
DeltaRobotics/Software
Beta/ftc_app-DR/FtcRobotController/src/main/java/com/delta/utilites/Wire.java
Java
mit
12,636
package ysoserial.payloads.util; import java.util.concurrent.Callable; import ysoserial.Deserializer; import ysoserial.Serializer; import static ysoserial.Deserializer.deserialize; import static ysoserial.Serializer.serialize; import ysoserial.payloads.ObjectPayload; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.secmgr.ExecCheckingSecurityManager; /* * utility class for running exploits locally from command line */ @SuppressWarnings("unused") public class PayloadRunner { public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // ensure payload generation doesn't throw an exception byte[] serialized = new ExecCheckingSecurityManager().callWrapped(new Callable<byte[]>(){ public byte[] call() throws Exception { final String command = args.length > 0 && args[0] != null ? args[0] : getDefaultTestCmd(); System.out.println("generating payload object(s) for command: '" + command + "'"); ObjectPayload<?> payload = clazz.newInstance(); final Object objBefore = payload.getObject(command); System.out.println("serializing payload"); byte[] ser = Serializer.serialize(objBefore); Utils.releasePayload(payload, objBefore); return ser; }}); try { System.out.println("deserializing payload"); final Object objAfter = Deserializer.deserialize(serialized); } catch (Exception e) { e.printStackTrace(); } } private static String getDefaultTestCmd() { return getFirstExistingFile( "C:\\Windows\\System32\\calc.exe", "/Applications/Calculator.app/Contents/MacOS/Calculator", "/usr/bin/gnome-calculator", "/usr/bin/kcalc" ); } private static String getFirstExistingFile(String ... files) { return "calc.exe"; // for (String path : files) { // if (new File(path).exists()) { // return path; // } // } // throw new UnsupportedOperationException("no known test executable"); } }
frohoff/ysoserial
src/main/java/ysoserial/payloads/util/PayloadRunner.java
Java
mit
2,079
package com.quemb.qmbform.sample.controller; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ListView; import com.kbeanie.multipicker.api.Picker; import com.kbeanie.multipicker.api.VideoPicker; import com.kbeanie.multipicker.api.callbacks.VideoPickerCallback; import com.kbeanie.multipicker.api.entity.ChosenVideo; import com.quemb.qmbform.FormManager; import com.quemb.qmbform.OnFormRowClickListener; import com.quemb.qmbform.descriptor.DataSource; import com.quemb.qmbform.descriptor.DataSourceListener; import com.quemb.qmbform.descriptor.FormDescriptor; import com.quemb.qmbform.descriptor.FormItemDescriptor; import com.quemb.qmbform.descriptor.FormOptionsObject; import com.quemb.qmbform.descriptor.OnFormRowValueChangedListener; import com.quemb.qmbform.descriptor.RowDescriptor; import com.quemb.qmbform.descriptor.SectionDescriptor; import com.quemb.qmbform.descriptor.Value; import com.quemb.qmbform.pojo.ProcessedFile; import com.quemb.qmbform.sample.R; import com.quemb.qmbform.sample.model.MockContent; import com.quemb.qmbform.view.FormMultipleProcessedImageFieldCell; import com.quemb.qmbform.view.FormSelectorPushFieldCell; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; /** * Created by tonimoeckel on 17.07.14. */ public class SampleFormFragment extends Fragment implements OnFormRowValueChangedListener, OnFormRowClickListener{ private RecyclerView mListView; private HashMap<String, Value<?>> mChangesMap; private MenuItem mSaveMenuItem; public static String TAG = "SampleFormFragment"; private FormManager mFormManager; VideoPicker videoPicker; public static final SampleFormFragment newInstance() { SampleFormFragment f = new SampleFormFragment(); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.form_sample_recycler, container, false); mListView = (RecyclerView) v.findViewById(R.id.list); return v; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mChangesMap = new HashMap<String, Value<?>>(); FormDescriptor descriptor = FormDescriptor.newInstance(); SectionDescriptor sectionDescriptor = SectionDescriptor.newInstance("section","Text Inputs"); descriptor.addSection(sectionDescriptor); RowDescriptor rowDescriptor = RowDescriptor.newInstance("image", RowDescriptor.FormRowDescriptorTypeImage, "Image"); sectionDescriptor.addRow(rowDescriptor); RowDescriptor rowDescriptorImages = RowDescriptor.newInstance("images", RowDescriptor.FormRowDescriptorTypeMultipleImage, "Images"); sectionDescriptor.addRow(rowDescriptorImages); rowDescriptor = RowDescriptor.newInstance("content", RowDescriptor.FormRowDescriptorTypeSelectorPush, "PushSelector", new Value<List<MockContent>>(new ArrayList<MockContent>())); HashMap<String, Object> config = new HashMap<>(); Intent intent = new Intent(getActivity(), ContentSelectActivity.class); config.put(FormSelectorPushFieldCell.PUSH_INTENT, intent); rowDescriptor.setCellConfig(config); sectionDescriptor.addRow(rowDescriptor); rowDescriptor = RowDescriptor.newInstance("segmented", RowDescriptor.FormRowDescriptorTypeSelectorSegmentedControlInline, "SegmentedControl", new Value<String>("false")); ArrayList<FormOptionsObject> objects = new ArrayList<>(); objects.add(FormOptionsObject.createFormOptionsObject("true", "Agree")); objects.add(FormOptionsObject.createFormOptionsObject("false", "Not Agree")); rowDescriptor.setSelectorOptions(objects); sectionDescriptor.addRow(rowDescriptor); RowDescriptor rowDescriptorFiles = RowDescriptor.newInstance("files", RowDescriptor.FormRowDescriptorTypeMultipleFile, "Files"); sectionDescriptor.addRow(rowDescriptorFiles); RowDescriptor rowDescriptorUploadImages = RowDescriptor.newInstance("uploadimages", RowDescriptor.FormRowDescriptorTypeMultipleProcessedImage, "Upload Images"); config = new HashMap<>(); config.put(FormMultipleProcessedImageFieldCell.MAX_COUNT, 9); rowDescriptorUploadImages.setCellConfig(config); sectionDescriptor.addRow(rowDescriptorUploadImages); sectionDescriptor.addRow( RowDescriptor.newInstance("detail", RowDescriptor.FormRowDescriptorTypeTextInline, "Title",new Value<String>("Detail")) ); sectionDescriptor.addRow( RowDescriptor.newInstance("detail", RowDescriptor.FormRowDescriptorTypeText, "Title",new Value<String>("Detail")) ); sectionDescriptor.addRow( RowDescriptor.newInstance("text",RowDescriptor.FormRowDescriptorTypeText, "Text", new Value<String>("test")) ); RowDescriptor textDisabled = RowDescriptor.newInstance("textViewDisabled",RowDescriptor.FormRowDescriptorTypeText, "Text Disabled", new Value<String>("test")); textDisabled.setDisabled(true); sectionDescriptor.addRow( textDisabled ); sectionDescriptor.addRow( RowDescriptor.newInstance("text",RowDescriptor.FormRowDescriptorTypeURL, "URL", new Value<String>("http://www.github.com/")) ); RowDescriptor textUrlDisabled = RowDescriptor.newInstance("textViewDisabled",RowDescriptor.FormRowDescriptorTypeURL, "URL Disabled", new Value<String>("http://www.github.com/")); textUrlDisabled.setDisabled(true); sectionDescriptor.addRow( textUrlDisabled ); sectionDescriptor.addRow( RowDescriptor.newInstance("text",RowDescriptor.FormRowDescriptorTypeEmail, "Email", new Value<String>("[email protected]")) ); RowDescriptor textEmailDisabled = RowDescriptor.newInstance("textDisabled",RowDescriptor.FormRowDescriptorTypeEmail, "Email Disabled", new Value<String>("[email protected]")); textEmailDisabled.setDisabled(true); sectionDescriptor.addRow( textEmailDisabled ); sectionDescriptor.addRow( RowDescriptor.newInstance("textView",RowDescriptor.FormRowDescriptorTypeTextView, "Text View", new Value<String>("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et ...")) ); RowDescriptor textViewDisabled = RowDescriptor.newInstance("textViewDisabled",RowDescriptor.FormRowDescriptorTypeTextView, "Text View Disabled", new Value<String>("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et ...")); textViewDisabled.setDisabled(true); sectionDescriptor.addRow( textViewDisabled ); sectionDescriptor.addRow( RowDescriptor.newInstance("number",RowDescriptor.FormRowDescriptorTypeNumber, "Number", new Value<Number>(555.456)) ); RowDescriptor numberRowDisabled = RowDescriptor.newInstance("numberDisabled",RowDescriptor.FormRowDescriptorTypeNumber, "Number Disabled", new Value<Number>(555.456)); numberRowDisabled.setDisabled(true); sectionDescriptor.addRow( numberRowDisabled ); final RowDescriptor integerRow = RowDescriptor.newInstance("integer",RowDescriptor.FormRowDescriptorTypeInteger, "Integer", new Value<Number>(55)); sectionDescriptor.addRow( integerRow ); final RowDescriptor integerRowDisabled = RowDescriptor.newInstance("integerDisabled",RowDescriptor.FormRowDescriptorTypeInteger, "Integer Disabled", new Value<Number>(55)); integerRowDisabled.setDisabled(true); sectionDescriptor.addRow( integerRowDisabled ); sectionDescriptor.addRow( RowDescriptor.newInstance("integerSlider",RowDescriptor.FormRowDescriptorTypeIntegerSlider, "Integer Slider", new Value<Integer>(50)) ); RowDescriptor integerSliderDisabled = RowDescriptor.newInstance("integerSliderDisabled",RowDescriptor.FormRowDescriptorTypeIntegerSlider, "Integer Slider Disabled", new Value<Number>(50)); integerSliderDisabled.setDisabled(true); sectionDescriptor.addRow( integerSliderDisabled ); SectionDescriptor sectionDescriptor1 = SectionDescriptor.newInstance("sectionOne","Picker"); descriptor.addSection(sectionDescriptor1); RowDescriptor pickerDescriptor = RowDescriptor.newInstance("picker",RowDescriptor.FormRowDescriptorTypeSelectorPickerDialog, "Picker", new Value<String>("Item 5")); pickerDescriptor.setDataSource(new DataSource() { @Override public void loadData(final DataSourceListener listener) { // Can be async CustomTask task = new CustomTask(); task.execute(listener); } }); sectionDescriptor1.addRow( pickerDescriptor ); RowDescriptor pickerDisabledDescriptor = RowDescriptor.newInstance("pickerDisabled",RowDescriptor.FormRowDescriptorTypeSelectorPickerDialog, "Picker Disabled", new Value<String>("Value")); pickerDisabledDescriptor.setDisabled(true); sectionDescriptor1.addRow(pickerDisabledDescriptor); SectionDescriptor sectionDescriptor2 = SectionDescriptor.newInstance("sectionTwo","Boolean Inputs"); descriptor.addSection(sectionDescriptor2); sectionDescriptor2.addRow( RowDescriptor.newInstance("boolean",RowDescriptor.FormRowDescriptorTypeBooleanSwitch, "Boolean Switch", new Value<Boolean>(true)) ); RowDescriptor booleanDisabled = RowDescriptor.newInstance("booleanDisabled",RowDescriptor.FormRowDescriptorTypeBooleanSwitch, "Boolean Switch Disabled", new Value<Boolean>(true)); booleanDisabled.setDisabled(true); sectionDescriptor2.addRow( booleanDisabled ); sectionDescriptor2.addRow( RowDescriptor.newInstance("check",RowDescriptor.FormRowDescriptorTypeBooleanCheck, "Check", new Value<Boolean>(true)) ); RowDescriptor checkDisabled = RowDescriptor.newInstance("checkDisabled",RowDescriptor.FormRowDescriptorTypeBooleanCheck, "Check Disabled", new Value<Boolean>(true)) ; checkDisabled.setDisabled(true); sectionDescriptor2.addRow(checkDisabled); SectionDescriptor sectionDescriptor3 = SectionDescriptor.newInstance("sectionThree","Button"); descriptor.addSection(sectionDescriptor3); final RowDescriptor button = RowDescriptor.newInstance("button",RowDescriptor.FormRowDescriptorTypeButton, "Tap Me"); button.setOnFormRowClickListener(new OnFormRowClickListener() { @Override public void onFormRowClick(FormItemDescriptor itemDescriptor) { // You need to call updateRows in order to update titles // itemDescriptor.setTitle("New Title"); // mFormManager.updateRows(); integerRow.getValue().setValue(100); integerRow.setDisabled(true); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Tapped"); builder.show(); } }); sectionDescriptor3.addRow( button ); RowDescriptor buttonDisabled = RowDescriptor.newInstance("buttonDisabled",RowDescriptor.FormRowDescriptorTypeButton, "Tap Me Disabled"); buttonDisabled.setOnFormRowClickListener(new OnFormRowClickListener() { @Override public void onFormRowClick(FormItemDescriptor itemDescriptor) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Tapped"); builder.show(); } }); buttonDisabled.setDisabled(true); sectionDescriptor3.addRow(buttonDisabled); sectionDescriptor3.addRow(RowDescriptor.newInstance("external",RowDescriptor.FormRowDescriptorTypeExternal, "github.com", new Value<String>("http://github.com"))); SectionDescriptor sectionDescriptor4 = SectionDescriptor.newInstance("sectionFour","Dates"); descriptor.addSection(sectionDescriptor4); sectionDescriptor4.addRow( RowDescriptor.newInstance("dateInline",RowDescriptor.FormRowDescriptorTypeDateInline, "Date Inline", new Value<Date>(new Date()) )); RowDescriptor dateInlineDisabled = RowDescriptor.newInstance("dateInlineDisabled",RowDescriptor.FormRowDescriptorTypeDateInline, "Date Inline Disabled", new Value<Date>(new Date()) ); dateInlineDisabled.setDisabled(true); sectionDescriptor4.addRow(dateInlineDisabled); sectionDescriptor4.addRow( RowDescriptor.newInstance("dateDialog",RowDescriptor.FormRowDescriptorTypeDate, "Date Dialog") ); RowDescriptor dateDialogDisabled = RowDescriptor.newInstance("dateDialogDisabled",RowDescriptor.FormRowDescriptorTypeDate, "Date Dialog Disabled" ); dateDialogDisabled.setDisabled(true); sectionDescriptor4.addRow(dateDialogDisabled); sectionDescriptor4.addRow( RowDescriptor.newInstance("timeInline",RowDescriptor.FormRowDescriptorTypeTimeInline, "Time Inline" , new Value<Date>(new Date())) ); RowDescriptor timeInlineDisabled = RowDescriptor.newInstance("timeInlineDisabled",RowDescriptor.FormRowDescriptorTypeTimeInline, "Time Inline Disabled", new Value<Date>(new Date()) ); timeInlineDisabled.setDisabled(true); sectionDescriptor4.addRow(timeInlineDisabled); sectionDescriptor4.addRow( RowDescriptor.newInstance("timeDialog",RowDescriptor.FormRowDescriptorTypeTime, "Time Dialog", new Value<Date>(new Date())) ); RowDescriptor timeDialogDisabled = RowDescriptor.newInstance("timeDialogDisabled",RowDescriptor.FormRowDescriptorTypeTime, "Time Dialog Disabled", new Value<Date>(new Date()) ); timeDialogDisabled.setDisabled(true); sectionDescriptor4.addRow(timeDialogDisabled); RowDescriptor datetime = RowDescriptor.newInstance("datetime",RowDescriptor.FormRowDescriptorTypeDateTime, "DateTime selected", new Value<Date>(new Date()) ); sectionDescriptor4.addRow(datetime); mFormManager = new FormManager(); mFormManager.setup(descriptor, mListView, this); Button button1 = new Button(getContext()); button1.setText("Header"); mFormManager.setHeader(button1); button1 = new Button(getContext()); button1.setText("Footer"); mFormManager.setFooter(button1); mFormManager.setOnFormRowClickListener(this); mFormManager.setOnFormRowValueChangedListener(this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.sample, menu); mSaveMenuItem = menu.findItem(R.id.action_save); } public void onAddIconLongClick(final RowDescriptor rowDescriptor) { Log.e("ddd", "onAddIconLongClick"); videoPicker = new VideoPicker(this); videoPicker.shouldGenerateMetadata(true); videoPicker.shouldGeneratePreviewImages(true); videoPicker.setVideoPickerCallback(new VideoPickerCallback() { @Override public void onVideosChosen(List<ChosenVideo> list) { ChosenVideo video = list.get(0); Value<List<ProcessedFile>> value = rowDescriptor.getValue(); ArrayList<ProcessedFile> imageItems = null; if (value != null && value.getValue() != null) { imageItems = (ArrayList<ProcessedFile>) value.getValue(); } if (imageItems == null) { imageItems = new ArrayList<>(); } ProcessedFile vv = new ProcessedFile(video.getOriginalPath()); vv.setVideo(true); vv.setThumbPath(video.getPreviewImage()); imageItems.add(vv); rowDescriptor.setValue(new Value<ArrayList<ProcessedFile>>(imageItems)); if (null != rowDescriptor.getCell()) { rowDescriptor.getCell().valueUpdate(); } } @Override public void onError(String s) { } }); videoPicker.pickVideo(); } @Override public void onPrepareOptionsMenu(Menu menu) { updateSaveItem(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item == mSaveMenuItem){ mChangesMap.clear(); updateSaveItem(); } return super.onOptionsItemSelected(item); } @Override public void onFormRowClick(FormItemDescriptor itemDescriptor) { } @Override public void onValueChanged(RowDescriptor rowDescriptor, Value<?> oldValue, Value<?> newValue) { Log.d(TAG, "Value Changed: " + rowDescriptor.getTitle()); // mChangesMap.put(rowDescriptor.getTag(), newValue); updateSaveItem(); if ("files".equals(rowDescriptor.getTag()) || "uploadimages".equals(rowDescriptor.getTag())) { ArrayList<ProcessedFile> processedFiles = (ArrayList<ProcessedFile>) newValue.getValue(); for (ProcessedFile file: processedFiles) { uploadFile(file); } } } private void uploadFile(final ProcessedFile processedFile) { if (processedFile.getProcessedStatus() != ProcessedFile.ProcessedStatus.READY) { return; } processedFile.setProcessedStatus(ProcessedFile.ProcessedStatus.UPLOADING); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i<= 100; i ++) { try { Thread.sleep(500); processedFile.setCurrentPercent(i); if(i == 100) { processedFile.setProcessedStatus(ProcessedFile.ProcessedStatus.SUCCESS); } } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { mFormManager.onActivityResult(requestCode, resultCode, data); if (requestCode == Picker.PICK_VIDEO_DEVICE && resultCode == Activity.RESULT_OK) { videoPicker.submit(data); } super.onActivityResult(requestCode, resultCode, data); } private void updateSaveItem() { if (mSaveMenuItem != null){ mSaveMenuItem.setVisible(mChangesMap.size()>0); } } private class CustomTask extends AsyncTask<DataSourceListener, Void, ArrayList<String>> { private DataSourceListener mListener; private ProgressDialog mProgressDialog; @Override protected void onPreExecute() { super.onPreExecute(); mProgressDialog = ProgressDialog.show(getActivity(), "Loading", "Do some work", true); } protected ArrayList<String> doInBackground(DataSourceListener... listeners) { mListener = (DataSourceListener)listeners[0]; ArrayList<String> items = new ArrayList<String>(); for (Integer i=0;i<10;i++){ doFakeWork(); items.add("Item "+String.valueOf(i)); } return items; } @Override protected void onPostExecute(ArrayList<String> strings) { super.onPostExecute(strings); mProgressDialog.dismiss(); mListener.onDataSourceLoaded(strings); } private void doFakeWork() { try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } }
zxy198717/QMBForm
app/src/main/java/com/quemb/qmbform/sample/controller/SampleFormFragment.java
Java
mit
20,710
package com.github.johnson; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; public class LongParser extends JohnsonParser<Long> { public static final LongParser INSTANCE = new LongParser(false); public static final LongParser INSTANCE_NULLABLE = new LongParser(true); public LongParser(boolean nullable) { super(nullable); } @Override public Long doParse(JsonParser jp) throws JsonParseException, IOException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) { if (nullable) return null; else throw new JsonParseException(jp, "null not allowed!"); } final long res = jp.getLongValue(); return res; } @Override public void doSerialize(Long value, JsonGenerator generator) throws IOException { generator.writeNumber(value); } }
ewanld/johnson-runtime
johnson-runtime/src/main/java/com/github/johnson/LongParser.java
Java
mit
975
package me.hao0.wechat.model.message.receive.msg; import me.hao0.wechat.model.message.receive.RecvMessage; /** * 接收微信服务器的普通消息 * Author: haolin * Email: [email protected] * Date: 9/11/15 */ public class RecvMsg extends RecvMessage { private static final long serialVersionUID = 8863935279441026878L; /** * 消息ID */ protected Long msgId; public Long getMsgId() { return msgId; } public void setMsgId(Long msgId) { this.msgId = msgId; } public RecvMsg(){} public RecvMsg(RecvMessage e){ super(e); } @Override public String toString() { return "RecvMsg{" + "msgId=" + msgId + "} " + super.toString(); } }
ihaolin/wechat
src/main/java/me/hao0/wechat/model/message/receive/msg/RecvMsg.java
Java
mit
770
package cz.creeper.customitemlibrary.data.mutable; import cz.creeper.customitemlibrary.data.CustomItemLibraryKeys; import cz.creeper.customitemlibrary.data.immutable.ImmutableCustomFeatureData; import lombok.AccessLevel; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import lombok.ToString; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.manipulator.mutable.common.AbstractData; import org.spongepowered.api.data.merge.MergeFunction; import org.spongepowered.api.data.value.mutable.Value; import javax.annotation.Nonnull; import java.util.Optional; @ToString public class CustomFeatureData extends AbstractData<CustomFeatureData, ImmutableCustomFeatureData> { public static final String ID_UNINITIALIZED = "__UNINITIALIZED__"; @Getter(AccessLevel.PRIVATE) @Setter(AccessLevel.PRIVATE) @NonNull private String customFeaturePluginId; @Getter(AccessLevel.PRIVATE) @Setter(AccessLevel.PRIVATE) @NonNull private String customFeatureTypeId; @Getter(AccessLevel.PRIVATE) @Setter(AccessLevel.PRIVATE) @NonNull private String customFeatureModel; public CustomFeatureData(String customFeaturePluginId, String customFeatureTypeId, String customFeatureModel) { this.customFeaturePluginId = customFeaturePluginId; this.customFeatureTypeId = customFeatureTypeId; this.customFeatureModel = customFeatureModel; registerGettersAndSetters(); } public CustomFeatureData() { this(ID_UNINITIALIZED, ID_UNINITIALIZED, ID_UNINITIALIZED); } @Override protected void registerGettersAndSetters() { registerFieldGetter(CustomItemLibraryKeys.CUSTOM_FEATURE_PLUGIN_ID, this::getCustomFeaturePluginId); registerFieldSetter(CustomItemLibraryKeys.CUSTOM_FEATURE_PLUGIN_ID, this::setCustomFeaturePluginId); registerKeyValue(CustomItemLibraryKeys.CUSTOM_FEATURE_PLUGIN_ID, this::customFeaturePluginId); registerFieldGetter(CustomItemLibraryKeys.CUSTOM_FEATURE_TYPE_ID, this::getCustomFeatureTypeId); registerFieldSetter(CustomItemLibraryKeys.CUSTOM_FEATURE_TYPE_ID, this::setCustomFeatureTypeId); registerKeyValue(CustomItemLibraryKeys.CUSTOM_FEATURE_TYPE_ID, this::customFeatureTypeId); registerFieldGetter(CustomItemLibraryKeys.CUSTOM_FEATURE_MODEL, this::getCustomFeatureModel); registerFieldSetter(CustomItemLibraryKeys.CUSTOM_FEATURE_MODEL, this::setCustomFeatureModel); registerKeyValue(CustomItemLibraryKeys.CUSTOM_FEATURE_MODEL, this::customFeatureModel); } public Value<String> customFeaturePluginId() { return customFeaturePluginId(customFeaturePluginId); } public static Value<String> customFeaturePluginId(String customFeaturePluginId) { return Sponge.getRegistry().getValueFactory().createValue(CustomItemLibraryKeys.CUSTOM_FEATURE_PLUGIN_ID, customFeaturePluginId, CustomFeatureData.ID_UNINITIALIZED); } public Value<String> customFeatureTypeId() { return customFeatureTypeId(customFeatureTypeId); } public static Value<String> customFeatureTypeId(String customFeatureTypeId) { return Sponge.getRegistry().getValueFactory().createValue(CustomItemLibraryKeys.CUSTOM_FEATURE_TYPE_ID, customFeatureTypeId, CustomFeatureData.ID_UNINITIALIZED); } public Value<String> customFeatureModel() { return customFeatureModel(customFeatureModel); } public static Value<String> customFeatureModel(String customFeatureModel) { return Sponge.getRegistry().getValueFactory().createValue(CustomItemLibraryKeys.CUSTOM_FEATURE_MODEL, customFeatureModel, CustomFeatureData.ID_UNINITIALIZED); } @Override @Nonnull public Optional<CustomFeatureData> fill(@Nonnull DataHolder dataHolder, @Nonnull MergeFunction mergeFunction) { CustomFeatureData data = new CustomFeatureData(); dataHolder.get(CustomItemLibraryKeys.CUSTOM_FEATURE_PLUGIN_ID) .ifPresent(pluginId -> data.customFeaturePluginId = pluginId); dataHolder.get(CustomItemLibraryKeys.CUSTOM_FEATURE_TYPE_ID) .ifPresent(typeId -> data.customFeatureTypeId = typeId); dataHolder.get(CustomItemLibraryKeys.CUSTOM_FEATURE_MODEL) .ifPresent(model -> data.customFeatureModel = model); return Optional.of(data); } @Override @Nonnull public Optional<CustomFeatureData> from(@Nonnull DataContainer dataContainer) { Optional<String> pluginId = dataContainer.getString(CustomItemLibraryKeys.CUSTOM_FEATURE_PLUGIN_ID.getQuery()); Optional<String> typeId = dataContainer.getString(CustomItemLibraryKeys.CUSTOM_FEATURE_TYPE_ID.getQuery()); Optional<String> model = dataContainer.getString(CustomItemLibraryKeys.CUSTOM_FEATURE_MODEL.getQuery()); if(pluginId.isPresent() && typeId.isPresent() && model.isPresent()) { return Optional.of(new CustomFeatureData(pluginId.get(), typeId.get(), model.get())); } else { return Optional.empty(); } } @Override @Nonnull public CustomFeatureData copy() { return new CustomFeatureData(customFeaturePluginId, customFeatureTypeId, customFeatureModel); } @Override @Nonnull public ImmutableCustomFeatureData asImmutable() { return new ImmutableCustomFeatureData(customFeaturePluginId, customFeatureTypeId, customFeatureModel); } @Override public int getContentVersion() { return 1; } @Override @Nonnull public DataContainer toContainer() { return super.toContainer() .set(CustomItemLibraryKeys.CUSTOM_FEATURE_PLUGIN_ID.getQuery(), customFeaturePluginId) .set(CustomItemLibraryKeys.CUSTOM_FEATURE_TYPE_ID.getQuery(), customFeatureTypeId) .set(CustomItemLibraryKeys.CUSTOM_FEATURE_MODEL.getQuery(), customFeatureModel); } }
Limeth/CustomItemLibrary
src/main/java/cz/creeper/customitemlibrary/data/mutable/CustomFeatureData.java
Java
mit
6,038
package com.panda.videoliveplatform.chat; import android.app.Activity; import android.content.Intent; import android.text.Editable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.panda.videolivecore.CommonDefine; import com.panda.videolivecore.data.EnterRoomState; import com.panda.videolivecore.net.LiveRoomRequest; import com.panda.videolivecore.net.http.IHttpRequestEvent; import com.panda.videolivecore.net.info.ResultMsgInfo; import com.panda.videolivecore.utils.CookieContiner; import com.panda.videolivecore.utils.ImeUtils; import com.panda.videolivecore.utils.ToastUtils; import com.panda.videoliveplatform.MyApplication; import com.panda.videoliveplatform.R; //import com.panda.videoliveplatform.activity.LoginActivity; //import com.panda.videoliveplatform.activity.TaskListActivity; import com.panda.videoliveplatform.activity.TaskListActivity; import com.panda.videoliveplatform.chat.Message.MsgReceiverType; //import com.sina.weibo.sdk.utils.LogUtil; import java.util.ArrayList; import java.util.List; import org.json.JSONObject; import tv.danmaku.ijk.media.player.IMediaPlayer; //import tv.danmaku.ijk.media.player.IMediaPlayer; public class ChatRoomView extends LinearLayout implements IHttpRequestEvent { private final String BROADCAST_COLOR = "#ff2846"; private final String RECEIVE_COLOR = "#0291eb"; private final String REQUEST_FUNC_GetMYBAMBOOS = "GetMyBamboos"; private final String REQUEST_FUNC_SENDBAMBOOS = "SendBamboos"; private final String REQUEST_FUNC_SENDGROUPMSG = "SendGroupMsg"; private final String SEND_COLOR = "#24b3b8"; private MessageAdapter mAdapter; private Activity mContext; private int mDefaultBambooNum = 100; private ArrayList<EmoticonBean> mEmoticonBeanList = null; private LinearLayout mGiftLayout; private TextView mGiveBambooNum = null; private MessageInputToolBox mInputBox; private long mLastSendMsgTime = 0; private ListView mListView; public OnOperationListener mOnOperationListener; private EnterRoomState mRoomState; private LinearLayout mSelectBambooComb; private LiveRoomRequest m_request = new LiveRoomRequest(this); private List<Message> messages; public ChatRoomView(Activity context, EnterRoomState roomState) { super(context); this.mContext = context; this.mRoomState = roomState; InitView(); } public void setDefaultBambooNum(int num) { this.mDefaultBambooNum = num; if (this.mGiveBambooNum != null) { this.mGiveBambooNum.setText(String.valueOf(num)); } } public void HideInputBox() { if (this.mInputBox != null) { this.mInputBox.hide(); } } private void InitView() { View container = LayoutInflater.from(this.mContext).inflate(R.layout.chat_room_view, this); this.messages = new ArrayList(); this.mEmoticonBeanList = new ArrayList(); initMessageInputToolBox(); this.mListView = (ListView) container.findViewById(R.id.messageListview); this.mAdapter = new MessageAdapter(this.mContext, this.messages, this.mEmoticonBeanList); this.mListView.setAdapter(this.mAdapter); this.mAdapter.notifyDataSetChanged(); this.mListView.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { ChatRoomView.this.mInputBox.hide(); return false; } }); InitBamboo(); BroadcastMessage("服务器连接中..."); } private void InitBamboo() { this.mSelectBambooComb = (LinearLayout) findViewById(R.id.select_bamboo_comb); this.mSelectBambooComb.setOnClickListener(new OnClickListener() { public void onClick(View v) { View popupView = ((LayoutInflater) ChatRoomView.this.mContext.getSystemService("layout_inflater")).inflate(R.layout.select_bamboo_list, null); SelectBambooPopupWindow popupWindow = new SelectBambooPopupWindow(ChatRoomView.this.mContext, ChatRoomView.this, popupView, -1, -1, true, ChatRoomView.this.mDefaultBambooNum); popupWindow.setAnimationStyle(0); popupWindow.showAtLocation(ChatRoomView.this, 17, 0, 0); } }); this.mGiveBambooNum = (TextView) findViewById(R.id.give_bamboo_num); ((TextView) findViewById(R.id.give_bamboo_btn)).setOnClickListener(new OnClickListener() { public void onClick(View v) { ChatRoomView.this.m_request.sendBamboos(String.valueOf(ChatRoomView.this.mDefaultBambooNum), String.valueOf(ChatRoomView.this.mRoomState.mInfoExtend.hostInfo.rid), ChatRoomView.this.mRoomState.mRoomId, "SendBamboos"); } }); ((TextView) findViewById(R.id.acquire_bamboo_btn)).setOnClickListener(new OnClickListener() { public void onClick(View v) { ChatRoomView.this.mContext.startActivityForResult(new Intent(ChatRoomView.this.mContext, TaskListActivity.class), TaskListActivity.TASK_LIST_REQUEST_CODE); } }); refreshBamboo(); } public void refreshBamboo() { if (CookieContiner.isLogin()) { this.m_request.sendMyBamboos("GetMyBamboos"); } } public void updateRoomInfo(EnterRoomState roomState) { this.mRoomState = roomState; } public void ReceiveMessage(String name, String content, MsgReceiverType receiver_type) { addMessageToListView(new Message(0, name + ":", "#0291eb", content, receiver_type)); } public void ReceiveBambooMessage(String name, String content, MsgReceiverType receiver_type) { addMessageToListView(new Message(1, name, "#0291eb", content, receiver_type)); } public void BroadcastMessage(String content) { addMessageToListView(new Message(0, content, "#ff2846", "", MsgReceiverType.MSG_RECEIVER_NORMAL)); } private void addMessageToListView(Message message) { List<Message> allmsg = this.mAdapter.getData(); allmsg.add(message); int size = allmsg.size(); if (size > 230) { this.mAdapter.setData(new ArrayList(allmsg.subList((size - 230) + 59, size - 1))); } this.mAdapter.notifyDataSetChanged(); this.mListView.setSelection(this.mAdapter.getCount() - 1); } private void initMessageInputToolBox() { this.mInputBox = (MessageInputToolBox) findViewById(R.id.messageInputToolBox); this.mGiftLayout = (LinearLayout) findViewById(R.id.gift_layout); this.mOnOperationListener = new OnOperationListener() { public boolean send(String content) { // if (LoginActivity.showLogin(ChatRoomView.this.mContext, false)) { // return false; // } if (System.currentTimeMillis() - ChatRoomView.this.mLastSendMsgTime < 2000) { ToastUtils.show(ChatRoomView.this.mContext, "请稍后发言"); return false; } ChatRoomView.this.addMessageToListView(new Message(Integer.valueOf(0), MyApplication.getInstance().GetLoginManager().GetUserDisplayName() + ":", "#24b3b8", content, MsgReceiverType.MSG_RECEIVER_NORMAL)); ChatRoomView.this.m_request.sendGroupMsg(ChatRoomView.this.mRoomState.mRoomId, content, "SendGroupMsg"); ChatRoomView.this.mLastSendMsgTime = System.currentTimeMillis(); return true; } public void SelectGift() { // if (!LoginActivity.showLogin(ChatRoomView.this.mContext, false)) { // if (ChatRoomView.this.mGiftLayout.getVisibility() == 0) { // ChatRoomView.this.mGiftLayout.setVisibility(8); // return; // } // ChatRoomView.this.mGiftLayout.setVisibility(0); // ImeUtils.hideSoftInputBox(ChatRoomView.this.mContext); // } } public void hideGiftLayout() { ChatRoomView.this.mGiftLayout.setVisibility(8); } public void selectedFace(String content) { String strBean = null; for (int i = 0; i < ChatRoomView.this.mEmoticonBeanList.size(); i++) { EmoticonBean bean = (EmoticonBean) ChatRoomView.this.mEmoticonBeanList.get(i); if (bean.getIconUri().compareToIgnoreCase(content) == 0) { strBean = bean.getContent(); break; } } if (!TextUtils.isEmpty(strBean) && ChatRoomView.this.mInputBox.getEditText().length() + strBean.length() <= 20) { int index = ChatRoomView.this.mInputBox.getEditText().getSelectionStart(); Editable editable = ChatRoomView.this.mInputBox.getEditText().getEditableText(); if (index < 0) { editable.append(strBean); } else { editable.insert(index, strBean); } } } public void selectedFuncation(int index) { switch (index) { } } }; this.mInputBox.setOnOperationListener(this.mOnOperationListener); } public boolean onResponse(boolean bResult, String strReponse, String strContext) { if ("SendGroupMsg" == strContext) { if (bResult) { try { int errno = new JSONObject(strReponse).getInt("errno"); if (errno != 0) { if (errno == IMediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) { ToastUtils.show(this.mContext, this.mContext.getString(R.string.notify_send_message_refuse)); } else { ToastUtils.show(this.mContext, this.mContext.getString(R.string.notify_send_message_fail)); } } } catch (Exception e) { ToastUtils.show(this.mContext, this.mContext.getString(R.string.notify_send_message_fail)); //LogUtil.e("ChatRoomView", e.toString()); } } else { ToastUtils.show(this.mContext, this.mContext.getString(R.string.notify_send_message_fail)); } } else if ("GetMyBamboos" == strContext) { String strBamboos = "0"; if (bResult) { ResultMsgInfo info = new ResultMsgInfo(); strBamboos = LiveRoomRequest.readBamboos(strReponse, info); if (strBamboos == null || strBamboos.isEmpty()) { strBamboos = "0"; } } MyApplication.getInstance().GetLoginManager().GetUserInfo().bamboos = strBamboos; ((TextView) findViewById(R.id.my_bamboo_num)).setText(strBamboos); } else if ("SendBamboos" == strContext) { if (bResult) { ResultMsgInfo info = new ResultMsgInfo(); String consume = LiveRoomRequest.readBamboos(strReponse, info); try { if (!TextUtils.isEmpty(consume) && Integer.parseInt(consume) > 0) { this.m_request.sendMyBamboos("GetMyBamboos"); Intent intent = new Intent(CommonDefine.BROADCAST_BAMBOOS_CHANGED); intent.setPackage(this.mContext.getPackageName()); this.mContext.sendBroadcast(intent); } else if (!TextUtils.isEmpty(info.errmsg)) { ToastUtils.show(this.mContext, info.errmsg); } } catch (Exception e2) { } } else { ToastUtils.show(this.mContext, this.mContext.getResources().getString(R.string.fail_for_network_error)); } } return false; } }
chenstrace/Videoliveplatform
app/src/main/java/com/panda/videoliveplatform/chat/ChatRoomView.java
Java
mit
12,642
package protocols.RC5; //import old.RC5SymbolDefinition; import protocols.*; import protocols.factories.FrameBuilderImpl; import protocols.factories.FrameSymbolAbstractFactory; import protocols.frame.Frame; import protocols.frame.FrameBit; import protocols.frame.Subframe; import java.util.LinkedList; import java.util.List; /** * Created by piotrek on 12.12.16. */ public class RC5FrameBuilder extends FrameBuilderImpl { private boolean toggle; public RC5FrameBuilder(FrameSymbolAbstractFactory seqFactory, IntToFrameStrategy intToFrameStrategy ) { super(seqFactory, intToFrameStrategy); } @Override public void setAddress(int addressValue) { this.addrVal = addressValue; address = intToFrameStrategy.intToFrame(addressValue, seqFactory.getMetric().getAddressLen(), seqFactory); } @Override public void setPreamble() { preamble = seqFactory.getPreamble(); } @Override public void setCommand(int commandValue) { this.commandVal = commandValue; command = intToFrameStrategy.intToFrame(commandValue, seqFactory.getMetric().getCommandLen(), seqFactory); } @Override public void setWholeFrame() { wholeFrame = new Subframe(); wholeFrame.add(pausePrefix); wholeFrame.addAllWithMerge(preamble); wholeFrame.addAllWithMerge(address); wholeFrame.addAllWithMerge(command); wholeFrame.addAllWithMerge(postamble); wholeFrame.addWithMerge(pauseSufix); } @Override public void setPostamble() { postamble = seqFactory.getPostamble(); } @Override public Frame getProduct() { toggle = !toggle; return super.getProduct(); } }
pworkshop/Peesdrq
tools/src/protocols/RC5/RC5FrameBuilder.java
Java
mit
1,796
package ee.telekom.workflow.graph.node.activity; import javax.el.ELProcessor; import ee.telekom.workflow.graph.Environment; import ee.telekom.workflow.graph.GraphEngine; import ee.telekom.workflow.graph.GraphInstance; import ee.telekom.workflow.graph.Token; import ee.telekom.workflow.graph.WorkflowException; import ee.telekom.workflow.graph.el.ElUtil; import ee.telekom.workflow.graph.node.AbstractNode; /** * Activity validating an attribute in the {@link GraphInstance}'s {@link Environment}. * * For a required attribute, it checks that the attribute's value is set in the environment (possibly also to <code>null</code>) * and that this value is assignable to the defined type. * For an optional attribute, it initialises the value to a default, if it is not yet set in the environment and ensures that * its value is assignable to the defined type. */ public class ValidateAttributeActivity extends AbstractNode{ private String attribute; private boolean isRequired; private Class<?> type; private Object defaultValue; public ValidateAttributeActivity( int id, String attribute, Class<?> type ){ this( id, null, attribute, type, true, null ); } public ValidateAttributeActivity( int id, String attribute, Class<?> type, boolean isRequired ){ this( id, null, attribute, type, isRequired, null ); } public ValidateAttributeActivity( int id, String attribute, Class<?> type, boolean isRequired, Object defaultValue ){ this( id, null, attribute, type, isRequired, defaultValue ); } public ValidateAttributeActivity( int id, String name, String attribute, Class<?> type, boolean isRequired, Object defaultValue ){ super( id, name ); this.attribute = attribute; this.type = type; this.isRequired = isRequired; this.defaultValue = defaultValue; } public String getAttribute(){ return attribute; } public boolean isRequired(){ return isRequired; } public Class<?> getType(){ return type; } public Object getDefaultValue(){ return defaultValue; } @Override public void execute( GraphEngine engine, Token token ){ GraphInstance instance = token.getInstance(); Environment environment = instance.getEnvironment(); if( !environment.containsAttribute( attribute ) ){ if( isRequired ){ // Throw exception throw new WorkflowException( "Missing required attribute '" + attribute + "'" ); } else{ // Use default value if( defaultValue instanceof String && ElUtil.hasBrackets( (String)defaultValue ) ){ ELProcessor processor = ElUtil.initNewELProcessor( environment, instance.getExternalId() ); Object expressionResult = processor.eval( ElUtil.removeBrackets( (String)defaultValue ) ); environment.setAttribute( attribute, expressionResult ); } else{ environment.setAttribute( attribute, defaultValue ); } } } // Validate type of value Object value = environment.getAttribute( attribute ); if( value != null && !type.isAssignableFrom( value.getClass() ) ){ throw new WorkflowException( "The value of attribute '" + attribute + "' is of type " + value.getClass().getCanonicalName() + " whis is not assignable to the expected type " + type.getCanonicalName() ); } engine.complete( token, null ); } @Override public void cancel( GraphEngine engine, Token token ){ // Tokens cannot "wait" at this kind of node since the execution // is synchronous. Hence, no "cancel" action is required. } @Override public void store( Environment environment, Object result ){ // This type of node does not produce a result } }
zutnop/telekom-workflow-engine
telekom-workflow-engine/src/main/java/ee/telekom/workflow/graph/node/activity/ValidateAttributeActivity.java
Java
mit
4,024
package com.moviles.clases; public class Menu { private String mNombreMenu, mDescripcion, mFechaInicioAplicacion, mFechaFinalAplicacion, mEstadoAplicacion, mKeyValue; public String get_sNombre() { return mNombreMenu; } public void set_sNombre(String _sNombre) { this.mNombreMenu = _sNombre; } public String get_sDescripcion() { return mDescripcion; } public void set_sDescripcion(String _sDescripcion) { this.mDescripcion = _sDescripcion; } public String get_sFechaInicio() { return mFechaInicioAplicacion; } public void set_sFechaInicio(String _sFechaInicio) { this.mFechaInicioAplicacion = _sFechaInicio; } public String get_sFechaFin() { return mFechaFinalAplicacion; } public void set_sFechaFin(String _sFechaFin) { this.mFechaFinalAplicacion = _sFechaFin; } public String get_sEstado() { return mEstadoAplicacion; } public void set_sEstado(String _sEstado) { this.mEstadoAplicacion = _sEstado; } public String getmKeyValue() { return mKeyValue; } public void setmKeyValue(String mKeyValue) { this.mKeyValue = mKeyValue; } }
Tito77/Proyecto-Menu-del-Restaurante
Proyecto1/src/com/moviles/clases/Menu.java
Java
mit
1,088
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. /** * Package containing the implementations for AzureCognitiveServiceMetricsAdvisorRestAPIOpenAPIV2. Azure Cognitive * Service Metrics Advisor REST API (OpenAPI v2). */ package com.azure.ai.metricsadvisor.implementation;
Azure/azure-sdk-for-java
sdk/metricsadvisor/azure-ai-metricsadvisor/src/main/java/com/azure/ai/metricsadvisor/implementation/package-info.java
Java
mit
382
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dev.kumpulatd.objects; import java.awt.image.BufferedImage; import java.util.List; /** * Interface for all Enemy classes * @author antti */ public interface Enemy { /** * * @return Returns the current HP of Enemy */ public int getHP(); /** *Method to damage the Enemy * * @param type Sets the type of damage * @param amount Sets the amount of damage */ public void damage(int type, int amount); /** * * @return Returns speed or the average for group */ public int getSpeed(); /** * * @return Returns x value */ public int getX(); /** * * @return Returns y value */ public int getY(); /** * * @return Returns the image associated with the enemy, null for groups. */ public BufferedImage getImg(); /** * * @return Returns list of Enemies included in the group. Null for Lowest level. */ public List<Enemy> getMembers(); /** * * @param newx Set new x value */ public void setX(int newx); /** * * @param newy Set new y value */ public void setY(int newy); /** * * @return Returns the value that the Enemy is currently moving towards to */ public int currentTarget(); /** *Increases the target variable for the Enemy pathfinder so that it can seek for the next object */ public void increaseTarget(); /** * * @return */ public String getName(); }
kummitus/justanothertd
KumpulaTD/src/main/java/dev/kumpulatd/objects/Enemy.java
Java
mit
1,788
package annadess; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import annadess.model.GameState; /** * Class containing the methods that are used to generate new values for each * {@code GameState}. * * @author annadess */ public class GameStateGenerator { /** * Returns a new {@code GameState} object with a randomized board, and a * random "next" value from 1 to 3. The stored "next" value represents the * next number which will appear on the board. * * @return a new {@code GameState} object with a randomized board, and a * random "next" value from 1 to 3 */ public static GameState generateGameState() { int[][] returnMatrix = new int[4][4]; Random randGen = ThreadLocalRandom.current(); generateInitialBoard(returnMatrix, randGen); mixBoard(returnMatrix, randGen); GameState gs = new GameState(returnMatrix, 0); gs.setNextElement(generateNextElement(gs)); return gs; } /** * Returns a number between 1 to 3. Intended to be used as a new stored next * value for the {@code GameState} object passed as the parameter, since the * value returned depends on the game board's contents. (a design decision * to make the game feel fairer and more accessible) * * @param currentGameState * the {@code GameState} object that the returned value depends * on * @return returns a number between 1 to 3 */ public static int generateNextElement(GameState currentGameState) { int[][] matrix = currentGameState.getBoardElements(); int sum1 = sumOnBoard(matrix, 1); int sum2 = sumOnBoard(matrix, 2); return getRandomNextElement(sum1, sum2); } private static void generateInitialBoard(int[][] returnMatrix, Random randGen) { for (int i = 0; i < 9; i++) { returnMatrix[i / 4][i % 4] = randGen.nextInt(3) + 1; } } private static void mixBoard(int[][] returnMatrix, Random randGen) { for (int i = 15; i > 0; i--) { int randomIndex = randGen.nextInt(i + 1); int randomXIndex = randomIndex / 4; int randomYIndex = randomIndex % 4; int xIndex = i / 4; int yIndex = i % 4; int tempInt = returnMatrix[randomXIndex][randomYIndex]; returnMatrix[randomXIndex][randomYIndex] = returnMatrix[xIndex][yIndex]; returnMatrix[xIndex][yIndex] = tempInt; } } private static int sumOnBoard(int[][] matrix, int numberToCount) { int sum = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (matrix[i][j] == numberToCount) { sum++; } } } return sum; } private static int getRandomNextElement(int sum1, int sum2) { if (sum1 > sum2 * 3) { return 2; } else if (sum2 > sum1 * 3) { return 1; } else { Random randGen = ThreadLocalRandom.current(); return randGen.nextInt(3) + 1; } } }
annadess/java-threes
src/main/java/annadess/GameStateGenerator.java
Java
mit
2,790
package Screens; import javax.swing.*; import Data.QueryAdaptor; import Data.UpdateAdaptor; import Screens.EmployeeScreens.EmployeeHomePage; import Screens.MemberScreens.PersonalInfoScreen; import java.awt.event.*; public class RegistrationScreen extends JPanel{ private final String[] fields= {"Georgia Tech student/faculty","GTCR employee"}; private JLabel usn,pwd,confirmpwd,usertype; private JTextField username; private JPasswordField password,passwordconf; private JComboBox<String> type; private JButton cancel, register; public RegistrationScreen(JFrame frame){ //instantiates layout GroupLayout layout = new GroupLayout(this); setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); /***************************labels**************************/ usn = new JLabel("Username: "); pwd = new JLabel("Password: "); confirmpwd = new JLabel("Confirm Password: "); usertype = new JLabel("Type of User: "); /**********************Text Fields**************************/ username = new JTextField(30); password = new JPasswordField(30); passwordconf = new JPasswordField(30); /**********************Combobox*****************************/ type = new JComboBox<String>(fields); /***********************JButton*****************************/ register = new JButton("Register"); register.addActionListener(new ButtonListener(frame)); cancel = new JButton("Cancel"); cancel.addActionListener(new Cancel(frame)); //layout declaration GroupLayout.SequentialGroup leftToRight = layout.createSequentialGroup(); GroupLayout.ParallelGroup col1 = layout.createParallelGroup(); col1.addComponent(usn); col1.addComponent(pwd); col1.addComponent(confirmpwd); col1.addComponent(usertype); GroupLayout.ParallelGroup col2 = layout.createParallelGroup(); col2.addComponent(username); col2.addComponent(password); col2.addComponent(passwordconf); col2.addComponent(type); GroupLayout.SequentialGroup mid = layout.createSequentialGroup(); mid.addComponent(register); mid.addComponent(cancel); col2.addGroup(mid); leftToRight.addGroup(col1); leftToRight.addGroup(col2); GroupLayout.SequentialGroup topToBottom = layout.createSequentialGroup(); GroupLayout.ParallelGroup row1 = layout.createParallelGroup(); row1.addComponent(usn); row1.addComponent(username); GroupLayout.ParallelGroup row2 = layout.createParallelGroup(); row2.addComponent(pwd); row2.addComponent(password); GroupLayout.ParallelGroup row3 = layout.createParallelGroup(); row3.addComponent(confirmpwd); row3.addComponent(passwordconf); GroupLayout.ParallelGroup row4 = layout.createParallelGroup(); row4.addComponent(usertype); row4.addComponent(type); GroupLayout.ParallelGroup row5 = layout.createParallelGroup(); row5.addComponent(register); row5.addComponent(cancel); topToBottom.addGroup(row1); topToBottom.addGroup(row2); topToBottom.addGroup(row3); topToBottom.addGroup(row4); topToBottom.addGroup(row5); layout.setHorizontalGroup(leftToRight); layout.setVerticalGroup(topToBottom); } private class Cancel implements ActionListener{ JFrame frame; public Cancel(JFrame frame){ this.frame = frame; } @Override public void actionPerformed(ActionEvent e){ changeScreen(new LoginScreen(frame),frame); } } private class ButtonListener implements ActionListener{ JFrame frame; //TODO better validations public ButtonListener(JFrame frame){ this.frame = frame; } @Override public void actionPerformed(ActionEvent e){ boolean flag; if(password.getText().equals(passwordconf.getText())) flag = true; else{ flag = false; JOptionPane.showMessageDialog(frame,"Password does not match"); } if(flag&&(username.getText().length()==0||password.getText().length()==0)){ JOptionPane.showMessageDialog(frame,"Please do not leave any fields empty"); flag = false; } if(flag) QueryAdaptor.connect(); try { if(flag&&QueryAdaptor.findUser(username.getText())){ JOptionPane.showMessageDialog(frame,"Username already exist"); flag = false; QueryAdaptor.close(); } } catch (Exception e1) { e1.printStackTrace(); } if(flag){ UpdateAdaptor.connect(); try { if(type.getSelectedIndex()==0){ UpdateAdaptor.makeUser(username.getText(), password.getText(), 0, 0, 1); changeScreen(new PersonalInfoScreen(frame,username.getText(),true),frame); } else { UpdateAdaptor.makeUser(username.getText(), password.getText(), 1, 0, 0); changeScreen(new EmployeeHomePage(frame,username.getText()),frame); } } catch (Exception e1) { e1.printStackTrace(); } finally{ UpdateAdaptor.close(); } } } } /** * change screen method * @param newScreen * @param frame */ private static void changeScreen(JPanel newScreen,JFrame frame){ frame.getContentPane().removeAll(); frame.getContentPane().add(newScreen); frame.pack(); frame.setVisible(true); } }
joker23/GT-Car-Rental
src/Screens/RegistrationScreen.java
Java
mit
5,247
/* * Copyright (c) 2009-2011 Dropbox, Inc. * * 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.dropbox.client2; import com.dropbox.client2.DropboxAPI.RequestAndResponse; import com.dropbox.client2.exception.DropboxException; import com.dropbox.client2.exception.DropboxIOException; import com.dropbox.client2.exception.DropboxParseException; import com.dropbox.client2.exception.DropboxSSLException; import com.dropbox.client2.exception.DropboxServerException; import com.dropbox.client2.exception.DropboxUnlinkedException; import com.dropbox.client2.session.Session; import com.dropbox.client2.session.Session.ProxyInfo; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Scanner; import javax.net.ssl.SSLException; /** * This class is mostly used internally by {@link DropboxAPI} for creating and * executing REST requests to the Dropbox API, and parsing responses. You * probably won't have a use for it other than {@link #parseDate(String)} for * parsing modified times returned in metadata, or (in very rare circumstances) * writing your own API calls. */ public class RESTUtility { private RESTUtility() { } private static final DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss ZZZZZ", Locale.US); public enum RequestMethod { GET, POST; } /** * Creates and sends a request to the Dropbox API, parses the response as * JSON, and returns the result. * * @param method GET or POST. * @param host the hostname to use. Should be either api server, * content server, or web server. * @param path the URL path, starting with a '/'. * @param apiVersion the API version to use. This should almost always be * set to {@code DropboxAPI.VERSION}. * @param params the URL params in an array, with the even numbered * elements the parameter names and odd numbered elements the * values, e.g. <code>new String[] {"path", "/Public", "locale", * "en"}</code>. * @param session the {@link Session} to use for this request. * @return a parsed JSON object, typically a Map or a JSONArray. * @throws DropboxServerException if the server responds with an error * code. See the constants in {@link DropboxServerException} * for * the meaning of each error code. * @throws DropboxIOException if any network-related error occurs. * @throws DropboxUnlinkedException if the user has revoked access. * @throws DropboxParseException if a malformed or unknown response was * received from the server. * @throws DropboxException for any other unknown errors. This is also a * superclass of all other Dropbox exceptions, so you may want * to * only catch this exception which signals that some kind of * error * occurred. */ static public Object request(RequestMethod method, String host, String path, int apiVersion, String[] params, Session session) throws DropboxException { HttpResponse resp = streamRequest(method, host, path, apiVersion, params, session).response; return parseAsJSON(resp); } /** * Creates and sends a request to the Dropbox API, and returns a * {@link RequestAndResponse} containing the {@link HttpUriRequest} and * {@link HttpResponse}. * * @param method GET or POST. * @param host the hostname to use. Should be either api server, * content server, or web server. * @param path the URL path, starting with a '/'. * @param apiVersion the API version to use. This should almost always be * set to {@code DropboxAPI.VERSION}. * @param params the URL params in an array, with the even numbered * elements the parameter names and odd numbered elements the * values, e.g. <code>new String[] {"path", "/Public", "locale", * "en"}</code>. * @param session the {@link Session} to use for this request. * @return a parsed JSON object, typically a Map or a JSONArray. * @throws DropboxServerException if the server responds with an error * code. See the constants in {@link DropboxServerException} * for * the meaning of each error code. * @throws DropboxIOException if any network-related error occurs. * @throws DropboxUnlinkedException if the user has revoked access. * @throws DropboxException for any other unknown errors. This is also a * superclass of all other Dropbox exceptions, so you may want * to * only catch this exception which signals that some kind of * error * occurred. */ static public RequestAndResponse streamRequest(RequestMethod method, String host, String path, int apiVersion, String params[], Session session) throws DropboxException { HttpUriRequest req = null; String target = null; if (method == RequestMethod.GET) { target = buildURL(host, apiVersion, path, params); req = new HttpGet(target); } else { target = buildURL(host, apiVersion, path, null); HttpPost post = new HttpPost(target); if (params != null && params.length >= 2) { if (params.length % 2 != 0) { throw new IllegalArgumentException("Params must have an even number of elements."); } List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (int i = 0; i < params.length; i += 2) { if (params[i + 1] != null) { nvps.add(new BasicNameValuePair(params[i], params[i + 1])); } } try { post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { throw new DropboxException(e); } } req = post; } session.sign(req); HttpResponse resp = execute(session, req); return new RequestAndResponse(req, resp); } /** * Reads in content from an {@link HttpResponse} and parses it as JSON. * * @param response the {@link HttpResponse}. * @return a parsed JSON object, typically a Map or a JSONArray. * @throws DropboxServerException if the server responds with an error * code. See the constants in {@link DropboxServerException} * for * the meaning of each error code. * @throws DropboxIOException if any network-related error occurs while * reading in content from the {@link HttpResponse}. * @throws DropboxUnlinkedException if the user has revoked access. * @throws DropboxParseException if a malformed or unknown response was * received from the server. * @throws DropboxException for any other unknown errors. This is also a * superclass of all other Dropbox exceptions, so you may want * to * only catch this exception which signals that some kind of * error * occurred. */ public static Object parseAsJSON(HttpResponse response) throws DropboxException { Object result = null; BufferedReader bin = null; try { HttpEntity ent = response.getEntity(); if (ent != null) { InputStreamReader in = new InputStreamReader(ent.getContent()); // Wrap this with a Buffer, so we can re-parse it if it's // not JSON // Has to be at least 16384, because this is defined as the buffer size in // org.json.simple.parser.Yylex.java // and otherwise the reset() call won't work bin = new BufferedReader(in, 16384); bin.mark(16384); JSONParser parser = new JSONParser(); result = parser.parse(bin); } } catch (IOException e) { throw new DropboxIOException(e); } catch (ParseException e) { if (DropboxServerException.isValidWithNullBody(response)) { // We have something from Dropbox, but it's an error with no reason throw new DropboxServerException(response); } else { // This is from Dropbox, and we shouldn't be getting it throw new DropboxParseException(bin); } } catch (OutOfMemoryError e) { throw new DropboxException(e); } finally { if (bin != null) { try { bin.close(); } catch (IOException e) { } } } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != DropboxServerException._200_OK) { if (statusCode == DropboxServerException._401_UNAUTHORIZED) { throw new DropboxUnlinkedException(); } else { throw new DropboxServerException(response, result); } } return result; } /** * Reads in content from an {@link HttpResponse} and parses it as a query * string. * * @param response the {@link HttpResponse}. * @return a map of parameter names to values from the query string. * @throws DropboxIOException if any network-related error occurs while * reading in content from the {@link HttpResponse}. * @throws DropboxParseException if a malformed or unknown response was * received from the server. * @throws DropboxException for any other unknown errors. This is also a * superclass of all other Dropbox exceptions, so you may want to * only catch this exception which signals that some kind of * error * occurred. */ public static Map<String, String> parseAsQueryString(HttpResponse response) throws DropboxException { HttpEntity entity = response.getEntity(); if (entity == null) { throw new DropboxParseException("Bad response from Dropbox."); } Scanner scanner; try { scanner = new Scanner(entity.getContent()).useDelimiter("&"); } catch (IOException e) { throw new DropboxIOException(e); } Map<String, String> result = new HashMap<String, String>(); while (scanner.hasNext()) { String nameValue = scanner.next(); String[] parts = nameValue.split("="); if (parts.length != 2) { throw new DropboxParseException("Bad query string from Dropbox."); } result.put(parts[0], parts[1]); } return result; } /** * Executes an {@link HttpUriRequest} with the given {@link Session} and * returns an {@link HttpResponse}. * * @param session the session to use. * @param req the request to execute. * @return an {@link HttpResponse}. * @throws DropboxServerException if the server responds with an error * code. See the constants in {@link DropboxServerException} * for * the meaning of each error code. * @throws DropboxIOException if any network-related error occurs. * @throws DropboxUnlinkedException if the user has revoked access. * @throws DropboxException for any other unknown errors. This is also a * superclass of all other Dropbox exceptions, so you may want * to * only catch this exception which signals that some kind of * error * occurred. */ public static HttpResponse execute(Session session, HttpUriRequest req) throws DropboxException { return execute(session, req, -1); } /** * Executes an {@link HttpUriRequest} with the given {@link Session} and * returns an {@link HttpResponse}. * * @param session the session to use. * @param req the request to execute. * @param socketTimeoutOverrideMs if >= 0, the socket timeout to set on * this request. Does nothing if set to a negative number. * @return an {@link HttpResponse}. * @throws DropboxServerException if the server responds with an error * code. See the constants in {@link DropboxServerException} * for * the meaning of each error code. * @throws DropboxIOException if any network-related error occurs. * @throws DropboxUnlinkedException if the user has revoked access. * @throws DropboxException for any other unknown errors. This is also a * superclass of all other Dropbox exceptions, so you may want * to * only catch this exception which signals that some kind of * error * occurred. */ public static HttpResponse execute(Session session, HttpUriRequest req, int socketTimeoutOverrideMs) throws DropboxException { HttpClient client = updatedHttpClient(session); // Set request timeouts. session.setRequestTimeout(req); if (socketTimeoutOverrideMs >= 0) { HttpParams reqParams = req.getParams(); HttpConnectionParams.setSoTimeout(reqParams, socketTimeoutOverrideMs); } try { HttpResponse response = null; for (int retries = 0; response == null && retries < 5; retries++) { /* * The try/catch is a workaround for a bug in the HttpClient * libraries. It should be returning null instead when an * error occurs. Fixed in HttpClient 4.1, but we're stuck with * this for now. See: * http://code.google.com/p/android/issues/detail?id=5255 */ try { response = client.execute(req); } catch (NullPointerException e) { } /* * We've potentially connected to a different network, but are * still using the old proxy settings. Refresh proxy settings * so that we can retry this request. */ if (response == null) { updateClientProxy(client, session); } } if (response == null) { // This is from that bug, and retrying hasn't fixed it. throw new DropboxIOException("Apache HTTPClient encountered an error. No response, try again."); } else if (response.getStatusLine().getStatusCode() != DropboxServerException._200_OK // support resume && response.getStatusLine().getStatusCode() != 206) { // This will throw the right thing: either a DropboxServerException or a DropboxProxyException parseAsJSON(response); } return response; } catch (SSLException e) { throw new DropboxSSLException(e); } catch (IOException e) { // Quite common for network going up & down or the request being // cancelled, so don't worry about logging this throw new DropboxIOException(e); } catch (OutOfMemoryError e) { throw new DropboxException(e); } } /** * Creates a URL for a request to the Dropbox API. * * @param host the Dropbox host (i.e., api server, content server, or web * server). * @param apiVersion the API version to use. You should almost always use * {@code DropboxAPI.VERSION} for this. * @param target the target path, staring with a '/'. * @param params any URL params in an array, with the even numbered * elements the parameter names and odd numbered elements the * values, e.g. <code>new String[] {"path", "/Public", "locale", * "en"}</code>. * @return a full URL for making a request. */ public static String buildURL(String host, int apiVersion, String target, String[] params) { if (!target.startsWith("/")) { target = "/" + target; } try { // We have to encode the whole line, then remove + and / encoding // to get a good OAuth URL. target = URLEncoder.encode("/" + apiVersion + target, "UTF-8"); target = target.replace("%2F", "/"); if (params != null && params.length > 0) { target += "?" + urlencode(params); } // These substitutions must be made to keep OAuth happy. target = target.replace("+", "%20").replace("*", "%2A"); } catch (UnsupportedEncodingException uce) { return null; } return "https://" + host + ":443" + target; } /** * Parses a date/time returned by the Dropbox API. Returns null if it * cannot be parsed. * * @param date a date returned by the API. * @return a {@link Date}. */ public static Date parseDate(String date) { try { return dateFormat.parse(date); } catch (java.text.ParseException e) { return null; } } /** * Gets the session's client and updates its proxy. */ private static synchronized HttpClient updatedHttpClient(Session session) { HttpClient client = session.getHttpClient(); updateClientProxy(client, session); return client; } /** * Updates the given client's proxy from the session. */ private static void updateClientProxy(HttpClient client, Session session) { ProxyInfo proxyInfo = session.getProxyInfo(); if (proxyInfo != null && proxyInfo.host != null && !proxyInfo.host.equals("")) { HttpHost proxy; if (proxyInfo.port < 0) { proxy = new HttpHost(proxyInfo.host); } else { proxy = new HttpHost(proxyInfo.host, proxyInfo.port); } client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { client.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); } } /** * URL encodes an array of parameters into a query string. */ private static String urlencode(String[] params) { if (params.length % 2 != 0) { throw new IllegalArgumentException("Params must have an even number of elements."); } String result = ""; try { boolean firstTime = true; for (int i = 0; i < params.length; i += 2) { if (params[i + 1] != null) { if (firstTime) { firstTime = false; } else { result += "&"; } result += URLEncoder.encode(params[i], "UTF-8") + "=" + URLEncoder.encode(params[i + 1], "UTF-8"); } } result.replace("*", "%2A"); } catch (UnsupportedEncodingException e) { return null; } return result; } }
eaglesakura/eglibrary
deprecated/eglibrary-android-dropbox/src/com/dropbox/client2/RESTUtility.java
Java
mit
23,224
//https://leetcode.com/problems/house-robber/ #198 class HouseRobber { public int rob(int[] nums) { int[] maxCash = new int[nums.length]; if (nums.length == 0) { return 0; } if (nums.length == 1) { return nums[0]; } maxCash[0] = nums[0]; maxCash[1] = (nums[1] > nums[0])? nums[1] : nums[0]; for (int i=2; i <nums.length; i++){ maxCash[i] = Math.max(maxCash[i-2] + nums[i] , maxCash[i-1]); } int maxInt = 0; for (int j = 0; j < maxCash.length; j++) { if (maxCash[j] >= maxInt) { maxInt = maxCash[j]; } } return maxInt; } }
Breadamonium/CodingPractice
HouseRobber.java
Java
mit
729
package com.shc.gwtal.client.webaudio.nodes; import com.google.gwt.dom.client.EventTarget; import com.shc.gwtal.client.webaudio.AudioContext; import com.shc.gwtal.client.webaudio.AudioParam; import com.shc.gwtal.client.webaudio.enums.ChannelCountMode; import com.shc.gwtal.client.webaudio.enums.ChannelInterpretation; /** * @author Sri Harsha Chilakapati */ public class AudioNode extends EventTarget { protected AudioNode() { } public final AudioNode connect(AudioNode destination) { return connect(destination, 0); } public final AudioNode connect(AudioNode destination, int output) { return connect(destination, output, 0); } public final native AudioNode connect(AudioNode destination, int output, int input) /*-{ return this.connect(destination, output, input); }-*/; public final void connect(AudioParam destination) { connect(destination, 0); } public final native void connect(AudioParam destination, int output) /*-{ this.connect(destination, output); }-*/; public final native void disconnect() /*-{ this.disconnect(); }-*/; public final native void disconnect(int output) /*-{ this.disconnect(output); }-*/; public final native void disconnect(AudioNode destination) /*-{ this.disconnect(destination); }-*/; public final native void disconnect(AudioNode destination, int output) /*-{ this.disconnect(destination, output); }-*/; public final native void disconnect(AudioNode destination, int output, int input) /*-{ this.disconnect(destination, output, input); }-*/; public final native void disconnect(AudioParam destination) /*-{ this.disconnect(destination); }-*/; public final native void disconnect(AudioParam destination, int output) /*-{ this.disconnect(destination, output); }-*/; public final native AudioContext getContext() /*-{ return this.context; }-*/; public final native int getNumberOfInputs() /*-{ return this.numberOfInputs; }-*/; public final native int getNumberOfOutputs() /*-{ return this.numberOfOutputs; }-*/; public final native int getChannelCount() /*-{ return this.channelCount; }-*/; public final native void setChannelCount(int channelCount) /*-{ this.channelCount = channelCount; }-*/; public final ChannelCountMode getChannelCountMode() { return ChannelCountMode.forJsState(nGetChannelCountMode()); } public final void setChannelCountMode(ChannelCountMode channelCountMode) { nSetChannelCountMode(channelCountMode.getJsState()); } private native String nGetChannelCountMode() /*-{ return this.channelCountMode; }-*/; private native void nSetChannelCountMode(String channelCountMode) /*-{ this.channelCountMode = channelCountMode; }-*/; public final ChannelInterpretation getChannelInterpretation() { return ChannelInterpretation.forJsState(nGetChannelInterpretation()); } public final void setChannelInterpretation(ChannelInterpretation channelInterpretation) { nSetChannelInterpretation(channelInterpretation.getJsState()); } private native String nGetChannelInterpretation() /*-{ return this.channelInterpretation; }-*/; private native void nSetChannelInterpretation(String channelInterpretation) /*-{ this.channelInterpretation = channelInterpretation; }-*/; }
sriharshachilakapati/GWT-AL
gwt-al/src/main/java/com/shc/gwtal/client/webaudio/nodes/AudioNode.java
Java
mit
3,576
package org.robolectric.tester.android.view; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.ActionProvider; import android.view.ContextMenu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import org.robolectric.Robolectric; public class TestMenuItem implements MenuItem { private int itemId; private int groupId; private CharSequence title; private boolean enabled = true; private boolean checked = false; private boolean checkable = false; private boolean visible = true; private boolean expanded = false; private OnMenuItemClickListener menuItemClickListener; public int iconRes; private Intent intent; private SubMenu subMenu; private View actionView; private OnActionExpandListener actionExpandListener; public TestMenuItem() { super(); } public TestMenuItem(int itemId) { super(); this.itemId = itemId; } public void setItemId(int itemId) { this.itemId = itemId; } public void setGroupId(int groupId) { this.groupId = groupId; } @Override public int getItemId() { return itemId; } @Override public int getGroupId() { return groupId; } @Override public int getOrder() { return 0; } @Override public MenuItem setTitle(CharSequence title) { this.title = title; return this; } @Override public MenuItem setTitle(int title) { return null; } @Override public CharSequence getTitle() { return title; } @Override public MenuItem setTitleCondensed(CharSequence title) { return null; } @Override public CharSequence getTitleCondensed() { return null; } @Override public MenuItem setIcon(Drawable icon) { return null; } @Override public MenuItem setIcon(int iconRes) { this.iconRes = iconRes; return this; } @Override public Drawable getIcon() { return null; } @Override public MenuItem setIntent(Intent intent) { this.intent = intent; return this; } @Override public Intent getIntent() { return this.intent; } @Override public MenuItem setShortcut(char numericChar, char alphaChar) { return null; } @Override public MenuItem setNumericShortcut(char numericChar) { return null; } @Override public char getNumericShortcut() { return 0; } @Override public MenuItem setAlphabeticShortcut(char alphaChar) { return null; } @Override public char getAlphabeticShortcut() { return 0; } @Override public MenuItem setCheckable(boolean checkable) { this.checkable = checkable; return this; } @Override public boolean isCheckable() { return checkable; } @Override public MenuItem setChecked(boolean checked) { this.checked = checked; return this; } @Override public boolean isChecked() { return checked; } @Override public MenuItem setVisible(boolean visible) { this.visible = visible; return this; } @Override public boolean isVisible() { return visible; } @Override public MenuItem setEnabled(boolean enabled) { this.enabled = enabled; return this; } @Override public boolean isEnabled() { return enabled; } @Override public boolean hasSubMenu() { return subMenu != null; } @Override public SubMenu getSubMenu() { return subMenu; } public void setSubMenu(SubMenu subMenu) { this.subMenu = subMenu; } @Override public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) { this.menuItemClickListener = menuItemClickListener; return this; } @Override public ContextMenu.ContextMenuInfo getMenuInfo() { return null; } public void click() { if (enabled && menuItemClickListener != null) { menuItemClickListener.onMenuItemClick(this); } else if (enabled && intent != null) { Robolectric.application.startActivity(intent); } } @Override public void setShowAsAction(int actionEnum) { } @Override public MenuItem setShowAsActionFlags(int actionEnum) { return null; } @Override public MenuItem setActionView(View view) { actionView = view; return this; } @Override public MenuItem setActionView(int resId) { return null; } @Override public View getActionView() { return actionView; } @Override public MenuItem setActionProvider(ActionProvider actionProvider) { return null; } @Override public ActionProvider getActionProvider() { return null; } @Override public boolean expandActionView() { if (actionView != null) { if (actionExpandListener != null) { actionExpandListener.onMenuItemActionExpand(this); } expanded = true; return true; } return false; } @Override public boolean collapseActionView() { if (actionView != null) { if (actionExpandListener != null) { actionExpandListener.onMenuItemActionCollapse(this); } expanded = false; return true; } return false; } @Override public boolean isActionViewExpanded() { return expanded; } @Override public MenuItem setOnActionExpandListener(OnActionExpandListener listener) { actionExpandListener = listener; return this; } }
qx/FullRobolectricTestSample
src/main/java/org/robolectric/tester/android/view/TestMenuItem.java
Java
mit
5,344
// Generated from C:\github\duro\eclipse\src\duro\reflang\antlr4\Duro.g4 by ANTLR 4.1 package duro.reflang.antlr4; import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.tree.ParseTreeVisitor; /** * This interface defines a complete generic visitor for a parse tree produced * by {@link DuroParser}. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ public interface DuroVisitor<T> extends ParseTreeVisitor<T> { /** * Visit a parse tree produced by {@link DuroParser#binaryMessageChain}. * @param ctx the parse tree * @return the visitor result */ T visitBinaryMessageChain(@NotNull DuroParser.BinaryMessageChainContext ctx); /** * Visit a parse tree produced by {@link DuroParser#assignmentOperator}. * @param ctx the parse tree * @return the visitor result */ T visitAssignmentOperator(@NotNull DuroParser.AssignmentOperatorContext ctx); /** * Visit a parse tree produced by {@link DuroParser#program}. * @param ctx the parse tree * @return the visitor result */ T visitProgram(@NotNull DuroParser.ProgramContext ctx); /** * Visit a parse tree produced by {@link DuroParser#integer}. * @param ctx the parse tree * @return the visitor result */ T visitInteger(@NotNull DuroParser.IntegerContext ctx); /** * Visit a parse tree produced by {@link DuroParser#unaryMessage}. * @param ctx the parse tree * @return the visitor result */ T visitUnaryMessage(@NotNull DuroParser.UnaryMessageContext ctx); /** * Visit a parse tree produced by {@link DuroParser#multiKeyMessageModifier}. * @param ctx the parse tree * @return the visitor result */ T visitMultiKeyMessageModifier(@NotNull DuroParser.MultiKeyMessageModifierContext ctx); /** * Visit a parse tree produced by {@link DuroParser#multiKeyMessageArgChain}. * @param ctx the parse tree * @return the visitor result */ T visitMultiKeyMessageArgChain(@NotNull DuroParser.MultiKeyMessageArgChainContext ctx); /** * Visit a parse tree produced by {@link DuroParser#multiKeyMessageArgEnd}. * @param ctx the parse tree * @return the visitor result */ T visitMultiKeyMessageArgEnd(@NotNull DuroParser.MultiKeyMessageArgEndContext ctx); /** * Visit a parse tree produced by {@link DuroParser#dict}. * @param ctx the parse tree * @return the visitor result */ T visitDict(@NotNull DuroParser.DictContext ctx); /** * Visit a parse tree produced by {@link DuroParser#id}. * @param ctx the parse tree * @return the visitor result */ T visitId(@NotNull DuroParser.IdContext ctx); /** * Visit a parse tree produced by {@link DuroParser#multiKeyMessageArg}. * @param ctx the parse tree * @return the visitor result */ T visitMultiKeyMessageArg(@NotNull DuroParser.MultiKeyMessageArgContext ctx); /** * Visit a parse tree produced by {@link DuroParser#closure}. * @param ctx the parse tree * @return the visitor result */ T visitClosure(@NotNull DuroParser.ClosureContext ctx); /** * Visit a parse tree produced by {@link DuroParser#receiver}. * @param ctx the parse tree * @return the visitor result */ T visitReceiver(@NotNull DuroParser.ReceiverContext ctx); /** * Visit a parse tree produced by {@link DuroParser#grouping}. * @param ctx the parse tree * @return the visitor result */ T visitGrouping(@NotNull DuroParser.GroupingContext ctx); /** * Visit a parse tree produced by {@link DuroParser#selfMultiKeyMessage}. * @param ctx the parse tree * @return the visitor result */ T visitSelfMultiKeyMessage(@NotNull DuroParser.SelfMultiKeyMessageContext ctx); /** * Visit a parse tree produced by {@link DuroParser#indexAccess}. * @param ctx the parse tree * @return the visitor result */ T visitIndexAccess(@NotNull DuroParser.IndexAccessContext ctx); /** * Visit a parse tree produced by {@link DuroParser#multiKeyMessage}. * @param ctx the parse tree * @return the visitor result */ T visitMultiKeyMessage(@NotNull DuroParser.MultiKeyMessageContext ctx); /** * Visit a parse tree produced by {@link DuroParser#multiKeyMessageHead}. * @param ctx the parse tree * @return the visitor result */ T visitMultiKeyMessageHead(@NotNull DuroParser.MultiKeyMessageHeadContext ctx); /** * Visit a parse tree produced by {@link DuroParser#expressionReceiver}. * @param ctx the parse tree * @return the visitor result */ T visitExpressionReceiver(@NotNull DuroParser.ExpressionReceiverContext ctx); /** * Visit a parse tree produced by {@link DuroParser#binaryMessageArg}. * @param ctx the parse tree * @return the visitor result */ T visitBinaryMessageArg(@NotNull DuroParser.BinaryMessageArgContext ctx); /** * Visit a parse tree produced by {@link DuroParser#expressionChain}. * @param ctx the parse tree * @return the visitor result */ T visitExpressionChain(@NotNull DuroParser.ExpressionChainContext ctx); /** * Visit a parse tree produced by {@link DuroParser#messageChain}. * @param ctx the parse tree * @return the visitor result */ T visitMessageChain(@NotNull DuroParser.MessageChainContext ctx); /** * Visit a parse tree produced by {@link DuroParser#pseudoVar}. * @param ctx the parse tree * @return the visitor result */ T visitPseudoVar(@NotNull DuroParser.PseudoVarContext ctx); /** * Visit a parse tree produced by {@link DuroParser#access}. * @param ctx the parse tree * @return the visitor result */ T visitAccess(@NotNull DuroParser.AccessContext ctx); /** * Visit a parse tree produced by {@link DuroParser#binaryMessageArgChain}. * @param ctx the parse tree * @return the visitor result */ T visitBinaryMessageArgChain(@NotNull DuroParser.BinaryMessageArgChainContext ctx); /** * Visit a parse tree produced by {@link DuroParser#string}. * @param ctx the parse tree * @return the visitor result */ T visitString(@NotNull DuroParser.StringContext ctx); /** * Visit a parse tree produced by {@link DuroParser#selfSingleKeyMessage}. * @param ctx the parse tree * @return the visitor result */ T visitSelfSingleKeyMessage(@NotNull DuroParser.SelfSingleKeyMessageContext ctx); /** * Visit a parse tree produced by {@link DuroParser#multiKeyMessageTail}. * @param ctx the parse tree * @return the visitor result */ T visitMultiKeyMessageTail(@NotNull DuroParser.MultiKeyMessageTailContext ctx); /** * Visit a parse tree produced by {@link DuroParser#multiKeyMessageArgs}. * @param ctx the parse tree * @return the visitor result */ T visitMultiKeyMessageArgs(@NotNull DuroParser.MultiKeyMessageArgsContext ctx); /** * Visit a parse tree produced by {@link DuroParser#dictEntry}. * @param ctx the parse tree * @return the visitor result */ T visitDictEntry(@NotNull DuroParser.DictEntryContext ctx); /** * Visit a parse tree produced by {@link DuroParser#literal}. * @param ctx the parse tree * @return the visitor result */ T visitLiteral(@NotNull DuroParser.LiteralContext ctx); /** * Visit a parse tree produced by {@link DuroParser#array}. * @param ctx the parse tree * @return the visitor result */ T visitArray(@NotNull DuroParser.ArrayContext ctx); /** * Visit a parse tree produced by {@link DuroParser#binaryMessageArgEnd}. * @param ctx the parse tree * @return the visitor result */ T visitBinaryMessageArgEnd(@NotNull DuroParser.BinaryMessageArgEndContext ctx); /** * Visit a parse tree produced by {@link DuroParser#selector}. * @param ctx the parse tree * @return the visitor result */ T visitSelector(@NotNull DuroParser.SelectorContext ctx); /** * Visit a parse tree produced by {@link DuroParser#singleKeyMessage}. * @param ctx the parse tree * @return the visitor result */ T visitSingleKeyMessage(@NotNull DuroParser.SingleKeyMessageContext ctx); /** * Visit a parse tree produced by {@link DuroParser#slotAccess}. * @param ctx the parse tree * @return the visitor result */ T visitSlotAccess(@NotNull DuroParser.SlotAccessContext ctx); /** * Visit a parse tree produced by {@link DuroParser#parArg}. * @param ctx the parse tree * @return the visitor result */ T visitParArg(@NotNull DuroParser.ParArgContext ctx); /** * Visit a parse tree produced by {@link DuroParser#expression}. * @param ctx the parse tree * @return the visitor result */ T visitExpression(@NotNull DuroParser.ExpressionContext ctx); /** * Visit a parse tree produced by {@link DuroParser#assignment}. * @param ctx the parse tree * @return the visitor result */ T visitAssignment(@NotNull DuroParser.AssignmentContext ctx); /** * Visit a parse tree produced by {@link DuroParser#slotAssignment}. * @param ctx the parse tree * @return the visitor result */ T visitSlotAssignment(@NotNull DuroParser.SlotAssignmentContext ctx); /** * Visit a parse tree produced by {@link DuroParser#behaviorParams}. * @param ctx the parse tree * @return the visitor result */ T visitBehaviorParams(@NotNull DuroParser.BehaviorParamsContext ctx); /** * Visit a parse tree produced by {@link DuroParser#indexOperator}. * @param ctx the parse tree * @return the visitor result */ T visitIndexOperator(@NotNull DuroParser.IndexOperatorContext ctx); /** * Visit a parse tree produced by {@link DuroParser#messageEnd}. * @param ctx the parse tree * @return the visitor result */ T visitMessageEnd(@NotNull DuroParser.MessageEndContext ctx); /** * Visit a parse tree produced by {@link DuroParser#variableDeclaration}. * @param ctx the parse tree * @return the visitor result */ T visitVariableDeclaration(@NotNull DuroParser.VariableDeclarationContext ctx); /** * Visit a parse tree produced by {@link DuroParser#binaryMessage}. * @param ctx the parse tree * @return the visitor result */ T visitBinaryMessage(@NotNull DuroParser.BinaryMessageContext ctx); /** * Visit a parse tree produced by {@link DuroParser#spawn}. * @param ctx the parse tree * @return the visitor result */ T visitSpawn(@NotNull DuroParser.SpawnContext ctx); /** * Visit a parse tree produced by {@link DuroParser#multiKeyMessageArgReceiver}. * @param ctx the parse tree * @return the visitor result */ T visitMultiKeyMessageArgReceiver(@NotNull DuroParser.MultiKeyMessageArgReceiverContext ctx); /** * Visit a parse tree produced by {@link DuroParser#binaryOperator}. * @param ctx the parse tree * @return the visitor result */ T visitBinaryOperator(@NotNull DuroParser.BinaryOperatorContext ctx); /** * Visit a parse tree produced by {@link DuroParser#messageExchange}. * @param ctx the parse tree * @return the visitor result */ T visitMessageExchange(@NotNull DuroParser.MessageExchangeContext ctx); /** * Visit a parse tree produced by {@link DuroParser#interfaceId}. * @param ctx the parse tree * @return the visitor result */ T visitInterfaceId(@NotNull DuroParser.InterfaceIdContext ctx); /** * Visit a parse tree produced by {@link DuroParser#atom}. * @param ctx the parse tree * @return the visitor result */ T visitAtom(@NotNull DuroParser.AtomContext ctx); /** * Visit a parse tree produced by {@link DuroParser#indexAssignment}. * @param ctx the parse tree * @return the visitor result */ T visitIndexAssignment(@NotNull DuroParser.IndexAssignmentContext ctx); }
jakobehmsen/duro
eclipse/src/duro/reflang/antlr4/DuroVisitor.java
Java
mit
11,411
package org.blackbox.bricksole; /** * Exception thrown in the call phase. */ public class CommandCallException extends CommandRuntimeException { public CommandCallException() { } public CommandCallException(String message) { super(message); } public CommandCallException(String message, Throwable cause) { super(message, cause); } public CommandCallException(Throwable cause) { super(cause); } public CommandCallException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
theblackboxio/bricksole
bricksole-core/src/main/java/org/blackbox/bricksole/CommandCallException.java
Java
mit
658
/* * The MIT License (MIT) * * Copyright (c) 2015-2016, Max Roncace <[email protected]> * * 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 net.caseif.flint.steel.util.agent.rollback.serialization; import net.caseif.flint.serialization.Serializer; import org.bukkit.util.EulerAngle; /** * {@link Serializer} for {@link EulerAngle} objects. * * @author Max Roncacé * @since 1.0 */ public class EulerAngleSerializer implements Serializer<EulerAngle> { private static EulerAngleSerializer instance; private EulerAngleSerializer() { } public static EulerAngleSerializer getInstance() { return instance != null ? instance : (instance = new EulerAngleSerializer()); } @Override public String serialize(EulerAngle angle) { return "(" + angle.getX() + "," + angle.getY() + "," + angle.getZ() + ")"; } @Override public EulerAngle deserialize(String serial) throws IllegalArgumentException { if (serial.startsWith("(") && serial.endsWith(")")) { String[] arr = serial.substring(1, serial.length() - 1).split(","); if (arr.length == 3) { try { double x = Double.parseDouble(arr[0]); double y = Double.parseDouble(arr[0]); double z = Double.parseDouble(arr[0]); return new EulerAngle(x, y, z); } catch (NumberFormatException ignored) { } // continue to the IllegalArgumentException at the bottom } } throw new IllegalArgumentException("Invalid serial for EulerAngle"); } }
caseif/Steel
src/main/java/net/caseif/flint/steel/util/agent/rollback/serialization/EulerAngleSerializer.java
Java
mit
2,645
package de.lalo5.particleeffectlib.effect; import de.lalo5.particleeffectlib.Effect; import de.lalo5.particleeffectlib.util.ParticleEffect; import de.lalo5.particleeffectlib.EffectType; import de.lalo5.particleeffectlib.util.VectorUtils; import de.lalo5.particleeffectlib.EffectManager; import de.lalo5.particleeffectlib.util.MathUtils; import java.util.Collection; import java.util.HashSet; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.util.Vector; public class WaveEffect extends Effect { public ParticleEffect particle = ParticleEffect.DRIP_WATER; public ParticleEffect cloudParticle = ParticleEffect.CLOUD; public Color cloudColor = null; /** * Velocity of the wave * Call velocity.zero() if the wave should be stationary */ public Vector velocity = new Vector(); /** * Caches the Vectors used to build the wave */ protected final Collection<Vector> waterCache, cloudCache; /** * Amount of particles forming the tube */ public int particlesFront = 10; /** * Amount of particles forming the back */ public int particlesBack = 10; /** * Rows to build the wave in the width */ public int rows = 20; /** * The distance from the origin location to the first point of the wave */ public float lengthFront = 1.5f; /** * The distance from the origin location to the last point of the wave */ public float lengthBack = 3; /** * Depth of the parabola tube */ public float depthFront = 1; /** * Height of the parabola arc forming the back */ public float heightBack = .5f; /** * Height of the wave in blocks */ public float height = 2; /** * Width of the wave in blocks */ public float width = 5; /** * Do not mess with the following attributes. They build a cache to gain performance. */ protected boolean firstStep = true; public WaveEffect(EffectManager effectManager) { super(effectManager); type = EffectType.REPEATING; period = 5; iterations = 50; waterCache = new HashSet<Vector>(); cloudCache = new HashSet<Vector>(); } /** * Call this method when you change anything related to the creation of the wave */ public void invalidate(Location location) { firstStep = false; waterCache.clear(); cloudCache.clear(); Vector s1 = new Vector(-lengthFront, 0, 0); Vector s2 = new Vector(lengthBack, 0, 0); Vector h = new Vector(-0.5 * lengthFront, height, 0); Vector n1, n2, n_s1ToH, n_s2ToH, c1, c2, s1ToH, s2ToH; float len_s1ToH, len_s2ToH, yaw; s1ToH = h.clone().subtract(s1); c1 = s1.clone().add(s1ToH.clone().multiply(0.5)); len_s1ToH = (float) s1ToH.length(); n_s1ToH = s1ToH.clone().multiply(1f / len_s1ToH); n1 = new Vector(s1ToH.getY(), -s1ToH.getX(), 0).normalize(); if (n1.getX() < 0) { n1.multiply(-1); } s2ToH = h.clone().subtract(s2); c2 = s2.clone().add(s2ToH.clone().multiply(0.5)); len_s2ToH = (float) s2ToH.length(); n_s2ToH = s2ToH.clone().multiply(1f / len_s2ToH); n2 = new Vector(s2ToH.getY(), -s2ToH.getX(), 0).normalize(); if (n2.getX() < 0) { n2.multiply(-1); } yaw = (-location.getYaw() + 90) * MathUtils.degreesToRadians; for (int i = 0; i < particlesFront; i++) { float ratio = (float) i / particlesFront; float x = (ratio - .5f) * len_s1ToH; float y = (float) (-depthFront / Math.pow((len_s1ToH / 2), 2) * Math.pow(x, 2) + depthFront); Vector v = c1.clone(); v.add(n_s1ToH.clone().multiply(x)); v.add(n1.clone().multiply(y)); for (int j = 0; j < rows; j++) { float z = ((float) j / rows - .5f) * width; Vector vec = v.clone().setZ(v.getZ() + z); VectorUtils.rotateAroundAxisY(vec, yaw); if (i == 0 || i == particlesFront - 1) { cloudCache.add(vec); } else { waterCache.add(vec); } } } for (int i = 0; i < particlesBack; i++) { float ratio = (float) i / particlesBack; float x = (ratio - .5f) * len_s2ToH; float y = (float) (-heightBack / Math.pow((len_s2ToH / 2), 2) * Math.pow(x, 2) + heightBack); Vector v = c2.clone(); v.add(n_s2ToH.clone().multiply(x)); v.add(n2.clone().multiply(y)); for (int j = 0; j < rows; j++) { float z = ((float) j / rows - .5f) * width; Vector vec = v.clone().setZ(v.getZ() + z); VectorUtils.rotateAroundAxisY(vec, yaw); if (i == particlesFront - 1) { cloudCache.add(vec); } else { waterCache.add(vec); } } } } @Override public void onRun() { Location location = getLocation(); if (firstStep) { velocity.copy(location.getDirection().setY(0).normalize().multiply(0.2)); invalidate(location); } location.add(velocity); for (Vector v : cloudCache) { location.add(v); display(cloudParticle, location, cloudColor, 0, 1); location.subtract(v); } for (Vector v : waterCache) { location.add(v); display(particle, location); location.subtract(v); } } }
axelrindle/ParticleEffectLib
src/main/java/de/lalo5/particleeffectlib/effect/WaveEffect.java
Java
mit
5,732
/* * Name: Matt DeSilvey * */ package bufmgr; import chainexception.*; public class ErrorException extends ChainException { public ErrorException( Exception e, String name ) { super( e, name ); } }
mdesilvey/classprojects
javaminibase/src/bufmgr/ErrorException.java
Java
mit
206
package com.base.game.entity.monsters; import java.awt.Graphics; import java.awt.Rectangle; import com.base.game.Animation; import com.base.game.Assets; import com.base.game.Handler; import com.base.game.Utils; import com.base.game.entity.attacks.ElectroBall; public class Wolf extends Monster { public Wolf(Handler handler, float x, float y, int layer, int level) { super(handler, x, y, layer, 88, 80, level); setBounds(new Rectangle(18, 26, 44, 54)); baseSpeed = 3.5f; currSpeed = baseSpeed; myHealth = 30; health = myHealth; damage = 0; reach = 10; attackProb = 200; dwnLft = new Animation(125, Assets.wolfDwnLft, 0); dwnRgt = new Animation(125, Assets.wolfDwnRgt, 0); upLft = new Animation(125, Assets.wolfUpLft, 0); upRgt = new Animation(125, Assets.wolfUpRgt, 0); idleDwnLft = new Animation(175, Assets.wolfIdleDwnLft, 0); atkDwnLft = new Animation(100, Assets.wolfAtkDwnLft, 1); idleUpLft = new Animation(175, Assets.wolfIdleUpLft, 0); atkUpLft = new Animation(100, Assets.wolfAtkUpLft, 1); idleDwnRgt = new Animation(175, Assets.wolfIdleDwnRgt, 0); atkDwnRgt = new Animation(100, Assets.wolfAtkDwnRgt, 1); idleUpRgt = new Animation(175, Assets.wolfIdleUpRgt, 0); atkUpRgt = new Animation(100, Assets.wolfAtkUpRgt, 1); currentAnimation = idleDwnRgt; } @Override public void update() { super.update(); stateUpdate(); } @Override public void render(Graphics g) { if(rVal == 0 && gVal == 0 && bVal == 0) { if(getCurrentAnimation() != null) g.drawImage(currentAnimation.getCurrentFrame(), (int) (x - handler.getCamera().getxOffset()), (int) (y - handler.getCamera().getyOffset()), width, height, null); } else { if(getCurrentAnimation() != null) g.drawImage(Utils.tintImage(currentAnimation.getCurrentFrame(), rVal, bVal, gVal), (int) (x - handler.getCamera().getxOffset()), (int) (y - handler.getCamera().getyOffset()), width, height, null); } // g.setColor(Color.MAGENTA); // g.fillRect((int)(attackBounds.x), (int) (attackBounds.y), attackBounds.width, attackBounds.height); // // g.setColor(Color.red); // g.fillRect((int)(x + bounds.x - handler.getCamera().getxOffset()), (int)(y + bounds.y - handler.getCamera().getyOffset()), bounds.width, bounds.height); } @Override public void attack() { if(currentAnimation.isComplete()) { currentAnimation.reset(); state = "CHASE"; } if(target.getX() < x && target.getY() < y) currentAnimation = atkUpLft; else if(target.getX() > x && target.getY() < y) currentAnimation = atkUpRgt; else if(target.getX() < x && target.getY() > y) currentAnimation = atkDwnLft; else currentAnimation = atkDwnRgt; damageEntity(); } }
NikHammon/GameProject
src/main/java/com/base/game/entity/monsters/Wolf.java
Java
mit
2,745
package com.epicelric.draconians.activity; /** * Created by Elric on 5/12/2016. */ import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.epicelric.draconians.R; public class HomeFragment extends Fragment { public HomeFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_home, container, false); // Inflate the layout for this fragment return rootView; } // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // } @Override public void onDetach() { super.onDetach(); } }
EpicElric/Draconians
app/src/main/java/com/epicelric/draconians/activity/HomeFragment.java
Java
mit
1,056
package org.doublelong.tests; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; public class ProjectionViewportCameraTest { public static void main(String[] args) { // ProjectionViewportCamera game = new ProjectionViewportCamera(); // new LwjglApplication(game); Box2dTest game = new Box2dTest(); new LwjglApplication(game); } }
xzela/jastroblast
jastroblast-desktop/src/org/doublelong/tests/ProjectionViewportCameraTest.java
Java
mit
353