repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
vkorobkov/jfixtures | src/main/java/com/github/vkorobkov/jfixtures/sql/Appender.java | 353 | package com.github.vkorobkov.jfixtures.sql;
import java.io.IOException;
@FunctionalInterface
public interface Appender {
default void append(CharSequence... sequences) throws IOException {
for (CharSequence sequence : sequences) {
append(sequence);
}
}
void append(CharSequence sequence) throws IOException;
}
| mit |
gems-uff/oceano | tools/peixe-espada/src/main/java/br/uff/ic/gems/peixeespadacliente/action/DoSendMessageAboutNotImproveNorWorselRefactoring.java | 1210 | package br.uff.ic.gems.peixeespadacliente.action;
import br.uff.ic.gems.peixeespadacliente.model.agent.LocalManagerAgent;
import br.uff.ic.gems.peixeespadacliente.symptom.Symptom;
import br.uff.ic.oceano.core.exception.ServiceException;
import br.uff.ic.oceano.core.exception.VCSException;
import translation.Translate;
/**
*
* @author Heliomar, João Felipe
*/
public class DoSendMessageAboutNotImproveNorWorselRefactoring extends AbstractAction {
private Symptom symptom;
public DoSendMessageAboutNotImproveNorWorselRefactoring(Symptom symptom) {
this.symptom = symptom;
}
@Override
public LocalManagerAgent execute(LocalManagerAgent agentPeixeEspada) throws ServiceException {
Translate translate = Translate.getTranslate();
agentPeixeEspada.appendMessage(translate.notImprovedWorsened());
agentPeixeEspada.appendMessage(translate.revertingChanges());
try {
agentPeixeEspada.getProjectVCS().doReset();
} catch (VCSException ex) {
throw new ServiceException(ex);
}
clientService.sendMessageToNotImproveNorWorseRefactoring(agentPeixeEspada, symptom);
return agentPeixeEspada;
}
}
| mit |
xavierhardy/amazed | src/amazed/maze/LabyrintheAbstrait.java | 4221 | /*
The MIT License (MIT)
Copyright (c) 2014 Xavier Hardy
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 amazed.maze;
import java.awt.Point;
public abstract class LabyrintheAbstrait {
//Coordonn�es de l'entr�e
protected int entreeX = 0;
protected int entreeY = 0;
//Coordonn�es de la sortie
protected int sortieX = 1;
protected int sortieY = 1;
protected int largeur;
protected int hauteur;
public Case[][] carte;
public LabyrintheAbstrait(int largeur, int hauteur, Case[][] carte) {
this.largeur = largeur ;
this.hauteur = hauteur ;
this.carte = new Case[largeur][hauteur];
for(int i=0;i<largeur;i++){
for(int j=0;j<hauteur;j++){
this.carte[i][j] = carte[i][j].clone();
}
}
setEntreeHasard();
setSortieHasard();
}
public LabyrintheAbstrait(int largeur, int hauteur) {
this.largeur = largeur ;
this.hauteur = hauteur ;
}
public Point getEntree(){
return new Point(entreeX,entreeY);
}
public Point getSortie(){
return new Point(sortieX,sortieY);
}
public void setEntree(int x, int y){
entreeX = x;
entreeY = y;
}
public void setSortie(int x, int y){
sortieX = x;
sortieY = y;
}
public void initEntreeSortie(){
int x = 0,y = 0;
//INITIALISATION DE L'ENTREE ET DE LA SORTIE DU LABYRINTHE
while(!carte[x][y].dansLaby() && x < largeur && y < hauteur){
x++;
y++;
System.out.println(x + " " + y);
}
if(x == largeur || y == hauteur){ //Si on sort du labyrinthe, c'est que la diagonale n'appartient pas au labyrinthe
setEntreeHasard();
}
else {
setEntree(x,y);
}
x = largeur - 1;
y = hauteur - 1;
while(!carte[x][y].dansLaby() && x >= 0 && y >= 0){
x--;
y--;
}
if(x < 0 || y < 0 || (x == getEntree().x && y == getEntree().y)){
//Si on est sorti par la gauche ou le haut OU
//Si il n'y a qu'un point sur la diagonale, entr�e et sortie sont confondues
setSortieHasard();
}
else{
setSortie(x,y);
}
}
public void setEntreeHasard(){
entreeX = (int)(largeur*Math.random());
entreeY = (int)(hauteur*Math.random());
while((entreeX == sortieX && entreeY == sortieY) || !carte[entreeX][entreeY].dansLaby()){
entreeX = (int)(largeur*Math.random());
entreeY = (int)(hauteur*Math.random());
}
}
public void setSortieHasard(){
sortieX = (int)(largeur*Math.random());
sortieY = (int)(hauteur*Math.random());
while((entreeX == sortieX && entreeY == sortieY) || !carte[sortieX][sortieY].dansLaby()){
sortieX = (int)(largeur*Math.random());
sortieY = (int)(hauteur*Math.random());
}
}
public int getHauteur() {
return hauteur;
}
public int getLargeur() {
return largeur;
}
public boolean isEntree(int x, int y){
return entreeX == x && entreeY == y;
}
public boolean isSortie(int x, int y){
return sortieX == x && sortieY == y;
}
abstract public void creuser(int x, int y, int dir);
abstract public CaseAbstraite getCase(int x, int y);
}
| mit |
Zimbra/qless-java | qless-web/src/main/java/com/zimbra/qless/web/controller/PriorityController.java | 1490 | package com.zimbra.qless.web.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zimbra.qless.Job;
import com.zimbra.qless.QlessClient;
@Controller
public class PriorityController {
final Logger LOGGER = LoggerFactory.getLogger(PriorityController.class);
@Autowired private QlessClient qlessClient;
@RequestMapping(value="/priority", method=RequestMethod.POST, headers={"Content-Type=application/json"})
@ResponseBody
public Map<String,Object> priority(@RequestBody Map<String,Integer> body) {
// Expects a JSON-encoded dictionary of jid => priority
Map<String,Object> response = new HashMap<String,Object>();
for (Map.Entry<String,Integer> entry: body.entrySet()) {
String jid = entry.getKey();
Integer priority = entry.getValue();
try {
Job job = qlessClient.getJob(jid);
job.priority(priority);
response.put(jid, priority);
} catch (IOException e) {
response.put(jid, "failed");
}
}
return response;
}
}
| mit |
jhsx/hacklang-idea | gen/io/github/josehsantos/hack/lang/psi/HackWhereClause.java | 3259 | // This is a generated file. Not intended for manual editing.
package io.github.josehsantos.hack.lang.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface HackWhereClause extends HackPsiElement {
@Nullable
HackAdditiveConcatenationExpression getAdditiveConcatenationExpression();
@Nullable
HackArrayAccessExpression getArrayAccessExpression();
@Nullable
HackArrayLiteralExpression getArrayLiteralExpression();
@Nullable
HackAssignmentExpression getAssignmentExpression();
@Nullable
HackBackticksExpression getBackticksExpression();
@Nullable
HackBitwiseExpression getBitwiseExpression();
@Nullable
HackCallableFunctionCallExpression getCallableFunctionCallExpression();
@NotNull
List<HackCastExpression> getCastExpressionList();
@Nullable
HackCloneExpression getCloneExpression();
@Nullable
HackClosureExpression getClosureExpression();
@Nullable
HackCollectionLiteralExpression getCollectionLiteralExpression();
@Nullable
HackComparativeExpression getComparativeExpression();
@Nullable
HackDynamicVariableExpression getDynamicVariableExpression();
@Nullable
HackEmptyExpression getEmptyExpression();
@Nullable
HackEspecialParenthesisedExpression getEspecialParenthesisedExpression();
@Nullable
HackEvalExpression getEvalExpression();
@Nullable
HackExitExpression getExitExpression();
@Nullable
HackFunctionCallExpression getFunctionCallExpression();
@Nullable
HackIncludeExpression getIncludeExpression();
@Nullable
HackInstanceofExpression getInstanceofExpression();
@Nullable
HackIssetExpression getIssetExpression();
@Nullable
HackLambdaExpression getLambdaExpression();
@Nullable
HackListAssignmentExpression getListAssignmentExpression();
@Nullable
HackLogicalExpression getLogicalExpression();
@Nullable
HackMapArrayLiteralExpression getMapArrayLiteralExpression();
@Nullable
HackMemberVariableExpression getMemberVariableExpression();
@Nullable
HackMethodCallExpression getMethodCallExpression();
@Nullable
HackMultiplicativeExpression getMultiplicativeExpression();
@Nullable
HackNewExpression getNewExpression();
@Nullable
HackParenthesizedExpression getParenthesizedExpression();
@Nullable
HackPrefixOperator getPrefixOperator();
@Nullable
HackPrintExpression getPrintExpression();
@Nullable
HackRequireExpression getRequireExpression();
@Nullable
HackScalarExpression getScalarExpression();
@Nullable
HackShapeLiteralExpression getShapeLiteralExpression();
@Nullable
HackShiftExpression getShiftExpression();
@Nullable
HackStaticClassVariableExpression getStaticClassVariableExpression();
@Nullable
HackStaticMethodCallExpression getStaticMethodCallExpression();
@Nullable
HackSuffixOperator getSuffixOperator();
@Nullable
HackTernaryExpression getTernaryExpression();
@Nullable
HackTupleExpression getTupleExpression();
@Nullable
HackVArrayLiteralExpression getVArrayLiteralExpression();
@Nullable
HackVariableExpression getVariableExpression();
@Nullable
HackVariableNameHolder getVariableNameHolder();
@Nullable
HackXhpExpression getXhpExpression();
}
| mit |
fifth-postulate/finding-the-planets | java/src/main/java/nl/fifth/postulate/circuit/pipe/Smooth.java | 1066 | package nl.fifth.postulate.circuit.pipe;
import nl.fifth.postulate.circuit.ChainingPipe;
import nl.fifth.postulate.circuit.TrappistData;
public class Smooth extends ChainingPipe {
public static Smooth smooth(float alpha) {
return new Smooth(alpha);
}
public static final String COLUMN_NAME = "SMOOTH";
private final float alpha;
public Smooth(float alpha) {
super(COLUMN_NAME);
this.alpha = alpha;
}
@Override
public Object calculate(TrappistData trappistData) {
float[] averages = (float[]) trappistData.dataFor(Average.COLUMN_NAME);
float[] smootheds = new float[averages.length];
float smoothed = 0f;
for (int row = 0, rowLimit = averages.length; row < rowLimit; row++ ) {
float average = averages[row];
if (row != 0) {
smoothed = alpha * average + (1 - alpha) * smoothed;
} else {
smoothed = average;
}
smootheds[row] = smoothed;
}
return smootheds;
}
}
| mit |
Bernardinhouessou/Projets_Autres | Java Projets (TPs - Autres)/Autres/Data-structures-and-Algorithm/DisjointSetMain.java | 5099 |
import java.util.*;
class WeightedNode implements Comparable<WeightedNode> {
public String name;
private ArrayList<WeightedNode> neighbors = new ArrayList<WeightedNode>();
private HashMap<WeightedNode, Integer> weightMap = new HashMap<>();
private boolean isVisited = false;
private WeightedNode parent;
private int distance;
private DisjointSet set; //used in DisjointSet Algorithm
public WeightedNode(String name) {
this.name = name;
distance = Integer.MAX_VALUE;
}
public DisjointSet getSet() {
return set;
}
public void setSet(DisjointSet set) { //used in DisjointSet Algorithm
this.set = set;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<WeightedNode> getNeighbors() {
return neighbors;
}
public void setNeighbors(ArrayList<WeightedNode> neighbors) {
this.neighbors = neighbors;
}
public HashMap<WeightedNode, Integer> getWeightMap() {
return weightMap;
}
public void setWeightMap(HashMap<WeightedNode, Integer> weightMap) {
this.weightMap = weightMap;
}
public boolean isVisited() {
return isVisited;
}
public void setVisited(boolean isVisited) {
this.isVisited = isVisited;
}
public WeightedNode getParent() {
return parent;
}
public void setParent(WeightedNode parent) {
this.parent = parent;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(WeightedNode o) {
return this.distance - o.distance;
}
}
class DisjointSet {
private ArrayList<WeightedNode> nodes = new ArrayList<>();
public static void driver(ArrayList<WeightedNode> nodeList){
makeSet(nodeList); //Create Disjoint Sets for each node in this list.
for(int i= 0; i<nodeList.size()-1; i++) {
WeightedNode firstNode = nodeList.get(i);
WeightedNode secondNode = nodeList.get(i+1);
System.out.println("Checking if node "+firstNode.getName()+" and "+secondNode.getName() +" belongs to different set, if yes, will Union them...");
System.out.println("\nFirst Set name is: " + firstNode.getName());
firstNode.getSet().printAllNodesOfThisSet();
System.out.println("\nSecond Set name is: " + secondNode.getName());
secondNode.getSet().printAllNodesOfThisSet();
if(!findSet(firstNode).equals(findSet(secondNode))) {
System.out.println("\nMaking union "+firstNode+" and "+secondNode );
DisjointSet unionedSet = union(firstNode, secondNode);
unionedSet.printAllNodesOfThisSet();
}
System.out.println("\n**************************************\n");
}
}//end of method
public static void makeSet(ArrayList<WeightedNode> nodeList) {
//for each node in list, create a disjoint set
for(WeightedNode node: nodeList) {
DisjointSet set = new DisjointSet();
set.getNodes().add(node);
node.setSet(set);//Storing the reference of this Disjoint set in Node class
}
}//end of method
public static DisjointSet getSet(WeightedNode node) {
return node.getSet();
}//end of method
public static DisjointSet findSet(WeightedNode node) {
return node.getSet();
}//end of method
public static DisjointSet union(WeightedNode node1, WeightedNode node2) {
if(node1.getSet().equals(node2.getSet())) { //if two nodes are of same set then no union needed
return null;
}
else {
//get set object of two nodes
DisjointSet set1 = node1.getSet();
DisjointSet set2 = node2.getSet();
// if first set is bigger then update each node of second set to merge to set1
if(set1.getNodes().size()>set2.getNodes().size()) {
ArrayList<WeightedNode> nodeSet2 = set2.getNodes();
for(WeightedNode node: nodeSet2) { //update each node of second set to merge to set1
node.setSet(set1);
set1.getNodes().add(node);
}
return set1;
}
else {
// if second set is bigger/equal then update each node of first set to merge to set2
ArrayList<WeightedNode> nodeSet1 = set1.getNodes();
for(WeightedNode node: nodeSet1) {//update each node of first set to merge to set2
node.setSet(set2);
set2.getNodes().add(node);
}
return set2;
}//end of inner if-else
}//end of outer if-else
}//end of method
public ArrayList<WeightedNode> getNodes() {
return nodes;
}//end of method
public void setNodes(ArrayList<WeightedNode> nodes) {
this.nodes = nodes;
}//end of method
public void printAllNodesOfThisSet() {
System.out.println("Printing all nodes of the set: ");
for(WeightedNode node: nodes) {
System.out.print(node + " ");
}
System.out.println();
}//end of method
}//end of class
public class DisjointSetMain {
public static void main(String[] args) {
// Constructor for ArrayList
ArrayList<WeightedNode> nodeList = new ArrayList<>();
// create 10 nodes: 1-10
for (int i = 0; i < 10; i++) {
nodeList.add(new WeightedNode("" + (char) (65 + i)));
}
// Calling DisjointSet
DisjointSet.driver(nodeList);
}// end of method
}// end of class
| mit |
cpowell3/course-scheduler-csi480 | StartMenu.java | 15598 | import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
/*
* 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.
*/
public class StartMenu extends javax.swing.JFrame {
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton FinishButton;
private javax.swing.JButton RemoveButton;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem2;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem3;
private javax.swing.JComboBox<String> jComboDepartment;
private javax.swing.JComboBox<String> jComboYear;
private javax.swing.JComboBox<String> jComboSemester;
private javax.swing.JInternalFrame jInternalFrame1;
private javax.swing.JLabel DepartmentLabel;
private javax.swing.JLabel YearLabel;
private javax.swing.JLabel SemesterLabel;
private javax.swing.JLabel jLabel4;
private javax.swing.JList<String> jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
//private javax.swing.JTable jTable1;
// End of variables declaration
public ArrayList<String> selected_classes = new ArrayList<String>();
public ArrayList<String> selected_classes_abrv = new ArrayList<String>();
final DefaultListModel department_list_model = new DefaultListModel();
private String year, semester;
/**
* Creates new form Course_Scheduler_GUI
*/
public StartMenu() {
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">
private void initComponents() {
jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuItem2 = new javax.swing.JCheckBoxMenuItem();
jCheckBoxMenuItem3 = new javax.swing.JCheckBoxMenuItem();
buttonGroup1 = new javax.swing.ButtonGroup();
jScrollPane2 = new javax.swing.JScrollPane();
//jTable1 = new javax.swing.JTable();
jInternalFrame1 = new javax.swing.JInternalFrame();
DepartmentLabel = new javax.swing.JLabel();
jComboDepartment = new javax.swing.JComboBox<>();
YearLabel = new javax.swing.JLabel();
jComboYear = new javax.swing.JComboBox<>();
SemesterLabel = new javax.swing.JLabel();
jComboSemester = new javax.swing.JComboBox<>();
FinishButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList<>();
RemoveButton = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jCheckBoxMenuItem1.setSelected(true);
jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1");
jCheckBoxMenuItem2.setSelected(true);
jCheckBoxMenuItem2.setText("jCheckBoxMenuItem2");
jCheckBoxMenuItem3.setSelected(true);
jCheckBoxMenuItem3.setText("jCheckBoxMenuItem3");
jInternalFrame1.setVisible(true);
DepartmentLabel.setText("Department:");
String[] department_strings_lowercase = { "American Studies", "Anthropology", "Art/Art History", "Biology", "Black Studies", "Business Management", "Chemistry", "Chinese", "Computer Science", "Dance", "Economics", "Education", "English Language Learning", "English", "Environmental Science/Studies", "French Studies", "Gender Studies", "German Studies", "Global Perspectives", "History", "Humanities", "Hispanic Studies", "Int'l Literature & Culture", "International Studies", "Mathematics", "Music", "Physical Education", "Philosophy", "Physics", "Political Science", "Psychology", "Sociology", "Theatre"};
String[] department_strings = { "AMERICAN STUDIES", "ANTHROPOLOGY", "ART/ART HISTORY", "BIOLOGY", "BLACK STUDIES", "BUSINESS MANAGEMENT", "CHEMISTRY", "CHINESE", "COMPUTER SCIENCE", "DANCE", "ECONOMICS", "EDUCATION", "ENGLISH LANGUAGE LEARNING", "ENGLISH", "ENVIRONMENTAL SCIENCE/STUDIES", "FRENCH STUDIES", "GENDER STUDIES", "GERMAN STUDIES", "GLOBAL PERSPECTIVES", "HISTORY", "HUMANITIES", "HISPANIC STUDIES", "INT'L LITERATURE & CULTURE", "INTERNATIONAL STUDIES", "MATHEMATICS", "MUSIC", "PHYSICAL EDUCATION", "PHILOSOPHY", "PHYSICS", "POLITICAL SCIENCE", "PSYCHOLOGY", "SOCIOLOGY", "THEATRE"};
String[] department_abrv = { "AMS", "ANT", "ART", "BIO", "BLS", "BUS", "CHE", "CHN", "CSI", "DAN", "ECN", "EDU", "ELL", "ENG", "ENV", "FRS", "GEN", "GRS", "GRW", "HIS", "HMN", "HPS", "ILC", "INT", "MAT", "MUS", "PED", "PHL", "PHY", "POL", "PSY", "SOC", "THE" };
jComboDepartment.setModel(new javax.swing.DefaultComboBoxModel<>(department_strings_lowercase));
jComboDepartment.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
//jComboDepartmentActionPerformed(jComboDepartment.getSelectedItem().toString());
int index = jComboDepartment.getSelectedIndex();
jComboDepartmentActionPerformed(department_strings[index], department_abrv[index], department_strings_lowercase[index]);
}
});
YearLabel.setText("Year:");
jComboYear.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] {"2017", "2018", "2019", "2020"}));
jComboYear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
year = jComboYear.getSelectedItem().toString();
}
});
SemesterLabel.setText("Semester:");
jComboSemester.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] {"FALL", "SPRING"}));
jComboSemester.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
semester = jComboSemester.getSelectedItem().toString();
}
});
FinishButton.setText("Finish");
FinishButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FinishButtonActionPerformed(evt);
}
});
jList1.setModel(department_list_model);
jScrollPane1.setViewportView(jList1);
RemoveButton.setText("Remove Selected");
RemoveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RemoveButtonActionPerformed(evt);
}
});
jLabel4.setText("COURSE SCHEDULER");
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(FinishButton)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(DepartmentLabel)
.addComponent(YearLabel)
.addComponent(SemesterLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jComboSemester, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jComboDepartment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(59, 59, 59)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(RemoveButton))))
.addContainerGap(25, Short.MAX_VALUE))
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4)
.addGap(29, 29, 29)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(DepartmentLabel)
.addComponent(jComboDepartment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(YearLabel)
.addComponent(jComboYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SemesterLabel)
.addComponent(jComboSemester, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(RemoveButton)
.addComponent(FinishButton))))
.addContainerGap(62, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1)
);
pack();
}// </editor-fold>
public String getYearSemester(){
return year + semester;
}
public ArrayList<String> getDepartments(){
return selected_classes;
}
public ArrayList<String> getDepartmentCodes(){
return selected_classes_abrv;
}
private void RemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int toRemove = jList1.getSelectedIndex();
department_list_model.remove(toRemove);
selected_classes.remove(toRemove);
selected_classes_abrv.remove(toRemove);
System.out.println(selected_classes);
}
private void jComboDepartmentActionPerformed(String departmentName, String departmentAbrv, String departmentLowercase) {
// TODO add your handling code here:
if(!selected_classes.contains(departmentName)){
selected_classes.add(departmentName);
selected_classes_abrv.add(departmentAbrv);
department_list_model.addElement(departmentLowercase);
}
System.out.println(selected_classes);
System.out.println(selected_classes_abrv);
}
private void FinishButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//new CalendarUI().setVisible(true);
JFrame newFrame = new JFrame();
newFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
newFrame.add(new CalendarUI());
newFrame.pack();
newFrame.setVisible(true);
}
public static void openStartMenu(){
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StartMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StartMenu().setVisible(true);
}
});
}
}
| mit |
emanuell/revistaonline-fip | src/main/java/br/com/fip/gati/revistaonline/infrastructure/mail/EmailException.java | 223 | package br.com.fip.gati.revistaonline.infrastructure.mail;
public class EmailException extends Exception {
public EmailException(String msg) {
super(msg);
}
public EmailException(Throwable t) {
super(t);
}
}
| mit |
Seiferxx/firegoblin | src/com/seifernet/firegoblin/servlet/ContextServlet.java | 2391 | package com.seifernet.firegoblin.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.seifernet.firegoblin.dispatcher.ContextDispatcher;
/**
* Simple dispatch servlet implementation
*
* @author Seifer ( Cuauhtemoc Herrera Muñoz )
* @version 1.0.0
* @since 1.0.0
*/
public abstract class ContextServlet extends DispatcherServlet{
private static final long serialVersionUID = 1L;
public static final int HTTP_RESPONSE = 1;
public static final int HTML_RESPONSE = 2;
public static final int HTTP_REDIRECT = 3;
public static final int JSON_RESPONSE = 4;
public static final int NO_RESPONSE = 5;
/**
* Here must be referenced the dispatcherHelper implementation
* used to dispatch servlet request action.
*
* @return The dispatcherHelper object
*/
protected abstract ContextDispatcher getDispatcher( );
/**
* Sends a response based on DispatcherHelper getResponseType
* value
*
* @param request - The http request
* @param response - The http response
* @param data - Data to be sent ( Can be URL or DATA/ENCODED DATA )
*/
protected void sendResponse( HttpServletRequest request, HttpServletResponse response, String data, int responseType ) throws ServletException, IOException{
switch( responseType ){
case HTTP_RESPONSE:
httpResponse( request, response, data );
break;
case HTTP_REDIRECT:
httpRedirect( request, response, data );
break;
case HTML_RESPONSE:
htmlResponse( request, response, data );
break;
case JSON_RESPONSE:
jsonResponse( request, response, data );
break;
case NO_RESPONSE:
noResponse( request, response, data );
}
}
/**
* Simple listen implementation for tiles, gets the action from request URL, then the action
* dispatch is delegated to the dispatcherHelper using object's dispatchAction method.
*/
@Override
protected void listen( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
String action = getRequestContext( request );
ContextDispatcher dispatcher = getDispatcher( );
String actionResponse = dispatcher.dispatchAction( request, response, action );
sendResponse( request, response, actionResponse,dispatcher.getResponseType( ) );
}
}
| mit |
karsany/obridge | obridge-maven-plugin/src/main/java/org/obridge/maven/OBridgeMojo.java | 2989 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ferenc Karsany
*
* 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.obridge.maven;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.obridge.OBridge;
import org.obridge.context.OBridgeConfiguration;
import java.io.File;
@Mojo(name = "obridge", requiresProject = true, defaultPhase = LifecyclePhase.GENERATE_SOURCES,
requiresDependencyResolution = ResolutionScope.COMPILE)
public class OBridgeMojo extends AbstractMojo {
@Parameter(property = "project", required = true, readonly = true)
protected MavenProject project;
@Parameter(defaultValue = "${project.build.directory}/generated-sources/obridge")
private String baseDir;
@Parameter(defaultValue = "${project.groupId}")
private String groupId;
@Parameter(property = "obridge.configuration", defaultValue = "${basedir}/obridge.xml")
private File configurationFile;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info(this.toString());
OBridge o = new OBridge();
OBridgeConfiguration config = o.loadConfiguration(configurationFile);
config.setSourceRoot(baseDir);
if (config.getRootPackageName() == null || "".equals(config.getRootPackageName())) {
config.setRootPackageName(groupId);
}
getLog().info(config.toString());
o.generate(config);
project.addCompileSourceRoot(config.getSourceRoot());
project.addTestCompileSourceRoot(config.getSourceRoot());
}
}
| mit |
tjitze/RankPL | src/main/java/com/tr/rp/RankPL.java | 10125 | package com.tr.rp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.tr.rp.ast.statements.Program;
import com.tr.rp.base.ExecutionContext;
import com.tr.rp.base.Rank;
import com.tr.rp.base.RankedItem;
import com.tr.rp.exceptions.RPLException;
import com.tr.rp.exceptions.RPLInterruptedException;
import com.tr.rp.exceptions.RPLMiscException;
import com.tr.rp.parser.ConcreteParser;
import com.tr.rp.parser.RankPLLexer;
import com.tr.rp.parser.RankPLParser;
public class RankPL {
protected static int maxRank = 0;
protected static int rankCutOff = Rank.MAX;
protected static int timeOut = Integer.MAX_VALUE;
protected static boolean noExecStats = false;
protected static boolean noRanks = false;
protected static boolean terminateAfterFirst = false;
protected static String fileName = null;
public static void main(String[] args) {
// Handle options
if (!parseOptions(args)) {
return;
}
// Parse input
String source = "";
try {
source = getFileContent(fileName);
} catch (IOException e) {
System.err.println("I/O Exception while reading source file: " + e.getMessage());
return;
}
// Parse
Program program = null;
try {
program = parse(source);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
if (program == null) {
System.exit(-1);
}
// Execute
try {
execute(program, rankCutOff, maxRank, noRanks, terminateAfterFirst);
} catch (RPLException e) {
System.out.println(e.getDetailedDescription());
System.exit(-1);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
public static Program parse(String source) {
RankPLLexer lexer = new RankPLLexer(new ANTLRInputStream(source));
TokenStream tokens = new CommonTokenStream(lexer);
RankPLParser parser = new RankPLParser(tokens);
parser.setErrorHandler(new BailErrorStrategy());
ConcreteParser classVisitor = new ConcreteParser();
// Parse
Program program = null;
try {
program = (Program) classVisitor.visit(parser.program());
} catch (ParseCancellationException e) {
System.out.println("Syntax error");
lexer = new RankPLLexer(new ANTLRInputStream(source));
tokens = new CommonTokenStream(lexer);
parser = new RankPLParser(tokens);
classVisitor = new ConcreteParser();
try {
program = (Program) classVisitor.visit(parser.program());
} catch (Exception ex) {
// Ignore
}
return null;
}
return program;
}
/**
* Execute program, keeping track of timeout, and print results to console.
*
* @param program Program to execute
* @throws RPLException Exception occurring during execution of program
*/
public static Map<Integer, Set<String>> execute(Program program, int rankCutOff, int maxRank, boolean noRanks, boolean terminateAfterFirst) throws RPLException {
final Map<Integer, Set<String>> resultMap = new LinkedHashMap<Integer, Set<String>>();
ExecutionContext c = new ExecutionContext();
c.setRankCutOff(rankCutOff);
long startTime = System.currentTimeMillis();
if (!noRanks) {
System.out.println("Rank Outcome");
}
try {
program.run(c, new Function<RankedItem<String>, Boolean>() {
@Override
public Boolean apply(RankedItem<String> item) {
// Normal termination
if (item == null) {
return false;
}
// Terminate due to maxRank
if (item.rank > maxRank) {
return false;
}
// Print outcome
if (noRanks) {
System.out.println(item.item);
} else {
System.out.println(String.format(" %3d ", item.rank) + item.item);
}
// Store outcome in map
Set<String> rankResults = resultMap.get(item.rank);
if (rankResults == null) {
rankResults = new LinkedHashSet<String>();
resultMap.put(item.rank, rankResults);
}
rankResults.add(item.item);
// Terminate after first
if (terminateAfterFirst) {
return false;
}
// Terminate after time-out
if (System.currentTimeMillis() - startTime > timeOut) {
System.out.println("Remaining results omitted due to timeout.");
return false;
}
// Continue
return true;
}
});
} catch (RPLInterruptedException ie) {
// Thrown due to timeOut, terminateAfterFirst or maxRank
} catch (RPLException re) {
throw re;
}
// Print exec stats
if (!noExecStats) {
System.out.println("Took: " + (System.currentTimeMillis() - startTime) + " ms");
}
return resultMap;
}
/**
* @return Options object
*/
private static Options createOptions() {
Options options = new Options();
options.addOption(Option.builder("source").hasArg().argName("source_file")
.desc("source file to execute").build());
options.addOption(Option.builder("rank").hasArg().type(Number.class).argName("max_rank")
.desc("generate outcomes with ranks up to max_rank (defaults to 0)").build());
options.addOption(Option.builder("all")
.desc("generate all outcomes").build());
options.addOption(Option.builder("c").hasArg().type(Number.class).argName("rank_cutoff")
.desc("discard computations above this rank (default ∞)").build());
options.addOption(Option.builder("f")
.desc("terminate after first answer").build());
options.addOption(Option.builder("t").hasArg().type(Number.class).argName("timeout")
.desc("execution time-out (in milliseconds)").build());
options.addOption(Option.builder("ns").desc("don't print execution stats").build());
options.addOption(Option.builder("nr").desc("don't print ranks").build());
options.addOption(Option.builder("help").desc("show help message").build());
options.addOption(Option.builder("version").desc("show version").build());
return options;
}
/**
* Parse options and set static fields. Returns true if successful.
*
* @param args Options to parse
* @return True if execution can proceed
*/
private static boolean parseOptions(String[] args) {
try {
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(createOptions(), args);
if (cmd.hasOption("version")) {
printVersion();
return false;
}
if (cmd.hasOption("help")) {
printUsage();
return false;
}
if (cmd.hasOption("source")) {
fileName = cmd.getOptionValue("source");
} else {
System.err.println("Missing -source argument");
printUsage();
return false;
}
if (cmd.hasOption("rank")) {
try {
maxRank = ((Number) cmd.getParsedOptionValue("rank")).intValue();
} catch (Exception e) {
System.err.println("Illegal value provided for -rank option.");
return false;
}
}
if (cmd.hasOption("all")) {
if (cmd.hasOption("rank")) {
System.err.println("Cannot use both -rank and -all options.");
return false;
}
maxRank = Rank.MAX;
}
if (cmd.hasOption("t")) {
try {
timeOut = ((Number) cmd.getParsedOptionValue("t")).intValue();
} catch (Exception e) {
System.err.println("Illegal value provided for -t option.");
return false;
}
}
if (cmd.hasOption("c")) {
try {
rankCutOff = ((Number) cmd.getParsedOptionValue("c")).intValue();
} catch (Exception e) {
System.err.println("Illegal value provided for -c option.");
return false;
}
}
if (cmd.hasOption("f")) {
terminateAfterFirst = true;
}
if (cmd.hasOption("ns")) {
noExecStats = true;
}
if (cmd.hasOption("nr")) {
noRanks = true;
}
} catch (ParseException pe) {
System.out.println(pe.getMessage());
return false;
}
return true;
}
private static void printUsage() {
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(160);
List<String> order = Arrays.asList("source", "r", "t", "c", "d", "m", "f", "ns", "nr", "help");
formatter.setOptionComparator(new Comparator<Option>() {
@Override
public int compare(Option o1, Option o2) {
String s1 = ((Option) o1).getOpt();
String s2 = ((Option) o2).getOpt();
return order.indexOf(s1) - order.indexOf(s2);
}
});
formatter.printHelp("java -jar RankPL.jar", createOptions(), true);
}
private static void printVersion() {
final Properties properties = new Properties();
try {
properties.load(new RankPL().getClass().getClassLoader().getResourceAsStream(".properties"));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println(properties.getProperty("version"));
}
public static String getFileContent(String sourceFile) throws IOException {
File file = new File(sourceFile);
FileInputStream fis = new FileInputStream(file);
StringBuilder sb = new StringBuilder();
Reader r = new InputStreamReader(fis, "UTF-8"); // or whatever encoding
int ch = r.read();
while (ch >= 0) {
sb.append((char) ch);
ch = r.read();
}
r.close();
return sb.toString();
}
}
| mit |
robotzero/FXCounter | src/main/java/com/robotzero/counter/event/InitViewEvent.java | 93 | package com.robotzero.counter.event;
public class InitViewEvent implements MainViewEvent {}
| mit |
eduardorost/meutransporte-api | src/main/java/br/com/meutransporte/entities/EnderecoEntity.java | 1060 | package br.com.meutransporte.entities;
import javax.persistence.*;
import java.util.Set;
@Entity(name = "endereco")
public class EnderecoEntity {
@Id
@GeneratedValue
private Long id;
private String logradouro, cep;
private Integer numero;
@OneToMany(mappedBy = "endereco")
private Set<EventoEntity> eventos;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogradouro() {
return logradouro;
}
public void setLogradouro(String logradouro) {
this.logradouro = logradouro;
}
public Integer getNumero() {
return numero;
}
public void setNumero(Integer numero) {
this.numero = numero;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public Set<EventoEntity> getEventos() {
return eventos;
}
public void setEventos(Set<EventoEntity> eventos) {
this.eventos = eventos;
}
}
| mit |
surli/spinefm | spinefm-eclipseplugins-root/spinefm-core/src/fr/unice/spinefm/ActionModel/SystemActionModel/impl/SystemActionImplDelegate.java | 778 | package fr.unice.spinefm.ActionModel.SystemActionModel.impl;
import java.lang.reflect.Field;
public class SystemActionImplDelegate extends SystemActionImpl {
@Override
public boolean equals(Object obj) {
Class<? extends SystemActionImplDelegate> c = this.getClass();
if (obj.getClass().equals(c)) {
Field[] fields = c.getFields();
boolean result = true;
for (Field f : fields) {
try {
Object o1 = f.get(this);
Object o2 = f.get(obj);
result = result && (o1.equals(o2));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
return false;
}
}
| mit |
pulse00/Symfony-2-Eclipse-Plugin | com.dubture.symfony.core/src/com/dubture/symfony/core/codeassist/strategies/TransUnitCompletionStrategy.java | 1907 | /*******************************************************************************
* This file is part of the Symfony eclipse plugin.
*
* (c) Robert Gruendler <r.gruendler@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
******************************************************************************/
package com.dubture.symfony.core.codeassist.strategies;
import org.eclipse.dltk.core.CompletionRequestor;
import org.eclipse.dltk.core.IScriptProject;
import org.eclipse.dltk.core.ISourceRange;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.php.core.codeassist.ICompletionContext;
import org.eclipse.php.core.codeassist.ICompletionReporter;
import org.eclipse.php.internal.core.codeassist.strategies.MethodParameterKeywordStrategy;
import com.dubture.symfony.core.codeassist.CodeassistUtils;
import com.dubture.symfony.core.codeassist.contexts.TransUnitCompletionContext;
/**
*
* Strategy to complete Symfony translations.
*
*
* @author Robert Gruendler <r.gruendler@gmail.com>
*
*/
@SuppressWarnings({ "restriction" })
public class TransUnitCompletionStrategy extends MethodParameterKeywordStrategy {
public TransUnitCompletionStrategy(ICompletionContext context) {
super(context);
}
@Override
public void apply(ICompletionReporter reporter) throws BadLocationException {
TransUnitCompletionContext context = (TransUnitCompletionContext) getContext();
CompletionRequestor req = context.getCompletionRequestor();
if (!req.getClass().getName().contains("Symfony")) {
return;
}
IScriptProject project = getCompanion().getSourceModule().getScriptProject();
ISourceRange range = getReplacementRange(context);
String prefix = context.getPrefix();
CodeassistUtils.reportTranslations(reporter, prefix, range, project );
}
}
| mit |
giraud/reasonml-idea-plugin | src/com/reason/lang/core/psi/impl/PsiJsObject.java | 2652 | package com.reason.lang.core.psi.impl;
import com.intellij.lang.*;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.tree.*;
import com.reason.lang.*;
import com.reason.lang.core.*;
import com.reason.lang.core.psi.*;
import com.reason.lang.ocaml.*;
import org.jetbrains.annotations.*;
import java.util.*;
public class PsiJsObject extends CompositePsiElement implements PsiLanguageConverter {
protected PsiJsObject(@NotNull IElementType type) {
super(type);
}
public @NotNull Collection<PsiObjectField> getFields() {
return ORUtil.findImmediateChildrenOfClass(this, PsiObjectField.class);
}
public @Nullable PsiObjectField getField(@NotNull String name) {
for (PsiObjectField field : getFields()) {
if (name.equals(field.getName())) {
return field;
}
}
return null;
}
@Override
public @NotNull String asText(@Nullable ORLanguageProperties toLang) {
StringBuilder convertedText = null;
Language fromLang = getLanguage();
if (fromLang != toLang) {
convertedText = new StringBuilder();
boolean firstField = true;
if (toLang == OclLanguage.INSTANCE) {
// Convert to OCaml
convertedText.append("<");
for (PsiElement element : getChildren()) {
if (element instanceof PsiObjectField) {
if (firstField) {
firstField = false;
} else {
convertedText.append("; ");
}
convertedText.append(((PsiObjectField) element).asText(toLang));
}
}
convertedText.append("> Js.t");
} else {
// Convert from OCaml
convertedText.append("{. ");
for (PsiElement element : getChildren()) {
if (element instanceof PsiObjectField) {
if (firstField) {
firstField = false;
} else {
convertedText.append(", ");
}
convertedText.append(((PsiObjectField) element).asText(toLang));
}
}
convertedText.append(" }");
}
}
return convertedText == null ? getText() : convertedText.toString();
}
@Override
public @NotNull String toString() {
return "JsObject";
}
}
| mit |
JohnBenjaminCassel/Conditionable | src/com/johnbenjamincassel/conditionable/datatypes/ConditionableDateTime.java | 1278 | package com.johnbenjamincassel.conditionable.datatypes;
import java.util.ArrayList;
import org.joda.time.DateTime;
import com.johnbenjamincassel.conditionable.Conditionable;
import com.johnbenjamincassel.utilities.datastructures.DateTimeWrapper;
public class ConditionableDateTime implements Conditionable {
DateTime m_date_time;
public ConditionableDateTime(DateTime date_time) {
m_date_time = date_time;
}
@Override
public boolean evaluateCondition(String condition,
ArrayList<Object> arguments) {
if(condition.equals("after")) {
if(arguments.size() < 1) {
return false;
}
DateTime arg_date;
if(arguments.get(0) instanceof String && arguments.get(0).equals("time")) {
arg_date = parseDate(arguments);
if(arg_date == null) {
return false;
}
}
else if(arguments.get(0) instanceof DateTime) {
arg_date = (DateTime) arguments.get(0);
}
else {
return false;
}
return m_date_time.isAfter(arg_date);
}
return false;
}
public static DateTime parseDate(ArrayList<Object> args) {
DateTimeWrapper dtw = new DateTimeWrapper();
for(int index = 1;index < args.size();index++) {
dtw.setNextMagnitude(Integer.parseInt((String) args.get(index)));
}
return dtw.getDateTime();
}
}
| mit |
Team-Fruit/BnnWidget | sources/universal/src/api/java/net/teamfruit/bnnwidget/component/package-info.java | 135 | /**
* BnnWidgetの実用的なコンポーネントが含まれるサブセットです
*/
package net.teamfruit.bnnwidget.component; | mit |
tools4j/unix4j | unix4j-core/unix4j-base/src/test/java/org/unix4j/util/RangeTest.java | 1494 | package org.unix4j.util;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
public class RangeTest {
@Test
public void testOf(){
assertWithinRange(Range.of(1,2,5,6), 1,2,5,6);
assertNotWithinRange(Range.of(1, 2, 5, 6), 3,4,7,100);
}
@Test
public void testFromStartTo(){
assertWithinRange(Range.fromStartTo(3), 1,2,3);
assertNotWithinRange(Range.fromStartTo(3), 4,5,6);
}
@Test
public void testToEndFrom(){
assertWithinRange(Range.toEndFrom(3), 3,4,10000);
assertNotWithinRange(Range.toEndFrom(3), 1,2);
}
@Test
public void testBetween(){
assertWithinRange(Range.between(3, 6), 3,4,5,6);
assertNotWithinRange(Range.between(3, 6), 1,2,7,8,9);
}
@Test
public void testComposite1(){
final Range range = Range.of(1,2,3).andBetween(6,9).andBetween(11,12).andToEndFrom(40);
assertWithinRange(range, 1,2,3,6,7,8,9,11,12,40,210);
assertNotWithinRange(range, 4,5,10,13,30,39);
}
@Test
public void testComposite2(){
final Range range = Range.of(10, 12, 13).andFromStartTo(3).andBetween(11, 12).andOf(40,41);
assertWithinRange(range, 1,2,3,10,11,12,13,40,41);
assertNotWithinRange(range, 4,5,6,7,8,9,14,1000);
}
private void assertWithinRange(Range range, int ... indexes) {
for(int i: indexes){
assertTrue(range.isWithinRange(i));
}
}
private void assertNotWithinRange(Range range, int ... indexes) {
for(int i: indexes){
assertFalse(range.isWithinRange(i));
}
}
}
| mit |
marcandreuf/ToolBox | src/test/java/org/mandfer/tools/system/ArchiverServiceTest.java | 2255 | package org.mandfer.tools.system;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import static org.mockito.Mockito.*;
/**
* Created by marc on 21/08/16.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({Path.class, DateTime.class})
public class ArchiverServiceTest {
private Path mock_path, mock_destPath, mock_failed, mock_relPath, mock_fullPath;
private DateTime mock_creationDate;
private OS mock_Os;
private MediaService mock_mediaService;
private ArchiverService archiverService;
@Before
public void setUP() throws FileNotFoundException {
mock_path = mock(Path.class);
mock_destPath = mock(Path.class);
mock_failed = mock(Path.class);
mock_relPath = mock(Path.class);
mock_fullPath = mock(Path.class);
mock_creationDate = PowerMockito.mock(DateTime.class);
mock_Os = mock(OS.class);
mock_mediaService = mock(MediaService.class);
archiverService = new ArchiverService(mock_Os, mock_mediaService);
}
@Test
public void testArchiveFile() throws Exception {
when(mock_mediaService.findCreationDate(mock_path)).thenReturn(mock_creationDate);
when(mock_Os.calcDateRelPath(mock_path, mock_creationDate)).thenReturn(mock_relPath);
when(mock_destPath.resolve(mock_relPath)).thenReturn(mock_fullPath);
archiverService.archive(mock_path, mock_destPath, mock_failed);
verify(mock_mediaService).findCreationDate(mock_path);
verify(mock_Os).calcDateRelPath(mock_path, mock_creationDate);
verify(mock_Os).moveFileTo(mock_path, mock_fullPath);
}
@Test
public void moveFileToBackupFolderIfThereIsAnyException() throws Exception {
when(mock_mediaService.findCreationDate(mock_path)).thenThrow(FileNotFoundException.class);
archiverService.archive(mock_path, mock_destPath, mock_failed);
verify(mock_Os).moveFileTo(mock_path, mock_failed);
}
}
| mit |
jameszhan/athena | toolkit/src/main/java/com/mulberry/athena/toolkit/compile/StringClassFile.java | 799 | package com.mulberry.athena.toolkit.compile;
import javax.tools.SimpleJavaFileObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
/**
* Created with IntelliJ IDEA.
*
* @author James Zhan
* Date: 6/17/14
* Time: 7:44 PM
*/
public class StringClassFile extends SimpleJavaFileObject {
private ByteArrayOutputStream baos;
protected StringClassFile(String name) {
super(URI.create("string:///" + name.replaceAll("\\.", "/") + Kind.CLASS.extension), Kind.CLASS);
this.baos = new ByteArrayOutputStream();
}
public OutputStream openOutputStream() throws IOException {
return baos;
}
public byte[] getClassAsBytes(){
return baos.toByteArray();
}
}
| mit |
artem-gabbasov/otus_java_2017_04_L1 | L15.1/src/main/java/ru/otus/orm/jpa/IllegalJPAStateException.java | 266 | package ru.otus.orm.jpa;
/**
* Created by Artem Gabbasov on 01.07.2017.
* <p>
*/
@SuppressWarnings("WeakerAccess")
public class IllegalJPAStateException extends JPAException {
public IllegalJPAStateException(String message) {
super(message);
}
}
| mit |
mikolajs/java-teaching | ZadaniaKurs/src/pl/xxlo/Zadanie56.java | 832 | package pl.xxlo;
import java.math.BigInteger;
public class Zadanie56 {
public static void main(String[] args) {
Zadanie56 z = new Zadanie56();
for(int i = 0; i < 10; i++)
System.out.println("Podsilnia z liczby " + i + " wynosi: "
+ z.subfactorial(i));
int i = 21;
System.out.println("Podsilnia z liczby " + i + " wynosi: "
+ z.subfactorial(i));
}
public BigInteger subfactorial(int n) {
BigInteger f = BigInteger.valueOf(1);
//long s = n % 2 == 0 ? 1 : -1;
BigInteger sub = n % 2 == 0 ? BigInteger.valueOf(1L) : BigInteger.valueOf(-1L);
if(n <= 0) return BigInteger.valueOf(1);
else if(n == 1) return BigInteger.ZERO;
for(int i = n; i > 2; i--) {
f = f.multiply(BigInteger.valueOf(i));
if( i % 2 == 0) sub = sub.subtract(f);
else sub = sub.add(f);
}
return sub;
}
}
| mit |
Martin404/jeecg-activiti-framework | src/main/java/org/jeecgframework/web/activiti/util/GraphElement.java | 373 | package org.jeecgframework.web.activiti.util;
public class GraphElement {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| mit |
burntcookie90/rx-example | app/src/androidTest/java/com/example/vrajeevan/myapplication/ApplicationTest.java | 366 | package com.example.vrajeevan.myapplication;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
jbosboom/streamjit | src/edu/mit/streamjit/impl/distributed/runtimer/CommunicationManager.java | 3744 | /*
* Copyright (c) 2013-2014 Massachusetts Institute of Technology
*
* 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 edu.mit.streamjit.impl.distributed.runtimer;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Map;
import edu.mit.streamjit.impl.distributed.node.StreamNode;
/**
* {@link CommunicationManager} manages all type of communications. Its
* responsible to establish the connection with {@link StreamNode}s and keep
* track of all {@link StreamNodeAgent}s. Further, communication manager should
* handle all IO threads as well.
* <p>
* Mainly two type of CommunicationManager is expected to be implemented.
* <li>Blocking IO using java IO package. In this case each
* {@link StreamNodeAgent} can be made to run on individual thread and keep on
* reading for incoming {@link MessageElement} from the corresponding
* {@link StreamNode} and process it.
* <li>Non-blocking IO using java NIO package. In this case,
* {@link CommunicationManager} should handle the dispatcher thread pool which
* may select ready channels and process the send/receive operation.
* </p>
* TODO: Need to handle the connection loss and reconnection. Assigns nodeID
* based on the connecting order.
*
* @author Sumanan sumanan@mit.edu
* @since May 13, 2013
*/
public interface CommunicationManager {
/**
* The type of communication between two machine nodes.
*/
public enum CommunicationType {
TCP, LOCAL, UDP, BUFFER;
}
/**
* Establishes all connections based on the argument comTypeCount. But only
* one local connection can be created. So the value for the key
* {@link CommunicationType}.LOCAL in the argument comTypeCount has no
* effect. This is a blocking call.
*
* @param comTypeCount
* Map that tells the number of connections need to be
* established for each {@link CommunicationType}.
* @throws IOException
*
* @return A map in where the key is assigned nodeID of the connected
* {@link StreamNode}s and value is {@link StreamNodeAgent}.
* StreamNodeAgent is representative of streamnode at controller
* side.
*/
public Map<Integer, StreamNodeAgent> connectMachines(
Map<CommunicationType, Integer> comTypeCount) throws IOException;
/**
* Close all connections. Further, it stops all threads and release all
* resources of this {@link CommunicationManager}.
*
* @throws IOException
*/
public void closeAllConnections() throws IOException;
/**
* See the comment of {@link StreamNodeAgent#getAddress()} to figure out why
* this method was introduced.
*
* @return the inetaddress of the local machine.
*/
public InetAddress getLocalAddress();
} | mit |
medooze/sdp | src/org/murillo/abnf/Rule$fingerprint_attribute.java | 3556 | /* -----------------------------------------------------------------------------
* Rule$fingerprint_attribute.java
* -----------------------------------------------------------------------------
*
* Producer : com.parse2.aparse.Parser 2.2
* Produced : Thu Jan 05 18:57:59 CET 2017
*
* -----------------------------------------------------------------------------
*/
package org.murillo.abnf;
import java.util.ArrayList;
final public class Rule$fingerprint_attribute extends Rule
{
private Rule$fingerprint_attribute(String spelling, ArrayList<Rule> rules)
{
super(spelling, rules);
}
public Object accept(Visitor visitor)
{
return visitor.visit(this);
}
public static Rule$fingerprint_attribute parse(ParserContext context)
{
context.push("fingerprint-attribute");
boolean parsed = true;
int s0 = context.index;
ArrayList<Rule> e0 = new ArrayList<Rule>();
Rule rule;
parsed = false;
if (!parsed)
{
{
ArrayList<Rule> e1 = new ArrayList<Rule>();
int s1 = context.index;
parsed = true;
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Terminal$StringValue.parse(context, "fingerprint");
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Terminal$StringValue.parse(context, ":");
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Rule$hash_func.parse(context);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Rule$SP.parse(context);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Rule$fingerprint.parse(context);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
e0.addAll(e1);
else
context.index = s1;
}
}
rule = null;
if (parsed)
rule = new Rule$fingerprint_attribute(context.text.substring(s0, context.index), e0);
else
context.index = s0;
context.pop("fingerprint-attribute", parsed);
return (Rule$fingerprint_attribute)rule;
}
}
/* -----------------------------------------------------------------------------
* eof
* -----------------------------------------------------------------------------
*/
| mit |
ComMouse/SE228-Answers | src/iteration2/src/com/bookstore/util/UrlUtil.java | 842 | package com.bookstore.util;
import javax.servlet.http.HttpServletRequest;
/**
* Class UrlUtil
*/
public class UrlUtil {
/**
* Generate site url
* @param request
* @param path
* @return Generated url
*/
public static String generate(HttpServletRequest request, String path) {
return getContextUrl(request) + (path.charAt(0) == '/' ? path.substring(1) : path);
}
/**
* Get context url for this site
* @param request
* @return Context url
*/
public static String getContextUrl(HttpServletRequest request) {
StringBuffer url = request.getRequestURL();
return url.delete(url.length() - request.getRequestURI().length(), url.length())
.append(request.getServletContext().getContextPath()).append("/")
.toString();
}
}
| mit |
chenjishi/usite | u148/app/src/main/java/com/chenjishi/u148/utils/JSCallback.java | 176 | package com.chenjishi.u148.utils;
/**
* Created by chenjishi on 14-4-25.
*/
public interface JSCallback {
void onImageClicked(String url);
void onThemeChange();
}
| mit |
kalabron/redpoppy | src/main/java/com/kalabron/redpoppy/items/tools/BloodStoneShovel.java | 426 | package com.kalabron.redpoppy.items.tools;
import com.kalabron.redpoppy.Reference;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemSpade;
public class BloodStoneShovel extends ItemSpade
{
public BloodStoneShovel(ToolMaterial material, String name)
{
super(material);
this.setUnlocalizedName(Reference.MODID + "_" + "bloodStoneShovel");
this.setCreativeTab(CreativeTabs.tabTools);
}
}
| mit |
CCI-MIT/XCoLab | view/src/main/java/org/xcolab/view/activityentry/contest/ContestBaseActivityEntry.java | 2158 | package org.xcolab.view.activityentry.contest;
import org.springframework.context.i18n.LocaleContextHolder;
import org.xcolab.client.admin.pojo.ContestType;
import org.xcolab.client.contest.StaticContestContext;
import org.xcolab.client.contest.exceptions.ContestNotFoundException;
import org.xcolab.client.contest.pojo.wrapper.ContestWrapper;
import org.xcolab.client.contest.pojo.wrapper.ProposalWrapper;
import org.xcolab.client.contest.proposals.StaticProposalContext;
import org.xcolab.util.activities.enums.ContestActivityType;
import org.xcolab.view.activityentry.ActivityInitializationException;
import org.xcolab.view.activityentry.provider.AbstractActivityEntryContentProvider;
public abstract class ContestBaseActivityEntry extends AbstractActivityEntryContentProvider {
private ContestWrapper contest;
private ContestType contestType;
@Override
protected void initializeInternal() throws ActivityInitializationException {
try {
contest = new ContestWrapper(StaticContestContext.getContestClient().getContest(getActivityEntry()
.getCategoryId()));
} catch (ContestNotFoundException e) {
//TODO COLAB-2486: This won't be needed once legacy activities are fixed
if (ContestActivityType.PROPOSAL_CREATED.equals(getActivityType())) {
contest = new ProposalWrapper(StaticProposalContext.getProposalClient()
.getProposal(getActivityEntry().getAdditionalId(), true))
.getContest();
} else {
throw new ActivityInitializationException(getActivityEntry().getId(), e);
}
}
contestType = contest.getContestType()
.withLocale(LocaleContextHolder.getLocale().getLanguage());
}
protected ContestWrapper getContest() {
return contest;
}
protected ContestType getContestType() {
return contestType;
}
protected String getContestLink() {
return String.format(HYPERLINK_FORMAT, getContest().getContestUrl() + "/discussion",
getContest().getTitleWithEndYear());
}
}
| mit |
fredyw/leetcode | src/main/java/leetcode/Problem1854.java | 1372 | package leetcode;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* https://leetcode.com/problems/maximum-population-year/
*/
public class Problem1854 {
public int maximumPopulation(int[][] logs) {
Arrays.sort(logs, (a, b) -> {
int cmp = Integer.compare(a[0], b[0]);
if (cmp == 0) {
return Integer.compare(a[1], b[1]);
}
return cmp;
});
Map</* year */ Integer, /* count */ Integer> map = new HashMap<>();
for (int i = 0; i < logs.length; i++) {
int birth1 = logs[i][0];
if (map.containsKey(birth1)) {
map.put(birth1, map.getOrDefault(birth1, 0) + 1);
continue;
}
map.put(birth1, 1);
for (int j = i - 1; j >= 0; j--) {
int death2 = logs[j][1];
if (birth1 < death2) {
map.put(birth1, map.getOrDefault(birth1, 0) + 1);
}
}
}
return Collections.max(map.entrySet(), (a, b) -> {
int cmp = Integer.compare(a.getValue(),b.getValue()); // by count
if (cmp == 0) {
return Integer.compare(b.getKey(), a.getKey()); // by year
}
return cmp;
}).getKey();
}
}
| mit |
trungnt13/fasta-game | TNTEngine/src/org/tntstudio/interfaces/FrameRenderer.java | 228 |
package org.tntstudio.interfaces;
import org.tntstudio.graphics.FrameObject.ViewportSize;
/** This class for rendering stuff
* @author trungnt13 */
public interface FrameRenderer {
public void render (ViewportSize size);
}
| mit |
hovsepm/azure-sdk-for-java | storage/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/storage/v2018_02_01/implementation/SkuInner.java | 4281 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.storage.v2018_02_01.implementation;
import com.microsoft.azure.management.storage.v2018_02_01.SkuName;
import com.microsoft.azure.management.storage.v2018_02_01.SkuTier;
import com.microsoft.azure.management.storage.v2018_02_01.Kind;
import java.util.List;
import com.microsoft.azure.management.storage.v2018_02_01.SKUCapability;
import com.microsoft.azure.management.storage.v2018_02_01.Restriction;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The SKU of the storage account.
*/
public class SkuInner {
/**
* Gets or sets the sku name. Required for account creation; optional for
* update. Note that in older versions, sku name was called accountType.
* Possible values include: 'Standard_LRS', 'Standard_GRS',
* 'Standard_RAGRS', 'Standard_ZRS', 'Premium_LRS'.
*/
@JsonProperty(value = "name", required = true)
private SkuName name;
/**
* Gets the sku tier. This is based on the SKU name. Possible values
* include: 'Standard', 'Premium'.
*/
@JsonProperty(value = "tier", access = JsonProperty.Access.WRITE_ONLY)
private SkuTier tier;
/**
* The type of the resource, usually it is 'storageAccounts'.
*/
@JsonProperty(value = "resourceType", access = JsonProperty.Access.WRITE_ONLY)
private String resourceType;
/**
* Indicates the type of storage account. Possible values include:
* 'Storage', 'StorageV2', 'BlobStorage'.
*/
@JsonProperty(value = "kind", access = JsonProperty.Access.WRITE_ONLY)
private Kind kind;
/**
* The set of locations that the SKU is available. This will be supported
* and registered Azure Geo Regions (e.g. West US, East US, Southeast Asia,
* etc.).
*/
@JsonProperty(value = "locations", access = JsonProperty.Access.WRITE_ONLY)
private List<String> locations;
/**
* The capability information in the specified sku, including file
* encryption, network acls, change notification, etc.
*/
@JsonProperty(value = "capabilities", access = JsonProperty.Access.WRITE_ONLY)
private List<SKUCapability> capabilities;
/**
* The restrictions because of which SKU cannot be used. This is empty if
* there are no restrictions.
*/
@JsonProperty(value = "restrictions")
private List<Restriction> restrictions;
/**
* Get the name value.
*
* @return the name value
*/
public SkuName name() {
return this.name;
}
/**
* Set the name value.
*
* @param name the name value to set
* @return the SkuInner object itself.
*/
public SkuInner withName(SkuName name) {
this.name = name;
return this;
}
/**
* Get the tier value.
*
* @return the tier value
*/
public SkuTier tier() {
return this.tier;
}
/**
* Get the resourceType value.
*
* @return the resourceType value
*/
public String resourceType() {
return this.resourceType;
}
/**
* Get the kind value.
*
* @return the kind value
*/
public Kind kind() {
return this.kind;
}
/**
* Get the locations value.
*
* @return the locations value
*/
public List<String> locations() {
return this.locations;
}
/**
* Get the capabilities value.
*
* @return the capabilities value
*/
public List<SKUCapability> capabilities() {
return this.capabilities;
}
/**
* Get the restrictions value.
*
* @return the restrictions value
*/
public List<Restriction> restrictions() {
return this.restrictions;
}
/**
* Set the restrictions value.
*
* @param restrictions the restrictions value to set
* @return the SkuInner object itself.
*/
public SkuInner withRestrictions(List<Restriction> restrictions) {
this.restrictions = restrictions;
return this;
}
}
| mit |
mayc2/PseudoKnot_research | RNAstructure_Source/java_interface/src/ur_rna/RNAstructureUI/utilities/RadioButtonPanel.java | 5606 | /*
* (c) 2011 Mathews Lab, University of Rochester Medical Center.
*
* This software is part of a group specifically designed for the RNAstructure
* secondary structure prediction program and its related applications.
*/
package ur_rna.RNAstructureUI.utilities;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
/**
* A class that creates a panel containing a group of radio buttons.
*
* @author Jessica S. Reuter
*/
public class RadioButtonPanel
extends JPanel {
private static final long serialVersionUID = 20120802;
/**
* The button group connected to this panel.
*/
private ButtonGroup group;
/**
* The button group, as a list, for ease of access to each.
*/
private ArrayList<JRadioButton> group2;
/**
* The names of the buttons in the group.
*/
private String[] names;
/**
* Constructor.
*
* @param title The title of the panel.
* @param layout The layout of the panel, horizontal or vertical.
* @param listener The action listener connected to the buttons.
* @param names The names of the buttons.
*/
private RadioButtonPanel(
String title, String layout, ActionListener listener,
String... names ) {
// Determine the number of rows and columns in the panel.
int rows = ( layout.equals( "Horizontal" ) ) ? 1 : names.length;
int cols = ( layout.equals( "Vertical" ) ) ? 1 : names.length;
// Set the panel's layout.
setLayout( new GridLayout( rows, cols ) );
// Create its titled border, if necessary
if( title != null ) {
new BorderBuilder().makeTitledBorder( title, this );
}
// Create the button group and determine how many buttons should be
// in it. Also, create the button list and save the button names.
group = new ButtonGroup();
int numButtons = names.length;
group2 = new ArrayList<JRadioButton>( numButtons );
this.names = names;
// Create a radio button for each name, and add each button to the
// panel and to the button group.
for( int i = 1; i <= numButtons; i++ ) {
JRadioButton button = new JRadioButton( names[i-1] );
button.setActionCommand( names[i-1] );
if( listener != null ) { button.addActionListener( listener ); }
if( i == 1 ) { button.setSelected( true ); }
group.add( button );
group2.add( button );
add( button );
}
}
/**
* Get the index of the selected button from this panel.
*
* @return The button index, one-indexed.
*/
public int getSelectedIndex() {
for( int i = 1; i <= names.length; i++ ) {
if( names[i-1].equals( getSelectedName() ) ) { return i; }
}
return 0;
}
/**
* Get the command of the selected button from this panel.
*
* @return The button name.
*/
public String getSelectedName() {
return group.getSelection().getActionCommand();
}
/**
* Create a button panel with a horizontal layout.
*
* @param names The names of the buttons.
*/
public static RadioButtonPanel makeHorizontal( String[] names ) {
return new RadioButtonPanel( null, "Horizontal", null, names );
}
/**
* Create a button panel with a vertical layout.
*
* @param names The names of the buttons.
*/
public static RadioButtonPanel makeVertical( String[] names ) {
return new RadioButtonPanel( null, "Vertical", null, names );
}
/**
* Create a button panel with a title and horizontal layout.
*
* @param title The title of the panel.
* @param names The names of the buttons.
*/
public static RadioButtonPanel makeHorizontal(
String title, String... names ) {
return new RadioButtonPanel( title, "Horizontal", null, names );
}
/**
* Create a button panel with a title and vertical layout.
*
* @param title The title of the panel.
* @param names The names of the buttons.
*/
public static RadioButtonPanel makeVertical(
String title, String... names ) {
return new RadioButtonPanel( title, "Vertical", null, names );
}
/**
* Create a button panel with a title, horizontal layout, and an action
* listener associated with the buttons.
*
* @param title The title of the panel.
* @param listener The listener that controls the actions done by buttons.
* @param names The names of the buttons.
*/
public static RadioButtonPanel makeHorizontal(
String title, ActionListener listener, String... names ) {
return new RadioButtonPanel( title, "Horizontal", listener, names );
}
/**
* Create a button panel with a title, vertical layout, and an action
* listener associated with the buttons.
*
* @param title The title of the panel.
* @param listener The listener that controls the actions done by buttons.
* @param names The names of the buttons.
*/
public static RadioButtonPanel makeVertical(
String title, ActionListener listener, String... names ) {
return new RadioButtonPanel( title, "Vertical", listener, names );
}
/**
* Set a particular button in this group to be selected.
*
* @param name The name of the button to be selected.
*/
public void setSelectedButton( String name ) {
// Get the button to select.
JRadioButton selectedButton = null;
for( JRadioButton button: group2 ) {
if( button.getText().equals( name ) ) {
selectedButton = button;
break;
}
}
// Set the button selected in both groups.
group.setSelected( selectedButton.getModel(), true );
for( JRadioButton button: group2 ) {
boolean doSelect = button.getText().equals( name );
button.setSelected( doSelect );
}
}
}
| mit |
yDelouis/selfoss-android | app/src/main/java/fr/ydelouis/selfoss/config/ui/ConfigAuthView.java | 1913 | package fr.ydelouis.selfoss.config.ui;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
import fr.ydelouis.selfoss.R;
import fr.ydelouis.selfoss.config.model.ConfigValidator;
@EViewGroup(R.layout.view_config_auth)
public class ConfigAuthView extends LinearLayout {
@ViewById(R.id.username) protected EditText usernameEditText;
@ViewById(R.id.password) protected EditText passwordEditText;
public ConfigAuthView(Context context) {
super(context);
}
public ConfigAuthView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ConfigAuthView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ConfigAuthView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setUsername(String username) {
usernameEditText.setText(username);
}
public String getUsername() {
return usernameEditText.getText().toString();
}
public void setPassword(String password) {
passwordEditText.setText(password);
}
public String getPassword() {
return passwordEditText.getText().toString();
}
public void showError(Exception exception) {
if (exception instanceof ConfigValidator.InvalidUsernameException) {
usernameEditText.setError(getContext().getString(R.string.error_usernameEmpty));
} else if (exception instanceof ConfigValidator.IncorrectPasswordException) {
passwordEditText.setError(getContext().getString(R.string.error_usernamePassword));
} else {
passwordEditText.setError(exception.getLocalizedMessage());
}
}
}
| mit |
seph-lang/seph | src/main/seph/lang/structure/SephObject_1_19.java | 4995 | /* THIS FILE IS GENERATED. DO NOT EDIT */
package seph.lang.structure;
import seph.lang.*;
import seph.lang.persistent.*;
public class SephObject_1_19 extends SephObjectStructure {
public final SephObject parent0;
public final String selector0;
public final SephObject cell0;
public final String selector1;
public final SephObject cell1;
public final String selector2;
public final SephObject cell2;
public final String selector3;
public final SephObject cell3;
public final String selector4;
public final SephObject cell4;
public final String selector5;
public final SephObject cell5;
public final String selector6;
public final SephObject cell6;
public final String selector7;
public final SephObject cell7;
public final String selector8;
public final SephObject cell8;
public final String selector9;
public final SephObject cell9;
public final String selector10;
public final SephObject cell10;
public final String selector11;
public final SephObject cell11;
public final String selector12;
public final SephObject cell12;
public final String selector13;
public final SephObject cell13;
public final String selector14;
public final SephObject cell14;
public final String selector15;
public final SephObject cell15;
public final String selector16;
public final SephObject cell16;
public final String selector17;
public final SephObject cell17;
public final String selector18;
public final SephObject cell18;
public SephObject_1_19(IPersistentMap meta, SephObject parent0, String selector0, SephObject cell0, String selector1, SephObject cell1, String selector2, SephObject cell2, String selector3, SephObject cell3, String selector4, SephObject cell4, String selector5, SephObject cell5, String selector6, SephObject cell6, String selector7, SephObject cell7, String selector8, SephObject cell8, String selector9, SephObject cell9, String selector10, SephObject cell10, String selector11, SephObject cell11, String selector12, SephObject cell12, String selector13, SephObject cell13, String selector14, SephObject cell14, String selector15, SephObject cell15, String selector16, SephObject cell16, String selector17, SephObject cell17, String selector18, SephObject cell18) {
super(meta);
this.parent0 = parent0;
this.selector0 = selector0.intern();
this.cell0 = cell0;
this.selector1 = selector1.intern();
this.cell1 = cell1;
this.selector2 = selector2.intern();
this.cell2 = cell2;
this.selector3 = selector3.intern();
this.cell3 = cell3;
this.selector4 = selector4.intern();
this.cell4 = cell4;
this.selector5 = selector5.intern();
this.cell5 = cell5;
this.selector6 = selector6.intern();
this.cell6 = cell6;
this.selector7 = selector7.intern();
this.cell7 = cell7;
this.selector8 = selector8.intern();
this.cell8 = cell8;
this.selector9 = selector9.intern();
this.cell9 = cell9;
this.selector10 = selector10.intern();
this.cell10 = cell10;
this.selector11 = selector11.intern();
this.cell11 = cell11;
this.selector12 = selector12.intern();
this.cell12 = cell12;
this.selector13 = selector13.intern();
this.cell13 = cell13;
this.selector14 = selector14.intern();
this.cell14 = cell14;
this.selector15 = selector15.intern();
this.cell15 = cell15;
this.selector16 = selector16.intern();
this.cell16 = cell16;
this.selector17 = selector17.intern();
this.cell17 = cell17;
this.selector18 = selector18.intern();
this.cell18 = cell18;
}
public final SephObject get(String name) {
name = name.intern();
if(name == this.selector0) return this.cell0;
if(name == this.selector1) return this.cell1;
if(name == this.selector2) return this.cell2;
if(name == this.selector3) return this.cell3;
if(name == this.selector4) return this.cell4;
if(name == this.selector5) return this.cell5;
if(name == this.selector6) return this.cell6;
if(name == this.selector7) return this.cell7;
if(name == this.selector8) return this.cell8;
if(name == this.selector9) return this.cell9;
if(name == this.selector10) return this.cell10;
if(name == this.selector11) return this.cell11;
if(name == this.selector12) return this.cell12;
if(name == this.selector13) return this.cell13;
if(name == this.selector14) return this.cell14;
if(name == this.selector15) return this.cell15;
if(name == this.selector16) return this.cell16;
if(name == this.selector17) return this.cell17;
if(name == this.selector18) return this.cell18;
return this.parent0.get(name);
}
}
| mit |
SerCeMan/cjdb | src/main/java/ru/cjdb/sql/parser/QueryParser.java | 330 | package ru.cjdb.sql.parser;
import ru.cjdb.sql.queries.Query;
/**
* Парсер запросов. Принимает строчку SQL, возвращает объект, реализующий Query
*
* @author Sergey Tselovalnikov
* @since 28.09.14
*/
public interface QueryParser {
Query parseQuery(String sql);
}
| mit |
danielebiagi/easyDLX | src/easyDLXsimulation/EasyDLXMemoryManager.java | 6299 | /**
Copyright (c) 2011 Daniele Biagi
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 easyDLXsimulation;
/**
*
* @author Daniele Biagi biagi.daniele@gmail.com
*
*/
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
public class EasyDLXMemoryManager {
//ADDRESS - VALUE ex: 34d-"10010001"
private Hashtable<String, String> memory;
public EasyDLXMemoryManager() {
memory= new Hashtable<String, String>();
}
public void eraseMemory(){
memory.clear();
memory= new Hashtable<String, String>();
}
public boolean storeByte(String address, String value){
address=signExtentionTo32bits(address);
int length=8;
if (value.length()<(length)){
length= value.length();
//System.out.println("value:"+value.substring(0, length));
memory.put(address, value.substring(0, length));
}else{
//System.out.println("value:"+value.substring(value.length()-8, value.length()));
memory.put(address, value.substring(value.length()-8, value.length()));
}
return true;
}
public boolean storeHalfWord(String address, String value){
//The address must be aligned to 2
address=signExtentionTo32bits(address);
value=signExtentionTo32bits(value);
memory.put(address, value.substring(24,32));
memory.put(EasyDLXALU.add(address, EasyDLXMemoryManager.signExtentionTo32bits(Integer.toBinaryString(1)), false), value.substring(16,24));
return true;
}
public boolean storeWord(String address, String value){
//The address must be aligned to 4
address=signExtentionTo32bits(address);
value=signExtentionTo32bits(value);
memory.put(address, value.substring(24,32));
memory.put(EasyDLXALU.add(address, EasyDLXMemoryManager.signExtentionTo32bits(Integer.toBinaryString(1)), false), value.substring(16,24));
memory.put(EasyDLXALU.add(address, EasyDLXMemoryManager.signExtentionTo32bits(Integer.toBinaryString(2)), false), value.substring(8,16));
memory.put(EasyDLXALU.add(address, EasyDLXMemoryManager.signExtentionTo32bits(Integer.toBinaryString(3)), false), value.substring(0,8));
return true;
}
public String loadByte(String address, boolean signed){
address=signExtentionTo32bits(address);
String result=memory.get(address);
if (result==null){
return null;
}
if (signed){
result=signExtentionTo32bitsSigned(result);
}else{
result=signExtentionTo32bits(result);
}
return result;
}
public String loadHalfWord(String address, boolean signed){
address=signExtentionTo32bits(address);
String result= memory.get(address);
if (result==null){
return null;
}
String addrh=EasyDLXALU.add(address, EasyDLXMemoryManager.signExtentionTo32bits(Integer.toBinaryString(1)), false);
String temp=memory.get(addrh);
//System.out.println("addresses: "+ address +"\n"+ addrh);
//System.out.println("results: "+ result +"\n"+ temp);
if (temp==null){
return null;
}
result=temp+""+ result;
if (signed){
result=signExtentionTo32bitsSigned(result);
}else{
result=signExtentionTo32bits(result);
}
return result;
}
public String loadWord(String address){
address=signExtentionTo32bits(address);
String result=memory.get(address);
if (result==null){
return null;
}
String addrh=EasyDLXALU.add(address, EasyDLXMemoryManager.signExtentionTo32bits(Integer.toBinaryString(1)), false);
String temp=memory.get(addrh);
if (temp==null){
return null;
}
result=temp+""+result;
addrh=EasyDLXALU.add(address, EasyDLXMemoryManager.signExtentionTo32bits(Integer.toBinaryString(2)), false);
temp=memory.get(addrh);
if (temp==null){
return null;
}
result=temp+""+result;
addrh=EasyDLXALU.add(address, EasyDLXMemoryManager.signExtentionTo32bits(Integer.toBinaryString(3)), false);
temp=memory.get(addrh);
if (temp==null){
return null;
}
result=temp+""+result;
return result;
}
public static boolean checkAlignedAddress(String address, int alignedTo){
address=signExtentionTo32bits(address);
long addr=EasyDLXALU.convertToInt(address, false);
if ((addr%alignedTo)!=0){
return false;
}
return true;
}
public static String signExtentionTo32bits(String binaryString){
String result=binaryString;
while(result.length()<32){
result="0"+result;
}
if (result.length()>32){
result= result.substring(result.length()-32, result.length());
}
return result;
}
public static String signExtentionTo32bitsSigned(String binaryString){
String result=binaryString;
while(result.length()<32){
result=binaryString.charAt(0)+result;
}
if (result.length()>32){
result= result.substring(result.length()-32, result.length());
}
return result;
}
@SuppressWarnings("unchecked")
@Override
public String toString() {
String result="";
@SuppressWarnings({ "rawtypes" })
Vector v = new Vector(memory.keySet());
Collections.sort(v);
Iterator<String> it = v.iterator();
while (it.hasNext()) {
String key=it.next();
if(memory.get(key).contains("CODE")){
result =result+ "ADDR: 0x"+Long.toHexString(EasyDLXALU.convertToInt(key,false)) +" - "+memory.get(key)+"\n";
}else{
result =result+ "ADDR: 0x"+Long.toHexString(EasyDLXALU.convertToInt(key,false))+" - byte: 0b"+memory.get(key)+"\n";
}
}
return result;
}
}
| mit |
lew/mitzi | src/mitzi/IrreversibleMoveStack.java | 1556 | package mitzi;
import java.util.LinkedList;
/**
* This class represents a stack, storing the information, which cannot be
* reverted only with a given move. It is implemented as a LinkedList containing
* a class which stores the half move clock, the castling, the en passant target
* and the captured piece. (en passant captures does not count as capture). The
* elements should be accessed via irr_move_info.removeLast();
*/
public class IrreversibleMoveStack {
static public class MoveInfo {
int half_move_clock;
int[] castling = new int[4];
int en_passant_square;
Piece capture;
Boolean is_check;
}
/**
* the stack containing the information
*/
static public LinkedList<MoveInfo> irr_move_info = new LinkedList<MoveInfo>();
private IrreversibleMoveStack() {
}
/**
* add a new entry.
*
* @param half_move_clock
* the old half move clock
* @param castling
* the castling array
* @param en_passant_square
* the en passant target square
* @param capture
* the piece, which got captured (null if no capture)
*/
static public void addInfo(int half_move_clock, int[] castling,
int en_passant_square, Piece capture, Boolean is_check) {
MoveInfo inf = new MoveInfo();
System.arraycopy(castling, 0, inf.castling, 0, 4);
inf.en_passant_square = en_passant_square;
inf.half_move_clock = half_move_clock;
inf.capture = capture;
inf.is_check = is_check;
irr_move_info.addLast(inf);
}
}
| mit |
Schoperation/SchopCraft | src/main/java/schoperation/schopcraft/cap/temperature/ITemperature.java | 665 | package schoperation.schopcraft.cap.temperature;
public interface ITemperature {
// Stuff we can do with temperature.
public void increase(float amount);
public void decrease(float amount);
public void set(float amount);
// Messing with mins and maxes.
public void setMax(float amount);
public void setMin(float amount);
// Messing with the "target temperature."
public void increaseTarget(float amount);
public void decreaseTarget(float amount);
public void setTarget(float amount);
// Getting values.
public float getTemperature();
public float getMaxTemperature();
public float getMinTemperature();
public float getTargetTemperature();
} | mit |
automain/automain | core/src/main/java/com/github/automain/bean/SysUserRole.java | 3310 | package com.github.automain.bean;
import com.github.fastjdbc.BaseBean;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class SysUserRole implements BaseBean<SysUserRole> {
// 主键
private Integer id;
// 创建时间
private Integer createTime;
// 更新时间
private Integer updateTime;
// 是否有效(0:否,1:是)
private Integer isValid;
// sys_user表gid
private String userGid;
// sys_role表主键
private Integer roleId;
public Integer getId() {
return id;
}
public SysUserRole setId(Integer id) {
this.id = id;
return this;
}
public Integer getCreateTime() {
return createTime;
}
public SysUserRole setCreateTime(Integer createTime) {
this.createTime = createTime;
return this;
}
public Integer getUpdateTime() {
return updateTime;
}
public SysUserRole setUpdateTime(Integer updateTime) {
this.updateTime = updateTime;
return this;
}
public Integer getIsValid() {
return isValid;
}
public SysUserRole setIsValid(Integer isValid) {
this.isValid = isValid;
return this;
}
public String getUserGid() {
return userGid;
}
public SysUserRole setUserGid(String userGid) {
this.userGid = userGid;
return this;
}
public Integer getRoleId() {
return roleId;
}
public SysUserRole setRoleId(Integer roleId) {
this.roleId = roleId;
return this;
}
@Override
public String tableName() {
return "sys_user_role";
}
@Override
public Map<String, Object> columnMap(boolean all) {
Map<String, Object> map = new HashMap<String, Object>(6);
if (all || this.getId() != null) {
map.put("id", this.getId());
}
if (all || this.getCreateTime() != null) {
map.put("create_time", this.getCreateTime());
}
if (all || this.getUpdateTime() != null) {
map.put("update_time", this.getUpdateTime());
}
if (all || this.getIsValid() != null) {
map.put("is_valid", this.getIsValid());
}
if (all || this.getUserGid() != null) {
map.put("user_gid", this.getUserGid());
}
if (all || this.getRoleId() != null) {
map.put("role_id", this.getRoleId());
}
return map;
}
@Override
public SysUserRole beanFromResultSet(ResultSet rs) throws SQLException {
return new SysUserRole()
.setId(rs.getInt("id"))
.setCreateTime(rs.getInt("create_time"))
.setUpdateTime(rs.getInt("update_time"))
.setIsValid(rs.getInt("is_valid"))
.setUserGid(rs.getString("user_gid"))
.setRoleId(rs.getInt("role_id"));
}
@Override
public String toString() {
return "SysUserRole{" +
"id=" + id +
", createTime=" + createTime +
", updateTime=" + updateTime +
", isValid=" + isValid +
", userGid=" + userGid +
", roleId=" + roleId +
'}';
}
} | mit |
ivelin1936/Studing-SoftUni- | Java Fundamentals/Java OOP Basic/Exercise - Encapsulation/src/p06_footballTeamGenerator/models/Player.java | 1023 | package p06_footballTeamGenerator.models;
import p06_footballTeamGenerator.util.ConfigExMessage;
import java.util.Objects;
public class Player {
private String name;
private Stat stats;
public Player(String name) {
this.setName(name);
}
public String getName() {
return this.name;
}
private void setName(String name) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException(ConfigExMessage.INVALID_NAME_EX_MESSAGE);
}
this.name = name;
}
public Stat getStats() {
return this.stats;
}
public void setStats(Stat stats) {
this.stats = stats;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Player)) return false;
Player player = (Player) o;
return Objects.equals(getName(), player.getName());
}
@Override
public int hashCode() {
return Objects.hash(getName());
}
}
| mit |
kmhasan-class/spring2017java | Property Demo/src/property/demo/Property.java | 686 | /*
* 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 property.demo;
/**
*
* @author kmhasan
*/
public class Property {
private int propertyId;
private String ownersName;
public Property(int id, String name) {
propertyId = id;
ownersName = name;
}
public int getPropertyId() {
return propertyId;
}
public String getOwnersName() {
return ownersName;
}
public String toString() {
//return propertyId + " - " + ownersName;
return ownersName;
}
}
| mit |
archimatetool/archi | org.eclipse.draw2d/src/org/eclipse/draw2d/text/LineBox.java | 3074 | /*******************************************************************************
* Copyright (c) 2000, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.draw2d.text;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @author hudsonr
* @since 2.1
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public abstract class LineBox extends CompositeBox {
/**
* The maximum ascent of all contained fragments.
*/
int contentAscent;
/**
* The maximum descent of all contained fragments.
*/
int contentDescent;
List fragments = new ArrayList();
/**
* @see org.eclipse.draw2d.text.CompositeBox#add(org.eclipse.draw2d.text.FlowBox)
*/
@Override
public void add(FlowBox child) {
fragments.add(child);
width += child.getWidth();
contentAscent = Math.max(contentAscent, child.getOuterAscent());
contentDescent = Math.max(contentDescent, child.getOuterDescent());
}
/**
* @see org.eclipse.draw2d.text.FlowBox#getAscent()
*/
@Override
public int getAscent() {
int ascent = 0;
for (int i = 0; i < fragments.size(); i++)
ascent = Math.max(ascent, ((FlowBox) fragments.get(i)).getAscent());
return ascent;
}
/**
* Returns the remaining width available for line content.
*
* @return the available width in pixels
*/
int getAvailableWidth() {
if (recommendedWidth < 0)
return Integer.MAX_VALUE;
return recommendedWidth - getWidth();
}
@Override
int getBottomMargin() {
return 0;
}
/**
* @see org.eclipse.draw2d.text.FlowBox#getDescent()
*/
@Override
public int getDescent() {
int descent = 0;
for (int i = 0; i < fragments.size(); i++)
descent = Math.max(descent,
((FlowBox) fragments.get(i)).getDescent());
return descent;
}
/**
* @return Returns the fragments.
*/
List getFragments() {
return fragments;
}
@Override
int getTopMargin() {
return 0;
}
/**
* @return <code>true</code> if this box contains any fragments
*/
public boolean isOccupied() {
return !fragments.isEmpty();
}
/**
* @see org.eclipse.draw2d.text.FlowBox#requiresBidi()
*/
@Override
public boolean requiresBidi() {
for (Iterator iter = getFragments().iterator(); iter.hasNext();) {
FlowBox box = (FlowBox) iter.next();
if (box.requiresBidi())
return true;
}
return false;
}
}
| mit |
cjld/THCO-MIPS-Simulator | src/simulator/core/MemoryIO.java | 2546 | package simulator.core;
import simulator.ui.Terminal;
import simulator.core.error.MemAccessViolationError;
/**
*
* @author LeeThree
*/
public class MemoryIO {
public MemoryIO() {
this.memory = new short[MAX_ADDR];
}
int convert(short addr) {return addr >= 0 ? (int)addr : ((int)addr) + 0x10000;}
public short load(short addr) throws MemAccessViolationError {
if (addr == IO_ADDR) {
short s = (short) Terminal.getInput();
//System.out.println("get:" + s);
return s;
} else if (false) {//if (addr < 0x4000 && addr > 0x27FF) {
throw new MemAccessViolationError(addr);
} {
try {
return memory[convert(addr)];
} catch (ArrayIndexOutOfBoundsException e) {
throw new MemAccessViolationError(addr);
}
}
}
public void store(short addr, short data) throws MemAccessViolationError {
if (addr == IO_ADDR) {
//System.out.print("print:" + (char) (data & 0xFF));
Terminal.output((char) (data & 0xFF));
} else if (false) {//if (addr < 0x4000) {
throw new MemAccessViolationError(addr);
} else {
try {
memory[convert(addr)] = data;
} catch (ArrayIndexOutOfBoundsException e) {
throw new MemAccessViolationError(addr);
}
}
}
public short get(int addr) throws ArrayIndexOutOfBoundsException {
return memory[addr];
}
public short get(short addr) throws ArrayIndexOutOfBoundsException {
return get(convert(addr));
}
public void set(int addr, short data) throws ArrayIndexOutOfBoundsException {
memory[addr] = data;
}
public void set(short addr, short data) throws ArrayIndexOutOfBoundsException {
set(convert(addr), data);
}
public void init(short PC) {
Terminal.reset();
Terminal.setTermVisible(true);
Terminal.showMessage("> Program started at " + PC + "...\n");
}
public void forceStop() {
Terminal.forceStop();
Terminal.showMessage("\n> Program terminated by user.\n");
}
public void stop(short PC) {
Terminal.showMessage("\n> Program stopped at " + PC + ".\n");
}
public static final int MAX_ADDR = 0x10000;
public static final short IO_ADDR = (short) 0xBF00;
public static final short SP_ADDR = (short) 0xBFFF;
private short memory[];
//private Terminal term;
}
| mit |
impsbro/StoryPlanner | tests/TestActor.java | 1124 | import static org.junit.Assert.*;
import org.junit.Test;
public class TestActor
{
@Test
public void testConstructedCorrectly()
{
Actor a = new Actor(1,2);
assertEquals(1,a.getType());
assertEquals(2,a.getValue());
a = new Actor();
assertEquals(-1,a.getType());
assertEquals(-1,a.getValue());
}
@Test
public void testCompareTwoActors()
{
Actor a = new Actor(2,3);
Actor b = new Actor(2,3);
assertTrue(a.equals(b));
b = new Actor(1,3);
assertFalse(a.equals(b));
b = new Actor(2,2);
assertFalse(a.equals(b));
}
@Test
public void testKeyGeneration()
{
Actor a = new Actor(3,4);
assertEquals("3:4",a.getKey());
}
@Test
public void testBindAndUnBind()
{
Actor a = new Actor(2,3);
a.unbind();
assertEquals("-1:-1",a.getKey());
assertFalse(a.bound());
Actor b = new Actor(2,3);
a.bindTo(b);
assertEquals("2:3",a.getKey());
assertTrue(a.bound());
}
}
| mit |
pomortaz/azure-sdk-for-java | azure-mgmt-dns/src/main/java/com/microsoft/azure/management/dns/implementation/AaaaRecordSetsImpl.java | 1760 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.dns.implementation;
import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.dns.AaaaRecordSet;
import com.microsoft.azure.management.dns.AaaaRecordSets;
import com.microsoft.azure.management.dns.RecordType;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.ReadableWrappersImpl;
/**
* Implementation of {@link AaaaRecordSets}.
*/
@LangDefinition
class AaaaRecordSetsImpl
extends ReadableWrappersImpl<AaaaRecordSet, AaaaRecordSetImpl, RecordSetInner>
implements AaaaRecordSets {
private final DnsZoneImpl dnsZone;
private final RecordSetsInner client;
AaaaRecordSetsImpl(DnsZoneImpl dnsZone, RecordSetsInner client) {
this.dnsZone = dnsZone;
this.client = client;
}
@Override
public AaaaRecordSetImpl getByName(String name) {
RecordSetInner inner = this.client.get(this.dnsZone.resourceGroupName(),
this.dnsZone.name(),
name,
RecordType.AAAA);
return new AaaaRecordSetImpl(this.dnsZone, inner, this.client);
}
@Override
public PagedList<AaaaRecordSet> list() {
return super.wrapList(this.client.listByType(this.dnsZone.resourceGroupName(),
this.dnsZone.name(),
RecordType.AAAA));
}
@Override
protected AaaaRecordSetImpl wrapModel(RecordSetInner inner) {
return new AaaaRecordSetImpl(this.dnsZone, inner, this.client);
}
}
| mit |
OreCruncher/DynamicSurroundings | src/main/java/org/orecruncher/dsurround/client/sound/SoundEffect.java | 11782 | /* This file is part of Dynamic Surroundings, licensed under the MIT License (MIT).
*
* Copyright (c) OreCruncher, Abastro
*
* 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.orecruncher.dsurround.client.sound;
import java.util.Random;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.orecruncher.dsurround.ModInfo;
import org.orecruncher.dsurround.client.fx.ISpecialEffect;
import org.orecruncher.dsurround.client.handlers.EnvironStateHandler.EnvironState;
import org.orecruncher.dsurround.client.handlers.SoundEffectHandler;
import org.orecruncher.dsurround.expression.ExpressionEngine;
import org.orecruncher.dsurround.registry.RegistryManager;
import org.orecruncher.dsurround.registry.config.SoundConfig;
import org.orecruncher.dsurround.registry.config.SoundType;
import org.orecruncher.dsurround.registry.sound.SoundMetadata;
import org.orecruncher.dsurround.registry.sound.SoundRegistry;
import org.orecruncher.lib.WeightTable;
import org.orecruncher.lib.WeightTable.IEntrySource;
import org.orecruncher.lib.WeightTable.IItem;
import org.orecruncher.lib.chunk.IBlockAccessEx;
import org.orecruncher.lib.random.XorShiftRandom;
import com.google.common.base.MoreObjects;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public final class SoundEffect implements ISpecialEffect, IEntrySource<SoundEffect>, WeightTable.IItem<SoundEffect> {
private static final int SPOT_SOUND_RANGE = 8;
private static final float[] pitchDelta = { -0.2F, 0.0F, 0.0F, 0.2F, 0.2F, 0.2F };
private static final Random RANDOM = XorShiftRandom.current();
private final SoundEvent sound;
private final String soundName;
private SoundType type;
private String conditions;
private SoundCategory category;
private float volume;
private float pitch;
private int weight;
private boolean variable;
private int repeatDelayRandom;
private int repeatDelay;
private String soundTitle = StringUtils.EMPTY;
protected SoundEffect(final ResourceLocation resource, final SoundCategory category) {
this(resource, category, 1.0F, 1.0F, 0, false);
}
protected SoundEffect(final ResourceLocation resource, final SoundCategory category, final float volume,
final float pitch, final int repeatDelay, final boolean variable) {
this.soundName = resource.toString();
this.sound = RegistryManager.SOUND.getSound(resource);
this.volume = volume;
this.pitch = pitch;
this.conditions = StringUtils.EMPTY;
this.weight = 10;
this.type = SoundType.SPOT;
this.category = MoreObjects.firstNonNull(category, SoundCategory.BLOCKS);
this.variable = variable;
this.repeatDelayRandom = 0;
this.repeatDelay = repeatDelay;
}
protected SoundEffect setVolume(final float vol) {
this.volume = vol;
return this;
}
protected SoundEffect setPitch(final float pitch) {
this.pitch = pitch;
return this;
}
protected SoundEffect setVariable(final boolean flag) {
this.variable = flag;
return this;
}
protected SoundEffect setSoundCategory(@Nonnull final SoundCategory cat) {
this.category = cat;
return this;
}
protected SoundEffect setConditions(@Nonnull final String cond) {
this.conditions = cond;
return this;
}
protected SoundEffect setWeight(final int w) {
this.weight = w;
return this;
}
protected SoundEffect setSoundType(@Nonnull final SoundType type) {
this.type = type;
return this;
}
protected SoundEffect setRepeatDelay(final int d) {
this.repeatDelay = d;
return this;
}
protected SoundEffect setRepeatDelayRandom(final int r) {
this.repeatDelayRandom = r;
return this;
}
protected SoundEffect setSoundTitle(@Nonnull final String title) {
this.soundTitle = title;
return this;
}
public String getSoundName() {
return this.soundName;
}
public String getSoundTitle() {
return this.soundTitle;
}
public SoundEvent getSound() {
return this.sound;
}
public SoundCategory getCategory() {
return this.category;
}
public SoundType getSoundType() {
return this.type;
}
protected float getVolume() {
return this.volume;
}
protected float getPitch(final Random rand) {
if (rand != null && this.variable)
return this.pitch + pitchDelta[rand.nextInt(pitchDelta.length)];
return this.pitch;
}
protected int getRepeat(final Random rand) {
if (this.repeatDelayRandom <= 0)
return Math.max(this.repeatDelay, 0);
return this.repeatDelay + rand.nextInt(this.repeatDelayRandom);
}
protected boolean isRepeatable() {
return this.type == SoundType.PERIODIC || this.type == SoundType.BACKGROUND;
}
private float randomRange(final int range) {
return RANDOM.nextInt(range) - RANDOM.nextInt(range);
}
@SideOnly(Side.CLIENT)
public SoundInstance createSoundAt(@Nonnull final BlockPos pos) {
return SoundBuilder.builder(this.sound, SoundRegistry.BIOME).setPosition(pos).build();
}
@SideOnly(Side.CLIENT)
public SoundInstance createSoundNear(@Nonnull final Entity player) {
final float posX = (float) (player.posX + randomRange(SPOT_SOUND_RANGE));
final float posY = (float) (player.posY + player.getEyeHeight() + randomRange(SPOT_SOUND_RANGE));
final float posZ = (float) (player.posZ + randomRange(SPOT_SOUND_RANGE));
return SoundBuilder.builder(this.sound, SoundRegistry.BIOME).setPosition(posX, posY, posZ).build();
}
@SideOnly(Side.CLIENT)
public SoundInstance createTrackingSound(@Nonnull final Entity player, final boolean fadeIn) {
final TrackingSoundInstance sound = new TrackingSoundInstance(player, this, fadeIn);
if (EnvironState.isPlayer(player))
sound.setAttenuationType(SoundInstance.noAttenuation());
return sound;
}
@Override
public boolean canTrigger(@Nonnull final IBlockAccessEx provider, @Nonnull final IBlockState state,
@Nonnull final BlockPos pos, @Nonnull final Random random) {
return true;
}
@Override
public void doEffect(@Nonnull final IBlockAccessEx provider, @Nonnull final IBlockState state,
@Nonnull final BlockPos pos, @Nonnull final Random random) {
SoundEffectHandler.INSTANCE.playSoundAt(pos, this, 0);
}
@Override
public boolean equals(final Object anObj) {
return this == anObj || this.soundName.equals(((SoundEffect) anObj).soundName);
}
@Override
public int hashCode() {
return this.sound.hashCode();
}
// WeightTable.IItem<T>
@Override
public SoundEffect getItem() {
return this;
}
// WeightTable.IItem<T>
@Override
public int getWeight() {
return this.weight;
}
// IEntrySource<T>
@Override
public IItem<SoundEffect> getEntry() {
return this;
}
// IEntrySource<T>
@Override
public boolean matches() {
return ExpressionEngine.instance().check(this.conditions);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(this.soundName);
builder.append('(').append(this.conditions).append(')');
builder.append(", v:").append(this.volume);
builder.append(", p:").append(this.pitch);
builder.append(", t:").append(this.type);
if (this.type == SoundType.SPOT)
builder.append(", w:").append(this.weight);
if (this.repeatDelay != 0 || this.repeatDelayRandom != 0)
builder.append(", d:").append(this.repeatDelay).append('+').append(this.repeatDelayRandom);
return builder.toString();
}
public static class Builder {
private final SoundEffect effect;
public Builder(@Nonnull final String sound, @Nonnull final SoundCategory cat) {
this(new ResourceLocation(ModInfo.RESOURCE_ID, sound), cat);
}
public Builder(@Nonnull final ResourceLocation resource, @Nonnull final SoundCategory cat) {
this.effect = new SoundEffect(resource, cat);
}
public Builder(@Nonnull final SoundConfig record) {
final ResourceLocation resource = new ResourceLocation(record.sound);
this.effect = new SoundEffect(resource, null);
setConditions(StringUtils.isEmpty(record.conditions) ? StringUtils.EMPTY : record.conditions.intern());
setVolume(record.volume == null ? 1.0F : record.volume);
setPitch(record.pitch == null ? 1.0F : record.pitch);
setWeight(record.weight == null ? 10 : record.weight);
setVariablePitch(record.variable != null && record.variable);
setRepeatDelay(record.repeatDelay == null ? 0 : record.repeatDelay);
setRepeatDelayRandom(record.repeatDelayRandom == null ? 0 : record.repeatDelayRandom);
setSoundTitle(record.title != null ? record.title : StringUtils.EMPTY);
SoundType t = null;
if (record.soundType != null)
t = SoundType.getType(record.soundType);
if (t == null) {
if (record.repeatDelay != null && record.repeatDelay > 0)
t = SoundType.PERIODIC;
else if (record.spotSound != null && record.spotSound)
t = SoundType.SPOT;
else
t = SoundType.BACKGROUND;
}
setSoundType(t);
SoundCategory sc = null;
if (record.soundCategory != null)
sc = SoundCategory.getByName(record.soundCategory);
if (sc == null) {
// There isn't an override - defer to the category info in
// the sounds.json.
final SoundMetadata meta = RegistryManager.SOUND.getSoundMetadata(resource);
if (meta != null)
sc = meta.getCategory();
// No info in sounds.json - best guess.
if (sc == null)
sc = SoundCategory.AMBIENT;
}
setSoundCategory(sc);
}
public Builder setSoundTitle(@Nonnull final String title) {
this.effect.setSoundTitle(title);
return this;
}
public Builder setVolume(final float v) {
this.effect.setVolume(v);
return this;
}
public Builder setPitch(final float p) {
this.effect.setPitch(p);
return this;
}
public Builder setVariablePitch(final boolean flag) {
this.effect.setVariable(flag);
return this;
}
public Builder setSoundCategory(@Nonnull final SoundCategory cat) {
this.effect.setSoundCategory(cat);
return this;
}
public Builder setConditions(@Nullable final String cond) {
this.effect.setConditions(cond == null ? "" : cond);
return this;
}
public Builder setWeight(final int w) {
this.effect.setWeight(w);
return this;
}
public Builder setRepeatDelay(final int d) {
this.effect.setRepeatDelay(d);
return this;
}
public Builder setRepeatDelayRandom(final int r) {
this.effect.setRepeatDelayRandom(r);
return this;
}
public Builder setSoundType(final SoundType type) {
this.effect.setSoundType(type);
return this;
}
public SoundEffect build() {
return this.effect;
}
}
} | mit |
remew/MCxWEB | src/main/java/net/remew/mods/mcxweb/JedisWrapper.java | 2486 | package net.remew.mods.mcxweb;
import redis.clients.jedis.Jedis;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by remew on 15/12/13.
*/
public class JedisWrapper
{
private static JedisWrapper instance;
private static Jedis jedis;
public static int REDIS_PORT;
public static int REDIS_TIMEOUT;
public static String REDIS_HOST;
public static String REDIS_PASS;
public static void setRedisHost(String host)
{
REDIS_HOST = host;
}
public static void setRedisPass(String pass)
{
REDIS_PASS = pass;
}
public static void setRedisTimeout(int timeout)
{
REDIS_TIMEOUT = timeout;
}
public static void setRedisPort(int port)
{
REDIS_PORT = port;
}
public static void connect()
{
if (JedisWrapper.jedis != null) throw new RuntimeException("Jedis instance is already connected");
JedisWrapper.jedis = new Jedis(REDIS_HOST, REDIS_PORT, REDIS_TIMEOUT);
if (!REDIS_PASS.equals(""))
{
JedisWrapper.jedis.auth(REDIS_PASS);
}
JedisWrapper.jedis.connect();
}
public static void disconnect()
{
if (JedisWrapper.jedis == null) throw new RuntimeException("Jedis instance is already disconnected");
JedisWrapper.jedis.del(KEY_LOGIN_USERS);
JedisWrapper.jedis.quit();
JedisWrapper.jedis = null;
}
private static final String KEY_LOGIN_USERS = "LoginUsers";
private static final String KEY_CHAT = "Chat";
private static final String KEY_STATE = "State";
public static void addLoginUser(String name)
{
JedisWrapper.jedis.sadd(KEY_LOGIN_USERS, name);
JedisWrapper.jedis.publish("Login", name);
}
public static void removeLoginUser(String name)
{
JedisWrapper.jedis.srem(KEY_LOGIN_USERS, name);
JedisWrapper.jedis.publish("Logout", name);
}
public static void addChatMessage(String name, Date date, String message)
{
String text = name + " " + new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss").format(date) + " " + message;
JedisWrapper.jedis.lpush(KEY_CHAT, text);
JedisWrapper.jedis.ltrim(KEY_CHAT, 0, MCxWEB.MAX_SAVE_CHAT - 1);
JedisWrapper.jedis.publish(KEY_CHAT, text);
}
public static void updateServerState(String state)
{
JedisWrapper.jedis.set(KEY_STATE, state);
JedisWrapper.jedis.publish(KEY_STATE, state);
}
}
| mit |
ArtificialPB/DevelopmentKit | src/com/artificial/cachereader/fs/CacheType.java | 1930 | package com.artificial.cachereader.fs;
import com.artificial.cachereader.DataSource;
import com.artificial.cachereader.GameType;
import com.artificial.cachereader.meta.*;
import java.io.IOException;
import java.util.Map;
import java.util.WeakHashMap;
public class CacheType {
private Map<Integer, Archive> archiveCache = new WeakHashMap<Integer, Archive>();
private final ReferenceTable table;
private final IndexFile index;
private final DataSource source;
private final int id;
public CacheType(CacheSource source, int id) {
this.source = source.getSourceSystem();
this.id = id;
this.table = source.getSourceSystem().getGameType() == GameType.RT6 ? new RS3ReferenceTable(source, id) : new OSRSReferenceTable(source, id);
this.index = new IndexFile(this.source, id);
}
public Archive getArchive(int archive) {
Archive ret = archiveCache.get(archive);
if (ret == null) {
byte[] data = getArchiveData(archive);
if (data == null)
return null;
ret = new Archive(this, archive, data);
}
archiveCache.put(archive, ret);
return ret;
}
private byte[] getArchiveData(int archive) {
ArchiveRequest query = index.getArchiveMeta(archive);
ArchiveMeta meta = table.getEntry(archive);
if (query == null || meta == null)
return null;
else
return source.readArchive(query);
}
public ReferenceTable getTable() {
return table;
}
public IndexFile getIndex() {
return index;
}
public int getId() {
return id;
}
public boolean init() {
try {
this.getTable().init();
this.getIndex().init();
return true;
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
}
}
| mit |
honjow/XDroidMvp_hzw | app/src/main/java/cn/honjow/leanc/ui/Activice/FileActivity.java | 2301 | package cn.honjow.leanc.ui.Activice;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import cn.droidlover.xdroidmvp.base.XFragmentAdapter;
import cn.droidlover.xdroidmvp.router.Router;
import cn.honjow.leanc.R;
import cn.honjow.leanc.ui.BaseActivity;
import cn.honjow.leanc.ui.Fragment.FileFragment;
public class FileActivity extends BaseActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
// @BindView(R.id.tabLayout)
// TabLayout tabLayout;
@BindView(R.id.viewPager)
ViewPager viewPager;
List<Fragment> fragmentList = new ArrayList<>();
String[] titles = {"文件"};
XFragmentAdapter adapter;
@Override
public void initData(Bundle savedInstanceState) {
initToolbar();
fragmentList.clear();
fragmentList.add(FileFragment.newInstance());
if (adapter == null) {
adapter = new XFragmentAdapter(getSupportFragmentManager(), fragmentList, titles);
}
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(1);
//tabLayout.setupWithViewPager(viewPager);
}
public void initToolbar() {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //左上角返回图标开启
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_white_24dp); //设置图标
getSupportActionBar().setTitle("资源下载");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: //左上角按键事件
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public int getLayoutId() {
return R.layout.activity_file;
}
@Override
public Object newP() {
return null;
}
public static void launch(Activity activity) {
Router.newIntent(activity)
.to(FileActivity.class)
.data(new Bundle())
.launch();
}
}
| mit |
PerimeterX/perimeterx-java-sdk | src/test/java/com/perimeterx/api/UnitTestVerificationHandler.java | 726 | package com.perimeterx.api;
import com.perimeterx.api.verificationhandler.VerificationHandler;
import com.perimeterx.models.PXContext;
import org.apache.http.HttpStatus;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
/**
* Created by nitzangoldfeder on 29/05/2017.
*/
public class UnitTestVerificationHandler implements VerificationHandler {
@Override
public boolean handleVerification(PXContext context, HttpServletResponseWrapper responseWrapper) throws IOException {
responseWrapper.setContentType("text/html");
responseWrapper.setStatus(HttpStatus.SC_OK);
responseWrapper.getWriter().print("custom verification handle");
return true;
}
}
| mit |
Paanceas/Devline | src/java/co/com/devline/mb/CotizacionHasMaterialController.java | 5653 | package co.com.devline.mb;
import co.com.devline.eo.CotizacionHasMaterial;
import co.com.devline.mb.util.JsfUtil;
import co.com.devline.mb.util.JsfUtil.PersistAction;
import co.com.devline.sb.CotizacionHasMaterialFacade;
import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
@ManagedBean(name = "cotizacionHasMaterialController")
@SessionScoped
public class CotizacionHasMaterialController implements Serializable {
@EJB
private co.com.devline.sb.CotizacionHasMaterialFacade ejbFacade;
private List<CotizacionHasMaterial> items = null;
private CotizacionHasMaterial selected;
public CotizacionHasMaterialController() {
}
public CotizacionHasMaterial getSelected() {
return selected;
}
public void setSelected(CotizacionHasMaterial selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
private CotizacionHasMaterialFacade getFacade() {
return ejbFacade;
}
public CotizacionHasMaterial prepareCreate() {
selected = new CotizacionHasMaterial();
initializeEmbeddableKey();
return selected;
}
public void create() {
persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("CotizacionHasMaterialCreated"));
if (!JsfUtil.isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
}
}
public void update() {
persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("CotizacionHasMaterialUpdated"));
}
public void destroy() {
persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("CotizacionHasMaterialDeleted"));
if (!JsfUtil.isValidationFailed()) {
selected = null; // Remove selection
items = null; // Invalidate list of items to trigger re-query.
}
}
public List<CotizacionHasMaterial> getItems() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
getFacade().edit(selected);
} else {
getFacade().remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = ex.getCause();
if (cause != null) {
msg = cause.getLocalizedMessage();
}
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
public List<CotizacionHasMaterial> getItemsAvailableSelectMany() {
return getFacade().findAll();
}
public List<CotizacionHasMaterial> getItemsAvailableSelectOne() {
return getFacade().findAll();
}
@FacesConverter(forClass = CotizacionHasMaterial.class)
public static class CotizacionHasMaterialControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
CotizacionHasMaterialController controller = (CotizacionHasMaterialController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "cotizacionHasMaterialController");
return controller.getFacade().find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof CotizacionHasMaterial) {
CotizacionHasMaterial o = (CotizacionHasMaterial) object;
return getStringKey(o.getIdCotizacionHasMaterial());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), CotizacionHasMaterial.class.getName()});
return null;
}
}
}
}
| mit |
sharathkmr/Hackerrank-Solutions | Algorithms/Implementations/AppleAndOrange.java | 1298 | // https://www.hackerrank.com/challenges/apple-and-orange
import java.util.Scanner;
public class AppleAndOrange {
public static void main(String[] args) {
// readig the input
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int t = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int m = in.nextInt();
int n = in.nextInt();
int[] apple = new int[m];
for(int apple_i=0; apple_i < m; apple_i++){
apple[apple_i] = in.nextInt();
}
int[] orange = new int[n];
for(int orange_i=0; orange_i < n; orange_i++){
orange[orange_i] = in.nextInt();
}
in.close();
int noApples = 0;
int noOranges = 0;
// counting the number of apples fallen inside
for (int i = 0; i < apple.length; i++) {
if(apple[i] > 0 && ((apple[i]+a) >= s && (apple[i]+a) <= t)) {
noApples++;
}
}
// counting the number of oranges fallen inside
for (int i = 0; i < orange.length; i++) {
if(orange[i] < 0 && ((orange[i]+b) >= s && (orange[i]+b) <= t)) {
noOranges++;
}
}
System.out.println(noApples);
System.out.println(noOranges);
}
}
| mit |
quantumlaser/code2016 | LeetCode/Answers/Leetcode-java-solution/integer_to_roman/IntegertoRoman.java | 1247 | package integer_to_roman;
public class IntegertoRoman {
public class Solution {
private final char[] symbols = new char[] { 'M', 'D', 'C', 'L', 'X',
'V', 'I' };
private String repeat(char c, int times) {
String re = "";
for (int i = 0; i < times; i++) {
re += c;
}
return re;
}
public String intToRoman(int num) {
String roman = "";
int scala = 1000;
for (int i = 0; i < symbols.length; i += 2) {
int digit = num / scala;
num %= scala;
scala /= 10;
if (digit == 9) {
roman += symbols[i];
roman += symbols[i - 2];
} else if (digit >= 5) {
roman += symbols[i - 1];
roman += repeat(symbols[i], digit - 5);
} else if (digit == 4) {
roman += symbols[i];
roman += symbols[i - 1];
} else {
roman += repeat(symbols[i], digit);
}
}
return roman;
}
}
public static class UnitTest {
}
}
| mit |
Tapad/tapestry-android-sdk | tapestry/src/com/tapad/tapestry/http/HttpStack.java | 206 | package com.tapad.tapestry.http;
/**
* Can perform HTTP requests.
*/
public interface HttpStack {
public abstract String performGet(String uri, String headerName, String headerValue) throws Exception;
} | mit |
swaplicado/siie32 | src/erp/mmkt/view/SViewCommissionsSalesAgents.java | 8950 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mmkt.view;
import erp.data.SDataConstants;
import erp.data.SDataConstantsSys;
import erp.lib.SLibConstants;
import erp.lib.table.STabFilterDeleted;
import erp.lib.table.STableColumn;
import erp.lib.table.STableConstants;
import erp.lib.table.STableField;
import erp.lib.table.STableSetting;
import javax.swing.JButton;
import sa.gui.util.SUtilConsts;
/**
*
* @author Néstor Ávalos
*/
public class SViewCommissionsSalesAgents extends erp.lib.table.STableTab implements java.awt.event.ActionListener {
private erp.lib.table.STabFilterDeleted moTabFilterDeleted;
public SViewCommissionsSalesAgents(erp.client.SClientInterface client, java.lang.String tabTitle, int auxType01) {
super(client, tabTitle, SDataConstants.MKTX_COMMS_SAL_AGTS, auxType01);
initComponents();
}
private void initComponents() {
int i;
int levelRightEdit = SDataConstantsSys.UNDEFINED;
moTabFilterDeleted = new STabFilterDeleted(this);
addTaskBarUpperSeparator();
addTaskBarUpperComponent(moTabFilterDeleted);
//jbDelete.setEnabled(false);
STableField[] aoKeyFields = new STableField[4];
STableColumn[] aoTableColumns = new STableColumn[10];
i = 0;
aoKeyFields[i++] = new STableField(SLibConstants.DATA_TYPE_INTEGER, isSalesType() ? "cm.id_tp_sal_agt" : "cm.id_sal_agt");
aoKeyFields[i++] = new STableField(SLibConstants.DATA_TYPE_INTEGER, "cm.id_tp_link");
aoKeyFields[i++] = new STableField(SLibConstants.DATA_TYPE_INTEGER, "cm.id_ref");
aoKeyFields[i++] = new STableField(SLibConstants.DATA_TYPE_STRING, "cm.id_dt_start");
for (i = 0; i < aoKeyFields.length; i++) {
moTablePane.getPrimaryKeyFields().add(aoKeyFields[i]);
}
i = 0;
aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_STRING, "link.tp_link", "Tipo referencia", 150);
aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_STRING, "ref", "Referencia", 200);
aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_DATE, "cm.id_dt_start", "Ini. vigencia", STableConstants.WIDTH_DATE);
aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_BOOLEAN, "cm.b_del", "Eliminado", STableConstants.WIDTH_BOOLEAN);
aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_STRING, "un.usr", "Usr. creación", STableConstants.WIDTH_USER);
aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_DATE_TIME, "cm.ts_new", "Creación", STableConstants.WIDTH_DATE_TIME);
aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_STRING, "ue.usr", "Usr. modificación", STableConstants.WIDTH_USER);
aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_DATE_TIME, "cm.ts_edit", "Modificación", STableConstants.WIDTH_DATE_TIME);
aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_STRING, "ud.usr", "Usr. eliminación", STableConstants.WIDTH_USER);
aoTableColumns[i++] = new STableColumn(SLibConstants.DATA_TYPE_DATE_TIME, "cm.ts_del", "Eliminación", STableConstants.WIDTH_DATE_TIME);
for (i = 0; i < aoTableColumns.length; i++) {
moTablePane.addTableColumn(aoTableColumns[i]);
}
levelRightEdit = miClient.getSessionXXX().getUser().hasRight(miClient, SDataConstantsSys.PRV_MKT_COMMS).Level;
jbNew.setEnabled(levelRightEdit >= SUtilConsts.LEV_AUTHOR);
jbEdit.setEnabled(levelRightEdit >= SUtilConsts.LEV_AUTHOR);
mvSuscriptors.add(mnTabType);
mvSuscriptors.add(SDataConstants.MKT_COMMS_SAL_AGT);
mvSuscriptors.add(SDataConstants.MKTX_COMMS_SAL_AGT_CONS);
mvSuscriptors.add(SDataConstants.BPSU_BP);
mvSuscriptors.add(SDataConstants.USRU_USR);
populateTable();
}
private boolean isSalesType() {
return mnTabTypeAux01 == SDataConstants.MKTX_COMMS_SAL_AGT_TPS;
}
@Override
public void actionNew() {
if (jbNew.isEnabled()) {
if (miClient.getGuiModule(SDataConstants.MOD_MKT).showForm(mnTabTypeAux01, null) == SLibConstants.DB_ACTION_SAVE_OK) {
miClient.getGuiModule(SDataConstants.MOD_MKT).refreshCatalogues(mnTabType);
}
}
}
@Override
public void actionEdit() {
if (jbEdit.isEnabled()) {
if (miClient.getGuiModule(SDataConstants.MOD_MKT).showForm(mnTabTypeAux01, moTablePane.getSelectedTableRow().getPrimaryKey()) == SLibConstants.DB_ACTION_SAVE_OK) {
miClient.getGuiModule(SDataConstants.MOD_MKT).refreshCatalogues(mnTabType);
}
}
}
@Override
public void actionDelete() {
if (jbDelete.isEnabled()) {
}
}
@Override
public void createSqlQuery() {
String sqlWhere = "";
STableSetting setting = null;
for (int i = 0; i < mvTableSettings.size(); i++) {
setting = (erp.lib.table.STableSetting) mvTableSettings.get(i);
if (setting.getType() == STableConstants.SETTING_FILTER_DELETED && setting.getStatus() == STableConstants.STATUS_ON) {
sqlWhere += (sqlWhere.length() == 0 ? "" : "AND ") + "cm.b_del = FALSE ";
}
}
msSql = "SELECT cm.*, " + (isSalesType() ? "tp.tp_sal_agt," : "b.bp,") + " t.tp_comms, un.usr, ue.usr, ud.usr, " +
"CASE cm.id_tp_link " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_ALL + " THEN " +
"('" + SDataConstantsSys.TXT_TRNS_TP_LINK_ALL + "') " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_CT_ITEM + " THEN (" +
"SELECT c.ct_item FROM erp.itms_ct_item c WHERE c.ct_idx = cm.id_ref) " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_CL_ITEM + " THEN (" +
"SELECT c.cl_item FROM erp.itms_cl_item c WHERE c.cl_idx = cm.id_ref) " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_TP_ITEM + " THEN (" +
"SELECT tp.tp_item FROM erp.itms_tp_item tp WHERE tp.tp_idx = cm.id_ref) " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_IFAM + " THEN (" +
"SELECT ifam.ifam FROM erp.itmu_ifam ifam WHERE ifam.id_ifam = cm.id_ref) " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_IGRP + " THEN (" +
"SELECT igrp.igrp FROM erp.itmu_igrp igrp WHERE igrp.id_igrp = cm.id_ref) " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_IGEN + " THEN (" +
"SELECT CONCAT(igen.igen, ' (', igen.code, ')') AS igen FROM erp.itmu_igen igen WHERE igen.id_igen = cm.id_ref) " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_LINE + " THEN (" +
"SELECT line.line FROM erp.itmu_line line WHERE line.id_line = cm.id_ref) " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_BRD + " THEN (" +
"SELECT CONCAT(brd.brd, ' (', brd.code, ')') AS brd FROM erp.itmu_brd brd WHERE brd.id_brd = cm.id_ref) " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_MFR + " THEN (" +
"SELECT CONCAT(mfr.mfr, ' (', mfr.code, ')') AS mfr FROM erp.itmu_mfr mfr WHERE mfr.id_mfr = cm.id_ref) " +
"WHEN " + SDataConstantsSys.TRNS_TP_LINK_ITEM + " THEN (" +
"SELECT " + (miClient.getSessionXXX().getParamsErp().getFkSortingItemTypeId() == SDataConstantsSys.CFGS_TP_SORT_KEY_NAME ? "CONCAT(item.item_key, ' - ', item.item)" : "CONCAT(item.item, ' - ', item.item_key)") + " " +
"FROM erp.itmu_item item WHERE item.id_item = cm.id_ref) " +
"ELSE 'No existe tipo' " +
"END AS ref, link.tp_link " +
"FROM " + (isSalesType() ? "mkt_comms_sal_agt_tp" : "mkt_comms_sal_agt") + " AS cm " +
(isSalesType() ?
"INNER JOIN mktu_tp_sal_agt AS tp ON cm.id_tp_sal_agt = tp.id_tp_sal_agt " :
"INNER JOIN erp.bpsu_bp AS b ON cm.id_sal_agt = b.id_bp ") +
"INNER JOIN erp.trns_tp_link AS link ON cm.id_tp_link = link.id_tp_link " +
"INNER JOIN erp.mkts_tp_comms AS t ON cm.fid_tp_comms = t.id_tp_comms " +
"INNER JOIN erp.usru_usr AS un ON cm.fid_usr_new = un.id_usr " +
"INNER JOIN erp.usru_usr AS ue ON cm.fid_usr_edit = ue.id_usr " +
"INNER JOIN erp.usru_usr AS ud ON cm.fid_usr_del = ud.id_usr " +
(sqlWhere.length() == 0 ? "" : "WHERE " + sqlWhere) + " " +
"GROUP BY cm.id_tp_link, cm.id_ref, cm.id_dt_start " +
"ORDER BY link.tp_link, ref ";
}
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
super.actionPerformed(e);
if (e.getSource() instanceof javax.swing.JButton) {
JButton button = (javax.swing.JButton) e.getSource();
}
}
}
| mit |
wamdy/scaffold | scaffold-common/scaffold-common-utils/src/main/java/com/wamdy/util/network/CookiesUtil.java | 1776 | package com.wamdy.util.network;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Cookies操作工具类
*/
public class CookiesUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(CookiesUtil.class);
/**
* 创建cookie,不过期,js不可操作。base64编码
*
* @param key
* @param value
* @return
*/
public static Cookie createCookie(final String key, final String value) {
return CookiesUtil.createCookie(key, value, true);
}
/**
* 创建cookie,不过期,js不可操作。base64编码
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("deprecation")
public static Cookie createCookie(final String key, final String value, final boolean httpOnly) {
final Cookie cookie = new Cookie(key, URLEncoder.encode(value));
cookie.setMaxAge(-1);
cookie.setPath("/");
return cookie;
}
/**
* 查找cookie内容
*
* @param cookies
* @param key
* @return
*/
@SuppressWarnings("deprecation")
public static String findCookieValue(final Cookie[] cookies, final String key) {
if (cookies != null) {
for (final Cookie cookie : cookies) {
if (cookie.getName().equals(key)) {
return URLDecoder.decode(cookie.getValue());
}
}
}
return null;
}
/**
* 将cookie过期
*
* @param key
* @return
*/
public static Cookie expireCookie(final String key) {
return CookiesUtil.expireCookieWithPath(key, "/");
}
/**
* 将cookie过期
*
* @param key
*/
public static Cookie expireCookieWithPath(final String key, final String path) {
final Cookie cookie = new Cookie(key, null);
cookie.setMaxAge(0);
cookie.setPath(path);
return cookie;
}
} | mit |
ailabitmo/hycson | DemoApp/app/src/main/java/ru/ifmo/hycson/demoapp/util/rx/ProfileDataTransformer.java | 2045 | package ru.ifmo.hycson.demoapp.util.rx;
import java.util.List;
import java.util.Map;
import ru.ifmo.hycson.demoapp.presentation.navigation.links.AppLink;
import ru.ifmo.hycson.demoapp.presentation.profile.entities.ProfileData;
import ru.ifmo.hymp.entities.Resource;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;
public class ProfileDataTransformer implements Observable.Transformer<Resource, ProfileData> {
private static final String PROFILE_GIVEN_NAME_KEY = "http://schema.org/givenName";
private static final String PROFILE_FAMILY_NAME_KEY = "http://schema.org/familyName";
private static final String PROFILE_IMAGE_KEY = "http://schema.org/image";
@Override
public Observable<ProfileData> call(Observable<Resource> resourceObservable) {
return resourceObservable.flatMap(new Func1<Resource, Observable<List<AppLink>>>() {
@Override
public Observable<List<AppLink>> call(Resource resource) {
return Observable.from(resource.getLinks())
.compose(new AppLinksTransformer());
}
}, new Func2<Resource, List<AppLink>, ProfileData>() {
@Override
public ProfileData call(Resource profileResource, List<AppLink> appLinks) {
return mapToProfileData(profileResource, appLinks);
}
});
}
private ProfileData mapToProfileData(Resource profileResource, List<AppLink> appLinks) {
Map<String, Object> resPropertyMap = profileResource.getPropertyMap();
ProfileData.Builder builder = new ProfileData.Builder();
ProfileData profileData = builder.setId(profileResource.getId())
.setGivenName((String) resPropertyMap.get(PROFILE_GIVEN_NAME_KEY))
.setFamilyName((String) resPropertyMap.get(PROFILE_FAMILY_NAME_KEY))
.setImage((String) resPropertyMap.get(PROFILE_IMAGE_KEY))
.setAppLinks(appLinks)
.build();
return profileData;
}
}
| mit |
konmik/Dagger2Example | app/src/main/java/info/android15/dagger2example/Dagger2Helper.java | 3324 | package info.android15.dagger2example;
import java.lang.reflect.Method;
import java.util.HashMap;
public class Dagger2Helper {
private static HashMap<Class<?>, HashMap<Class<?>, Method>> methodsCache = new HashMap<>();
/**
* This method is based on https://github.com/square/mortar/blob/master/dagger2support/src/main/java/mortar/dagger2support/Dagger2.java
* file that has been released with Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ by Square, Inc.
* <p/>
* Magic method that creates a component with its dependencies set, by reflection. Relies on
* Dagger2 naming conventions.
*/
public static <T> T buildComponent(Class<T> componentClass, Object... dependencies) {
buildMethodsCache(componentClass);
String fqn = componentClass.getName();
String packageName = componentClass.getPackage().getName();
// Accounts for inner classes, ie MyApplication$Component
String simpleName = fqn.substring(packageName.length() + 1);
String generatedName = (packageName + ".Dagger" + simpleName).replace('$', '_');
try {
Class<?> generatedClass = Class.forName(generatedName);
Object builder = generatedClass.getMethod("builder").invoke(null);
for (Method method : builder.getClass().getMethods()) {
Class<?>[] params = method.getParameterTypes();
if (params.length == 1) {
Class<?> dependencyClass = params[0];
for (Object dependency : dependencies) {
if (dependencyClass.isAssignableFrom(dependency.getClass())) {
method.invoke(builder, dependency);
break;
}
}
}
}
//noinspection unchecked
return (T)builder.getClass().getMethod("build").invoke(builder);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private static <T> void buildMethodsCache(Class<T> componentClass) {
if (!Dagger2Helper.methodsCache.containsKey(componentClass)) {
HashMap<Class<?>, Method> methods = new HashMap<>();
for (Method method : componentClass.getMethods()) {
Class<?>[] params = method.getParameterTypes();
if (params.length == 1)
methods.put(params[0], method);
}
Dagger2Helper.methodsCache.put(componentClass, methods);
}
}
public static void inject(Class<?> componentClass, Object component, Object target) {
HashMap<Class<?>, Method> methods = methodsCache.get(componentClass);
if (methods == null)
throw new RuntimeException("Component " + componentClass + " has not been built with " + Dagger2Helper.class);
Class targetClass = target.getClass();
Method method = methods.get(targetClass);
if (method == null)
throw new RuntimeException("Method for " + targetClass + " injection does not exist in " + componentClass);
try {
method.invoke(component, target);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| mit |
CS2103JAN2017-W14-B2/main | src/main/java/seedu/taskboss/commons/util/AppUtil.java | 353 | package seedu.taskboss.commons.util;
import javafx.scene.image.Image;
import seedu.taskboss.MainApp;
/**
* A container for App specific utility functions
*/
public class AppUtil {
public static Image getImage(String imagePath) {
assert imagePath != null;
return new Image(MainApp.class.getResourceAsStream(imagePath));
}
}
| mit |
evdubs/XChange | xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/service/OkCoinTradeServiceRaw.java | 4499 | package org.knowm.xchange.okcoin.service;
import java.io.IOException;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.okcoin.FuturesContract;
import org.knowm.xchange.okcoin.OkCoinAdapters;
import org.knowm.xchange.okcoin.dto.trade.OkCoinFuturesOrderResult;
import org.knowm.xchange.okcoin.dto.trade.OkCoinFuturesTradeHistoryResult;
import org.knowm.xchange.okcoin.dto.trade.OkCoinOrderResult;
import org.knowm.xchange.okcoin.dto.trade.OkCoinPositionResult;
import org.knowm.xchange.okcoin.dto.trade.OkCoinPriceLimit;
import org.knowm.xchange.okcoin.dto.trade.OkCoinTradeResult;
public class OkCoinTradeServiceRaw extends OKCoinBaseTradeService {
/**
* Constructor
*
* @param exchange
*/
protected OkCoinTradeServiceRaw(Exchange exchange) {
super(exchange);
}
public OkCoinTradeResult trade(String symbol, String type, String rate, String amount) throws IOException {
OkCoinTradeResult tradeResult = okCoin.trade(apikey, symbol, type, rate, amount, signatureCreator);
return returnOrThrow(tradeResult);
}
public OkCoinTradeResult cancelOrder(long orderId, String symbol) throws IOException {
OkCoinTradeResult tradeResult = okCoin.cancelOrder(apikey, orderId, symbol, signatureCreator);
return returnOrThrow(tradeResult);
}
public OkCoinOrderResult getOrder(long orderId, String symbol) throws IOException {
OkCoinOrderResult orderResult = okCoin.getOrder(apikey, orderId, symbol, signatureCreator);
return returnOrThrow(orderResult);
}
public OkCoinOrderResult getOrderHistory(String symbol, String status, String currentPage, String pageLength) throws IOException {
OkCoinOrderResult orderResult = okCoin.getOrderHistory(apikey, symbol, status, currentPage, pageLength, signatureCreator);
return returnOrThrow(orderResult);
}
/**
* OkCoin.com Futures API
**/
public OkCoinTradeResult futuresTrade(String symbol, String type, String price, String amount, FuturesContract contract, int matchPrice,
int leverRate) throws IOException {
OkCoinTradeResult tradeResult = okCoin.futuresTrade(apikey, symbol, contract.getName(), type, price, amount, matchPrice, leverRate,
signatureCreator);
return returnOrThrow(tradeResult);
}
public OkCoinTradeResult futuresCancelOrder(long orderId, String symbol, FuturesContract contract) throws IOException {
OkCoinTradeResult tradeResult = okCoin.futuresCancelOrder(apikey, orderId, symbol, contract.getName(), signatureCreator);
return returnOrThrow(tradeResult);
}
public OkCoinFuturesOrderResult getFuturesOrder(long orderId, String symbol, String currentPage, String pageLength, FuturesContract contract) throws IOException {
OkCoinFuturesOrderResult futuresOrder = okCoin.getFuturesOrder(apikey, orderId, symbol, "1", currentPage, pageLength, contract.getName(),
signatureCreator);
return returnOrThrow(futuresOrder);
}
public OkCoinPriceLimit getFuturesPriceLimits(CurrencyPair currencyPair, FuturesContract prompt) throws IOException {
return okCoin.getFuturesPriceLimits(OkCoinAdapters.adaptSymbol(currencyPair), prompt.getName());
}
public OkCoinFuturesOrderResult getFuturesFilledOrder(long orderId, String symbol, String currentPage, String pageLength, FuturesContract contract) throws IOException {
OkCoinFuturesOrderResult futuresOrder = okCoin.getFuturesOrder(apikey, orderId, symbol, "2", currentPage, pageLength, contract.getName(),
signatureCreator);
return returnOrThrow(futuresOrder);
}
public OkCoinFuturesOrderResult getFuturesOrders(String orderIds, String symbol, FuturesContract contract) throws IOException {
OkCoinFuturesOrderResult futuresOrder = okCoin.getFuturesOrders(apikey, orderIds, symbol, contract.getName(), signatureCreator);
return returnOrThrow(futuresOrder);
}
public OkCoinFuturesTradeHistoryResult[] getFuturesTradesHistory(String symbol, long since, String date) throws IOException {
OkCoinFuturesTradeHistoryResult[] futuresHistory = okCoin.getFuturesTradeHistory(apikey, since, symbol, date, signatureCreator);
return (futuresHistory);
}
public OkCoinPositionResult getFuturesPosition(String symbol, FuturesContract contract) throws IOException {
OkCoinPositionResult futuresPositionsCross = okCoin.getFuturesPositionsCross(apikey, symbol, contract.getName(), signatureCreator);
return returnOrThrow(futuresPositionsCross);
}
}
| mit |
pegurnee/2013-03-211 | complete/src/data_struct/in_class/d11_20/interfaces/NumberCarrier.java | 162 | package data_struct.in_class.d11_20.interfaces;
public interface NumberCarrier
{
public void setNumber(int value);
public int getNumber( );
}
| mit |
TyrfingX/TyrLib | legacy/TyrLib2PC/src/com/TyrLib2/PC/main/PCMatrixImpl.java | 15422 | package com.TyrLib2.PC.main;
import com.tyrlib2.math.IMatrixImpl;
import com.tyrlib2.math.Quaternion;
import com.tyrlib2.math.Vector3;
public class PCMatrixImpl implements IMatrixImpl{
public static final float[] matrix = new float[16];
public static final float[] a = new float[16];
public static final float[] b = new float[16];
@Override
public void setIdentityM(float[] m, int offset) {
m[0 + offset] = 1;
m[1 + offset] = 0;
m[2 + offset] = 0;
m[3 + offset] = 0;
m[4 + offset] = 0;
m[5 + offset] = 1;
m[6 + offset] = 0;
m[7 + offset] = 0;
m[8 + offset] = 0;
m[9 + offset] = 0;
m[10 + offset] = 1;
m[11 + offset] = 0;
m[12 + offset] = 0;
m[13 + offset] = 0;
m[14 + offset] = 0;
m[15 + offset] = 1;
}
@Override
public void scaleM(float[] m, int offset, float scaleX, float scaleY, float scaleZ) {
m[0 + offset] = m[0 + offset] * scaleX;
m[4 + offset] = m[4 + offset] * scaleY;
m[8 + offset] = m[8 + offset] * scaleZ;
m[1 + offset] = m[1 + offset] * scaleX;
m[5 + offset] = m[5 + offset] * scaleY;
m[9 + offset] = m[9 + offset] * scaleZ;
m[2 + offset] = m[2 + offset] * scaleX;
m[6 + offset] = m[6 + offset] * scaleY;
m[10 + offset] = m[10 + offset] * scaleZ;
m[3 + offset] = m[3 + offset] * scaleX;
m[7 + offset] = m[7 + offset] * scaleY;
m[11 + offset] = m[11 + offset] * scaleZ;
}
@Override
public void multiplyMM(float[] result, int offsetResult, float[] lhs, int offsetLeft, float[] rhs, int offsetRight) {
for(int i=0; i<16; i++){
a[i] = lhs[i+offsetLeft];
b[i] = rhs[i+offsetRight];
}
matrix[0] = a[0] * b[0] + a[4] * b[1] + a[8] * b[2] + a[12] * b[3];
matrix[1] = a[1] * b[0] + a[5] * b[1] + a[9] * b[2] + a[13] * b[3];
matrix[2] = a[2] * b[0] + a[6] * b[1] + a[10] * b[2] + a[14] * b[3];
matrix[3] = a[3] * b[0] + a[7] * b[1] + a[11] * b[2] + a[15] * b[3];
matrix[4] = a[0] * b[4] + a[4] * b[5] + a[8] * b[6] + a[12] * b[7];
matrix[5] = a[1] * b[4] + a[5] * b[5] + a[9] * b[6] + a[13] * b[7];
matrix[6] = a[2] * b[4] + a[6] * b[5] + a[10] * b[6] + a[14] * b[7];
matrix[7] = a[3] * b[4] + a[7] * b[5] + a[11] * b[6] + a[15] * b[7];
matrix[8] = a[0] * b[8] + a[4] * b[9] + a[8] * b[10] + a[12] * b[11];
matrix[9] = a[1] * b[8] + a[5] * b[9] + a[9] * b[10] + a[13] * b[11];
matrix[10] = a[2] * b[8] + a[6] * b[9] + a[10] * b[10] + a[14] * b[11];
matrix[11] = a[3] * b[8] + a[7] * b[9] + a[11] * b[10] + a[15] * b[11];
matrix[12] = a[0] * b[12] + a[4] * b[13] + a[8] * b[14] + a[12] * b[15];
matrix[13] = a[1] * b[12] + a[5] * b[13] + a[9] * b[14] + a[13] * b[15];
matrix[14] = a[2] * b[12] + a[6] * b[13] + a[10] * b[14] + a[14] * b[15];
matrix[15] = a[3] * b[12] + a[7] * b[13] + a[11] * b[14] + a[15] * b[15];
for(int i=0; i<16; i++){
result[i+offsetResult] = matrix[i];
}
}
@Override
public void translateM(float[] m, int offset, float x, float y, float z) {
for (int i=0 ; i<4 ; i++) {
int mi = offset + i;
m[12 + mi] += m[mi] * x + m[4 + mi] * y + m[8 + mi] * z;
}
}
@Override
public void multiplyMV(float[] result, int offsetResult, float[] m, int offsetMatrix, float[] v, int offsetVector) {
int indexM;
float x = v[offsetVector];
float y = v[1 + offsetVector];
float z = v[2 + offsetVector];
float w = v[3 + offsetVector];
for (int j=0; j<4; ++j) {
indexM = j + offsetMatrix;
result[j + offsetResult] = m[indexM] * x + m[indexM + 4] * y + m[indexM + 8] * z + m[indexM + 12] * w;
}
}
@Override
public void invertM(float[] inv, int offsetResult, float[] m, int offsetMatrix) {
float det;
int i;
inv[0 + offsetResult] = m[5 + offsetMatrix] * m[10 + offsetMatrix] * m[15 + offsetMatrix] -
m[5 + offsetMatrix] * m[11 + offsetMatrix] * m[14 + offsetMatrix] -
m[9 + offsetMatrix] * m[6 + offsetMatrix] * m[15 + offsetMatrix] +
m[9 + offsetMatrix] * m[7 + offsetMatrix] * m[14 + offsetMatrix] +
m[13 + offsetMatrix] * m[6 + offsetMatrix] * m[11 + offsetMatrix] -
m[13 + offsetMatrix] * m[7 + offsetMatrix] * m[10 + offsetMatrix];
inv[4 + offsetResult] = -m[4 + offsetMatrix] * m[10 + offsetMatrix] * m[15 + offsetMatrix] +
m[4 + offsetMatrix] * m[11 + offsetMatrix] * m[14 + offsetMatrix] +
m[8 + offsetMatrix] * m[6 + offsetMatrix] * m[15 + offsetMatrix] -
m[8 + offsetMatrix] * m[7 + offsetMatrix] * m[14 + offsetMatrix] -
m[12 + offsetMatrix] * m[6 + offsetMatrix] * m[11 + offsetMatrix] +
m[12 + offsetMatrix] * m[7 + offsetMatrix] * m[10 + offsetMatrix];
inv[8 + offsetResult] = m[4 + offsetMatrix] * m[9 + offsetMatrix] * m[15 + offsetMatrix] -
m[4 + offsetMatrix] * m[11 + offsetMatrix] * m[13 + offsetMatrix] -
m[8 + offsetMatrix] * m[5 + offsetMatrix] * m[15 + offsetMatrix] +
m[8 + offsetMatrix] * m[7 + offsetMatrix] * m[13 + offsetMatrix] +
m[12 + offsetMatrix] * m[5 + offsetMatrix] * m[11 + offsetMatrix] -
m[12 + offsetMatrix] * m[7 + offsetMatrix] * m[9 + offsetMatrix];
inv[12 + offsetResult] = -m[4 + offsetMatrix] * m[9 + offsetMatrix] * m[14 + offsetMatrix] +
m[4 + offsetMatrix] * m[10 + offsetMatrix] * m[13 + offsetMatrix] +
m[8 + offsetMatrix] * m[5 + offsetMatrix] * m[14 + offsetMatrix] -
m[8 + offsetMatrix] * m[6 + offsetMatrix] * m[13 + offsetMatrix] -
m[12 + offsetMatrix] * m[5 + offsetMatrix] * m[10 + offsetMatrix] +
m[12 + offsetMatrix] * m[6 + offsetMatrix] * m[9 + offsetMatrix];
inv[1 + offsetResult] = -m[1 + offsetMatrix] * m[10 + offsetMatrix] * m[15 + offsetMatrix] +
m[1 + offsetMatrix] * m[11 + offsetMatrix] * m[14 + offsetMatrix] +
m[9 + offsetMatrix] * m[2 + offsetMatrix] * m[15 + offsetMatrix] -
m[9 + offsetMatrix] * m[3 + offsetMatrix] * m[14 + offsetMatrix] -
m[13 + offsetMatrix] * m[2 + offsetMatrix] * m[11 + offsetMatrix] +
m[13 + offsetMatrix] * m[3 + offsetMatrix] * m[10 + offsetMatrix];
inv[5 + offsetResult] = m[0 + offsetMatrix] * m[10 + offsetMatrix] * m[15 + offsetMatrix] -
m[0 + offsetMatrix] * m[11 + offsetMatrix] * m[14 + offsetMatrix] -
m[8 + offsetMatrix] * m[2 + offsetMatrix] * m[15 + offsetMatrix] +
m[8 + offsetMatrix] * m[3 + offsetMatrix] * m[14 + offsetMatrix] +
m[12 + offsetMatrix] * m[2 + offsetMatrix] * m[11 + offsetMatrix] -
m[12 + offsetMatrix] * m[3 + offsetMatrix] * m[10 + offsetMatrix];
inv[9 + offsetResult] = -m[0] * m[9] * m[15 + offsetMatrix] +
m[0 + offsetMatrix] * m[11 + offsetMatrix] * m[13 + offsetMatrix] +
m[8 + offsetMatrix] * m[1 + offsetMatrix] * m[15 + offsetMatrix] -
m[8 + offsetMatrix] * m[3 + offsetMatrix] * m[13 + offsetMatrix] -
m[12 + offsetMatrix] * m[1 + offsetMatrix] * m[11 + offsetMatrix] +
m[12 + offsetMatrix] * m[3 + offsetMatrix] * m[9 + offsetMatrix];
inv[13 + offsetResult] = m[0 + offsetMatrix] * m[9 + offsetMatrix] * m[14 + offsetMatrix] -
m[0 + offsetMatrix] * m[10 + offsetMatrix] * m[13 + offsetMatrix] -
m[8 + offsetMatrix] * m[1 + offsetMatrix] * m[14 + offsetMatrix] +
m[8 + offsetMatrix] * m[2 + offsetMatrix] * m[13 + offsetMatrix] +
m[12 + offsetMatrix] * m[1 + offsetMatrix] * m[10 + offsetMatrix] -
m[12 + offsetMatrix] * m[2 + offsetMatrix] * m[9 + offsetMatrix];
inv[2 + offsetResult] = m[1 + offsetMatrix] * m[6 + offsetMatrix] * m[15 + offsetMatrix] -
m[1 + offsetMatrix] * m[7 + offsetMatrix] * m[14 + offsetMatrix] -
m[5 + offsetMatrix] * m[2 + offsetMatrix] * m[15 + offsetMatrix] +
m[5 + offsetMatrix] * m[3 + offsetMatrix] * m[14 + offsetMatrix] +
m[13 + offsetMatrix] * m[2 + offsetMatrix] * m[7 + offsetMatrix] -
m[13 + offsetMatrix] * m[3 + offsetMatrix] * m[6 + offsetMatrix];
inv[6 + offsetResult] = -m[0 + offsetMatrix] * m[6 + offsetMatrix] * m[15 + offsetMatrix] +
m[0 + offsetMatrix] * m[7 + offsetMatrix] * m[14 + offsetMatrix] +
m[4 + offsetMatrix] * m[2 + offsetMatrix] * m[15 + offsetMatrix] -
m[4 + offsetMatrix] * m[3 + offsetMatrix] * m[14 + offsetMatrix] -
m[12 + offsetMatrix] * m[2 + offsetMatrix] * m[7 + offsetMatrix] +
m[12 + offsetMatrix] * m[3 + offsetMatrix] * m[6 + offsetMatrix];
inv[10 + offsetResult] = m[0 + offsetMatrix] * m[5 + offsetMatrix] * m[15 + offsetMatrix] -
m[0 + offsetMatrix] * m[7 + offsetMatrix] * m[13 + offsetMatrix] -
m[4 + offsetMatrix] * m[1 + offsetMatrix] * m[15 + offsetMatrix] +
m[4 + offsetMatrix] * m[3 + offsetMatrix] * m[13 + offsetMatrix] +
m[12 + offsetMatrix] * m[1 + offsetMatrix] * m[7 + offsetMatrix] -
m[12 + offsetMatrix] * m[3 + offsetMatrix] * m[5 + offsetMatrix];
inv[14 + offsetResult] = -m[0 + offsetMatrix] * m[5 + offsetMatrix] * m[14 + offsetMatrix] +
m[0 + offsetMatrix] * m[6 + offsetMatrix] * m[13 + offsetMatrix] +
m[4 + offsetMatrix] * m[1 + offsetMatrix] * m[14 + offsetMatrix] -
m[4 + offsetMatrix] * m[2 + offsetMatrix] * m[13 + offsetMatrix] -
m[12 + offsetMatrix] * m[1 + offsetMatrix] * m[6 + offsetMatrix] +
m[12 + offsetMatrix] * m[2 + offsetMatrix] * m[5 + offsetMatrix];
inv[3 + offsetResult] = -m[1 + offsetMatrix] * m[6 + offsetMatrix] * m[11 + offsetMatrix] +
m[1 + offsetMatrix] * m[7 + offsetMatrix] * m[10 + offsetMatrix] +
m[5 + offsetMatrix] * m[2 + offsetMatrix] * m[11 + offsetMatrix] -
m[5 + offsetMatrix] * m[3 + offsetMatrix] * m[10 + offsetMatrix] -
m[9 + offsetMatrix] * m[2 + offsetMatrix] * m[7 + offsetMatrix] +
m[9 + offsetMatrix] * m[3 + offsetMatrix] * m[6 + offsetMatrix];
inv[7 + offsetResult] = m[0 + offsetMatrix] * m[6 + offsetMatrix] * m[11 + offsetMatrix] -
m[0 + offsetMatrix] * m[7 + offsetMatrix] * m[10 + offsetMatrix] -
m[4 + offsetMatrix] * m[2 + offsetMatrix] * m[11 + offsetMatrix] +
m[4 + offsetMatrix] * m[3 + offsetMatrix] * m[10 + offsetMatrix] +
m[8 + offsetMatrix] * m[2 + offsetMatrix] * m[7 + offsetMatrix] -
m[8 + offsetMatrix] * m[3 + offsetMatrix] * m[6 + offsetMatrix];
inv[11 + offsetResult] = -m[0 + offsetMatrix] * m[5 + offsetMatrix] * m[11 + offsetMatrix] +
m[0 + offsetMatrix] * m[7 + offsetMatrix] * m[9 + offsetMatrix] +
m[4 + offsetMatrix] * m[1 + offsetMatrix] * m[11 + offsetMatrix] -
m[4 + offsetMatrix] * m[3 + offsetMatrix] * m[9 + offsetMatrix] -
m[8 + offsetMatrix] * m[1 + offsetMatrix] * m[7 + offsetMatrix] +
m[8 + offsetMatrix] * m[3 + offsetMatrix] * m[5 + offsetMatrix];
inv[15 + offsetResult] = m[0 + offsetMatrix] * m[5 + offsetMatrix] * m[10 + offsetMatrix] -
m[0 + offsetMatrix] * m[6 + offsetMatrix] * m[9 + offsetMatrix] -
m[4 + offsetMatrix] * m[1 + offsetMatrix] * m[10 + offsetMatrix] +
m[4 + offsetMatrix] * m[2 + offsetMatrix] * m[9 + offsetMatrix] +
m[8 + offsetMatrix] * m[1 + offsetMatrix] * m[6 + offsetMatrix] -
m[8 + offsetMatrix] * m[2 + offsetMatrix] * m[5 + offsetMatrix];
det = m[0 + offsetMatrix] * inv[0 + offsetResult] + m[1 + offsetMatrix] * inv[4 + offsetResult] + m[2 + offsetMatrix] * inv[8 + offsetResult] + m[3 + offsetMatrix] * inv[12 + offsetResult];
if (det == 0)
return;
det = 1.0f / det;
for (i = 0; i < 16; i++)
inv[i + offsetResult] = inv[i + offsetResult] * det;
}
@Override
public void rotateM(float[] result, int offsetResult, float rotation, float x, float y, float z) {
Quaternion q = Quaternion.fromAxisAngle(new Vector3(x,y,z), rotation);
q.toMatrix(result);
}
@Override
public void orthoM(float[] result, int offsetResult, float left, float right, float bottom, float top, float near, float far) {
result[0 + offsetResult] = 2 / (right - left);
result[1 + offsetResult] = 0;
result[2 + offsetResult] = 0;
result[3 + offsetResult] = 0;
result[4 + offsetResult] = 0;
result[5 + offsetResult] = 2 / (top - bottom);
result[6 + offsetResult] = 0;
result[7 + offsetResult] = 0;
result[8 + offsetResult] = 0;
result[9 + offsetResult] = 0;
result[10 + offsetResult] = -2 / (far - near);
result[11 + offsetResult] = 0;
result[12 + offsetResult] = - (right+left) / (right - left);
result[13 + offsetResult] = - (top+bottom) / (top - bottom);
result[14 + offsetResult] = - (far+near) / (far - near);
result[15 + offsetResult] = 1;
}
@Override
public void frustumM(float[] m, int offsetResult, float left, float right, float bottom, float top, float near, float far) {
final float r_width = 1.0f / (right - left);
final float r_height = 1.0f / (top - bottom);
final float r_depth = 1.0f / (near - far);
final float x = 2.0f * (near * r_width);
final float y = 2.0f * (near * r_height);
final float A = 2.0f * ((right + left) * r_width);
final float B = (top + bottom) * r_height;
final float C = (far + near) * r_depth;
final float D = 2.0f * (far * near * r_depth);
m[offsetResult + 0] = x;
m[offsetResult + 5] = y;
m[offsetResult + 8] = A;
m[offsetResult + 9] = B;
m[offsetResult + 10] = C;
m[offsetResult + 14] = D;
m[offsetResult + 11] = -1.0f;
m[offsetResult + 1] = 0.0f;
m[offsetResult + 2] = 0.0f;
m[offsetResult + 3] = 0.0f;
m[offsetResult + 4] = 0.0f;
m[offsetResult + 6] = 0.0f;
m[offsetResult + 7] = 0.0f;
m[offsetResult + 12] = 0.0f;
m[offsetResult + 13] = 0.0f;
m[offsetResult + 15] = 0.0f;
}
public void setLookAtM(float[] rm, int rmOffset, float eyeX, float eyeY,
float eyeZ, float centerX, float centerY, float centerZ, float upX,
float upY, float upZ) {
float fx = centerX - eyeX;
float fy = centerY - eyeY;
float fz = centerZ - eyeZ;
// Normalize f
float rlf = 1.0f / Vector3.length(fx, fy, fz);
fx *= rlf;
fy *= rlf;
fz *= rlf;
// compute s = f x up (x means "cross product")
float sx = fy * upZ - fz * upY;
float sy = fz * upX - fx * upZ;
float sz = fx * upY - fy * upX;
// and normalize s
float rls = 1.0f / Vector3.length(sx, sy, sz);
sx *= rls;
sy *= rls;
sz *= rls;
// compute u = s x f
float ux = sy * fz - sz * fy;
float uy = sz * fx - sx * fz;
float uz = sx * fy - sy * fx;
rm[rmOffset + 0] = sx;
rm[rmOffset + 1] = ux;
rm[rmOffset + 2] = -fx;
rm[rmOffset + 3] = 0.0f;
rm[rmOffset + 4] = sy;
rm[rmOffset + 5] = uy;
rm[rmOffset + 6] = -fy;
rm[rmOffset + 7] = 0.0f;
rm[rmOffset + 8] = sz;
rm[rmOffset + 9] = uz;
rm[rmOffset + 10] = -fz;
rm[rmOffset + 11] = 0.0f;
rm[rmOffset + 12] = 0.0f;
rm[rmOffset + 13] = 0.0f;
rm[rmOffset + 14] = 0.0f;
rm[rmOffset + 15] = 1.0f;
translateM(rm, rmOffset, -eyeX, -eyeY, -eyeZ);
}
}
| mit |
Azure/azure-sdk-for-java | sdk/batch/azure-resourcemanager-batch/src/main/java/com/azure/resourcemanager/batch/implementation/CheckNameAvailabilityResultImpl.java | 1407 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.batch.implementation;
import com.azure.resourcemanager.batch.fluent.models.CheckNameAvailabilityResultInner;
import com.azure.resourcemanager.batch.models.CheckNameAvailabilityResult;
import com.azure.resourcemanager.batch.models.NameAvailabilityReason;
public final class CheckNameAvailabilityResultImpl implements CheckNameAvailabilityResult {
private CheckNameAvailabilityResultInner innerObject;
private final com.azure.resourcemanager.batch.BatchManager serviceManager;
CheckNameAvailabilityResultImpl(
CheckNameAvailabilityResultInner innerObject, com.azure.resourcemanager.batch.BatchManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
}
public Boolean nameAvailable() {
return this.innerModel().nameAvailable();
}
public NameAvailabilityReason reason() {
return this.innerModel().reason();
}
public String message() {
return this.innerModel().message();
}
public CheckNameAvailabilityResultInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.batch.BatchManager manager() {
return this.serviceManager;
}
}
| mit |
Cortex-Modders/CodeLyokoMod | src/main/java/net/cortexmodders/lyoko/blocks/ILyokoTerrain.java | 409 | /*
* Code Lyoko Mod for Minecraft ${version}
* Copyright 2014 Cortex Modders, Matthew Warren, Jacob Rhoda, and other contributors.
* Released under the MIT license http://opensource.org/licenses/MIT
*/
package net.cortexmodders.lyoko.blocks;
/**
* This interface is for making a block "Lyoko terrain."
*
* @author Jadar
*/
public interface ILyokoTerrain
{
public LyokoTerrainTypes getType();
}
| mit |
AgileInstitute/labs-java-junit | TestedTrek/src/StarTrek/Game.java | 2491 | package StarTrek;
import java.util.Random;
import Untouchables.WebGadget;
public class Game {
private int e = 10000;
private int t = 8;
public int EnergyRemaining() {
return e;
}
public void setTorpedoes(int value) {
t = value;
}
public int getTorpedoes() {
return t;
}
public void fireWeapon(WebGadget wg) {
fireWeapon(new Galaxy(wg));
}
public void fireWeapon(Galaxy wg) {
if (wg.parameter("command").equals("phaser")) {
int amount = Integer.parseInt(wg.parameter("amount"));
Klingon enemy = (Klingon) wg.variable("target");
if (e >= amount) {
int distance = enemy.distance();
if (distance > 4000) {
wg.writeLine("Klingon out of range of phasers at " + distance + " sectors...");
} else {
int damage = amount - (((amount /20)* distance /200) + rnd(200));
if (damage < 1)
damage = 1;
wg.writeLine("Phasers hit Klingon at " + distance + " sectors with " + damage + " units");
if (damage < enemy.getEnergy()) {
enemy.setEnergy(enemy.getEnergy() - damage);
wg.writeLine("Klingon has " + enemy.getEnergy() + " remaining");
} else {
wg.writeLine("Klingon destroyed!");
enemy.delete();
}
}
e -= amount;
} else {
wg.writeLine("Insufficient energy to fire phasers!");
}
} else if (wg.parameter("command").equals("photon")) {
Klingon enemy = (Klingon) wg.variable("target");
if (t > 0) {
int distance = enemy.distance();
if ((rnd(4) + ((distance / 500) + 1) > 7)) {
wg.writeLine("Torpedo missed Klingon at " + distance + " sectors...");
} else {
int damage = 800 + rnd(50);
wg.writeLine("Photons hit Klingon at " + distance + " sectors with " + damage + " units");
if (damage < enemy.getEnergy()) {
enemy.setEnergy(enemy.getEnergy() - damage);
wg.writeLine("Klingon has " + enemy.getEnergy() + " remaining");
} else {
wg.writeLine("Klingon destroyed!");
enemy.delete();
}
}
t -= 1;
} else {
wg.writeLine("No more photon torpedoes!");
}
}
}
// note we made generator public in order to mock it
// it's ugly, but it's telling us something about our *design!* ;-)
public static Random generator = new Random();
private static int rnd(int maximum) {
return generator.nextInt(maximum);
}
}
| mit |
TyrfingX/TyrLib | legacy/TyrLib/src/tyrfing/common/ui/widgets/ImageBox.java | 763 | package tyrfing.common.ui.widgets;
import android.graphics.Bitmap;
import tyrfing.common.render.SceneManager;
import tyrfing.common.renderables.Image;
import tyrfing.common.ui.Window;
public class ImageBox extends Window{
private Image image;
public ImageBox(String name, float x, float y, float w, float h, Bitmap bitmap) {
super(name, x, y, w, h);
image = SceneManager.createImage(bitmap, node);
components.add(image);
}
public void setImage(Bitmap bitmap)
{
Image img = image;
long prio = image.getPriority();
image = SceneManager.createImage(bitmap, node);
image.setPriority(prio);
image.setVisible(img.getVisible());
SceneManager.RENDER_THREAD.removeRenderable(img);
components.remove(img);
components.add(image);
}
}
| mit |
raoulvdberge/refinedstorage | src/main/java/com/refinedmods/refinedstorage/blockentity/ConstructorBlockEntity.java | 3152 | package com.refinedmods.refinedstorage.blockentity;
import com.refinedmods.refinedstorage.RSBlockEntities;
import com.refinedmods.refinedstorage.apiimpl.network.node.ConstructorNetworkNode;
import com.refinedmods.refinedstorage.apiimpl.network.node.cover.CoverManager;
import com.refinedmods.refinedstorage.blockentity.config.IComparable;
import com.refinedmods.refinedstorage.blockentity.config.IType;
import com.refinedmods.refinedstorage.blockentity.data.BlockEntitySynchronizationParameter;
import com.refinedmods.refinedstorage.util.WorldUtils;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.model.data.IModelData;
import net.minecraftforge.client.model.data.ModelDataMap;
import javax.annotation.Nonnull;
public class ConstructorBlockEntity extends NetworkNodeBlockEntity<ConstructorNetworkNode> {
public static final BlockEntitySynchronizationParameter<Integer, ConstructorBlockEntity> COMPARE = IComparable.createParameter();
public static final BlockEntitySynchronizationParameter<Integer, ConstructorBlockEntity> TYPE = IType.createParameter();
public static final BlockEntitySynchronizationParameter<Boolean, ConstructorBlockEntity> DROP = new BlockEntitySynchronizationParameter<>(EntityDataSerializers.BOOLEAN, false, t -> t.getNode().isDrop(), (t, v) -> {
t.getNode().setDrop(v);
t.getNode().markDirty();
});
public static final BlockEntitySynchronizationParameter<CompoundTag, ConstructorBlockEntity> COVER_MANAGER = new BlockEntitySynchronizationParameter<>(EntityDataSerializers.COMPOUND_TAG, new CompoundTag(),
t -> t.getNode().getCoverManager().writeToNbt(),
(t, v) -> t.getNode().getCoverManager().readFromNbt(v),
(initial, p) -> {
});
public ConstructorBlockEntity(BlockPos pos, BlockState state) {
super(RSBlockEntities.CONSTRUCTOR, pos, state);
dataManager.addWatchedParameter(COMPARE);
dataManager.addWatchedParameter(TYPE);
dataManager.addWatchedParameter(DROP);
dataManager.addWatchedParameter(COVER_MANAGER);
}
@Override
@Nonnull
public ConstructorNetworkNode createNode(Level level, BlockPos pos) {
return new ConstructorNetworkNode(level, pos);
}
@Nonnull
@Override
public IModelData getModelData() {
return new ModelDataMap.Builder().withInitial(CoverManager.PROPERTY, this.getNode().getCoverManager()).build();
}
@Override
public CompoundTag writeUpdate(CompoundTag tag) {
super.writeUpdate(tag);
tag.put(CoverManager.NBT_COVER_MANAGER, this.getNode().getCoverManager().writeToNbt());
return tag;
}
@Override
public void readUpdate(CompoundTag tag) {
super.readUpdate(tag);
this.getNode().getCoverManager().readFromNbt(tag.getCompound(CoverManager.NBT_COVER_MANAGER));
requestModelDataUpdate();
WorldUtils.updateBlock(level, worldPosition);
}
}
| mit |
cdut007/PMS_TASK | TaskTrackerPMS/src/com/thirdpart/tasktrackerpms/adapter/WitnesserAdapter.java | 6505 | package com.thirdpart.tasktrackerpms.adapter;
import java.text.DecimalFormat;
import java.util.Scanner;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.jameschen.framework.base.BaseActivity;
import com.jameschen.framework.base.BaseCheckItemAdapter;
import com.jameschen.framework.base.MyBaseAdapter;
import com.jameschen.framework.base.MyBaseAdapter.HoldView;
import com.thirdpart.model.ConstValues.Item;
import com.thirdpart.model.entity.IssueResult;
import com.thirdpart.model.entity.RollingPlan;
import com.thirdpart.model.entity.WitnessDistributed;
import com.thirdpart.model.entity.WorkStep;
import com.thirdpart.tasktrackerpms.R;
import com.thirdpart.tasktrackerpms.ui.IssueFeedbackActivity;
import com.thirdpart.tasktrackerpms.ui.WitnessChooseActivity;
import com.thirdpart.tasktrackerpms.ui.WitnessUpdateActivity;
import com.thirdpart.tasktrackerpms.ui.WorkStepDetailActivity;
import com.thirdpart.widget.DisplayItemView;
import com.thirdpart.widget.DisplayMultiLineItemView;
import com.thirdpart.widget.TouchImage;
public class WitnesserAdapter extends BaseCheckItemAdapter<WitnessDistributed> {
private Context context;
public boolean deliveryWitness,sanChooseWitness;
public WitnesserAdapter(Context context, boolean deliveryWitness,boolean scanChoose) {
super(context,R.layout.witness_item);
this.context = context;
this.deliveryWitness = deliveryWitness;
sanChooseWitness = scanChoose;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
ItemHoldView sHoldView = (ItemHoldView) convertView.getTag();
sHoldView.setInfo(position);
return convertView;
}
@Override
public void recycle() {
super.recycle();
}
@Override
protected HoldView<WitnessDistributed> createHoldView() {
// TODO Auto-generated method stub
return new ItemHoldView();
}
@Override
public boolean isEnabled(int position) {
// TODO Auto-generated method stub
return super.isEnabled(position);
}
boolean editMode = false;
public void setEditMode(boolean editMode) {
// TODO Auto-generated method stub
this.editMode = editMode;
}
private final static class ItemHoldView extends CheckItemHoldView<WitnessDistributed> {
TextView noTextView,adressTextView,tuzhiTextView,hankouTextView;
TextView chooseWitenss;
boolean Scanner = false,chooseWitness=false;
CheckBox isChecked;
BaseCheckItemAdapter<WitnessDistributed> mCheckItemAdapter;
@Override
protected void initChildView(View convertView,
final MyBaseAdapter<WitnessDistributed> myBaseAdapter) {
// TODO Auto-generated method stub
isChecked = (CheckBox) convertView.findViewById(R.id.witness_check);
mCheckItemAdapter = (BaseCheckItemAdapter<WitnessDistributed>) myBaseAdapter;
View checkContainer = (View)isChecked.getParent();
checkContainer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mCheckItemAdapter.setItemChecked((String)isChecked.getTag(), isChecked);
}
});
if (!((WitnesserAdapter)myBaseAdapter).editMode) {
checkContainer.setVisibility(View.GONE);
}
noTextView = (TextView) convertView.findViewById(R.id.witness_index_item);
hankouTextView = (TextView) convertView.findViewById(R.id.issue_hankou);
chooseWitenss = (TextView) convertView.findViewById(R.id.witness_choose);
DisplayMultiLineItemView issueDisplayItemView = (DisplayMultiLineItemView) convertView.findViewById(R.id.witnenss_address );
adressTextView = issueDisplayItemView.getContentView();
DisplayItemView issue2DisplayItemView = (DisplayItemView) convertView.findViewById(R.id.issue_tuzhi);
tuzhiTextView = issue2DisplayItemView.getContentView();
Scanner = ((WitnesserAdapter)myBaseAdapter).deliveryWitness;
chooseWitness = ((WitnesserAdapter)myBaseAdapter).sanChooseWitness;
chooseWitenss.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Context context = v.getContext();
Intent intent= new Intent(context,WitnessChooseActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
WitnessDistributed workStep = (WitnessDistributed) v.getTag();
intent.putExtra(Item.WITNESS, workStep);
if (Scanner) {
intent.putExtra("scan", true);
}
if ( ((WitnesserAdapter)myBaseAdapter).sanChooseWitness) {
intent.putExtra("scan", true);
}
context.startActivity(intent);
}
});
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Context context = v.getContext();
if (Scanner) {
return;
}
Intent intent= new Intent(context,WitnessUpdateActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
WitnessDistributed workStep = (WitnessDistributed)chooseWitenss.getTag();
intent.putExtra("scan", Scanner);
intent.putExtra(Item.WITNESS, workStep);
context.startActivity(intent);
}
});
}
public void setInfo( int position) {
// TODO Auto-generated method stub
noTextView.setText(""+(position+1));
}
@Override
protected void setInfo(WitnessDistributed object) {
// TODO Auto-generated method stub
adressTextView.setText(object.getWitnessaddress());
tuzhiTextView.setText(object.getWorkStep().getRollingPlan().getDrawno());
hankouTextView.setText(object.getWorkStep().getRollingPlan().getWeldno());
chooseWitenss.setTag(object);
chooseWitenss.setText(Scanner?"查看见证":"选择见证人");
if (chooseWitness) {
chooseWitenss.setText("查看见证");
}
}
@Override
public void setCheckedInfo(
BaseCheckItemAdapter<WitnessDistributed> adapter, int position,
WitnessDistributed item) {
mCheckItemAdapter.markItemCheckStatus(position, isChecked);
isChecked.setTag(position+"");
}
}
}
| mit |
MobileSolution/android-lol-api | library/src/main/java/com/mobilesolutions/lolapi/models/statics/SummonerSpellDto.java | 2396 | package com.mobilesolutions.lolapi.models.statics;
import java.io.Serializable;
import java.util.List;
public class SummonerSpellDto implements Serializable {
private List<Double> cooldown;
private List<Integer> cost;
private List<Object> effect;
private List<String> effectBurn;
private List<String> modes;
private Object range;
private List<SpellVarsDto> vars;
private String cooldownBurn;
private String costBurn;
private String costType;
private String description;
private String key;
private String name;
private String rangeBurn;
private String resource;
private String sanitizedDescription;
private String sanitizedTooltip;
private String tooltip;
private int id, maxrank, summonerLevel;
private ImageDto image;
private LevelTipDto leveltip;
public List<Double> getCooldown() {
return cooldown;
}
public List<Integer> getCost() {
return cost;
}
public List<Object> getEffect() {
return effect;
}
public List<String> getEffectBurn() {
return effectBurn;
}
public List<String> getModes() {
return modes;
}
public Object getRange() {
return range;
}
public List<SpellVarsDto> getVars() {
return vars;
}
public String getCooldownBurn() {
return cooldownBurn;
}
public String getCostBurn() {
return costBurn;
}
public String getCostType() {
return costType;
}
public String getDescription() {
return description;
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
public String getRangeBurn() {
return rangeBurn;
}
public String getResource() {
return resource;
}
public String getSanitizedDescription() {
return sanitizedDescription;
}
public String getSanitizedTooltip() {
return sanitizedTooltip;
}
public String getTooltip() {
return tooltip;
}
public int getId() {
return id;
}
public int getMaxrank() {
return maxrank;
}
public int getSummonerLevel() {
return summonerLevel;
}
public ImageDto getImage() {
return image;
}
public LevelTipDto getLeveltip() {
return leveltip;
}
}
| mit |
macbury/ForgE | core/src/macbury/forge/shaders/uniforms/UniformWorldTransform.java | 932 | package macbury.forge.shaders.uniforms;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Matrix4;
import macbury.forge.level.env.LevelEnv;
import macbury.forge.shaders.utils.BaseRenderableUniform;
/**
* Created by macbury on 29.04.15.
*/
public class UniformWorldTransform extends BaseRenderableUniform {
public static final String UNIFORM_WORLD_TRANSFORM = "u_worldTransform";
@Override
public void bind(ShaderProgram shader, LevelEnv env, RenderContext context, Camera camera, Renderable renderable) {
shader.setUniformMatrix(UNIFORM_WORLD_TRANSFORM, renderable.worldTransform);
}
@Override
public void dispose() {
}
@Override
public void defineUniforms() {
define(UNIFORM_WORLD_TRANSFORM, Matrix4.class);
}
}
| mit |
sel-utils/java | src/main/java/sul/protocol/bedrock137/play/ClientboundMapItemData.java | 3897 | /*
* This file was automatically generated by sel-utils and
* released under the MIT License.
*
* License: https://github.com/sel-project/sel-utils/blob/master/LICENSE
* Repository: https://github.com/sel-project/sel-utils
* Generated from https://github.com/sel-project/sel-utils/blob/master/xml/protocol/bedrock137.xml
*/
package sul.protocol.bedrock137.play;
import java.util.Arrays;
import sul.utils.*;
public class ClientboundMapItemData extends Packet {
public static final int ID = (int)67;
public static final boolean CLIENTBOUND = true;
public static final boolean SERVERBOUND = false;
@Override
public int getId() {
return ID;
}
// update
public static final int TEXTURE = (int)2;
public static final int DECORATIONS = (int)4;
public static final int ENTITIES = (int)8;
public long mapId;
public int update;
public byte scale;
public Tuples.IntXZ size = new Tuples.IntXZ();
public Tuples.IntXZ offset = new Tuples.IntXZ();
public byte[] data = new byte[0];
public sul.protocol.bedrock137.types.Decoration[] decorations = new sul.protocol.bedrock137.types.Decoration[0];
public ClientboundMapItemData() {}
public ClientboundMapItemData(long mapId, int update, byte scale, Tuples.IntXZ size, Tuples.IntXZ offset, byte[] data, sul.protocol.bedrock137.types.Decoration[] decorations) {
this.mapId = mapId;
this.update = update;
this.scale = scale;
this.size = size;
this.offset = offset;
this.data = data;
this.decorations = decorations;
}
@Override
public int length() {
int length=Buffer.varlongLength(mapId) + Buffer.varuintLength(update) + Buffer.varintLength(size.x) + Buffer.varintLength(size.z) + Buffer.varintLength(offset.x) + Buffer.varintLength(offset.z) + data.length + Buffer.varuintLength(decorations.length) + 3; for(sul.protocol.bedrock137.types.Decoration zvbjdlbm:decorations){ length+=zvbjdlbm.length(); } return length;
}
@Override
public byte[] encode() {
this._buffer = new byte[this.length()];
this.writeVaruint(ID);
this.writeVarlong(mapId);
this.writeVaruint(update);
if(update==2||update==4){ this.writeLittleEndianByte(scale); }
if(update==2){ this.writeVarint(size.x); this.writeVarint(size.z); }
if(update==2){ this.writeVarint(offset.x); this.writeVarint(offset.z); }
if(update==2){ this.writeBytes(data); }
if(update==4){ this.writeVaruint((int)decorations.length); for(sul.protocol.bedrock137.types.Decoration zvbjdlbm:decorations){ this.writeBytes(zvbjdlbm.encode()); } }
return this.getBuffer();
}
@Override
public void decode(byte[] buffer) {
this._buffer = buffer;
this.readVaruint();
mapId=this.readVarlong();
update=this.readVaruint();
if(update==2||update==4){ scale=readLittleEndianByte(); }
if(update==2){ size=new Tuples.IntXZ(); size.x=this.readVarint(); size.z=this.readVarint(); }
if(update==2){ offset=new Tuples.IntXZ(); offset.x=this.readVarint(); offset.z=this.readVarint(); }
if(update==2){ data=this.readBytes(this._buffer.length-this._index); }
if(update==4){ int bry9yrb5=this.readVaruint(); decorations=new sul.protocol.bedrock137.types.Decoration[bry9yrb5]; for(int zvbjdlbm=0;zvbjdlbm<decorations.length;zvbjdlbm++){ decorations[zvbjdlbm]=new sul.protocol.bedrock137.types.Decoration(); decorations[zvbjdlbm]._index=this._index; decorations[zvbjdlbm].decode(this._buffer); this._index=decorations[zvbjdlbm]._index; } }
}
public static ClientboundMapItemData fromBuffer(byte[] buffer) {
ClientboundMapItemData ret = new ClientboundMapItemData();
ret.decode(buffer);
return ret;
}
@Override
public String toString() {
return "ClientboundMapItemData(mapId: " + this.mapId + ", update: " + this.update + ", scale: " + this.scale + ", size: " + this.size.toString() + ", offset: " + this.offset.toString() + ", data: " + Arrays.toString(this.data) + ", decorations: " + Arrays.deepToString(this.decorations) + ")";
}
} | mit |
Kowalski-IO/cron-nark | src/main/java/io/kowalski/cronnark/views/StatusPageView.java | 534 | package io.kowalski.cronnark.views;
import java.io.Serializable;
import java.util.Collection;
import io.dropwizard.views.View;
import io.kowalski.cronnark.models.TrackedTask;
import lombok.Getter;
@Getter
public class StatusPageView extends View implements Serializable {
private static final long serialVersionUID = 1081208252133052923L;
private final Collection<TrackedTask> tasks;
public StatusPageView(final Collection<TrackedTask> tasks) {
super("status_page.ftl");
this.tasks = tasks;
}
}
| mit |
Open-RIO/ToastAPI | src/main/java/jaci/openrio/toast/core/command/cmd/CommandReloadConfigs.java | 1558 | package jaci.openrio.toast.core.command.cmd;
import jaci.openrio.toast.core.Toast;
import jaci.openrio.toast.core.command.AbstractCommand;
import jaci.openrio.toast.core.command.IHelpable;
import jaci.openrio.toast.lib.module.ModuleConfig;
/**
* The Command to reload all configuration files. This will re-read all the configs from file.
*
* @author Jaci
*/
public class CommandReloadConfigs extends AbstractCommand implements IHelpable {
/**
* Get the command name
* e.g. 'cmd' for a command such as 'cmd <your args>
*/
@Override
public String getCommandName() {
return "reloadcfg";
}
/**
* Returns a help message to display with the 'help' command
*/
@Override
public String getHelp() {
return "Reload all ModuleConfig files";
}
/**
* Invoke the command if the name matches the one to be triggered
* @param argLength The amount of arguments in the 'args' param
* @param args The arguments the command was invoked with. This can be empty if
* none were provided. Keep in mind this does NOT include the Command Name.
* Args are separated by spaces
* @param command The full command message
*/
@Override
public void invokeCommand(int argLength, String[] args, String command) {
int cnt = 0;
for (ModuleConfig config : ModuleConfig.allConfigs) {
config.reload();
cnt++;
}
Toast.log().info("All ModuleConfigs reloaded (" + cnt + " reloaded)");
}
}
| mit |
perrywang/OAuthGateway | gateway/src/main/java/org/thinkinghub/gateway/oauth/extractor/ResponseExtractor.java | 252 | package org.thinkinghub.gateway.oauth.extractor;
import org.thinkinghub.gateway.oauth.response.GatewayResponse;
import com.github.scribejava.core.model.Response;
public interface ResponseExtractor {
GatewayResponse extract(Response response);
}
| mit |
JCThePants/NucleusFramework | tests/src/com/jcwhatever/nucleus/utils/observer/result/_ResultTestSuite.java | 295 | package com.jcwhatever.nucleus.utils.observer.result;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
FutureResultAgentTest.class,
ResultAgentTest.class,
ResultTest.class
})
public class _ResultTestSuite {
}
| mit |
javagl/JglTF | jgltf-model/src/main/java/de/javagl/jgltf/model/gl/TechniqueStatesFunctionsModel.java | 3106 | /*
* www.javagl.de - JglTF
*
* Copyright 2015-2017 Marco Hutter - http://www.javagl.de
*
* 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.javagl.jgltf.model.gl;
/**
* Interface for technique state function parameters. <br>
* <br>
* <b>Note: The method comments here are placeholders. For details, refer
* to the glTF 1.0 specification and an OpenGL documentation!</b><br>
* <br>
* Note: The methods in this interface may return <i>references</i>
* to arrays that are stored internally. Callers should not store
* or modify the returned arrays!
*/
public interface TechniqueStatesFunctionsModel
{
/**
* Returns the blend color
*
* @return The blend color
*/
float[] getBlendColor();
/**
* Returns the blend equation
*
* @return the blend equation
*/
int[] getBlendEquationSeparate();
/**
* Returns the blend function
*
* @return The blend function
*/
int[] getBlendFuncSeparate();
/**
* Returns the color mask
*
* @return The color mask
*/
boolean[] getColorMask();
/**
* Returns the cull face
*
* @return The cull face
*/
int[] getCullFace();
/**
* Returns the depth func
*
* @return The depth func
*/
int[] getDepthFunc();
/**
* Returns the depth mask
*
* @return The depth mask
*/
boolean[] getDepthMask();
/**
* Returns the depth range
*
* @return The depth range
*/
float[] getDepthRange();
/**
* Returns the front face
*
* @return The front face
*/
int[] getFrontFace();
/**
* Returns the line width
*
* @return The line width
*/
float[] getLineWidth();
/**
* Returns the polygon offset
*
* @return The polygon offset
*/
float[] getPolygonOffset();
}
| mit |
modifier/jaba_labs | lab1_473/src/dno1/HandlerServlet.java | 1976 | package dno1;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Modifier on 28.02.14.
*/
public class HandlerServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String[] PositionX = request.getParameterValues("position_x");
String PositionY = request.getParameter("position_y");
String Radius = request.getParameter("radius");
float y, r;
float[] x;
try
{
y = Float.valueOf(PositionY);
r = Float.valueOf(Radius);
x = new float[PositionX.length];
for (int i = 0; i < PositionX.length; i++) {
x[i] = Float.valueOf(PositionX[i]);
}
if (r < 0) {
throw new Exception();
}
}
catch (Exception e)
{
response.setStatus(400);
request.getRequestDispatcher("/bad_request.jsp").forward(request, response);
return;
}
request.setAttribute("table", prepareArray(x, y, r));
request.getRequestDispatcher("/handle.jsp").forward(request, response);
}
private List<Map<String, String>> prepareArray(float[] x, float y, float r)
{
List<Map<String, String>> result = new ArrayList<Map<String, String>>();
for (float aX : x)
{
Map<String, String> obj = new HashMap<String, String>();
obj.put("x", Float.toString(aX));
obj.put("y", Float.toString(y));
obj.put("r", Float.toString(r));
obj.put("hit", Boolean.toString(checkPoint(aX, y, r)));
result.add(obj);
}
return result;
}
private boolean checkPoint(float x, float y, float r)
{
if (x >= 0 && y >= 0) {
return x + y <= r;
}
if (x < 0 && y >= 0) {
return x*x + y*y <= r*r;
}
if (x > 0 && y < 0) {
return x <= r / 2 && y >= -r;
}
return false;
}
}
| mit |
mobilerider/mobilerider-client-java | src/com/mobilerider/Channel.java | 831 | package com.mobilerider;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Channel implements Serializable
{
private static final long serialVersionUID = -5439175926991676724L;
@SerializedName("id")
private String _id;
public String getId() {
return _id;
}
private void setId(String id) {
_id = id;
}
@SerializedName("name")
private String _name;
public String getName()
{
return _name;
}
public void setName(String name)
{
_name = name;
}
@SerializedName("description")
private String _description;
public String getDescription()
{
return _description;
}
public void setDescription(String description)
{
_description = description;
}
} | mit |
xsank/Shour | src/main/java/org/nerdboy/chatbot/process/FilterHandler.java | 526 | package org.nerdboy.chatbot.process;
import org.nerdboy.chatbot.nlp.CoreNLP;
import java.util.List;
/**
* Created by xsank.mz on 2016/5/22.
*/
public class FilterHandler implements Handler {
public void process(Request request, Response response, HandlerChain chain) {
List<String> words = CoreNLP.filterWords(request.getQuestion());
request.setWords(words);
if (words.size() > 0) {
chain.handle(request, response);
} else {
chain.unReady();
}
}
}
| mit |
xuatz/ReactNativeReduxTodoApp | android/app/src/main/java/com/reactnativereduxtodoapp/MainActivity.java | 1060 | package com.reactnativereduxtodoapp;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "ReactNativeReduxTodoApp";
}
/**
* Returns whether dev mode should be enabled.
* This enables e.g. the dev menu.
*/
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
}
| mit |
ajwgeek/Modjam-2 | src/ironlionchefs/modjam/src/ColorRGB.java | 1207 | package ironlionchefs.modjam.src;
import net.minecraft.client.renderer.Tessellator;
public final class ColorRGB {
private int red;
private int green;
private int blue;
public ColorRGB(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
@Override
public String toString() {
return toHex(getRed()) + toHex(getGreen()) + toHex(getBlue());
}
public int getRed() {
return clamp(red);
}
public int getGreen() {
return clamp(green);
}
public int getBlue() {
return clamp(blue);
}
public float getRedF() {
return getRed() / 255F;
}
public float getGreenF() {
return getGreen() / 255F;
}
public float getBlueF() {
return getBlue() / 255F;
}
public static int clamp(int i) {
return i > 255 ? 255 : i < 0 ? 0 : i;
}
public void colorizeTessellator(Tessellator tessellator) {
colorizeTessellator(tessellator, 255);
}
public void colorizeTessellator(Tessellator tessellator, int alpha) {
tessellator.setColorRGBA(getRed(), getGreen(), getBlue(), alpha);
}
public static String toHex(int i) {
String s = Integer.toHexString(i & 0xff);
while (s.length() < 2)
s = s.concat("0");
return s.toUpperCase();
}
}
| mit |
infinitemule/spring-sandbox | src/java/com/infinitemule/spring/container/depinject/setter/RandomNumberGenerator.java | 237 | /*
* Spring Sandbox - Dependency Injection - Setter
*
* RandomNumberGenerator.java
*
*/
package com.infinitemule.spring.container.depinject.setter;
public interface RandomNumberGenerator {
public Integer randomInteger();
}
| mit |
Jasonette/JASONETTE-Android | app/src/main/java/com/jasonette/seed/Service/agent/JasonAgentService.java | 42431 | package com.jasonette.seed.Service.agent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.jasonette.seed.Core.JasonParser;
import com.jasonette.seed.Core.JasonViewActivity;
import com.jasonette.seed.Helper.JasonHelper;
import com.jasonette.seed.Launcher.Launcher;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class JasonAgentService {
private JSONObject pending = new JSONObject();
private JSONObject pending_injections = new JSONObject();
// Initialize
public JasonAgentService() {
}
private class JasonAgentInterface {
private WebView agent;
private Context context;
public JasonAgentInterface(WebView agent, Context context) {
this.agent = agent;
this.context = context;
}
// $agent to Jasonette interface
@JavascriptInterface
public void postMessage(String json) {
/****************************************
A message can be:
1. Request
{
"request": {
"data": [RPC Object],
"nonce": [Auto-generated nonce to handle return values later]
}
}
2. Response
{
"response": {
"data": [Return Value]
}
}
3. Trigger
{
"trigger": {
"name": [Jasonette Event Name],
"data": [The "$jason" value to pass along with the event]
}
}
4. Href
{
"href": {
"data": [Jasonette HREF object]
}
}
****************************************/
try {
JSONObject message = new JSONObject(json);
JSONObject transaction = (JSONObject) this.agent.getTag();
if (message.has("request")) {
/***
1. Request: Agent making request to another agent
{
"request": {
"data": [RPC Object],
"nonce": [Auto-generated nonce to handle return values later]
}
}
***/
if (transaction.has("to")) {
JSONObject content = message.getJSONObject("request");
/**
Compose an agent_request object
agent_request := {
"from": [SOURCE AGENT ID],
"request": [JSON-RPC Object],
"nonce": [NONCE]
}
**/
JSONObject agent_request = new JSONObject();
agent_request.put("from", transaction.getString("to"));
agent_request.put("request", content.getJSONObject("data"));
agent_request.put("nonce", content.getString("nonce"));
request(null, agent_request, this.context);
}
} else if (message.has("response")) {
/*****************
2. Response
{
"response": {
"data": [Return Value]
}
}
*****************/
if (transaction.has("to")) {
JSONObject res = message.getJSONObject("response");
// Params
Object param = res.get("data");
// "from": exists => the caller request was from another agent
if (transaction.has("from")) {
/**
Compose an agent_request object
agent_request := {
"from": [SOURCE AGENT ID],
"request": [JSON-RPC Object],
"nonce": [NONCE]
}
**/
JSONArray params = new JSONArray();
params.put(param);
// from
String from = transaction.getString("from");
if (transaction.has("nonce")) {
// 1. Construct jsonrpc
JSONObject jsonrpc = new JSONObject();
// 1.1. Method: Call the callback method stored under $agent.callbacks object
String method = "$agent.callbacks[\"" + transaction.getString("nonce") + "\"]";
jsonrpc.put("method", method);
// 1.2. id: need to call the callback method on the "from" agent
jsonrpc.put("id", from);
// 1.3. params array
jsonrpc.put("params", params);
// 2. Construct the callback agent_request
JSONObject agent_request = new JSONObject();
// 2.1. "from" and "nonce" should be set to null, since this is a return value, and there is no coming back again.
agent_request.put("from", null);
agent_request.put("nonce", null);
// 2.2. set JSON RPC request
agent_request.put("request", jsonrpc);
request(null, agent_request, this.context);
}
// "from" doesn't exist => call from Jasonette => return via success callback
} else {
if (transaction.has("jason")) {
JSONObject original_action = transaction.getJSONObject("jason");
// return param as a return value
JasonHelper.next("success", original_action, param, new JSONObject(), context);
}
}
}
} else if (message.has("trigger")) {
/************************
3. Trigger
{
"trigger": {
"name": [Jasonette Event Name],
"data": [The "$jason" value to pass along with the event]
}
}
************************/
// If the parent is not the same, don't trigger
String current_url = ((JasonViewActivity) context).model.url;
if (transaction.has("parent") && !transaction.getString("parent").equalsIgnoreCase(current_url)) {
return;
}
JSONObject trigger = message.getJSONObject("trigger");
JSONObject m = new JSONObject();
if(trigger.has("name")) {
// trigger
m.put("trigger", trigger.getString("name"));
// options
if (trigger.has("data")) {
m.put("options", trigger.get("data"));
}
// Call the Jasonette event
Intent intent = new Intent("call");
intent.putExtra("action", m.toString());
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
} else if (message.has("href")) {
/************************************
4. Href
{
"href": {
"data": [Jasonette HREF object]
}
}
************************************/
if (message.getJSONObject("href").has("data")) {
JSONObject m = message.getJSONObject("href").getJSONObject("data");
Intent intent = new Intent("call");
JSONObject href = new JSONObject();
href.put("type", "$href");
href.put("options", m);
intent.putExtra("action", href.toString());
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
}
}
}
public WebView setup(final JasonViewActivity context, final JSONObject options, final String id) {
/**
1. Initialize WebView
- Does an agent with the ID exist already?
YES => Use that one
NO =>
1. Create a new WebView
2. Attach to the parent view's agents object
2. Creating a WebView
- Hide it
- Set metadata payload on it so it can be referenced later
3. Filling a WebView
- Is the state "empty"?
YES => Load
NO => Ignore
**/
WebView agent;
/*******************************************
1. Initialize WebView
- Does an agent with the ID exist already?
YES => Use that one
NO =>
1. Create a new WebView
2. Attach to the parent view's agents object
*******************************************/
try {
// An agent with the ID already exists
if (context.agents.has(id)) {
agent = (WebView) context.agents.get(id);
// No such agent exists yet. Create one.
} else {
/*******************************************
2. Creating a WebView
*******************************************/
// 2.1. Initialize
CookieManager.getInstance().setAcceptCookie(true);
agent = new WebView(context);
agent.getSettings().setDefaultTextEncodingName("utf-8");
if (id.startsWith("$webcontainer")) {
ProgressBar pBar;
if (agent.findViewById(42) == null) {
pBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, agent.getId());
layoutParams.height = 5;
pBar.setScaleY(4f);
pBar.setLayoutParams(layoutParams);
int color;
if (options.has("style") && options.getJSONObject("style").has("progress")) {
color = JasonHelper.parse_color(options.getJSONObject("style").getString("progress"));
} else {
color = JasonHelper.parse_color("#007AFF");
}
pBar.getProgressDrawable().setColorFilter( color, android.graphics.PorterDuff.Mode.SRC_IN);
pBar.setId(42);
} else {
pBar = (ProgressBar) agent.findViewById(42);
}
final ProgressBar progressBar = pBar;
agent.addView(progressBar);
agent.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if (progress == 100) {
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.VISIBLE);
}
}
});
} else {
agent.setWebChromeClient(new WebChromeClient());
}
agent.setWebViewClient(new WebViewClient() {
@Override public void onPageFinished(WebView view, final String url) {
// Inject agent.js
try {
String injection_script = JasonHelper.read_file("agent", context);
String interface_script = "$agent.interface.postMessage = function(r) { JASON.postMessage(JSON.stringify(r)); };";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
view.evaluateJavascript(injection_script + " " + interface_script, null);
} else {
view.loadUrl("javascript:" + injection_script + " " + interface_script);
}
if (pending.has(id)) {
JSONObject q = pending.getJSONObject(id);
JSONObject jason_request;
if (q.has("jason_request")) {
jason_request = q.getJSONObject("jason_request");
} else {
jason_request = null;
}
JSONObject agent_request;
if (q.has("agent_request")) {
agent_request = q.getJSONObject("agent_request");
} else {
agent_request = null;
}
request(jason_request, agent_request, context);
pending.remove(id);
}
if (pending_injections.has(id)) {
inject(pending_injections.getJSONObject(id), context);
pending_injections.remove(id);
}
// only set state to rendered if it's not about:blank
if (!url.equalsIgnoreCase("about:blank")) {
JSONObject payload = (JSONObject)view.getTag();
payload.put("state", "rendered");
view.setTag(payload);
}
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
}
}
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
// resolve
final AtomicReference<JSONObject> notifier = new AtomicReference<>();
try {
JSONObject payload = (JSONObject)view.getTag();
// Only override behavior for web container
if (!id.startsWith("$webcontainer")) {
return false;
}
if (!payload.has("url")) {
return false;
}
if(view.getHitTestResult().getType() > 0){
if (options.has("action")) {
// 1. Parse the action if it's a trigger
Object resolved_action;
if (options.getJSONObject("action").has("trigger")) {
String event_name = options.getJSONObject("action").getString("trigger");
JSONObject head = ((JasonViewActivity)context).model.jason.getJSONObject("$jason").getJSONObject("head");
JSONObject events = head.getJSONObject("actions");
// Look up an action by event_name
resolved_action = events.get(event_name);
} else {
resolved_action = options.get("action");
}
/* set $jason */
JSONObject u = new JSONObject();
u.put("url", url);
JSONObject ev = new JSONObject();
ev.put("$jason", u);
context.model.set("state", ev);
JasonParser.getInstance(context).setParserListener(new JasonParser.JasonParserListener() {
@Override
public void onFinished(JSONObject reduced_action) {
synchronized (notifier) {
notifier.set(reduced_action);
notifier.notify();
}
}
});
JasonParser.getInstance(context).parse("json", ((JasonViewActivity)context).model.state, resolved_action, context);
synchronized (notifier) {
while (notifier.get() == null) {
notifier.wait();
}
}
JSONObject parsed = notifier.get();
if (parsed.has("type") && parsed.getString("type").equalsIgnoreCase("$default")) {
return false;
} else {
Intent intent = new Intent("call");
intent.putExtra("action", options.get("action").toString());
// file url handling
if (url.startsWith("file://")) {
if (url.startsWith("file:///android_asset/file")) {
url = url.replace("/android_asset/file/", "");
}
}
intent.putExtra("data", "{\"url\": \"" + url + "\"}");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
return true;
}
}
}
payload.put("state", "loading");
view.setTag(payload);
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
synchronized (notifier) {
notifier.notify();
}
}
return false;
}
});
agent.setVerticalScrollBarEnabled(false);
agent.setHorizontalScrollBarEnabled(false);
if (options.has("style") && options.getJSONObject("style").has("background")) {
agent.setBackgroundColor(JasonHelper.parse_color(options.getJSONObject("style").getString("background")));
} else {
agent.setBackgroundColor(Color.TRANSPARENT);
}
WebSettings settings = agent.getSettings();
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setMediaPlaybackRequiresUserGesture(false);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setAppCachePath(context.getCacheDir().getAbsolutePath());
settings.setAllowFileAccess(true);
settings.setAppCacheEnabled(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
// 2.2. Create and Attach JavaScript Interface
JasonAgentInterface agentInterface = new JasonAgentInterface(agent, context);
agent.addJavascriptInterface(agentInterface, "JASON");
// 2.3. Hide it
agent.setVisibility(View.GONE);
// 2.3. Set Payload
JSONObject payload = new JSONObject();
// 2.3.1. copy options
for (Iterator<String> iterator = options.keys(); iterator.hasNext(); ) {
String key = iterator.next();
Object value = options.get(key);
payload.put(key, value);
}
// 2.3.2. Add 'id' and 'state'
payload.put("to", id);
payload.put("state", "empty");
payload.put("parent", ((JasonViewActivity)context).model.url);
// 2.3.3. Set
agent.setTag(payload);
// 2.4. Attach to the parent view
context.agents.put(id, agent);
}
/*******************************************
3. Filling the WebView with content
- Is the state "empty"?
YES => Load
NO => Ignore
*******************************************/
JSONObject payload = (JSONObject)agent.getTag();
// Fill in the content if empty
if(payload.has("state") && payload.getString("state").equalsIgnoreCase("empty")) {
if (options.has("text")) {
String html = options.getString("text");
agent.loadDataWithBaseURL("http://localhost/", html, "text/html", "utf-8", null);
} else if (options.has("url")) {
String url = options.getString("url");
// 1. file url
if (url.startsWith("file://")) {
agent.loadUrl("file:///android_asset/file/" + url.substring(7));
// 2. remote url
} else {
if (context.savedInstance) {
agent.loadUrl(url);
}
}
}
}
} catch (Exception e) {
agent = new WebView(context);
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
}
return agent;
}
public void jason_request(final JSONObject jason_request, Context context) {
request(jason_request, null, context);
}
public void request(final JSONObject jason_request, final JSONObject agent_request, Context context) {
try {
/*****************************
1. jason_request is an entire Jasonette action which contains a JSON-RPC object as its options
jason_request := {
"type": "$agent.request",
"options": [JSON-RPC Object],
"success": [Next Jasonette Action]
}
2. agent_request is a JSON-RPC object
agent_request := {
"from": [SOURCE AGENT ID],
"request": [JSON-RPC Object],
"nonce": [NONCE]
}
*****************************/
/***
0. Check if it's jason_request or agent_request
- If jason_request => Use this to proceed
- If agent_request => Use this to proceed
1. Get JSON-RPC arguments
- id
- method
- params
2. Find the agent by ID
- iF agent exists, go on.
3. Set the $source on the agent's payload (tag)
4. Create a JavaScript call string
5. Run the call script
***/
// Get JSON RPC object
JSONObject jsonrpc;
if (jason_request != null) {
/**
1. jason_request is an entire Jasonette action which contains a JSON-RPC object as its options
jason_request := {
"type": "$agent.request",
"options": [JSON-RPC Object],
"success": [Next Jasonette Action]
}
**/
jsonrpc = jason_request.getJSONObject("options");
} else {
/**
2. agent_request is a JSON-RPC object
agent_request := {
"from": [SOURCE AGENT ID],
"request": [JSON-RPC Object],
"nonce": [NONCE]
}
**/
jsonrpc = agent_request.getJSONObject("request");
}
if (jsonrpc.has("id")) {
String identifier = jsonrpc.getString("id");
// Special case handling for $webcontainers (For sandboxing per view)
if (identifier.equalsIgnoreCase("$webcontainer")) {
identifier = "$webcontainer@" + ((JasonViewActivity)context).model.url;
}
if(((JasonViewActivity)context).agents.has(identifier)) {
// Find agent by ID
final WebView agent = (WebView)((JasonViewActivity)context).agents.get(identifier);
/**
A transaction looks like this:
{
"state": "empty",
"to": [Agent ID],
"from": [Desitnation Agent ID],
"nonce": [NONCE],
"jason": [The original Jason action that triggered everything],
"request": [JSON RPC object]
}
**/
// Set Transaction payload
// 1. Initialize
JSONObject transaction;
if (agent.getTag() != null) {
transaction = (JSONObject)agent.getTag();
} else {
transaction = new JSONObject();
}
// 2. Fill in
if (jason_request != null) {
// 2.1. From: Set it as the caller Jasonette action
transaction.put("from", null);
// 2.2. Nonce
transaction.put("nonce", null);
// 2.3. Original JASON Caller Action
transaction.put("jason", jason_request);
} else {
// 2.1. From: Set it as the caller agent ID
if (agent_request.has("from")) {
transaction.put("from", agent_request.getString("from"));
}
// 2.2. Nonce
if (agent_request.has("nonce")) {
transaction.put("nonce", agent_request.getString("nonce"));
}
}
agent.setTag(transaction);
// Create a JS call string
String params = "null";
if (jsonrpc.has("method")) {
String method = jsonrpc.getString("method");
if (jsonrpc.has("params")) {
params = jsonrpc.getJSONArray("params").toString();
}
final String callstring = method + ".apply(this, " + params + ");";
((JasonViewActivity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
agent.evaluateJavascript(callstring, null);
} else {
agent.loadUrl("javascript:" + callstring);
}
}
});
return;
}
} else {
// If the agent is not yet ready, put it in a pending queue,
// this will be triggered later when the webview becomes ready
JSONObject q = new JSONObject();
q.put("jason_request", jason_request);
q.put("agent_request", agent_request);
pending.put(identifier, q);
}
}
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
}
}
public void refresh(final JSONObject action, final Context context) {
// Get JSON RPC object
/**
action := {
"type": "$agent.refresh",
"options": {
"id": [AGENT ID]
},
"success": [Next Jasonette Action]
}
**/
try {
JSONObject jsonrpc = action.getJSONObject("options");
if (jsonrpc.has("id")) {
String identifier = jsonrpc.getString("id");
if (identifier.equalsIgnoreCase("$webcontainer")) {
identifier = "$webcontainer@" + ((JasonViewActivity) context).model.url;
}
if (((JasonViewActivity) context).agents.has(identifier)) {
final WebView agent = (WebView) ((JasonViewActivity) context).agents.get(identifier);
// Find agent by ID
((JasonViewActivity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
agent.loadUrl(agent.getUrl());
}
});
JasonHelper.next("success", action, new JSONObject(), new JSONObject(), context);
return;
}
}
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
}
JasonHelper.next("error", action, new JSONObject(), new JSONObject(), context);
}
public void clear(final JSONObject action, final Context context) {
// Get JSON RPC object
/**
action := {
"type": "$agent.clear",
"options": {
"id": [AGENT ID]
},
"success": [Next Jasonette Action]
}
**/
try {
JSONObject jsonrpc = action.getJSONObject("options");
if (jsonrpc.has("id")) {
String identifier = jsonrpc.getString("id");
if (identifier.equalsIgnoreCase("$webcontainer")) {
identifier = "$webcontainer@" + ((JasonViewActivity) context).model.url;
}
if (((JasonViewActivity) context).agents.has(identifier)) {
// Find agent by ID
final WebView agent = (WebView) ((JasonViewActivity) context).agents.get(identifier);
((JasonViewActivity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONObject newTag = (JSONObject)agent.getTag();
newTag.put("state", "empty");
agent.setTag(newTag);
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
}
agent.loadUrl("about:blank");
}
});
JasonHelper.next("success", action, new JSONObject(), new JSONObject(), context);
return;
}
}
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
}
JasonHelper.next("error", action, new JSONObject(), new JSONObject(), context);
}
/*************************************
$agent.inject: Inject JavaScript into $agent context
{
"type": "$agent.inject",
"options": {
"id": "app",
"items": [{
"url": "file://authentication.js"
}]
},
"success": {
"type": "$agent.request",
"options": {
"id": "app",
"method": "login",
"params": ["eth", "12341234"]
}
}
}
*************************************/
public void inject(final JSONObject action, final Context context) {
// id
// items
try {
JSONObject options = action.getJSONObject("options");
if (options.has("id")) {
String identifier = options.getString("id");
if (identifier.equalsIgnoreCase("$webcontainer")) {
identifier = "$webcontainer@" + ((JasonViewActivity) context).model.url;
}
if (((JasonViewActivity) context).agents.has(identifier)) {
final WebView agent = (WebView) ((JasonViewActivity) context).agents.get(identifier);
if (options.has("items")) {
JSONArray items = options.getJSONArray("items");
CountDownLatch latch = new CountDownLatch(items.length());
ExecutorService taskExecutor = Executors.newFixedThreadPool(items.length());
ArrayList<String> codes = new ArrayList<String>();
for (int i=0; i<items.length(); i++) {
codes.add("");
}
ArrayList<String> errors = new ArrayList<String>();
for (int i=0; i<items.length(); i++) {
final JSONObject item = items.getJSONObject(i);
taskExecutor.submit(new Fetcher(latch, item, i, codes, errors, context));
}
try {
latch.await();
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
}
// All finished. Now can utilize codes
String code_string = "";
for(String s : codes) {
code_string = code_string + s + "\n";
}
final String codestr = code_string;
((JasonViewActivity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
agent.evaluateJavascript(codestr, null);
} else {
agent.loadUrl("javascript:" + codestr);
}
JasonHelper.next("success", action, new JSONObject(), new JSONObject(), context);
}
});
} else {
JSONObject error = new JSONObject();
error.put("message", "need to specify items");
JasonHelper.next("error", action, error, new JSONObject(), context);
}
} else {
pending_injections.put(identifier, action);
}
}
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
}
}
class Fetcher implements Runnable {
CountDownLatch latch;
JSONObject item;
ArrayList<String> errors;
ArrayList<String> codes;
Context context;
int index;
public Fetcher(CountDownLatch latch, JSONObject item, int index, ArrayList<String> codes, ArrayList<String> errors, Context context) {
this.latch = latch;
this.item = item;
this.context = context;
this.index = index;
this.codes = codes;
this.errors = errors;
}
public void run() {
try {
if (item.has("url")) {
String url = item.getString("url");
if (url.startsWith("file://")) {
fetch_local(url, context);
} else if (url.startsWith("http")) {
fetch_remote(url, context);
} else {
errors.add("url must be either file:// or http:// or https://");
latch.countDown();
}
} else if (item.has("text")) {
String code = item.getString("text");
codes.set(index, code);
latch.countDown();
}
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
latch.countDown();
}
}
public void fetch_local(final String url, final Context context){
try {
Runnable r = new Runnable()
{
@Override
public void run()
{
try {
String code = JasonHelper.read_file_scheme(url, context);
codes.set(index, code);
latch.countDown();
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
errors.add("Couldn't read the file");
}
}
};
Thread t = new Thread(r);
t.start();
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
latch.countDown();
}
}
private void fetch_remote(String url, Context context){
try{
Request request;
Request.Builder builder = new Request.Builder();
request = builder.url(url).build();
OkHttpClient client = ((Launcher)((JasonViewActivity)context).getApplication()).getHttpClient(0);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
errors.add("Failed to fetch from url");
latch.countDown();
e.printStackTrace();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
try {
if (!response.isSuccessful()) {
errors.add("Response was not successful");
latch.countDown();
} else {
String code = response.body().string();
codes.set(index, code);
latch.countDown();
}
} catch (Exception e) {
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
latch.countDown();
}
}
});
} catch (Exception e){
Log.d("Warning", e.getStackTrace()[0].getMethodName() + " : " + e.toString());
latch.countDown();
}
}
}
}
| mit |
feliposz/spoj-solutions | java/ADDREV.java | 2427 | /*
SPOJ Problem Set (classical)
42. Adding Reversed Numbers
Problem code: ADDREV
The Antique Comedians of Malidinesia prefer comedies to tragedies.
Unfortunately, most of the ancient plays are tragedies. Therefore the
dramatic advisor of ACM has decided to transfigure some tragedies into
comedies. Obviously, this work is very hard because the basic sense of
the play must be kept intact, although all the things change to their
opposites. For example the numbers: if any number appears in the
tragedy, it must be converted to its reversed form before being
accepted into the comedy play.
Reversed number is a number written in arabic numerals but the order
of digits is reversed. The first digit becomes last and vice versa.
For example, if the main hero had 1245 strawberries in the tragedy,
he has 5421 of them now. Note that all the leading zeros are omitted.
That means if the number ends with a zero, the zero is lost by
reversing (e.g. 1200 gives 21). Also note that the reversed number
never has any trailing zeros.
ACM needs to calculate with reversed numbers. Your task is to add two
reversed numbers and output their reversed sum. Of course, the result
is not unique because any particular number is a reversed form of
several numbers (e.g. 21 could be 12, 120 or 1200 before reversing).
Thus we must assume that no zeros were lost by reversing (e.g. assume
that the original number was 12).
Input
The input consists of N cases (equal to about 10000). The first line
of the input contains only positive integer N. Then follow the cases.
Each case consists of exactly one line with two positive integers
separated by space. These are the reversed numbers you are to add.
Output
For each case, print exactly one line containing only one integer -
the reversed sum of two reversed numbers. Omit any leading zeros in
the output.
Example
Sample input:
3
24 1
4358 754
305 794
Sample output:
34
1998
1
*/
import java.util.*;
class ADDREV {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cases = sc.nextInt();
for (int i = 0; i < cases; i++) {
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int addrev = reverseNum(reverseNum(n1) + reverseNum(n2));
System.out.println(addrev);
}
}
private static int reverseNum(int num) {
int reversed = 0;
while (num > 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return reversed;
}
} | mit |
AncientMariner/Java_Nuggets | src/main/java/org/xander/FileChangeNotification.java | 3206 | package org.xander;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.FileTime;
import java.util.Calendar;
public class FileChangeNotification {
public static void main(String[] args) {
// watcher();
anotherWatcher();
}
private static void watcher() {
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("/home/xander/test/");
//registration for file/directory
//registration is done on the object being watched. In this case the Path class
dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
// poll for changes in a loop
while (true) {
// blocking. Unblocks as soon as stuff is created in the Directory
WatchKey key = watchService.take();
//iterate and process the events, they can be identified by their kind:
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
Path path = (Path) event.context();
System.out.println("additional info" + path.getFileSystem());
System.out.println("new entry " + path);
}
}
// must reset key in order to signal the watcher to keep monitoring the directory
key.reset();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void anotherWatcher() {
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("/home/xander/test/");
dir.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
FileTime lastModified = null;
while (true) {
WatchKey key = watchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
FileTime time = Files.getLastModifiedTime(dir.resolve(Paths.get("file.txt")));
if (lastModified == null) {
lastModified = time;
}
if (lastModified.compareTo(time) < 0) {
System.out.println("reload");
lastModified = time;
Calendar date = Calendar.getInstance();
date.setTimeInMillis(time.toMillis());
System.out.println("time is " + date.getTime() + "\n");
} else {
System.out.println("reload skipped");
}
}
}
key.reset();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
| mit |
jurgendl/hql-builder | hql-builder/hql-builder-demo/hql-builder-common-demo/src/main/java/org/tools/hqlbuilder/demo/package-info.java | 229 | @javax.xml.bind.annotation.XmlAccessorOrder(javax.xml.bind.annotation.XmlAccessOrder.ALPHABETICAL)
@javax.xml.bind.annotation.XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
package org.tools.hqlbuilder.demo;
| mit |
mythmayor/MyPreviousProjectFrame | app/src/main/java/com/mythmayor/mypreviousprojectframe/bean/UserLoginBean.java | 494 | package com.mythmayor.mypreviousprojectframe.bean;
/**
* Created by mythm on 2016/12/14.
*/
public class UserLoginBean {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| mit |
TheReturningVoid/bloodmoney | src/main/java/net/thereturningvoid/bloodmoney/listeners/PlayerDeathListener.java | 3594 | package net.thereturningvoid.bloodmoney.listeners;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import net.milkbowl.vault.permission.Permission;
import net.thereturningvoid.bloodmoney.BloodMoney;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import java.util.Map;
public class PlayerDeathListener implements Listener {
private BloodMoney plugin;
private Economy econ;
private Permission perm;
public PlayerDeathListener(BloodMoney instance) {
plugin = instance;
econ = instance.economy;
perm = instance.permission;
}
@EventHandler
public void onKillPlayer(PlayerDeathEvent e) throws InvalidConfigurationException {
if (e.getEntityType() == EntityType.PLAYER) {
Player pKilled = e.getEntity();
Player pKilledBy = pKilled.getKiller();
if (pKilledBy.getName().equals(pKilled.getName())) return;
if (pKilled.getKiller() != null && getRanks() != null) {
if (plugin.getConfig().getBoolean("bloodmoney.sendMessageToDeadPlayer") && !plugin.getConfig().getBoolean("bloodmoney.loseMoneyOnDeath")) {
String dMessage = plugin.getConfig().getString("bloodmoney.deathMessage").replace("%p", pKilledBy.getName());
pKilled.sendMessage(BloodMoney.CHAT_PREFIX + dMessage);
}
for (Map.Entry rank : getRanks().entrySet()) {
String rankName = (String) rank.getKey();
if (perm.has(pKilledBy, "bloodmoney.rank." + rank.getKey())) {
EconomyResponse creditPlayer = econ.depositPlayer(pKilledBy, plugin.getConfig().getDouble("bloodmoney.ranks." + rankName + ".gain"));
if (creditPlayer.transactionSuccess()) {
String kMessage = plugin.getConfig().getString("bloodmoney.killMessage").replace("%m", econ.format(creditPlayer.amount)).replace("%p", pKilled.getName());
pKilledBy.sendMessage(BloodMoney.CHAT_PREFIX + kMessage);
} else {
pKilledBy.sendMessage(BloodMoney.CHAT_PREFIX + "Something went wrong and the transaction was unsuccessful.");
}
}
if (plugin.getConfig().getBoolean("bloodmoney.loseMoneyOnDeath")) {
if (perm.has(pKilled, "bloodmoney.rank." + rank.getKey())) {
EconomyResponse takeFromPlayer = econ.withdrawPlayer(pKilled, plugin.getConfig().getDouble("bloodmoney.ranks." + rankName + ".loss"));
if (takeFromPlayer.transactionSuccess()) {
String kMessage2 = plugin.getConfig().getString("bloodmoney.deathMessage").replace("%p", pKilledBy.getName()).replace("%m", econ.format(takeFromPlayer.amount));
pKilled.sendMessage(BloodMoney.CHAT_PREFIX + kMessage2);
}
}
}
}
}
}
}
private Map<String, Object> getRanks() {
if (plugin.getConfig().isConfigurationSection("bloodmoney.ranks")) {
return plugin.getConfig().getConfigurationSection("bloodmoney.ranks").getValues(false);
} else return null;
}
}
| mit |
Ergzay/multibit | src/test/java/org/multibit/utils/VersionComparatorTest.java | 4269 | /**
* Copyright 2012 multibit.org
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.multibit.utils;
import junit.framework.TestCase;
import org.junit.Test;
public class VersionComparatorTest extends TestCase {
@Test
public void testRegular() throws Exception {
VersionComparator comparator = new VersionComparator();
assertTrue(comparator.compare("0.0.1", "0.0.1") == 0);
assertTrue(comparator.compare("0.0.2", "0.0.1") == 1);
assertTrue(comparator.compare("0.0.1", "0.0.2") == -1);
assertTrue(comparator.compare("0.1", "0.1") == 0);
assertTrue(comparator.compare("0.2", "0.1") == 1);
assertTrue(comparator.compare("0.1", "0.2") == -1);
assertTrue(comparator.compare("1.0", "1.0") == 0);
assertTrue(comparator.compare("2.0", "1.0") == 1);
assertTrue(comparator.compare("1.0", "2.0") == -1);
assertTrue(comparator.compare("1.4", "1.4") == 0);
assertTrue(comparator.compare("2.4", "2.3") == 1);
assertTrue(comparator.compare("2.3", "2.4") == -1);
assertTrue(comparator.compare("1.4.7", "1.4.7") == 0);
assertTrue(comparator.compare("1.4.8", "1.4.7") == 1);
assertTrue(comparator.compare("1.4.7", "1.4.8") == -1);
}
@Test
public void testAlpha() throws Exception {
VersionComparator comparator = new VersionComparator();
assertTrue(comparator.compare("0.0.1alpha", "0.0.1alpha") == 0);
assertTrue(comparator.compare("0.0.1", "0.0.1alpha") == 1);
assertTrue(comparator.compare("0.0.1alpha", "0.0.1") == -1);
assertTrue(comparator.compare("0.0.1alpha2", "0.0.1alpha2") == 0);
assertTrue(comparator.compare("0.0.1alpha2", "0.0.1alpha1") == 1);
assertTrue(comparator.compare("0.0.1alpha1", "0.0.1alpha2") == -1);
assertTrue(comparator.compare("0.1alpha", "0.1alpha") == 0);
assertTrue(comparator.compare("0.1", "0.1alpha") == 1);
assertTrue(comparator.compare("0.2", "0.1alpha") == 1);
assertTrue(comparator.compare("0.1alpha", "0.1") == -1);
assertTrue(comparator.compare("0.4.6", "0.5.0alpha") == -1);
}
@Test
public void testBeta() throws Exception {
VersionComparator comparator = new VersionComparator();
assertTrue(comparator.compare("0.0.1beta", "0.0.1beta") == 0);
assertTrue(comparator.compare("0.0.1", "0.0.1beta") == 1);
assertTrue(comparator.compare("0.0.1alpha", "0.0.1") == -1);
assertTrue(comparator.compare("0.0.1beta2", "0.0.1beta2") == 0);
assertTrue(comparator.compare("0.0.1beta2", "0.0.1beta1") == 1);
assertTrue(comparator.compare("0.0.1beta1", "0.0.1beta2") == -1);
assertTrue(comparator.compare("0.0.1alpha1", "0.0.1beta1") == -1);
assertTrue(comparator.compare("0.0.1alpha2", "0.0.1beta1") == -1);
}
@Test
public void testReleaseCandidate() throws Exception {
VersionComparator comparator = new VersionComparator();
assertTrue(comparator.compare("0.0.1rc", "0.0.1rc") == 0);
assertTrue(comparator.compare("0.0.1", "0.0.1rc") == 1);
assertTrue(comparator.compare("0.0.1rc", "0.0.1") == -1);
assertTrue(comparator.compare("0.0.1rc2", "0.0.1rc2") == 0);
assertTrue(comparator.compare("0.0.1rc2", "0.0.1rc1") == 1);
assertTrue(comparator.compare("0.0.1rc1", "0.0.1rc2") == -1);
assertTrue(comparator.compare("0.0.1rc1", "0.0.1beta1") == 1);
assertTrue(comparator.compare("0.0.1rc1", "0.0.1beta2") == 1);
assertTrue(comparator.compare("0.0.1rc2", "0.0.1alpha1") == 1);
assertTrue(comparator.compare("0.0.1rc2", "0.0.1alpha2") == 1);
}
}
| mit |
asposeforcloud/Aspose_Cloud_SDK_For_Java | Aspose.Cloud.SDK/src/com/aspose/cloud/pdf/TextItemResponse.java | 311 | /**
*
*/
package com.aspose.cloud.pdf;
/**
* @author Mudassir
*
*/
/// <summary>
/// represents response of a single text item
/// </summary>
public class TextItemResponse extends com.aspose.cloud.common.BaseResponse
{
private TextItem textItem;
public TextItem getTextItem(){return textItem;}
} | mit |
ScreenBasedSimulator/ScreenBasedSimulator2 | src/main/java/mil/tatrc/physiology/datamodel/bind/ScalarPressurePerVolumeData.java | 1265 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.12.09 at 06:16:52 PM EST
//
package mil.tatrc.physiology.datamodel.bind;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ScalarPressurePerVolumeData complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ScalarPressurePerVolumeData">
* <complexContent>
* <restriction base="{uri:/mil/tatrc/physiology/datamodel}ScalarData">
* <attribute name="unit" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ScalarPressurePerVolumeData")
public class ScalarPressurePerVolumeData
extends ScalarData
{
}
| mit |
farinc/FrameUtils | src/main/java/com/farincorporated/items/FocusedEnderlocatePlate.java | 761 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.farincorporated.items;
import com.farincorporated.framezaddon.FramezAddon;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
/**
*
* @author coolestbean
*/
public class FocusedEnderlocatePlate extends Item{
public FocusedEnderlocatePlate() {}
@SideOnly(Side.CLIENT)
@Override
public void registerIcons(IIconRegister reg)
{
this.itemIcon = reg.registerIcon(FramezAddon.MODID + ":enderplate");
}
}
| mit |
plankt/slingshot | core/src/se/slingshot/gui/Gui.java | 843 | package se.slingshot.gui;
import com.badlogic.gdx.scenes.scene2d.Stage;
import se.slingshot.interfaces.FuelInterface;
/**
* In-game gui. Renders all static graphics.
*
* @author Marc
* @since 2015-12
*/
public class Gui {
private Stage stage;
private FuelBar fuelBar;
public void create(FuelInterface fuel) {
stage = new Stage();
fuelBar = new FuelBar(fuel);
fuelBar.setPosition(0, 0);
fuelBar.setSize(stage.getWidth(), stage.getHeight() / 50);
stage.addActor(fuelBar);
}
public void resize(int width, int height) {
stage.getViewport().update(width, height);
fuelBar.setSize(width, height / 50);
}
public void render(float delta) {
stage.act(delta);
stage.draw();
}
public void dispose() {
stage.dispose();
}
}
| mit |
manorius/Processing | libraries/igeo/src/igeo/gui/IGraphicsGL.java | 1014 | /*---
iGeo - http://igeo.jp
Copyright (c) 2002-2013 Satoru Sugihara
This file is part of iGeo.
iGeo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, version 3.
iGeo 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 iGeo. If not, see <http://www.gnu.org/licenses/>.
---*/
package igeo.gui;
import igeo.*;
import javax.media.opengl.*;
/**
Interface of Graphics to draw 3D geometry with OpenGL
@author Satoru Sugihara
*/
public interface IGraphicsGL extends IGraphics3D{
public GL getGL();
public void setGL(GL g);
public void setBGImage(String imageFilename);
}
| mit |
frazer-rbsn/Kukuba | KukubaCreator/src/main/java/org/kukucorp/kukubacreator/app/IIndexEvent.java | 156 | package org.kukucorp.kukubacreator.app;
/**
* Created by Frazer on 17/08/2014.
*/
public interface IIndexEvent
{
void eventFired(int i, Object o);
}
| mit |
loic-fejoz/shapebuilder-java | src/turtle/TurtleInterpreter.java | 2364 | package turtle;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import shapegrammar.Axiom;
import shapegrammar.Interpreter;
import shapegrammar.Node;
import shapegrammar.Rule;
public class TurtleInterpreter<R extends Turtle> extends Interpreter<R> {
protected Map<Character, UserRuleDeclaration<R>> userRules = new HashMap<>();
private Map<Character, StochasticUserRuleDeclaration<R>> stochasticRule = new HashMap<>();
public TurtleInterpreter(final Random rnd) {
super(rnd);
}
public TurtleInterpreter() {
this(new Random());
}
public void declareRule(final char name, final UserRuleDeclaration<R> ruleDecl) {
userRules.put(name, ruleDecl);
}
public void declareRule(char name, StochasticUserRuleDeclaration<R> ruleDecl) {
stochasticRule.put(name, ruleDecl);
}
public Node<? super R> createAxiom(final String axioms) {
return new Axiom<R>(interpret(axioms));
}
public List<Node<? super R>> interpret(final String extension) {
final List<Node<? super R>> axiomsList = new LinkedList<>();
for(char c: extension.toCharArray()) {
if (userRules.containsKey(c)) {
final Node<? super R> child = new UserRule<R>(this, userRules.get(c));
axiomsList.add(child);
} else if (stochasticRule.containsKey(c)) {
final Node<? super R> child = new StochasticUserRule<>(this, stochasticRule.get(c));
axiomsList.add(child);
} else {
switch(c) {
case 'F':
axiomsList.add(new FConstant());
break;
case '+':
axiomsList.add(new PlusConstant());
break;
case '-':
axiomsList.add(new MinusConstant());
break;
case '[':
axiomsList.add(new PushConstant());
break;
case ']':
axiomsList.add(new PopConstant());
break;
default:
throw new IllegalArgumentException("Unknown: " + c);
}
}
}
return axiomsList;
}
public void writeToFile(
final Node<? super Turtle> axiom,
final String path,
final double defaultAngle
) throws IOException {
final FileWriter output = new FileWriter(new File(path));
final SVGTurtle svgTurtle = new SVGTurtle(output);
svgTurtle.setDefaultAngle(defaultAngle);
axiom.render(svgTurtle);
svgTurtle.close();
output.close();
}
}
| mit |