repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
sdcote/loader | src/test/java/coyote/i13n/EventListTest.java | 4336 | /*
* Copyright (c) 2014 Stephan D. Cote' - All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the MIT License which accompanies this distribution, and is
* available at http://creativecommons.org/licenses/MIT/
*
* Contributors:
* Stephan D. Cote
* - Initial concept and implementation
*/
package coyote.i13n;
//import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.AfterClass;
import org.junit.Test;
/**
*
*/
public class EventListTest {
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {}
/**
* Test method for {@link coyote.i13n.EventList#lastSequence()}.
*/
//@Test
public void testLastSequence() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#EventList()}.
*/
//@Test
public void testEventList() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getMaxEvents()}.
*/
@Test
public void testGetMaxEvents() {
EventList list = new EventList();
list.setMaxEvents( 5 );
AppEvent alert0 = list.createEvent( "Zero" );
AppEvent alert1 = list.createEvent( "One" );
AppEvent alert2 = list.createEvent( "Two" );
AppEvent alert3 = list.createEvent( "Three" );
AppEvent alert4 = list.createEvent( "Four" );
AppEvent alert5 = list.createEvent( "Five" );
AppEvent alert6 = list.createEvent( "Six" );
//System.out.println( "Max="+list.getMaxEvents()+" Size=" + list.getSize() );
assertTrue( list._list.size() == 5 );
// should result in the list being trimmed immediately
list.setMaxEvents( 2 );
assertTrue( list._list.size() == 2 );
list.add( alert0 );
list.add( alert1 );
list.add( alert2 );
list.add( alert3 );
list.add( alert4 );
list.add( alert5 );
list.add( alert6 );
// should still only contain 2 events
assertTrue( list._list.size() == 2 );
// Check the first and last event in the list
assertEquals( alert5, list.getFirst() );
assertEquals( alert6, list.getLast() );
}
/**
* Test method for {@link coyote.i13n.EventList#setMaxEvents(int)}.
*/
//@Test
public void testSetMaxEvents() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#add(coyote.i13n.AppEvent)}.
*/
//@Test
public void testAdd() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#remove(coyote.i13n.AppEvent)}.
*/
//@Test
public void testRemove() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#get(long)}.
*/
//@Test
public void testGet() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getFirst()}.
*/
//@Test
public void testGetFirst() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getLast()}.
*/
//@Test
public void testGetLast() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#getSize()}.
*/
//@Test
public void testGetSize() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#createEvent(java.lang.String, java.lang.String, java.lang.String, java.lang.String, int, int, int, java.lang.String)}.
*/
//@Test
public void testCreateEventStringStringStringStringIntIntIntString() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#createEvent(java.lang.String)}.
*/
//@Test
public void testCreateEventString() {
fail( "Not yet implemented" );
}
/**
* Test method for {@link coyote.i13n.EventList#createEvent(java.lang.String, int, int)}.
*/
//@Test
public void testCreateEventStringIntInt() {
fail( "Not yet implemented" );
}
}
| mit |
heyugtan/zteUI | ZTEUI/src/com/isme/zteui/cache/BitmapLruCache.java | 944 | package com.isme.zteui.cache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
/**
* Title: Volley 的缓存类</br><br>
* Description: </br><br>
* Copyright: Copyright(c)2003</br><br>
* Company: ihalma </br><br>
* @author and</br><br>
* @version 1 </br><br>
* data: 2015-3-17</br>
*/
public class BitmapLruCache implements ImageCache {
private LruCache<String, Bitmap> mCache;
/**
* 最大缓存 10 M
*/
public BitmapLruCache() {
int maxSize = 1024 * 1024 * 10; //最大缓存10M
mCache = new LruCache<String, Bitmap>(maxSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
}
@Override
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
}
| mit |
tomaszkowalczyk94/warhammer-rpg-helper | src/main/java/warhammerrpg/database/exception/DatabaseException.java | 335 | package warhammerrpg.database.exception;
import warhammerrpg.core.exception.WarhammerRpgException;
public class DatabaseException extends WarhammerRpgException {
public DatabaseException(Exception originalExceptionObject) {
super(originalExceptionObject);
}
public DatabaseException() {
super();
}
}
| mit |
BlockchainSociety/ethereumj-android | ethereumj-core-android/src/main/java/org/ethereum/android/service/ConnectorHandler.java | 240 | package org.ethereum.android.service;
import android.os.Message;
public interface ConnectorHandler {
boolean handleMessage(Message message);
void onConnectorConnected();
void onConnectorDisconnected();
String getID();
}
| mit |
accelazh/ThreeBodyProblem | lib/jME2_0_1-Stable/src/com/jme/curve/CurveController.java | 9311 | /*
* Copyright (c) 2003-2009 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme.curve;
import java.io.IOException;
import com.jme.math.Vector3f;
import com.jme.scene.Controller;
import com.jme.scene.Spatial;
import com.jme.util.export.InputCapsule;
import com.jme.util.export.JMEExporter;
import com.jme.util.export.JMEImporter;
import com.jme.util.export.OutputCapsule;
/**
* <code>CurveController</code> defines a controller that moves a supplied
* <code>Spatial</code> object along a curve. Attributes of the curve are set
* such as the up vector (if not set, the spacial object will roll along the
* curve), the orientation precision defines how accurate the orientation of the
* spatial will be.
* @author Mark Powell
* @version $Id: CurveController.java 4131 2009-03-19 20:15:28Z blaine.dev $
*/
public class CurveController extends Controller {
private static final long serialVersionUID = 1L;
private Spatial mover;
private Curve curve;
private Vector3f up;
private float orientationPrecision = 0.1f;
private float currentTime = 0.0f;
private float deltaTime = 0.0f;
private boolean cycleForward = true;
private boolean autoRotation = false;
/**
* Constructor instantiates a new <code>CurveController</code> object.
* The curve object that the controller operates on and the spatial object
* that is moved is specified during construction.
* @param curve the curve to operate on.
* @param mover the spatial to move.
*/
public CurveController(Curve curve, Spatial mover) {
this.curve = curve;
this.mover = mover;
setUpVector(new Vector3f(0,1,0));
setMinTime(0);
setMaxTime(Float.MAX_VALUE);
setRepeatType(Controller.RT_CLAMP);
setSpeed(1.0f);
}
/**
* Constructor instantiates a new <code>CurveController</code> object.
* The curve object that the controller operates on and the spatial object
* that is moved is specified during construction. The game time to
* start and the game time to finish is also supplied.
* @param curve the curve to operate on.
* @param mover the spatial to move.
* @param minTime the time to start the controller.
* @param maxTime the time to end the controller.
*/
public CurveController(
Curve curve,
Spatial mover,
float minTime,
float maxTime) {
this.curve = curve;
this.mover = mover;
setMinTime(minTime);
setMaxTime(maxTime);
setRepeatType(Controller.RT_CLAMP);
}
/**
*
* <code>setUpVector</code> sets the locking vector for the spatials up
* vector. This prevents rolling along the curve and allows for a better
* tracking.
* @param up the vector to lock as the spatials up vector.
*/
public void setUpVector(Vector3f up) {
this.up = up;
}
/**
*
* <code>setOrientationPrecision</code> sets a precision value for the
* spatials orientation. The smaller the number the higher the precision.
* By default 0.1 is used, and typically does not require changing.
* @param value the precision value of the spatial's orientation.
*/
public void setOrientationPrecision(float value) {
orientationPrecision = value;
}
/**
*
* <code>setAutoRotation</code> determines if the object assigned to
* the controller will rotate with the curve or just following the
* curve.
* @param value true if the object is to rotate with the curve, false
* otherwise.
*/
public void setAutoRotation(boolean value) {
autoRotation = value;
}
/**
*
* <code>isAutoRotating</code> returns true if the object is rotating with
* the curve and false if it is not.
* @return true if the object is following the curve, false otherwise.
*/
public boolean isAutoRotating() {
return autoRotation;
}
/**
* <code>update</code> moves a spatial along the given curve for along a
* time period.
* @see com.jme.scene.Controller#update(float)
*/
public void update(float time) {
if(mover == null || curve == null || up == null) {
return;
}
currentTime += time * getSpeed();
if (currentTime >= getMinTime() && currentTime <= getMaxTime()) {
if (getRepeatType() == RT_CLAMP) {
deltaTime = currentTime - getMinTime();
mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation()));
if(autoRotation) {
mover.setLocalRotation(
curve.getOrientation(
deltaTime,
orientationPrecision,
up));
}
} else if (getRepeatType() == RT_WRAP) {
deltaTime = (currentTime - getMinTime()) % 1.0f;
if (deltaTime > 1) {
currentTime = 0;
deltaTime = 0;
}
mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation()));
if(autoRotation) {
mover.setLocalRotation(
curve.getOrientation(
deltaTime,
orientationPrecision,
up));
}
} else if (getRepeatType() == RT_CYCLE) {
float prevTime = deltaTime;
deltaTime = (currentTime - getMinTime()) % 1.0f;
if (prevTime > deltaTime) {
cycleForward = !cycleForward;
}
if (cycleForward) {
mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation()));
if(autoRotation) {
mover.setLocalRotation(
curve.getOrientation(
deltaTime,
orientationPrecision,
up));
}
} else {
mover.setLocalTranslation(
curve.getPoint(1.0f - deltaTime,mover.getLocalTranslation()));
if(autoRotation) {
mover.setLocalRotation(
curve.getOrientation(
1.0f - deltaTime,
orientationPrecision,
up));
}
}
} else {
return;
}
}
}
public void reset() {
this.currentTime = 0;
}
public void write(JMEExporter e) throws IOException {
super.write(e);
OutputCapsule capsule = e.getCapsule(this);
capsule.write(mover, "mover", null);
capsule.write(curve, "Curve", null);
capsule.write(up, "up", null);
capsule.write(orientationPrecision, "orientationPrecision", 0.1f);
capsule.write(cycleForward, "cycleForward", true);
capsule.write(autoRotation, "autoRotation", false);
}
public void read(JMEImporter e) throws IOException {
super.read(e);
InputCapsule capsule = e.getCapsule(this);
mover = (Spatial)capsule.readSavable("mover", null);
curve = (Curve)capsule.readSavable("curve", null);
up = (Vector3f)capsule.readSavable("up", null);
orientationPrecision = capsule.readFloat("orientationPrecision", 0.1f);
cycleForward = capsule.readBoolean("cycleForward", true);
autoRotation = capsule.readBoolean("autoRotation", false);
}
}
| mit |
longluo/AndroidDemo | app/src/main/java/com/longluo/demo/qrcode/zxing/client/android/encode/Formatter.java | 1015 | /*
* Copyright (C) 2011 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.longluo.demo.qrcode.zxing.client.android.encode;
/**
* Encapsulates some simple formatting logic, to aid refactoring in {@link ContactEncoder}.
*
* @author Sean Owen
*/
interface Formatter {
/**
* @param value value to format
* @param index index of value in a list of values to be formatted
* @return formatted value
*/
CharSequence format(CharSequence value, int index);
}
| mit |
thekant/myCodeRepo | src/com/kant/datastructure/queues/GenerateBinaryNumbers1toN.java | 1022 | /**
*
*/
package com.kant.datastructure.queues;
import com.kant.sortingnsearching.MyUtil;
/**
* @author shaskant
*
*/
public class GenerateBinaryNumbers1toN {
/**
*
* @param n
* @return
* @throws OverFlowException
* @throws UnderFlowException
*/
public String[] solve(int n) throws OverFlowException, UnderFlowException {
String[] result = new String[n];
System.out.println("input # " + n);
Queue<String> dequeue = new QueueListImplementation<String>();
dequeue.enQueue("1");
for (int count = 0; count < n; count++) {
result[count] = dequeue.deQueue();
dequeue.enQueue(result[count]+"0");
dequeue.enQueue(result[count]+"1");
}
return result;
}
/**
*
* @param args
* @throws OverFlowException
* @throws UnderFlowException
*/
public static void main(String[] args) throws OverFlowException, UnderFlowException {
GenerateBinaryNumbers1toN prob = new GenerateBinaryNumbers1toN();
System.out.print("output # ");
MyUtil.printArrayType(prob.solve(10));
}
}
| mit |
baomidou/hibernate-plus | hibernate-plus/src/test/java/com/baomidou/hibernateplus/spring/vo/Vdemo.java | 1066 | package com.baomidou.hibernateplus.spring.vo;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.baomidou.hibernateplus.entity.Convert;
/**
* <p>
* Vdemo
* </p>
*
* @author Caratacus
* @date 2016-12-2
*/
public class Vdemo extends Convert implements Serializable {
protected Long id;
private String demo1;
private String demo2;
private String demo3;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDemo1() {
return demo1;
}
public void setDemo1(String demo1) {
this.demo1 = demo1;
}
public String getDemo2() {
return demo2;
}
public void setDemo2(String demo2) {
this.demo2 = demo2;
}
public String getDemo3() {
return demo3;
}
public void setDemo3(String demo3) {
this.demo3 = demo3;
}
} | mit |
rsmeral/semnet | SemNet/src/xsmeral/semnet/sink/RdbmsStoreFactory.java | 1465 | package xsmeral.semnet.sink;
import java.util.Properties;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.sail.rdbms.RdbmsStore;
/**
* Factory of {@link RdbmsStore} repositories.
* <br />
* Takes parameters corresponding to RdbmsStore {@linkplain RdbmsStore#RdbmsStore(java.lang.String, java.lang.String, java.lang.String, java.lang.String) constructor}:
* <ul>
* <li><code>driver</code> - FQN of JDBC driver</li>
* <li><code>url</code> - JDBC URL</li>
* <li><code>user</code> - DB user name</li>
* <li><code>password</code> - DB password</li>
* </ul>
* @author Ron Šmeral (xsmeral@fi.muni.cz)
*/
public class RdbmsStoreFactory extends RepositoryFactory {
@Override
public void initialize() throws RepositoryException {
Properties props = getProperties();
String jdbcDriver = props.getProperty("driver");
String url = props.getProperty("url");
String user = props.getProperty("user");
String pwd = props.getProperty("password");
if (jdbcDriver == null || url == null || user == null || pwd == null) {
throw new RepositoryException("Invalid parameters for repository");
} else {
Repository repo = new SailRepository(new RdbmsStore(jdbcDriver, url, user, pwd));
repo.initialize();
setRepository(repo);
}
}
}
| mit |
renzopalmieri/demomercaderia | spring-boot-2/src/main/java/com/test/SERVICE/MercaderiaService.java | 1116 | package com.test.SERVICE;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.DAO.IMercaderiaDAO;
import com.test.BEAN.Mercaderia;
@Service
public class MercaderiaService implements IMercaderiaService{
@Autowired
private IMercaderiaDAO mercaderiaDAO;
@Override
public List<Mercaderia> getAllMercaderia() {
return mercaderiaDAO.getAllMercaderia();
}
@Override
public Mercaderia getMercaderiaById(int mercaderiaId) {
Mercaderia merc = mercaderiaDAO.getMercaderiaById(mercaderiaId);
return merc;
}
@Override
public boolean createMercaderia(Mercaderia mercaderia) {
if (mercaderiaDAO.mercaderiaExists(mercaderia.getNombre())) {
return false;
} else {
mercaderiaDAO.createMercaderia(mercaderia);
return true;
}
}
@Override
public void updateMercaderia(Mercaderia mercaderia) {
// TODO Auto-generated method stub
mercaderiaDAO.updateMercaderia(mercaderia);
}
}
| mit |
gw4e/gw4e.project | bundles/gw4e-eclipse-plugin/src/org/gw4e/eclipse/builder/exception/SeverityConfigurationException.java | 1676 | package org.gw4e.eclipse.builder.exception;
/*-
* #%L
* gw4e
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2017 gw4e-project
* %%
* 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.
* #L%
*/
import org.gw4e.eclipse.builder.GW4EParser;
import org.gw4e.eclipse.builder.Location;
public class SeverityConfigurationException extends BuildPolicyConfigurationException {
/**
*
*/
private static final long serialVersionUID = 1L;
public SeverityConfigurationException(Location location, String message,ParserContextProperties p) {
super(location, message,p);
}
public int getProblemId () {
return GW4EParser.INVALID_SEVERITY;
}
}
| mit |
tobiasdiez/jabref | src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.java | 3726 | package org.jabref.gui.openoffice;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import org.jabref.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.logic.l10n.Localization;
import com.jgoodies.forms.builder.ButtonBarBuilder;
import com.jgoodies.forms.builder.FormBuilder;
import com.jgoodies.forms.layout.FormLayout;
/**
* Dialog for adding citation with page number info.
*/
class AdvancedCiteDialog {
private static boolean defaultInPar = true;
private boolean okPressed;
private final JDialog diag;
private final JTextField pageInfo = new JTextField(15);
public AdvancedCiteDialog(JabRefFrame parent) {
diag = new JDialog((JFrame) null, Localization.lang("Cite special"), true);
ButtonGroup bg = new ButtonGroup();
JRadioButton inPar = new JRadioButton(Localization.lang("Cite selected entries between parenthesis"));
JRadioButton inText = new JRadioButton(Localization.lang("Cite selected entries with in-text citation"));
bg.add(inPar);
bg.add(inText);
if (defaultInPar) {
inPar.setSelected(true);
} else {
inText.setSelected(true);
}
inPar.addChangeListener(changeEvent -> defaultInPar = inPar.isSelected());
FormBuilder builder = FormBuilder.create()
.layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref, 4dlu, pref"));
builder.add(inPar).xyw(1, 1, 3);
builder.add(inText).xyw(1, 3, 3);
builder.add(Localization.lang("Extra information (e.g. page number)") + ":").xy(1, 5);
builder.add(pageInfo).xy(3, 5);
builder.padding("10dlu, 10dlu, 10dlu, 10dlu");
diag.getContentPane().add(builder.getPanel(), BorderLayout.CENTER);
ButtonBarBuilder bb = new ButtonBarBuilder();
bb.addGlue();
JButton ok = new JButton(Localization.lang("OK"));
JButton cancel = new JButton(Localization.lang("Cancel"));
bb.addButton(ok);
bb.addButton(cancel);
bb.addGlue();
bb.padding("5dlu, 5dlu, 5dlu, 5dlu");
diag.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
diag.pack();
ActionListener okAction = actionEvent -> {
okPressed = true;
diag.dispose();
};
ok.addActionListener(okAction);
pageInfo.addActionListener(okAction);
inPar.addActionListener(okAction);
inText.addActionListener(okAction);
Action cancelAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
okPressed = false;
diag.dispose();
}
};
cancel.addActionListener(cancelAction);
builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE), "close");
builder.getPanel().getActionMap().put("close", cancelAction);
}
public void showDialog() {
diag.setLocationRelativeTo(diag.getParent());
diag.setVisible(true);
}
public boolean canceled() {
return !okPressed;
}
public String getPageInfo() {
return pageInfo.getText().trim();
}
public boolean isInParenthesisCite() {
return defaultInPar;
}
}
| mit |
mwcaisse/AndroidFT | aft-android/src/main/java/com/ricex/aft/android/request/AFTResponse.java | 1925 | package com.ricex.aft.android.request;
import org.springframework.http.HttpStatus;
public class AFTResponse<T> {
/** The successful response from the server */
private final T response;
/** The error response from the server */
private final String error;
/** The HttpStatus code of the response */
private final HttpStatus statusCode;
/** Whether or not this response is valid */
private final boolean valid;
/** Creates a new instance of AFTResponse, representing a successful response
*
* @param response The parsed response received from the server
* @param statusCode The status code of the response
*/
public AFTResponse(T response, HttpStatus statusCode) {
this.response = response;
this.statusCode = statusCode;
this.error = null;
valid = true;
}
/** Creates a new instance of AFTResponse, representing an invalid (error) response
*
* @param response The response (if any) received from the server
* @param error The error message received from the server
* @param statusCode The status code of the response
*/
public AFTResponse(T response, String error, HttpStatus statusCode) {
this.response = response;
this.error = error;
this.statusCode = statusCode;
valid = false;
}
/** Whether or not this response is valid
*
* @return True if the server returned Http OK (200), otherwise false
*/
public boolean isValid() {
return valid;
}
/** The response from the server if valid
*
* @return The response from the server
*/
public T getResponse() {
return response;
}
/** Returns the error received by the server, if invalid response
*
* @return The error the server returned
*/
public String getError() {
return error;
}
/** Return the status code received from the server
*
* @return the status code received from the server
*/
public HttpStatus getStatusCode() {
return statusCode;
}
}
| mit |
leerduo/ClubSeed | app/src/main/java/cn/edu/ustc/appseed/clubseed/activity/StarContentActivity.java | 2293 | package cn.edu.ustc.appseed.clubseed.activity;
/*
* Show the detail content of the event which you select.
* Why to use a custom toolbar instead of the default toolbar in ActionBarActivity?
* Because the custom toolbar is very convenient to edit it and good to unify the GUI.
*/
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import cn.edu.ustc.appseed.clubseed.R;
import cn.edu.ustc.appseed.clubseed.data.Event;
import cn.edu.ustc.appseed.clubseed.data.ViewActivityPhp;
import cn.edu.ustc.appseed.clubseed.fragment.NoticeFragment;
import cn.edu.ustc.appseed.clubseed.fragment.StarFragment;
import cn.edu.ustc.appseed.clubseed.utils.AppUtils;
public class StarContentActivity extends ActionBarActivity {
private Toolbar toolbar;
private TextView mTextView;
private ImageView mImageView;
private TextView nullTextView;
private Event mEvent;
int ID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_content);
toolbar = (Toolbar) findViewById(R.id.toolbar);
mTextView = (TextView) findViewById(R.id.textViewEventContent);
mImageView = (ImageView) findViewById(R.id.imgContent);
if (toolbar != null) {
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back));
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
ID = getIntent().getIntExtra(StarFragment.EXTRA_ID, 0);
mEvent = AppUtils.savedEvents.get(ID);
setTitle(mEvent.getTitle());
mTextView.setText(mEvent.getContent());
mImageView.setImageBitmap(mEvent.getBitmap());
}
}
| mit |
nindalf/smbc-droid | app/src/main/java/com/smbc/droid/MainActivity.java | 1709 | package com.smbc.droid;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.android.volley.toolbox.NetworkImageView;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ComicPagerAdapter adapter = new ComicPagerAdapter( getSupportFragmentManager());
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
// findViewById(R.id.btn_next).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// viewPager.setCurrentItem(viewPager.getCurrentItem()+1, true);
// }
// });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| mit |
Zedai/APCOMSCI | ApComSci/pictures_lab/lab/IntArrayWorker.java | 2755 | package lab;
public class IntArrayWorker
{
/** two dimensional matrix */
private int[][] matrix = null;
/** set the matrix to the passed one
* @param theMatrix the one to use
*/
public void setMatrix(int[][] theMatrix)
{
matrix = theMatrix;
}
/**
* Method to return the total
* @return the total of the values in the array
*/
public int getTotal()
{
int total = 0;
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length; col++)
{
total = total + matrix[row][col];
}
}
return total;
}
/**
* Method to return the total using a nested for-each loop
* @return the total of the values in the array
*/
public int getTotalNested()
{
int total = 0;
for (int[] rowArray : matrix)
{
for (int item : rowArray)
{
total = total + item;
}
}
return total;
}
/**
* Method to fill with an increasing count
*/
public void fillCount()
{
int numCols = matrix[0].length;
int count = 1;
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < numCols; col++)
{
matrix[row][col] = count;
count++;
}
}
}
/**
* print the values in the array in rows and columns
*/
public void print()
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length; col++)
{
System.out.print( matrix[row][col] + " " );
}
System.out.println();
}
System.out.println();
}
public int getCount(int num){
int count = 0;
for(int row = 0; row < matrix.length; row++)
for(int col = 0; col < matrix[0].length; col++)
if(matrix[row][col] == num)
count++;
return count;
}
public int getColTotal(int col){
int total = 0;
for(int row = 0; row < matrix.length; row++)
total += matrix[row][col];
return total;
}
public int getLargest(){
int largest = matrix[0][0];
for(int row = 0; row < matrix.length; row++)
for(int col = 0; col < matrix[0].length; col++)
if(matrix[row][col] > largest)
largest = matrix[row][col];
return largest;
}
/**
* fill the array with a pattern
*/
public void fillPattern1()
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length;
col++)
{
if (row < col)
matrix[row][col] = 1;
else if (row == col)
matrix[row][col] = 2;
else
matrix[row][col] = 3;
}
}
}
} | mit |
3mmarg97/LaravelStorm | src/com/smartbit8/laravelstorm/run/LaravelRunConf.java | 6140 | package com.smartbit8.laravelstorm.run;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.ide.browsers.*;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter;
import com.intellij.util.xmlb.XmlSerializer;
import com.jetbrains.php.config.interpreters.PhpInterpreter;
import com.jetbrains.php.config.interpreters.PhpInterpretersManagerImpl;
import com.smartbit8.laravelstorm.ui.LaravelRunConfSettingsEditor;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
public class LaravelRunConf extends RunConfigurationBase {
private Project project;
private String host = "localhost";
private int port = 8000;
private String route = "/";
private WebBrowser browser;
private PhpInterpreter interpreter;
LaravelRunConf(@NotNull Project project, @NotNull ConfigurationFactory factory, String name) {
super(project, factory, name);
this.project = project;
}
@Override
public void createAdditionalTabComponents(AdditionalTabComponentManager manager, ProcessHandler startedProcess) {
LogTab logTab = new LogTab(getProject());
manager.addAdditionalTabComponent(logTab, "Laravel.log");
startedProcess.addProcessListener(new ProcessAdapter() {
@Override
public void startNotified(ProcessEvent event) {
logTab.start();
}
@Override
public void processTerminated(ProcessEvent event) {
startedProcess.removeProcessListener(this);
}
});
}
@Override
public void readExternal(Element element) throws InvalidDataException {
super.readExternal(element);
Settings settings = XmlSerializer.deserialize(element, Settings.class);
this.host = settings.host;
this.port = settings.port;
this.route = settings.route;
this.browser = WebBrowserManager.getInstance().findBrowserById(settings.browser);
this.interpreter = PhpInterpretersManagerImpl.getInstance(getProject()).findInterpreter(settings.interpreterName);
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
Settings settings = new Settings();
settings.host = this.host;
settings.port = this.port;
settings.route = this.route;
if (this.browser != null)
settings.browser = this.browser.getId().toString();
else
settings.browser = "";
if (this.interpreter != null)
settings.interpreterName = this.interpreter.getName();
else
settings.interpreterName = "";
XmlSerializer.serializeInto(settings, element, new SkipDefaultsSerializationFilter());
super.writeExternal(element);
}
@NotNull
@Override
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return new LaravelRunConfSettingsEditor(getProject());
}
@Override
public void checkConfiguration() throws RuntimeConfigurationException {}
@Nullable
@Override
public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) throws ExecutionException {
return new CommandLineState(executionEnvironment) {
@NotNull
@Override
protected ProcessHandler startProcess() throws ExecutionException {
String phpExec = (interpreter != null? interpreter.getPathToPhpExecutable():"php");
GeneralCommandLine cmd = new GeneralCommandLine(phpExec, "artisan", "serve", "--host=" + host, "--port="+ port);
cmd.setWorkDirectory(project.getBasePath());
OSProcessHandler handler = new OSProcessHandler(cmd);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(ProcessEvent event, Key outputType) {
String text = event.getText();
if (text != null){
if (text.startsWith("Laravel development server started:")){
BrowserLauncher.getInstance().browse("http://" + host + ":" + port +
(route.startsWith("/") ? route : "/" + route), browser);
handler.removeProcessListener(this);
}
}
}
});
// new LaravelRunMgr(handler, new File(getProject().getBasePath()+("/storage/logs/laravel.log")));
return handler;
}
};
}
public int getPort() {
return port;
}
public String getHost() {
return host;
}
public void setPort(int port) {
this.port = port;
}
public void setHost(String host) {
this.host = host;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public WebBrowser getBrowser() {
return browser;
}
public void setBrowser(WebBrowser browser) {
this.browser = browser;
}
public PhpInterpreter getInterpreter() {
return interpreter;
}
public void setInterpreter(PhpInterpreter interpreter) {
this.interpreter = interpreter;
}
public static class Settings {
public String host;
public int port;
public String route;
public String browser;
public String interpreterName;
}
}
| mit |
fvasquezjatar/fermat-unused | fermat-bnk-api/src/main/java/com/bitdubai/fermat_bnk_api/layer/bnk_wallet/bank_money/exceptions/CantTransactionBankMoneyException.java | 533 | package com.bitdubai.fermat_bnk_api.layer.bnk_wallet.bank_money.exceptions;
import com.bitdubai.fermat_api.FermatException;
/**
* Created by Yordin Alayn on 18.09.15.
*/
public class CantTransactionBankMoneyException extends FermatException {
public static final String DEFAULT_MESSAGE = "Falled To Get Bank Transaction Wallet Bank Money.";
public CantTransactionBankMoneyException(String message, Exception cause, String context, String possibleReason) {
super(message, cause, context, possibleReason);
}
}
| mit |
deivisvieira/PosJava | src/java/modelo/Cotacao.java | 2527 | /*
* 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 modelo;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author Deivis
*/
public class Cotacao {
private int id;
private Date data;
private Double valor;
private TipoMoeda tipoMoeda;
public TipoMoeda getTipoMoeda() {
return tipoMoeda;
}
public void setTipoMoeda(TipoMoeda tipoMoeda) {
this.tipoMoeda = tipoMoeda;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getData() {
return data;
}
public String getDataString() {
if (this.data != null) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(this.data);
} else {
return null;
}
}
public String getDataStringBr() {
if (this.data != null) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
return df.format(this.data);
} else {
return null;
}
}
public void setData(String data) throws ParseException {
if (!"".equals(data)) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
this.data = df.parse(data);
} else {
this.data = null;
}
}
public void setDataBr(String data) throws ParseException {
if (!"".equals(data)) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
this.data = df.parse(data);
} else {
this.data = null;
}
}
public void setDataString(String data) throws ParseException {
if (!"".equals(data)) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
this.data = df.parse(data);
} else {
this.data = null;
}
}
public Double getValor() {
return valor;
}
public String getValorString() {
return valor.toString();
}
public void setValor(String valor) {
if (!"".equals(valor)) {
this.valor = Double.parseDouble(valor.replace(",", "."));
} else {
this.valor = null;
}
}
}
| mit |
dbsoftcombr/dbssdk | src/main/java/br/com/dbsoft/rest/dados/DadosStatus.java | 1014 | package br.com.dbsoft.rest.dados;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import br.com.dbsoft.rest.interfaces.IStatus;
@JsonInclude(value=Include.NON_NULL)
@JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class DadosStatus implements IStatus {
private static final long serialVersionUID = -6552296817145232368L;
@JsonProperty("status")
private Boolean wStatus;
@Override
public Boolean getStatus() {
return wStatus;
}
@Override
public void setStatus(Boolean pStatus) {
wStatus = pStatus;
}
}
| mit |
landenlabs2/all_FlipAnimation | app/src/main/java/com/landenlabs/all_flipanimation/ActivityRotAnimation.java | 10273 | package com.landenlabs.all_flipanimation;
/**
* Copyright (c) 2015 Dennis Lang (LanDen Labs) landenlabs@gmail.com
*
* 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.
*
* @author Dennis Lang (3/21/2015)
* @see http://landenlabs.com
*
*/
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import android.widget.CheckBox;
import android.widget.TextView;
/**
* Demonstrate rotating View animation using two rotating animations.
*
* @author Dennis Lang (LanDen Labs)
* @see <a href="http://landenlabs.com/android/index-m.html"> author's web-site </a>
* // http://www.inter-fuser.com/2009/08/android-animations-3d-flip.html
*/
public class ActivityRotAnimation extends Activity {
// ---- Layout ----
View mView1;
View mView2;
View mClickView;
DrawView mDrawView;
TextView mAngle1;
TextView mAngle2;
// ---- Data ----
float mCameraZ = -25;
Flip3dAnimation mRotation1;
Flip3dAnimation mRotation2;
boolean mRotateYaxis = true;
boolean mIsForward = true;
boolean mAutoMode = false;
MediaPlayer mSoundClick;
MediaPlayer mSoundShut;
// ---- Timer ----
private Handler m_handler = new Handler();
private int mDurationMsec = 3000;
private Runnable m_updateElapsedTimeTask = new Runnable() {
public void run() {
animateIt();
m_handler.postDelayed(this, mDurationMsec); // Re-execute after msec
}
};
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rot_animation);
mView1 = Ui.viewById(this, R.id.view1);
mView2 = Ui.viewById(this, R.id.view2);
// Create a new 3D rotation with the supplied parameter
mRotation1 = new Flip3dAnimation();
mRotation2 = new Flip3dAnimation();
Ui.<TextView>viewById(this, R.id.side_title).setText("Rotating Animation");
setupUI();
}
/**
* Start animation.
*/
public void animateIt() {
ObjectAnimator.ofFloat(mClickView, View.ALPHA, mClickView.getAlpha(), 0).start();
final float end = 90.0f;
if (mIsForward) {
mRotation1.mFromDegrees = 0.0f;
mRotation1.mToDegrees = end;
mRotation2.mFromDegrees = -end;
mRotation2.mToDegrees = 0.0f;
} else {
mRotation1.mFromDegrees = end;
mRotation1.mToDegrees = 0.0f;
mRotation2.mFromDegrees = 0.0f;
mRotation2.mToDegrees = -end;
}
mIsForward = !mIsForward;
if (mRotateYaxis) {
mRotation1.mCenterX = mView1.getWidth();
mRotation1.mCenterY = mView1.getHeight() / 2.0f;
mRotation2.mCenterX = 0.0f;
mRotation2.mCenterY = mView2.getHeight() / 2.0f;
} else {
mRotation1.mCenterY = 0.0f; // mView1.getHeight();
mRotation1.mCenterX = mView1.getWidth() / 2.0f;
mRotation2.mCenterY = mView1.getHeight(); // 0.0f;
mRotation2.mCenterX = mView2.getWidth() / 2.0f;
}
mRotation1.reset(mView1, mDurationMsec, mCameraZ);
mRotation2.reset(mView2, mDurationMsec, mCameraZ);
mRotation2.setAnimationListener(new Animation.AnimationListener() {
@Override public void onAnimationStart(Animation animation) { }
@Override public void onAnimationEnd(Animation animation) {
mSoundShut.start();
}
@Override public void onAnimationRepeat(Animation animation) { }
});
// Run both animations in parallel.
AnimationSet animationSet = new AnimationSet(true);
animationSet.setInterpolator(new LinearInterpolator());
animationSet.addAnimation(mRotation1);
animationSet.addAnimation(mRotation2);
animationSet.start();
}
public class Flip3dAnimation extends Animation {
float mFromDegrees;
float mToDegrees;
float mCenterX = 0;
float mCenterY = 0;
float mCameraZ = -8;
Camera mCamera;
View mView;
public Flip3dAnimation() {
setFillEnabled(true);
setFillAfter(true);
setFillBefore(true);
}
public void reset(View view, int durationMsec, float cameraZ) {
mCameraZ = cameraZ;
setDuration(durationMsec);
view.clearAnimation(); // This is very important to get 2nd..nth run to work.
view.setAnimation(this);
mView = view;
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
mCamera = new Camera();
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation trans) {
final float fromDegrees = mFromDegrees;
float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);
final Camera camera = mCamera;
final Matrix matrix = trans.getMatrix();
camera.save();
camera.setLocation(0, 0, mCameraZ);
if (mRotateYaxis)
camera.rotateY(degrees);
else
camera.rotateX(degrees);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-mCenterX, -mCenterY);
matrix.postTranslate(mCenterX, mCenterY);
final float degree3 = degrees;
if (mView == mView1) {
mDrawView.setAngle1(degree3);
mAngle1.setText(String.format("%.0f°", degree3));
} else {
mDrawView.setAngle2(degree3);
mAngle2.setText(String.format("%.0f°", degree3));
}
}
}
/**
* Build User Interface - setup callbacks.
*/
private void setupUI() {
mSoundClick = MediaPlayer.create(this, R.raw.click);
// mSoundClick.setVolume(0.5f, 0.5f);
mSoundShut = MediaPlayer.create(this, R.raw.shut);
// mSoundShut.setVolume(0.3f, 0.3f);
final TextView title = (TextView) this.findViewById(R.id.title);
mClickView = this.findViewById(R.id.click_view);
mClickView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mSoundClick.start();
animateIt();
}
});
final SlideBar seekspeedSB = new SlideBar(this.findViewById(R.id.seekSpeed), "Delay:");
seekspeedSB.setValueChanged(new SlideBar.ValueChanged() {
@Override
public float onValueChanged(View v, float value) {
mDurationMsec = (int) (value = 100 + value * 100);
title.setText(String.format("Delay:%d CameraZ:%.0f", mDurationMsec, mCameraZ));
return value;
}
});
final SlideBar cameraZpos = new SlideBar(this.findViewById(R.id.cameraZpos), "CamZ:");
cameraZpos.setProgress((int) (mCameraZ / -2 + 50));
cameraZpos.setValueChanged(new SlideBar.ValueChanged() {
@Override
public float onValueChanged(View v, float value) {
mCameraZ = value = (50 - value) * 2.0f;
title.setText(String.format("Delay:%d CameraZ:%.0f", mDurationMsec, mCameraZ));
return value;
}
});
final CheckBox autoFlipCb = Ui.viewById(this, R.id.autoflip);
autoFlipCb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mAutoMode = ((CheckBox) v).isChecked();
if (mAutoMode) {
m_handler.postDelayed(m_updateElapsedTimeTask, 0);
} else {
m_handler.removeCallbacks(m_updateElapsedTimeTask);
}
}
});
final CheckBox yaxisCb = Ui.viewById(this, R.id.yaxis);
mRotateYaxis = yaxisCb.isChecked();
yaxisCb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean autoMode = mAutoMode;
if (autoMode)
autoFlipCb.performClick(); // Stop automatic animation.
mRotateYaxis = ((CheckBox) v).isChecked();
if (autoMode)
autoFlipCb.performClick(); // Restart automatic animation.
}
});
mDrawView = Ui.viewById(this, R.id.drawView);
mAngle1 = Ui.viewById(this, R.id.angle1);
mAngle2 = Ui.viewById(this, R.id.angle2);
}
} | mit |
AriaPahlavan/Android-Apps | Top10Downloader/app/src/androidTest/java/com/example/apahlavan1/top10downloader/ApplicationTest.java | 369 | package com.example.apahlavan1.top10downloader;
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 |
kylm53/learn-android | RetrofitDemo/src/main/java/com/kkk/retrofitdemo/GitHubService.java | 655 | package com.kkk.retrofitdemo;
import com.kkk.retrofitdemo.bean.Repo;
import com.kkk.retrofitdemo.bean.SearchRepoResult;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Observable;
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
@GET("search/repositories")
Observable<SearchRepoResult> searchRepos(@Query("q") String keyword,
@Query("sort") String sort,
@Query("order") String order);
} | mit |
berserkingyadis/ImageDownloader | src/main/java/gui/GUI.java | 18735 | package gui;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.Toolkit;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.DefaultComboBoxModel;
import javax.swing.UIManager;
import app.Applikation;
import javax.swing.DropMode;
import parsers.*;
import java.io.IOException;
import java.util.Random;
public class GUI {
private JFrame frmImageDownloader;
private JTextField txtInsertTagHere;
private JTextArea textArea;
private JSpinner PageSpinner;
private JComboBox<Object> comboBox;
private ImageParser parser;
private JButton Parsebtn;
private JTextField DelayField;
private BufferedImage bgImage;
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JLabel lblTag;
private final String FOURCHAN_THREAD = "4chan-Thread - http://boards.4chan.org/x/res/123123";
private final String FOURCHAN_BOARD = "4chan-Board - http://boards.4chan.org/x/catalog";
private final String INFINITYCHAN_THREAD = "Infinity Chan Thread - https://8chan.co/BOARD/res/THREADNR.html";
private final String INFINITYCHAN_BOARD = "Infinity Chan Board - https://8chan.co/BOARDNR/";
private final String PAHEAL = "http://rule34.paheal.net/";
private final String XXX = "http://rule34.xxx/";
private final String GELBOORU = "http://gelbooru.com/";
private final String R34HENTAI = "http://rule34hentai.net/";
private final String TUMBLR = "Tumblr Artist - http://XxXxXxX.tumblr.com";
private final String IMGUR = "Imgur-Album - http://imgur.com/a/xXxXx";
private final String GE_HENTAI_SINGLE = "http://g.e-hentai.org/ - Single Album Page";
private final String GE_HENTAI_MORE = "http://g.e-hentai.org/ - >=1 Pages";
private final String ARCHIVE_MOE_THREAD = "archive.moe/fgts.jp (Thread) - https://archive.moe/BOARD/thread/THREADNR/";
private final String ARCHIVE_MOE_BOARD = "archive-moe (Board) - https://archive.moe/BOARD/";
private final String FGTS_JP_BOARD = "fgts.jp (Board) - http://fgts.jp/BOARD/";
private boolean parsing;
public GUI() {
System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
frmImageDownloader = new JFrame();
frmImageDownloader.setIconImage(Toolkit.getDefaultToolkit()
.getImage(this.getClass().getResource("/images/icon.png")));
frmImageDownloader.getContentPane().setBackground(
UIManager.getColor("Button.background"));
frmImageDownloader.setResizable(false);
frmImageDownloader.setTitle("Image Downloader v1.5.1");
frmImageDownloader.setBounds(100, 100, 761, 558);
frmImageDownloader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmImageDownloader.getContentPane().setLayout(null);
JLabel lblMadeByLars = new JLabel("@ berserkingyadis");
lblMadeByLars.setFont(new Font("Dialog", Font.PLAIN, 12));
lblMadeByLars.setBounds(14, 468, 157, 40);
frmImageDownloader.getContentPane().add(lblMadeByLars);
JScrollPane scrollPane = new JScrollPane();
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(205, 185, 542, 331);
scrollPane.setAutoscrolls(true);
frmImageDownloader.getContentPane().add(scrollPane);
try {
bgImage = ImageIO.read(Applikation.class.getResource("/images/bg" + (new Random().nextInt(4) + 1) + ".png"));
} catch (IOException e) {
appendLog("Could not get Background Image", true);
}
textArea = new BackgroundArea(bgImage);
textArea.setEditable(false);
textArea.setDropMode(DropMode.INSERT);
textArea.setColumns(2);
textArea.setFont(new Font("Monospaced", Font.PLAIN, 11));
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
txtInsertTagHere = new JTextField();
txtInsertTagHere.setText("insert tag here");
txtInsertTagHere.setFont(new Font("Dialog", Font.PLAIN, 14));
txtInsertTagHere.setBounds(14, 208, 181, 30);
frmImageDownloader.getContentPane().add(txtInsertTagHere);
txtInsertTagHere.setColumns(10);
lblTag = new JLabel("Tag:");
lblTag.setFont(new Font("Dialog", Font.BOLD, 12));
lblTag.setBounds(12, 183, 175, 24);
frmImageDownloader.getContentPane().add(lblTag);
Parsebtn = new JButton("start parsing");
Parsebtn.setBounds(12, 372, 181, 85);
frmImageDownloader.getContentPane().add(Parsebtn);
PageSpinner = new JSpinner();
PageSpinner.setModel(new SpinnerNumberModel(new Integer(1),
new Integer(1), null, new Integer(1)));
PageSpinner.setBounds(155, 249, 40, 30);
frmImageDownloader.getContentPane().add(PageSpinner);
lblNewLabel = new JLabel("Pages to parse:");
lblNewLabel.setFont(new Font("Dialog", Font.BOLD, 11));
lblNewLabel.setBounds(12, 249, 123, 30);
frmImageDownloader.getContentPane().add(lblNewLabel);
lblNewLabel_1 = new JLabel("1 Page = 50-60 Pictures");
lblNewLabel_1.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewLabel_1.setBounds(12, 290, 175, 30);
frmImageDownloader.getContentPane().add(lblNewLabel_1);
comboBox = new JComboBox<Object>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
switch (comboBox.getSelectedItem().toString()) {
case GE_HENTAI_SINGLE:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(false);
lblTag.setText("Page URL:");
txtInsertTagHere.setText("insert page URL here");
lblNewLabel.setEnabled(false);
break;
case GE_HENTAI_MORE:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Album URL:");
txtInsertTagHere.setText("insert album URL here");
break;
case PAHEAL:
case GELBOORU:
case R34HENTAI:
case XXX:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Tag:");
txtInsertTagHere.setText("insert tag here");
lblNewLabel.setText("Pages to parse:");
break;
case FOURCHAN_THREAD:
case INFINITYCHAN_THREAD:
case ARCHIVE_MOE_THREAD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setText("Pages to parse:");
lblNewLabel.setEnabled(false);
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(false);
lblTag.setText("Thread URL:");
txtInsertTagHere.setText("insert link here");
break;
case FOURCHAN_BOARD:
case INFINITYCHAN_BOARD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setEnabled(true);
lblNewLabel.setText("Threads to parse:");
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(true);
lblTag.setText("Board(eg: v or e):");
txtInsertTagHere.setText("insert Board Letter here");
break;
case ARCHIVE_MOE_BOARD:
case FGTS_JP_BOARD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setEnabled(true);
lblNewLabel.setText("Sites to parse(1 Site = 100 Threads):");
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(true);
lblTag.setText("Board(eg: v or e):");
txtInsertTagHere.setText("insert Board Letter here");
break;
case TUMBLR:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Artist name:");
txtInsertTagHere.setText("insert artist name here");
lblNewLabel.setText("Pages to parse:");
break;
case IMGUR:
lblNewLabel.setEnabled(false);
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(false);
DelayField.setText("100");
lblTag.setText("Album Letters: (eg: \"Bl1QP\")");
txtInsertTagHere.setText("insert the letters here");
Parsebtn.setText("start parsing");
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setEnabled(true);
break;
}
}
});
comboBox.setModel(new DefaultComboBoxModel<Object>(
new String[]{
PAHEAL,
XXX,
R34HENTAI,
GELBOORU,
GE_HENTAI_SINGLE,
GE_HENTAI_MORE,
FOURCHAN_THREAD,
FOURCHAN_BOARD,
//ARCHIVE_MOE_THREAD,
//ARCHIVE_MOE_BOARD,
//FGTS_JP_BOARD,
INFINITYCHAN_THREAD,
INFINITYCHAN_BOARD,
TUMBLR,
IMGUR
}));
comboBox.setBounds(434, 35, 313, 24);
comboBox.setFont(new Font("Dialog", Font.PLAIN, 11));
frmImageDownloader.getContentPane().add(comboBox);
JLabel lblNewLabel_2 = new JLabel("choose the Site to parse:");
lblNewLabel_2.setFont(new Font("Dialog", Font.BOLD, 12));
lblNewLabel_2.setBounds(434, 5, 268, 30);
frmImageDownloader.getContentPane().add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel(
"<html>\nWelcome to the Image Downloader. <br>\nYour can enter the Tag of the images you are looking for below. <br>\nImgur is not supported yet. <br>\nWhen you click parse a folder with the name of the tag will be <br>\ncreated and the images will be downloaded into it. <br><br>\nI strongly advise you to not set the delay under 100 ms, <br>\nif you abuse this you will get banned from the site <br><br>\n\nhave fun :)\n\n\n</html>");
lblNewLabel_3.setVerticalAlignment(SwingConstants.TOP);
lblNewLabel_3.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewLabel_3.setBounds(12, 12, 404, 195);
frmImageDownloader.getContentPane().add(lblNewLabel_3);
JLabel lblDelay = new JLabel("Delay(ms):");
lblDelay.setFont(new Font("Dialog", Font.BOLD, 12));
lblDelay.setBounds(12, 331, 85, 30);
frmImageDownloader.getContentPane().add(lblDelay);
DelayField = new JTextField();
DelayField.setText("100");
DelayField.setBounds(140, 331, 55, 30);
frmImageDownloader.getContentPane().add(DelayField);
DelayField.setColumns(10);
JLabel lblPahealSearchFor = new JLabel(
"<html>\r\npaheal: Search for Characters or Artists\r\n\t\t eg: Tifa Lockhart, Fugtrup<br>\r\nrule34.xxx: Search for things\r\n\t\teg: long hair, hand on hip<br>\r\ngelbooru: Search for what you want<br>\r\n4chan/8chan: paste the Thread URL/Boardletter in the\r\n\t\tTextfield <br>\r\ntumblr: enter the artist's name<br>imgur: enter the album id</html>");
lblPahealSearchFor.setVerticalAlignment(SwingConstants.TOP);
lblPahealSearchFor.setFont(new Font("Dialog", Font.PLAIN, 11));
lblPahealSearchFor.setBounds(434, 71, 313, 109);
frmImageDownloader.getContentPane().add(lblPahealSearchFor);
Parsebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (parsing) {
parser.diePlease();
parser = null;
} else {
GUI g = getGUI();
textArea.setText("");
frmImageDownloader
.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
String tag = txtInsertTagHere.getText().replace(' ', '_');
int pages = (int) PageSpinner.getValue();
String site = comboBox.getSelectedItem().toString();
int delay = Integer.parseInt(DelayField.getText());
switch (site) {
case PAHEAL:
parser = new PahealParser();
parser.setup(tag, pages, g, delay);
break;
case XXX:
parser = new XXXParser();
parser.setup(tag, pages, g, delay);
break;
case R34HENTAI:
parser = new R34HentaiParser();
parser.setup(tag, pages, g, delay);
break;
case GELBOORU:
parser = new GelBooruParser();
parser.setup(tag, pages, g, delay);
break;
case FOURCHAN_THREAD:
parser = new FourChanParser(tag, delay, g, 0);
break;
case FOURCHAN_BOARD:
parser = new FourChanParser(tag, delay, g, 1, pages);
break;
case INFINITYCHAN_THREAD:
parser = new InfinityChanParser(tag, delay, g, 0);
break;
case INFINITYCHAN_BOARD:
parser = new InfinityChanParser(tag, delay, g, 1, pages);
break;
case ARCHIVE_MOE_THREAD:
parser = new ArchiveMoeParser(tag, delay, g, 0);
break;
case ARCHIVE_MOE_BOARD:
parser = new ArchiveMoeParser(tag, delay, g, 1, pages);
break;
case FGTS_JP_BOARD:
parser = new ArchiveMoeParser(tag, delay, g, 2, pages);
break;
case TUMBLR:
parser = new TumblrParser();
parser.setup(tag, pages, g, delay);
break;
case IMGUR:
parser = new ImgurParser(tag, delay, g);
break;
case GE_HENTAI_SINGLE:
parser = new GEHentaiParser(tag, delay, g, false, pages);
break;
case GE_HENTAI_MORE:
parser = new GEHentaiParser(tag, delay, g, true, pages);
}
parser.start();
parsing = true;
Parsebtn.setText("stop parsing");
}
}
});
frmImageDownloader.setVisible(true);
parsing = false;
}
public void appendLog(String txt, boolean brk) {
textArea.append(txt);
if (brk)
textArea.append("\n");
}
private GUI getGUI() {
return this;
}
public void reportback() {
Parsebtn.setEnabled(true);
frmImageDownloader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Parsebtn.setText("start parsing");
parsing = false;
}
}
| mit |
shamanDevel/CurveAverage | src/curveavg/CircularArc.java | 4540 | /*
* 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 curveavg;
/**
* Small helper class for computing the circular arc between two points.
* @author Sebastian Weiss
*/
public class CircularArc {
private static final float EPSILON = 1e-5f;
private final Vector3f P;
private final Vector3f A;
private final Vector3f B;
private Vector3f C;
private float r;
private Vector3f N;
private Vector3f CA;
private float angle;
/**
* Computes the circular arc between the points A and B, with the point P on the
* medial axis (i.e. |A-N|==|B-N|).
* @param P the point on the medial axis, A and B are at the same distance from P
* @param A the closest point from P on the first control curve
* @param B the closest point from P on the second control curve
*/
public CircularArc(Vector3f P, Vector3f A, Vector3f B) {
this.P = P;
this.A = A;
this.B = B;
computeCenter();
}
private void computeCenter() {
Vector3f PA = A.subtract(P);
Vector3f PB = B.subtract(P);
N = PA.cross(PB);
//check for degenerated case
if (N.lengthSquared() <= EPSILON*EPSILON) {
// System.out.println("A="+A+", B="+B+" P="+P+" -> it is a line");
r = 0;
return; //Degenerated to a line
}
//compute directions of A,B to the center C
N.normalizeLocal();
PA.normalizeLocal();
PB.normalizeLocal();
Vector3f U = N.cross(PA);
Vector3f V = N.cross(PB);
//C is now the intersection of A+aU and B+bV
Vector3f UxV = U.cross(V);
Vector3f rhs = (B.subtract(A)).cross(V);
float a1 = rhs.x / UxV.x;
float a2 = rhs.y / UxV.y;
float a3 = rhs.z / UxV.z; //all a1,a2,a3 have to be equal
C = A.addScaled(a1, U);
//compute radius and angle
r = C.distance(A);
CA = A.subtract(C);
angle = (CA.normalize()).angleBetween((B.subtract(C).normalizeLocal()));
}
private float computeCenter_old() {
//check for degenerated case
Vector3f PA = A.subtract(P);
Vector3f PB = B.subtract(P);
N = PA.cross(PB);
if (N.lengthSquared() <= EPSILON*EPSILON) {
// System.out.println("A="+A+", B="+B+" P="+P+" -> it is a line");
return 0; //Degenerated to a line
}
//define orthonormal basis I,J,K
N.normalizeLocal();
Vector3f I = PA.normalize();
Vector3f J = N.cross(I);
Vector3f K = N;
Vector3f IxK = I.cross(K);
Vector3f JxK = J.cross(K);
//project points in the plane PAB
Vector3f PAxN = PA.cross(N);
Vector3f PBxN = PB.cross(N);
Vector2f P2 = new Vector2f(0, 0);
Vector2f A2 = new Vector2f(PA.dot(JxK)/I.dot(JxK), PA.dot(IxK)/J.dot(IxK));
Vector2f B2 = new Vector2f(PB.dot(JxK)/I.dot(JxK), PB.dot(IxK)/J.dot(IxK));
//compute time t of C=P+tPA°
float t;
if (B2.x == A2.x) {
t = (B2.y - A2.y) / (A2.x - B2.x);
} else {
t = (B2.x - A2.x) / (A2.y - B2.y);
}
//compute C
Vector2f PArot = new Vector2f(A.y-P.y, P.x-A.x);
Vector2f C2 = P2.addLocal(PArot.multLocal(t));
//project back
C = new Vector3f(P);
C.addScaledLocal(C2.x, I);
C.addScaledLocal(C2.y, J);
//Debug
// System.out.println("A="+A+", B="+B+" P="+P+" -> I="+I+", J="+J+", K="+K+", P'="+P2+", A'="+A2+", B'="+B2+", t="+t+", C'="+C2+", C="+C);
//set radius
return C.distance(A);
}
/**
* Computes a point on the actual circular arc from A to B.
* The vectors C and the float r are the result from
* {@link #computeCenter(curveavg.Vector3f, curveavg.Vector3f, curveavg.Vector3f, curveavg.Vector3f) }.
* It interpolates from A (alpha=0) to B (alpha=1) in a circular arc.
* @param alpha
* @return
*/
public Vector3f getPointOnArc(float alpha) {
if (isDegenerated()) {
Vector3f V = new Vector3f();
return V.interpolateLocal(A, B, alpha); //degenerated case
}
//normal case, rotate
Vector3f V = rotate(alpha*angle, CA, N);
return V.addLocal(C);
}
private static Vector3f rotate(float angle, Vector3f X, Vector3f N) {
Vector3f W = N.mult(N.dot(X));
Vector3f U = X.subtract(W);
return W.add(U.mult((float) Math.cos(angle)))
.subtract(N.cross(U).mult((float) Math.sin(angle)));
}
public boolean isDegenerated() {
return r==0;
}
public Vector3f getCenter() {
return C;
}
public float getRadius() {
return r;
}
public Vector3f getNormal() {
return N;
}
public float getAngle() {
return angle;
}
@Override
public String toString() {
return "CircularArc{" + "P=" + P + ", A=" + A + ", B=" + B + " -> C=" + C + ", r=" + r + ", N=" + N + ", angle=" + angle + '}';
}
}
| mit |
sendgrid/sendgrid-java | examples/helpers/mail/SingleEmailMultipleRecipients.java | 1666 | import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;
import com.sendgrid.helpers.mail.objects.Personalization;
import java.io.IOException;
public class SingleEmailMultipleRecipients {
public static void main(String[] args) throws IOException {
final Mail mail = new Mail();
mail.setFrom(new Email("test@example.com", "Example User"));
mail.setSubject("Sending with Twilio SendGrid is Fun");
final Personalization personalization = new Personalization();
personalization.addTo(new Email("test1@example.com", "Example User1"));
personalization.addTo(new Email("test2@example.com", "Example User2"));
personalization.addTo(new Email("test3@example.com", "Example User3"));
mail.addPersonalization(personalization);
mail.addContent(new Content("text/plain", "and easy to do anywhere, even with Java"));
mail.addContent(new Content("text/html", "<strong>and easy to do anywhere, even with Java</strong>"));
send(mail);
}
private static void send(final Mail mail) throws IOException {
final SendGrid client = new SendGrid(System.getenv("SENDGRID_API_KEY"));
final Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
final Response response = client.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
}
}
| mit |
tuura/workcraft | workcraft/CircuitPlugin/src/org/workcraft/plugins/circuit/VisualFunctionContact.java | 13140 | package org.workcraft.plugins.circuit;
import org.workcraft.annotations.DisplayName;
import org.workcraft.annotations.Hotkey;
import org.workcraft.annotations.SVGIcon;
import org.workcraft.dom.Node;
import org.workcraft.dom.visual.BoundingBoxHelper;
import org.workcraft.dom.visual.DrawRequest;
import org.workcraft.formula.BooleanFormula;
import org.workcraft.formula.visitors.FormulaRenderingResult;
import org.workcraft.formula.visitors.FormulaToGraphics;
import org.workcraft.gui.tools.Decoration;
import org.workcraft.observation.PropertyChangedEvent;
import org.workcraft.observation.StateEvent;
import org.workcraft.observation.StateObserver;
import org.workcraft.plugins.circuit.renderers.ComponentRenderingResult.RenderType;
import org.workcraft.serialisation.NoAutoSerialisation;
import org.workcraft.utils.ColorUtils;
import org.workcraft.utils.Hierarchy;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.font.FontRenderContext;
import java.awt.geom.*;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
@DisplayName("Input/output port")
@Hotkey(KeyEvent.VK_P)
@SVGIcon("images/circuit-node-port.svg")
public class VisualFunctionContact extends VisualContact implements StateObserver {
private static final double size = 0.3;
private static FontRenderContext context = new FontRenderContext(AffineTransform.getScaleInstance(1000.0, 1000.0), true, true);
private static Font functionFont;
private FormulaRenderingResult renderedSetFunction = null;
private FormulaRenderingResult renderedResetFunction = null;
private static double functionFontSize = CircuitSettings.getFunctionFontSize();
static {
try {
functionFont = Font.createFont(Font.TYPE1_FONT, ClassLoader.getSystemResourceAsStream("fonts/eurm10.pfb"));
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
}
public VisualFunctionContact(FunctionContact contact) {
super(contact);
}
@Override
public FunctionContact getReferencedComponent() {
return (FunctionContact) super.getReferencedComponent();
}
@NoAutoSerialisation
public BooleanFormula getSetFunction() {
return getReferencedComponent().getSetFunction();
}
@NoAutoSerialisation
public void setSetFunction(BooleanFormula setFunction) {
if (getParent() instanceof VisualFunctionComponent) {
VisualFunctionComponent p = (VisualFunctionComponent) getParent();
p.invalidateRenderingResult();
}
renderedSetFunction = null;
getReferencedComponent().setSetFunction(setFunction);
}
@NoAutoSerialisation
public BooleanFormula getResetFunction() {
return getReferencedComponent().getResetFunction();
}
@NoAutoSerialisation
public void setForcedInit(boolean value) {
getReferencedComponent().setForcedInit(value);
}
@NoAutoSerialisation
public boolean getForcedInit() {
return getReferencedComponent().getForcedInit();
}
@NoAutoSerialisation
public void setInitToOne(boolean value) {
getReferencedComponent().setInitToOne(value);
}
@NoAutoSerialisation
public boolean getInitToOne() {
return getReferencedComponent().getInitToOne();
}
@NoAutoSerialisation
public void setResetFunction(BooleanFormula resetFunction) {
if (getParent() instanceof VisualFunctionComponent) {
VisualFunctionComponent p = (VisualFunctionComponent) getParent();
p.invalidateRenderingResult();
}
renderedResetFunction = null;
getReferencedComponent().setResetFunction(resetFunction);
}
public void invalidateRenderedFormula() {
renderedSetFunction = null;
renderedResetFunction = null;
}
private Font getFunctionFont() {
return functionFont.deriveFont((float) CircuitSettings.getFunctionFontSize());
}
private FormulaRenderingResult getRenderedSetFunction() {
if (Math.abs(CircuitSettings.getFunctionFontSize() - functionFontSize) > 0.001) {
functionFontSize = CircuitSettings.getContactFontSize();
renderedSetFunction = null;
}
BooleanFormula setFunction = getReferencedComponent().getSetFunction();
if (setFunction == null) {
renderedSetFunction = null;
} else if (renderedSetFunction == null) {
renderedSetFunction = FormulaToGraphics.render(setFunction, context, getFunctionFont());
}
return renderedSetFunction;
}
private Point2D getSetFormulaOffset() {
double xOffset = size;
double yOffset = -size / 2;
FormulaRenderingResult renderingResult = getRenderedSetFunction();
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
xOffset = -(size + renderingResult.boundingBox.getWidth());
}
}
return new Point2D.Double(xOffset, yOffset);
}
private Rectangle2D getSetBoundingBox() {
Rectangle2D bb = null;
FormulaRenderingResult setRenderingResult = getRenderedSetFunction();
if (setRenderingResult != null) {
bb = BoundingBoxHelper.move(setRenderingResult.boundingBox, getSetFormulaOffset());
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
bb = BoundingBoxHelper.transform(bb, rotateTransform);
}
}
return bb;
}
private FormulaRenderingResult getRenderedResetFunction() {
if (Math.abs(CircuitSettings.getFunctionFontSize() - functionFontSize) > 0.001) {
functionFontSize = CircuitSettings.getContactFontSize();
renderedResetFunction = null;
}
BooleanFormula resetFunction = getReferencedComponent().getResetFunction();
if (resetFunction == null) {
renderedResetFunction = null;
} else if (renderedResetFunction == null) {
renderedResetFunction = FormulaToGraphics.render(resetFunction, context, getFunctionFont());
}
return renderedResetFunction;
}
private Point2D getResetFormulaOffset() {
double xOffset = size;
double yOffset = size / 2;
FormulaRenderingResult renderingResult = getRenderedResetFunction();
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
xOffset = -(size + renderingResult.boundingBox.getWidth());
}
yOffset = size / 2 + renderingResult.boundingBox.getHeight();
}
return new Point2D.Double(xOffset, yOffset);
}
private Rectangle2D getResetBoundingBox() {
Rectangle2D bb = null;
FormulaRenderingResult renderingResult = getRenderedResetFunction();
if (renderingResult != null) {
bb = BoundingBoxHelper.move(renderingResult.boundingBox, getResetFormulaOffset());
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
bb = BoundingBoxHelper.transform(bb, rotateTransform);
}
}
return bb;
}
private void drawArrow(Graphics2D g, int arrowType, double arrX, double arrY) {
double s = CircuitSettings.getFunctionFontSize();
g.setStroke(new BasicStroke((float) s / 25));
double s1 = 0.75 * s;
double s2 = 0.45 * s;
double s3 = 0.30 * s;
if (arrowType == 1) {
// arrow down
Line2D line = new Line2D.Double(arrX, arrY - s1, arrX, arrY - s3);
Path2D path = new Path2D.Double();
path.moveTo(arrX - 0.05, arrY - s3);
path.lineTo(arrX + 0.05, arrY - s3);
path.lineTo(arrX, arrY);
path.closePath();
g.fill(path);
g.draw(line);
} else if (arrowType == 2) {
// arrow up
Line2D line = new Line2D.Double(arrX, arrY, arrX, arrY - s2);
Path2D path = new Path2D.Double();
path.moveTo(arrX - 0.05, arrY - s2);
path.lineTo(arrX + 0.05, arrY - s2);
path.lineTo(arrX, arrY - s1);
path.closePath();
g.fill(path);
g.draw(line);
}
}
private void drawFormula(Graphics2D g, int arrowType, Point2D offset, FormulaRenderingResult renderingResult) {
if (renderingResult != null) {
Direction dir = getDirection();
if (!(getParent() instanceof VisualFunctionComponent)) {
dir = dir.flip();
}
AffineTransform savedTransform = g.getTransform();
if ((dir == Direction.NORTH) || (dir == Direction.SOUTH)) {
AffineTransform rotateTransform = new AffineTransform();
rotateTransform.quadrantRotate(-1);
g.transform(rotateTransform);
}
double dXArrow = -0.15;
if ((dir == Direction.SOUTH) || (dir == Direction.WEST)) {
dXArrow = renderingResult.boundingBox.getWidth() + 0.15;
}
drawArrow(g, arrowType, offset.getX() + dXArrow, offset.getY());
g.translate(offset.getX(), offset.getY());
renderingResult.draw(g);
g.setTransform(savedTransform);
}
}
@Override
public void draw(DrawRequest r) {
if (needsFormulas()) {
Graphics2D g = r.getGraphics();
Decoration d = r.getDecoration();
g.setColor(ColorUtils.colorise(getForegroundColor(), d.getColorisation()));
FormulaRenderingResult renderingResult;
renderingResult = getRenderedSetFunction();
if (renderingResult != null) {
Point2D offset = getSetFormulaOffset();
drawFormula(g, 2, offset, renderingResult);
}
renderingResult = getRenderedResetFunction();
if (renderingResult != null) {
Point2D offset = getResetFormulaOffset();
drawFormula(g, 1, offset, renderingResult);
}
}
super.draw(r);
}
private boolean needsFormulas() {
boolean result = false;
Node parent = getParent();
if (parent != null) {
// Primary input port
if (!(parent instanceof VisualCircuitComponent) && isInput()) {
result = true;
}
// Output port of a BOX-rendered component
if ((parent instanceof VisualFunctionComponent) && isOutput()) {
VisualFunctionComponent component = (VisualFunctionComponent) parent;
if (component.getRenderType() == RenderType.BOX) {
result = true;
}
}
}
return result;
}
@Override
public Rectangle2D getBoundingBoxInLocalSpace() {
Rectangle2D bb = super.getBoundingBoxInLocalSpace();
if (needsFormulas()) {
bb = BoundingBoxHelper.union(bb, getSetBoundingBox());
bb = BoundingBoxHelper.union(bb, getResetBoundingBox());
}
return bb;
}
private Collection<VisualFunctionContact> getAllContacts() {
HashSet<VisualFunctionContact> result = new HashSet<>();
Node root = Hierarchy.getRoot(this);
if (root != null) {
result.addAll(Hierarchy.getDescendantsOfType(root, VisualFunctionContact.class));
}
return result;
}
@Override
public void notify(StateEvent e) {
if (e instanceof PropertyChangedEvent) {
PropertyChangedEvent pc = (PropertyChangedEvent) e;
String propertyName = pc.getPropertyName();
if (propertyName.equals(FunctionContact.PROPERTY_SET_FUNCTION) || propertyName.equals(FunctionContact.PROPERTY_RESET_FUNCTION)) {
invalidateRenderedFormula();
}
if (propertyName.equals(Contact.PROPERTY_NAME)) {
for (VisualFunctionContact vc : getAllContacts()) {
vc.invalidateRenderedFormula();
}
}
}
super.notify(e);
}
}
| mit |
dirtyfilthy/dirtyfilthy-bouncycastle | net/dirtyfilthy/bouncycastle/asn1/nist/NISTNamedCurves.java | 2937 | package net.dirtyfilthy.bouncycastle.asn1.nist;
import net.dirtyfilthy.bouncycastle.asn1.DERObjectIdentifier;
import net.dirtyfilthy.bouncycastle.asn1.sec.SECNamedCurves;
import net.dirtyfilthy.bouncycastle.asn1.sec.SECObjectIdentifiers;
import net.dirtyfilthy.bouncycastle.asn1.x9.X9ECParameters;
import net.dirtyfilthy.bouncycastle.util.Strings;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* Utility class for fetching curves using their NIST names as published in FIPS-PUB 186-2
*/
public class NISTNamedCurves
{
static final Hashtable objIds = new Hashtable();
static final Hashtable names = new Hashtable();
static void defineCurve(String name, DERObjectIdentifier oid)
{
objIds.put(name, oid);
names.put(oid, name);
}
static
{
// TODO Missing the "K-" curves
defineCurve("B-571", SECObjectIdentifiers.sect571r1);
defineCurve("B-409", SECObjectIdentifiers.sect409r1);
defineCurve("B-283", SECObjectIdentifiers.sect283r1);
defineCurve("B-233", SECObjectIdentifiers.sect233r1);
defineCurve("B-163", SECObjectIdentifiers.sect163r2);
defineCurve("P-521", SECObjectIdentifiers.secp521r1);
defineCurve("P-384", SECObjectIdentifiers.secp384r1);
defineCurve("P-256", SECObjectIdentifiers.secp256r1);
defineCurve("P-224", SECObjectIdentifiers.secp224r1);
defineCurve("P-192", SECObjectIdentifiers.secp192r1);
}
public static X9ECParameters getByName(
String name)
{
DERObjectIdentifier oid = (DERObjectIdentifier)objIds.get(Strings.toUpperCase(name));
if (oid != null)
{
return getByOID(oid);
}
return null;
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters getByOID(
DERObjectIdentifier oid)
{
return SECNamedCurves.getByOID(oid);
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DERObjectIdentifier getOID(
String name)
{
return (DERObjectIdentifier)objIds.get(Strings.toUpperCase(name));
}
/**
* return the named curve name represented by the given object identifier.
*/
public static String getName(
DERObjectIdentifier oid)
{
return (String)names.get(oid);
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static Enumeration getNames()
{
return objIds.keys();
}
}
| mit |
dantin/kafka-demo | kafka-producer/src/main/java/com/cosmos/kafka/client/producer/MultipleBrokerProducer.java | 1747 | package com.cosmos.kafka.client.producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;
import java.util.Random;
import static org.apache.kafka.clients.producer.ProducerConfig.*;
/**
* Producer using multiple partition
*/
public class MultipleBrokerProducer implements Runnable {
private KafkaProducer<Integer, String> producer;
private String topic;
public MultipleBrokerProducer(String topic) {
final Properties props = new Properties();
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092,localhost:9093,localhost:9094");
props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.IntegerSerializer");
props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(PARTITIONER_CLASS_CONFIG, "org.apache.kafka.clients.producer.internals.DefaultPartitioner");
props.put(ACKS_CONFIG, "1");
this.producer = new KafkaProducer<>(props);
this.topic = topic;
}
@Override
public void run() {
System.out.println("Sending 1000 messages");
Random rnd = new Random();
int i = 1;
while (i <= 1000) {
int key = rnd.nextInt(255);
String message = String.format("Message for key - [%d]: %d", key, i);
System.out.printf("Send: %s\n", message);
this.producer.send(new ProducerRecord<>(this.topic, key, message));
i++;
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
producer.close();
}
}
| mit |
MPDL/MPDL-Cam | app/src/main/java/de/mpg/mpdl/labcam/code/common/widget/Constants.java | 1174 | /*
* Copyright (c) 2016. Xiaomu Tech.(Beijing) LLC. All rights reserved.
*/
package de.mpg.mpdl.labcam.code.common.widget;
/**
* Created by yingli on 10/19/15.
*/
public class Constants {
public static final String STATUS_SUCCESS = "SUCCESS";
public static final String KEY_CLASS_NAME = "key_class_name";
/************************** SHARED_PREFERENCES **********************************/
public static final String SHARED_PREFERENCES = "myPref"; // name of shared preferences
public static final String API_KEY = "apiKey";
public static final String USER_ID = "userId";
public static final String USER_NAME = "username";
public static final String FAMILY_NAME = "familyName";
public static final String GIVEN_NAME = "givenName";
public static final String PASSWORD = "password";
public static final String EMAIL = "email";
public static final String SERVER_NAME = "serverName";
public static final String OTHER_SERVER = "otherServer";
public static final String COLLECTION_ID = "collectionID";
public static final String OCR_IS_ON = "ocrIsOn";
public static final String IS_ALBUM = "isAlbum";
}
| mit |
gavilancomun/irc-explorer | src/main/java/gavilan/irc/TwitchCore.java | 366 |
package gavilan.irc;
import java.util.Set;
import javax.annotation.PreDestroy;
import org.pircbotx.PircBotX;
public interface TwitchCore {
void doGreet(ChatMessage cm);
Set<String> getPendings();
void message(String channel, String message);
void onMessage(ChatMessage cm);
@PreDestroy
void shutdown();
void startAll(PircBotX pircBotX);
}
| mit |
visGeek/JavaVisGeekCollections | src/src/main/java/com/github/visgeek/utils/collections/LinqConcateIterator.java | 1003 | package com.github.visgeek.utils.collections;
import java.util.Iterator;
class LinqConcateIterator<T> implements Iterator<T> {
// コンストラクター
public LinqConcateIterator(Iterable<T> source, Iterable<? extends T> second) {
this.second = second;
this.itr = source.iterator();
this.isSwitched = false;
}
// フィールド
private final Iterable<? extends T> second;
private Iterator<? extends T> itr;
private boolean isSwitched;
// プロパティ
// メソッド
@Override
public boolean hasNext() {
boolean result = false;
result = this.itr.hasNext();
if (!this.isSwitched) {
if (!result) {
this.itr = this.second.iterator();
result = this.itr.hasNext();
this.isSwitched = true;
}
}
return result;
}
@Override
public T next() {
return this.itr.next();
}
// スタティックフィールド
// スタティックイニシャライザー
// スタティックメソッド
}
| mit |
lpcsmath/QTReader | src/main/java/de/csmath/QT/FTypeAtomBuilder.java | 1783 | package de.csmath.QT;
import java.util.Collection;
import java.util.List;
/**
* This class builds a FTypeAtom from given parameters.
* @author lpfeiler
*/
public class FTypeAtomBuilder extends QTAtomBuilder {
/**
* @see FTypeAtom#majBrand
*/
private int majBrand = 0;
/**
* @see FTypeAtom#minVersion
*/
private int minVersion = 0;
/**
* @see FTypeAtom#compBrands
*/
private Collection<Integer> compBrands;
/**
* Constructs a FTypeAtomBuilder.
* @param size the size of the FTypeAtom in the file
* @param type the type of the atom, should be set to 'ftyp'
*/
public FTypeAtomBuilder(int size, int type) {
super(size, type);
}
/**
* Returns a new FTypeAtom.
* @return a new FTypeAtom
*/
public FTypeAtom build() {
return new FTypeAtom(size,type,majBrand,minVersion,compBrands);
}
/**
* Sets the major brand.
* @see FTypeAtom#majBrand
* @param majBrand the major brand
* @return a reference to this object
*/
public FTypeAtomBuilder withMajBrand(int majBrand) {
this.majBrand = majBrand;
return this;
}
/**
* Sets the minor version.
* @see FTypeAtom#minVersion
* @param minVersion the minor version
* @return a reference to this object
*/
public FTypeAtomBuilder withMinVersion(int minVersion) {
this.minVersion = minVersion;
return this;
}
/**
* Sets the compatible brands.
* @param compBrands a collection of compatible brands
* @return a reference to this object
*/
public FTypeAtomBuilder withCompBrands(Collection<Integer> compBrands) {
this.compBrands = compBrands;
return this;
}
}
| mit |
allen12/Personifiler | test/personifiler/cluster/TestRandIndex.java | 554 | package personifiler.cluster;
import static org.junit.Assert.*;
import org.junit.Test;
import personifiler.util.TestUtils;
/**
* Tests for {@link RandIndex}
*
* @author Allen Cheng
*/
public class TestRandIndex
{
/**
* Tests that the rand index of a cluster is between 0.0 and 1.0
*/
@Test
public void testRandIndex()
{
ClusterPeople cluster = new ClusterPeople(TestUtils.getSampleFeatureMatrix());
double randIndex = cluster.randIndex(TestUtils.getSampleGroundTruth());
assertTrue(randIndex >= 0.0 && randIndex <= 1.0);
}
}
| mit |
emadhilo/capstone | SymptomCheckerService/src/main/java/org/coursera/androidcapstone/symptomchecker/repository/PatientRepository.java | 860 | package org.coursera.androidcapstone.symptomchecker.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface PatientRepository extends PagingAndSortingRepository<Patient, Long> {
@Query("From Patient p where :doctor member p.doctors")
public Page<Patient> findByDoctor(@Param("doctor") Doctor doctor, Pageable page);
@Query("From Patient p where :doctor member p.doctors AND UPPER(fullName)=:fullName")
public List<Patient> findByDoctorAndFullName(@Param("doctor") Doctor doctor, @Param("fullName") String fullName);
}
| mit |
dudehook/Cliche2 | src/main/java/net/dudehook/cliche2/util/ArrayHashMultiMap.java | 2003 | /*
* This file is part of the Cliche project, licensed under MIT License. See LICENSE.txt file in root folder of Cliche
* sources.
*/
package net.dudehook.cliche2.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author ASG
*/
public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V>
{
private Map<K, List<V>> listMap;
public ArrayHashMultiMap()
{
listMap = new HashMap<K, List<V>>();
}
public ArrayHashMultiMap(MultiMap<K, V> map)
{
this();
putAll(map);
}
public void put(K key, V value)
{
List<V> values = listMap.get(key);
if (values == null)
{
values = new ArrayList<V>();
listMap.put(key, values);
}
values.add(value);
}
public Collection<V> get(K key)
{
List<V> result = listMap.get(key);
if (result == null)
{
result = new ArrayList<V>();
}
return result;
}
public Set<K> keySet()
{
return listMap.keySet();
}
public void remove(K key, V value)
{
List<V> values = listMap.get(key);
if (values != null)
{
values.remove(value);
if (values.isEmpty())
{
listMap.remove(key);
}
}
}
public void removeAll(K key)
{
listMap.remove(key);
}
public int size()
{
int sum = 0;
for (K key : listMap.keySet())
{
sum += listMap.get(key).size();
}
return sum;
}
public void putAll(MultiMap<K, V> map)
{
for (K key : map.keySet())
{
for (V val : map.get(key))
{
put(key, val);
}
}
}
@Override
public String toString()
{
return listMap.toString();
}
}
| mit |
lakshmi-nair/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/clients/commerce/customer/accounts/CustomerNoteClient.java | 12436 | /**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.clients.commerce.customer.accounts;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import org.joda.time.DateTime;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;
/** <summary>
* Tenant administrators can add and view internal notes for a customer account. For example, a client can track a shopper's interests or complaints. Only clients can add and view notes. Shoppers cannot view these notes from the My Account page.
* </summary>
*/
public class CustomerNoteClient {
/**
* Retrieves the contents of a particular note attached to a specified customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=GetAccountNoteClient( accountId, noteId);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param noteId Unique identifier of a particular note to retrieve.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> getAccountNoteClient(Integer accountId, Integer noteId) throws Exception
{
return getAccountNoteClient( accountId, noteId, null);
}
/**
* Retrieves the contents of a particular note attached to a specified customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=GetAccountNoteClient( accountId, noteId, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param noteId Unique identifier of a particular note to retrieve.
* @param responseFields Use this field to include those fields which are not included by default.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> getAccountNoteClient(Integer accountId, Integer noteId, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.getAccountNoteUrl(accountId, noteId, responseFields);
String verb = "GET";
Class<?> clz = com.mozu.api.contracts.customer.CustomerNote.class;
MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNote>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
return mozuClient;
}
/**
* Retrieves a list of notes added to a customer account according to any specified filter criteria and sort options.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection> mozuClient=GetAccountNotesClient( accountId);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNoteCollection customerNoteCollection = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNoteCollection>
* @see com.mozu.api.contracts.customer.CustomerNoteCollection
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection> getAccountNotesClient(Integer accountId) throws Exception
{
return getAccountNotesClient( accountId, null, null, null, null, null);
}
/**
* Retrieves a list of notes added to a customer account according to any specified filter criteria and sort options.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection> mozuClient=GetAccountNotesClient( accountId, startIndex, pageSize, sortBy, filter, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNoteCollection customerNoteCollection = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true"
* @param pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200.
* @param responseFields Use this field to include those fields which are not included by default.
* @param sortBy The property by which to sort results and whether the results appear in ascending (a-z) order, represented by ASC or in descending (z-a) order, represented by DESC. The sortBy parameter follows an available property. For example: "sortBy=productCode+asc"
* @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a PageSize of 25, to get the 51st through the 75th items, use startIndex=3.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNoteCollection>
* @see com.mozu.api.contracts.customer.CustomerNoteCollection
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection> getAccountNotesClient(Integer accountId, Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.getAccountNotesUrl(accountId, filter, pageSize, responseFields, sortBy, startIndex);
String verb = "GET";
Class<?> clz = com.mozu.api.contracts.customer.CustomerNoteCollection.class;
MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNoteCollection>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
return mozuClient;
}
/**
* Adds a new note to the specified customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=AddAccountNoteClient( note, accountId);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param note Properties of a note configured for a customer account.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> addAccountNoteClient(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId) throws Exception
{
return addAccountNoteClient( note, accountId, null);
}
/**
* Adds a new note to the specified customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=AddAccountNoteClient( note, accountId, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param responseFields Use this field to include those fields which are not included by default.
* @param note Properties of a note configured for a customer account.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> addAccountNoteClient(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.addAccountNoteUrl(accountId, responseFields);
String verb = "POST";
Class<?> clz = com.mozu.api.contracts.customer.CustomerNote.class;
MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNote>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
mozuClient.setBody(note);
return mozuClient;
}
/**
* Modifies an existing note for a customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=UpdateAccountNoteClient( note, accountId, noteId);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param noteId Unique identifier of a particular note to retrieve.
* @param note Properties of a note configured for a customer account.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> updateAccountNoteClient(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId, Integer noteId) throws Exception
{
return updateAccountNoteClient( note, accountId, noteId, null);
}
/**
* Modifies an existing note for a customer account.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient=UpdateAccountNoteClient( note, accountId, noteId, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* CustomerNote customerNote = client.Result();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param noteId Unique identifier of a particular note to retrieve.
* @param responseFields Use this field to include those fields which are not included by default.
* @param note Properties of a note configured for a customer account.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.CustomerNote>
* @see com.mozu.api.contracts.customer.CustomerNote
* @see com.mozu.api.contracts.customer.CustomerNote
*/
public static MozuClient<com.mozu.api.contracts.customer.CustomerNote> updateAccountNoteClient(com.mozu.api.contracts.customer.CustomerNote note, Integer accountId, Integer noteId, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.updateAccountNoteUrl(accountId, noteId, responseFields);
String verb = "PUT";
Class<?> clz = com.mozu.api.contracts.customer.CustomerNote.class;
MozuClient<com.mozu.api.contracts.customer.CustomerNote> mozuClient = (MozuClient<com.mozu.api.contracts.customer.CustomerNote>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
mozuClient.setBody(note);
return mozuClient;
}
/**
* Removes a note from the specified customer account.
* <p><pre><code>
* MozuClient mozuClient=DeleteAccountNoteClient( accountId, noteId);
* client.setBaseAddress(url);
* client.executeRequest();
* </code></pre></p>
* @param accountId Unique identifier of the customer account.
* @param noteId Unique identifier of a particular note to retrieve.
* @return Mozu.Api.MozuClient
*/
public static MozuClient deleteAccountNoteClient(Integer accountId, Integer noteId) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.customer.accounts.CustomerNoteUrl.deleteAccountNoteUrl(accountId, noteId);
String verb = "DELETE";
MozuClient mozuClient = (MozuClient) MozuClientFactory.getInstance();
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
return mozuClient;
}
}
| mit |
frig-neutron/PIPE | pipe-gui/src/main/java/pipe/actions/gui/TokenAction.java | 2378 | package pipe.actions.gui;
import pipe.controllers.PetriNetController;
import pipe.controllers.PlaceController;
import uk.ac.imperial.pipe.models.petrinet.Connectable;
import uk.ac.imperial.pipe.models.petrinet.Place;
import java.awt.event.MouseEvent;
import java.util.Map;
/**
* Abstract action responsible for adding and deleting tokens to places
*/
public abstract class TokenAction extends CreateAction {
/**
*
* @param name image name
* @param tooltip tooltip message
* @param key keyboard shortcut
* @param modifiers keyboard accelerator
* @param applicationModel current PIPE application model
*/
public TokenAction(String name, String tooltip, int key, int modifiers, PipeApplicationModel applicationModel) {
super(name, tooltip, key, modifiers, applicationModel);
}
/**
* Noop action when a component has not been clicked on
* @param event mouse event
* @param petriNetController controller for the petri net
*/
@Override
public void doAction(MouseEvent event, PetriNetController petriNetController) {
// Do nothing unless clicked a connectable
}
/**
* Performs the subclass token action on the place
* @param connectable item clicked
* @param petriNetController controller for the petri net
*/
@Override
public void doConnectableAction(Connectable connectable, PetriNetController petriNetController) {
//TODO: Maybe a method, connectable.containsTokens() or visitor pattern
if (connectable instanceof Place) {
Place place = (Place) connectable;
String token = petriNetController.getSelectedToken();
performTokenAction(petriNetController.getPlaceController(place), token);
}
}
/**
* Subclasses should perform their relevant action on the token e.g. add/delete
*
* @param placeController
* @param token
*/
protected abstract void performTokenAction(PlaceController placeController, String token);
/**
* Sets the place to contain counts.
* <p/>
* Creates a new history edit
*
* @param placeController
* @param counts
*/
protected void setTokenCounts(PlaceController placeController, Map<String, Integer> counts) {
placeController.setTokenCounts(counts);
}
}
| mit |
tugrulkarakaya/NeVarNeYok | app/src/main/java/uk/co/nevarneyok/entities/product/ProductSize.java | 1689 | package uk.co.nevarneyok.entities.product;
import com.google.gson.annotations.SerializedName;
public class ProductSize {
private long id;
@SerializedName("remote_id")
private long remoteId;
private String value;
public ProductSize() {
}
public ProductSize(long id, long remoteId, String value) {
this.id = id;
this.remoteId = remoteId;
this.value = value;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getRemoteId() {
return remoteId;
}
public void setRemoteId(long remoteId) {
this.remoteId = remoteId;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductSize that = (ProductSize) o;
if (id != that.id) return false;
if (remoteId != that.remoteId) return false;
return !(value != null ? !value.equals(that.value) : that.value != null);
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (int) (remoteId ^ (remoteId >>> 32));
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ProductSize{" +
"id=" + id +
", remoteId=" + remoteId +
", value='" + value + '\'' +
'}';
}
}
| mit |
Permafrost/Tundra.java | src/main/java/permafrost/tundra/math/IntegerHelper.java | 4471 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Lachlan Dowding
*
* 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 permafrost.tundra.math;
import java.text.MessageFormat;
/**
* A collection of convenience methods for working with integers.
*/
public final class IntegerHelper {
/**
* The default value used when parsing a null string.
*/
private static int DEFAULT_INT_VALUE = 0;
/**
* Disallow instantiation of this class.
*/
private IntegerHelper() {}
/**
* Converts the given object to a Integer.
*
* @param object The object to be converted.
* @return The converted object.
*/
public static Integer normalize(Object object) {
Integer value = null;
if (object instanceof Number) {
value = ((Number)object).intValue();
} else if (object instanceof String) {
value = parse((String)object);
}
return value;
}
/**
* Parses the given string as an integer.
*
* @param input A string to be parsed as integer.
* @return Integer representing the given string, or 0 if the given string was null.
*/
public static int parse(String input) {
return parse(input, DEFAULT_INT_VALUE);
}
/**
* Parses the given string as an integer.
*
* @param input A string to be parsed as integer.
* @param defaultValue The value returned if the given string is null.
* @return Integer representing the given string, or defaultValue if the given string is null.
*/
public static int parse(String input, int defaultValue) {
if (input == null) return defaultValue;
return Integer.parseInt(input);
}
/**
* Parses the given strings as integers.
*
* @param input A list of strings to be parsed as integers.
* @return A list of integers representing the given strings.
*/
public static int[] parse(String[] input) {
return parse(input, DEFAULT_INT_VALUE);
}
/**
* Parses the given strings as integers.
*
* @param input A list of strings to be parsed as integers.
* @param defaultValue The value returned if a string in the list is null.
* @return A list of integers representing the given strings.
*/
public static int[] parse(String[] input, int defaultValue) {
if (input == null) return null;
int[] output = new int[input.length];
for (int i = 0; i < input.length; i++) {
output[i] = parse(input[i], defaultValue);
}
return output;
}
/**
* Serializes the given integer as a string.
*
* @param input The integer to be serialized.
* @return A string representation of the given integer.
*/
public static String emit(int input) {
return Integer.toString(input);
}
/**
* Serializes the given integers as strings.
*
* @param input A list of integers to be serialized.
* @return A list of string representations of the given integers.
*/
public static String[] emit(int[] input) {
if (input == null) return null;
String[] output = new String[input.length];
for (int i = 0; i < input.length; i++) {
output[i] = emit(input[i]);
}
return output;
}
}
| mit |
OleksandrKucherenko/spacefish | _libs/artfulbits-sdk/src/main/com/artfulbits/utils/StringUtils.java | 1547 | package com.artfulbits.utils;
import android.text.TextUtils;
import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;
/** Common string routine. */
public final class StringUtils {
/* [ CONSTANTS ] ======================================================================================================================================= */
/** Our own class Logger instance. */
private final static Logger _log = LogEx.getLogger(StringUtils.class);
/** Default strings encoding. */
public final static String UTF8 = "UTF-8";
/* [ CONSTRUCTORS ] ==================================================================================================================================== */
/** Hidden constructor. */
private StringUtils() {
throw new AssertionError();
}
/* [ STATIC METHODS ] ================================================================================================================================== */
/**
* Convert string to utf 8 bytes.
*
* @param value the value to convert
* @return the bytes in UTF8 encoding.
*/
public static byte[] toUtf8Bytes(final String value) {
ValidUtils.isEmpty(value, "Expected not null value.");
// try to avoid NULL values, better to return empty array
byte[] buffer = new byte[]{};
if (!TextUtils.isEmpty(value)) {
try {
buffer = value.getBytes(StringUtils.UTF8);
} catch (final UnsupportedEncodingException e) {
_log.severe(LogEx.dump(e));
}
}
return buffer;
}
}
| mit |
wmzsoft/JXADF | Source/JxADF/JxPlatform/src/main/java/com/jxtech/distributed/zookeeper/pool/ZookeeperPoolManager.java | 3203 | package com.jxtech.distributed.zookeeper.pool;
import java.util.NoSuchElementException;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.StackObjectPool;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jxtech.distributed.Configuration;
/**
* ZK实例池管理器
*
* @author wmzsoft@gmail.com
*/
public class ZookeeperPoolManager {
private static final Logger LOG = LoggerFactory.getLogger(ZookeeperPoolManager.class);
/** 单例 */
protected static ZookeeperPoolManager instance;
private ObjectPool pool;
/**
* 构造方法
*/
private ZookeeperPoolManager() {
init();
}
/**
* 返回单例的对象
*
* @return
*/
public static ZookeeperPoolManager getInstance() {
if (instance == null) {
instance = new ZookeeperPoolManager();
}
return instance;
}
/**
* 初始化方法zookeeper连接池
*
* @param config
*/
private void init() {
if (pool != null) {
LOG.debug("pool is already init");
return;
}
Configuration config = Configuration.getInstance();
if (!config.isDeploy()) {
LOG.info("Can't init , deploy = false.");
return;
}
PoolableObjectFactory factory = new ZookeeperPoolableObjectFactory(config);
// 初始化ZK对象池
int maxIdle = config.getMaxIdle();
int initIdleCapacity = config.getInitIdleCapacity();
pool = new StackObjectPool(factory, maxIdle, initIdleCapacity);
// 初始化池
for (int i = 0; i < initIdleCapacity; i++) {
try {
pool.addObject();
} catch (IllegalStateException | UnsupportedOperationException ex) {
LOG.error(ex.getMessage(), ex);
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
/**
* 将ZK对象从对象池中取出
*
* @return
*/
public ZooKeeper borrowObject() {
if (pool != null) {
try {
return (ZooKeeper) pool.borrowObject();
} catch (NoSuchElementException | IllegalStateException ex) {
LOG.error(ex.getMessage(), ex);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
return null;
}
/**
* 将ZK实例返回对象池
*
* @param zk
*/
public void returnObject(ZooKeeper zk) {
if (pool != null && zk != null) {
try {
pool.returnObject(zk);
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
/**
* 关闭对象池
*/
public void close() {
if (pool != null) {
try {
pool.close();
LOG.info("关闭ZK对象池完成");
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
}
}
| mit |
NathanJAdams/verJ | src/math/Vector3.java | 4539 | package math;
import util.IReplicable;
public class Vector3 implements IReplicable<Vector3> {
private static final float MIN_TOLERANCE = (float) 1E-9;
public float x;
public float y;
public float z;
public static Vector3 of(float x, float y, float z) {
Vector3 vector = new Vector3();
vector.x = x;
vector.y = y;
vector.z = z;
return vector;
}
public static Vector3 getUnitX() {
Vector3 vector = new Vector3();
vector.x = 1;
return vector;
}
public static Vector3 getUnitY() {
Vector3 vector = new Vector3();
vector.y = 1;
return vector;
}
public static Vector3 getUnitZ() {
Vector3 vector = new Vector3();
vector.z = 1;
return vector;
}
public static Vector3 getUnit() {
Vector3 vector = new Vector3();
vector.x = 1;
vector.y = 1;
vector.z = 1;
return vector;
}
public boolean isUnitX() {
return (x == 1) && (y == 0) && (z == 0);
}
public boolean isUnitY() {
return (x == 0) && (y == 1) && (z == 0);
}
public boolean isUnitZ() {
return (x == 0) && (y == 0) && (z == 1);
}
public boolean isUnit() {
return (x == 1) && (y == 1) && (z == 1);
}
public float lengthSquared() {
return (x * x) + (y * y) + (z * z);
}
public float length() {
return (float) Math.sqrt(lengthSquared());
}
public float inverseLength() {
return 1f / length();
}
public static Vector3 add(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
add(result, a, b);
return result;
}
public static void add(Vector3 result, Vector3 a, Vector3 b) {
result.x = a.x + b.x;
result.y = a.y + b.y;
result.z = a.z + b.z;
}
public static Vector3 subtract(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
subtract(result, a, b);
return result;
}
public static void subtract(Vector3 result, Vector3 a, Vector3 b) {
result.x = a.x - b.x;
result.y = a.y - b.y;
result.z = a.z - b.z;
}
public static Vector3 multiply(Vector3 a, float scalar) {
Vector3 result = new Vector3();
multiply(result, a, scalar);
return result;
}
public static void multiply(Vector3 result, Vector3 a, float scalar) {
result.x = a.x * scalar;
result.y = a.y * scalar;
result.z = a.z * scalar;
}
public static Vector3 divide(Vector3 a, float scalar) {
Vector3 result = new Vector3();
divide(result, a, scalar);
return result;
}
public static void divide(Vector3 result, Vector3 a, float scalar) {
float multiplier = (scalar <= MIN_TOLERANCE)
? 0
: 1f / scalar;
multiply(result, a, multiplier);
}
public static float dot(Vector3 a, Vector3 b) {
return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
}
public static Vector3 cross(Vector3 a, Vector3 b) {
Vector3 result = new Vector3();
cross(result, a, b);
return result;
}
public static void cross(Vector3 result, Vector3 a, Vector3 b) {
float x = (a.y * b.z) - (a.z * b.y);
float y = (a.z * b.x) - (a.x * b.z);
float z = (a.x * b.y) - (a.y * b.x);
result.x = x;
result.y = y;
result.z = z;
}
public static Vector3 negate(Vector3 a) {
Vector3 result = new Vector3();
negate(result, a);
return result;
}
public static void negate(Vector3 result, Vector3 a) {
result.x = -a.x;
result.y = -a.y;
result.z = -a.z;
}
public static Vector3 normalise(Vector3 a) {
Vector3 result = new Vector3();
normalise(result, a);
return result;
}
public static void normalise(Vector3 result, Vector3 a) {
float sumSq = (a.x * a.x) + (a.y * a.y) + (a.z * a.z);
if (sumSq <= MIN_TOLERANCE) {
result.x = 0;
result.y = 1;
result.z = 0;
} else {
double sum = Math.sqrt(sumSq);
multiply(result, a, (float) (1.0 / sum));
}
}
@Override
public Vector3 createBlank() {
return new Vector3();
}
@Override
public void copyFrom(Vector3 master) {
this.x = master.x;
this.y = master.y;
this.z = master.z;
}
}
| mit |
TechnoWolves5518/2015RobotCode | JoystickDemo2/src/org/usfirst/frc/team5518/robot/subsystems/DrivingSys.java | 1232 | package org.usfirst.frc.team5518.robot.subsystems;
import org.usfirst.frc.team5518.robot.RobotMap;
import org.usfirst.frc.team5518.robot.commands.ArcadeDriveJoystick;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class DrivingSys extends Subsystem {
private RobotDrive robotDrive;
public DrivingSys() {
super();
robotDrive = new RobotDrive(RobotMap.FRONT_LEFT_MOTOR, RobotMap.REAR_LEFT_MOTOR,
RobotMap.FRONT_RIGHT_MOTOR, RobotMap.REAR_RIGHT_MOTOR);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
setDefaultCommand(new ArcadeDriveJoystick());
}
public void drive(GenericHID moveStick, final int moveAxis,
GenericHID rotateStick, final int rotateAxis) {
robotDrive.arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis);
}
public void drive(double moveValue, double rotateValue) {
robotDrive.arcadeDrive(moveValue, rotateValue);
}
public void log() {
}
}
| mit |
RCoon/HackerRank | algorithms/sorting/FindIndexIntro.java | 1297 | package algorithms.sorting;
import java.util.Scanner;
/*
* Sample Challenge
* This is a simple challenge to get things started. Given a sorted array (ar)
* and a number (V), can you print the index location of V in the array?
*
* Input Format:
* There will be three lines of input:
*
* V - the value that has to be searched.
* n - the size of the array.
* ar - n numbers that make up the array.
*
* Output Format:
* Output the index of V in the array.
*
* Constraints:
* 1 <= n <= 1000
* -1000 <= V <= 1000, V is an element of ar
* It is guaranteed that V will occur in ar exactly once.
*
* Sample Input:
* 4
* 6
* 1 4 5 7 9 12
*
* Sample Output:
* 1
*/
public class FindIndexIntro {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int target = sc.nextInt();
int arraySize = sc.nextInt();
int targetIndex = -1;
int arrayIndex = 0;
while (arrayIndex < arraySize) {
if (target == sc.nextInt()) {
targetIndex = arrayIndex;
break;
}
arrayIndex++;
}
sc.close();
System.out.println(targetIndex);
}
} | mit |
selvasingh/azure-sdk-for-java | sdk/storage/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/storage/v2019_04_01/StorageAccountUpdateParameters.java | 14066 | /**
* 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.v2019_04_01;
import com.microsoft.azure.management.storage.v2019_04_01.implementation.SkuInner;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
/**
* The parameters that can be provided when updating the storage account
* properties.
*/
@JsonFlatten
public class StorageAccountUpdateParameters {
/**
* Gets or sets the SKU name. Note that the SKU name cannot be updated to
* Standard_ZRS, Premium_LRS or Premium_ZRS, nor can accounts of those SKU
* names be updated to any other value.
*/
@JsonProperty(value = "sku")
private SkuInner sku;
/**
* Gets or sets a list of key value pairs that describe the resource. These
* tags can be used in viewing and grouping this resource (across resource
* groups). A maximum of 15 tags can be provided for a resource. Each tag
* must have a key no greater in length than 128 characters and a value no
* greater in length than 256 characters.
*/
@JsonProperty(value = "tags")
private Map<String, String> tags;
/**
* The identity of the resource.
*/
@JsonProperty(value = "identity")
private Identity identity;
/**
* Custom domain assigned to the storage account by the user. Name is the
* CNAME source. Only one custom domain is supported per storage account at
* this time. To clear the existing custom domain, use an empty string for
* the custom domain name property.
*/
@JsonProperty(value = "properties.customDomain")
private CustomDomain customDomain;
/**
* Provides the encryption settings on the account. The default setting is
* unencrypted.
*/
@JsonProperty(value = "properties.encryption")
private Encryption encryption;
/**
* Required for storage accounts where kind = BlobStorage. The access tier
* used for billing. Possible values include: 'Hot', 'Cool'.
*/
@JsonProperty(value = "properties.accessTier")
private AccessTier accessTier;
/**
* Provides the identity based authentication settings for Azure Files.
*/
@JsonProperty(value = "properties.azureFilesIdentityBasedAuthentication")
private AzureFilesIdentityBasedAuthentication azureFilesIdentityBasedAuthentication;
/**
* Allows https traffic only to storage service if sets to true.
*/
@JsonProperty(value = "properties.supportsHttpsTrafficOnly")
private Boolean enableHttpsTrafficOnly;
/**
* Network rule set.
*/
@JsonProperty(value = "properties.networkAcls")
private NetworkRuleSet networkRuleSet;
/**
* Allow large file shares if sets to Enabled. It cannot be disabled once
* it is enabled. Possible values include: 'Disabled', 'Enabled'.
*/
@JsonProperty(value = "properties.largeFileSharesState")
private LargeFileSharesState largeFileSharesState;
/**
* Allow or disallow public access to all blobs or containers in the
* storage account. The default interpretation is true for this property.
*/
@JsonProperty(value = "properties.allowBlobPublicAccess")
private Boolean allowBlobPublicAccess;
/**
* Set the minimum TLS version to be permitted on requests to storage. The
* default interpretation is TLS 1.0 for this property. Possible values
* include: 'TLS1_0', 'TLS1_1', 'TLS1_2'.
*/
@JsonProperty(value = "properties.minimumTlsVersion")
private MinimumTlsVersion minimumTlsVersion;
/**
* Optional. Indicates the type of storage account. Currently only
* StorageV2 value supported by server. Possible values include: 'Storage',
* 'StorageV2', 'BlobStorage', 'FileStorage', 'BlockBlobStorage'.
*/
@JsonProperty(value = "kind")
private Kind kind;
/**
* Get gets or sets the SKU name. Note that the SKU name cannot be updated to Standard_ZRS, Premium_LRS or Premium_ZRS, nor can accounts of those SKU names be updated to any other value.
*
* @return the sku value
*/
public SkuInner sku() {
return this.sku;
}
/**
* Set gets or sets the SKU name. Note that the SKU name cannot be updated to Standard_ZRS, Premium_LRS or Premium_ZRS, nor can accounts of those SKU names be updated to any other value.
*
* @param sku the sku value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withSku(SkuInner sku) {
this.sku = sku;
return this;
}
/**
* Get gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater in length than 128 characters and a value no greater in length than 256 characters.
*
* @return the tags value
*/
public Map<String, String> tags() {
return this.tags;
}
/**
* Set gets or sets a list of key value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater in length than 128 characters and a value no greater in length than 256 characters.
*
* @param tags the tags value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
/**
* Get the identity of the resource.
*
* @return the identity value
*/
public Identity identity() {
return this.identity;
}
/**
* Set the identity of the resource.
*
* @param identity the identity value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withIdentity(Identity identity) {
this.identity = identity;
return this;
}
/**
* Get custom domain assigned to the storage account by the user. Name is the CNAME source. Only one custom domain is supported per storage account at this time. To clear the existing custom domain, use an empty string for the custom domain name property.
*
* @return the customDomain value
*/
public CustomDomain customDomain() {
return this.customDomain;
}
/**
* Set custom domain assigned to the storage account by the user. Name is the CNAME source. Only one custom domain is supported per storage account at this time. To clear the existing custom domain, use an empty string for the custom domain name property.
*
* @param customDomain the customDomain value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withCustomDomain(CustomDomain customDomain) {
this.customDomain = customDomain;
return this;
}
/**
* Get provides the encryption settings on the account. The default setting is unencrypted.
*
* @return the encryption value
*/
public Encryption encryption() {
return this.encryption;
}
/**
* Set provides the encryption settings on the account. The default setting is unencrypted.
*
* @param encryption the encryption value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withEncryption(Encryption encryption) {
this.encryption = encryption;
return this;
}
/**
* Get required for storage accounts where kind = BlobStorage. The access tier used for billing. Possible values include: 'Hot', 'Cool'.
*
* @return the accessTier value
*/
public AccessTier accessTier() {
return this.accessTier;
}
/**
* Set required for storage accounts where kind = BlobStorage. The access tier used for billing. Possible values include: 'Hot', 'Cool'.
*
* @param accessTier the accessTier value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withAccessTier(AccessTier accessTier) {
this.accessTier = accessTier;
return this;
}
/**
* Get provides the identity based authentication settings for Azure Files.
*
* @return the azureFilesIdentityBasedAuthentication value
*/
public AzureFilesIdentityBasedAuthentication azureFilesIdentityBasedAuthentication() {
return this.azureFilesIdentityBasedAuthentication;
}
/**
* Set provides the identity based authentication settings for Azure Files.
*
* @param azureFilesIdentityBasedAuthentication the azureFilesIdentityBasedAuthentication value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withAzureFilesIdentityBasedAuthentication(AzureFilesIdentityBasedAuthentication azureFilesIdentityBasedAuthentication) {
this.azureFilesIdentityBasedAuthentication = azureFilesIdentityBasedAuthentication;
return this;
}
/**
* Get allows https traffic only to storage service if sets to true.
*
* @return the enableHttpsTrafficOnly value
*/
public Boolean enableHttpsTrafficOnly() {
return this.enableHttpsTrafficOnly;
}
/**
* Set allows https traffic only to storage service if sets to true.
*
* @param enableHttpsTrafficOnly the enableHttpsTrafficOnly value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withEnableHttpsTrafficOnly(Boolean enableHttpsTrafficOnly) {
this.enableHttpsTrafficOnly = enableHttpsTrafficOnly;
return this;
}
/**
* Get network rule set.
*
* @return the networkRuleSet value
*/
public NetworkRuleSet networkRuleSet() {
return this.networkRuleSet;
}
/**
* Set network rule set.
*
* @param networkRuleSet the networkRuleSet value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withNetworkRuleSet(NetworkRuleSet networkRuleSet) {
this.networkRuleSet = networkRuleSet;
return this;
}
/**
* Get allow large file shares if sets to Enabled. It cannot be disabled once it is enabled. Possible values include: 'Disabled', 'Enabled'.
*
* @return the largeFileSharesState value
*/
public LargeFileSharesState largeFileSharesState() {
return this.largeFileSharesState;
}
/**
* Set allow large file shares if sets to Enabled. It cannot be disabled once it is enabled. Possible values include: 'Disabled', 'Enabled'.
*
* @param largeFileSharesState the largeFileSharesState value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withLargeFileSharesState(LargeFileSharesState largeFileSharesState) {
this.largeFileSharesState = largeFileSharesState;
return this;
}
/**
* Get allow or disallow public access to all blobs or containers in the storage account. The default interpretation is true for this property.
*
* @return the allowBlobPublicAccess value
*/
public Boolean allowBlobPublicAccess() {
return this.allowBlobPublicAccess;
}
/**
* Set allow or disallow public access to all blobs or containers in the storage account. The default interpretation is true for this property.
*
* @param allowBlobPublicAccess the allowBlobPublicAccess value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withAllowBlobPublicAccess(Boolean allowBlobPublicAccess) {
this.allowBlobPublicAccess = allowBlobPublicAccess;
return this;
}
/**
* Get set the minimum TLS version to be permitted on requests to storage. The default interpretation is TLS 1.0 for this property. Possible values include: 'TLS1_0', 'TLS1_1', 'TLS1_2'.
*
* @return the minimumTlsVersion value
*/
public MinimumTlsVersion minimumTlsVersion() {
return this.minimumTlsVersion;
}
/**
* Set set the minimum TLS version to be permitted on requests to storage. The default interpretation is TLS 1.0 for this property. Possible values include: 'TLS1_0', 'TLS1_1', 'TLS1_2'.
*
* @param minimumTlsVersion the minimumTlsVersion value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withMinimumTlsVersion(MinimumTlsVersion minimumTlsVersion) {
this.minimumTlsVersion = minimumTlsVersion;
return this;
}
/**
* Get optional. Indicates the type of storage account. Currently only StorageV2 value supported by server. Possible values include: 'Storage', 'StorageV2', 'BlobStorage', 'FileStorage', 'BlockBlobStorage'.
*
* @return the kind value
*/
public Kind kind() {
return this.kind;
}
/**
* Set optional. Indicates the type of storage account. Currently only StorageV2 value supported by server. Possible values include: 'Storage', 'StorageV2', 'BlobStorage', 'FileStorage', 'BlockBlobStorage'.
*
* @param kind the kind value to set
* @return the StorageAccountUpdateParameters object itself.
*/
public StorageAccountUpdateParameters withKind(Kind kind) {
this.kind = kind;
return this;
}
}
| mit |
julianmendez/desktop-search | search-core/src/main/java/com/semantic/swing/tree/querybuilder/QueryPipeline.java | 1651 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.semantic.swing.tree.querybuilder;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
/**
*
* @author Christian Plonka (cplonka81@gmail.com)
*/
public class QueryPipeline {
private List<IQueryBuilder> builders;
private Query currentQuery;
public Query getCurrentQuery() {
return currentQuery;
}
public Query generateQuery() {
return currentQuery = generateQuery(false);
}
public Query generateBaseQuery() {
return generateQuery(true);
}
private Query generateQuery(boolean baseQuery) {
BooleanQuery.Builder ret = new BooleanQuery.Builder();
for (IQueryBuilder builder : builders) {
Query query = null;
if (baseQuery) {
// only create basequery
if (builder.isBaseQuery()) {
query = builder.createQuery();
}
} else {
query = builder.createQuery();
}
if (query != null) {
ret.add(query, builder.getCondition());
}
}
return ret.build();
}
public void addQueryBuilder(IQueryBuilder builder) {
if (builders == null) {
builders = new ArrayList<IQueryBuilder>();
}
builders.add(builder);
}
public void removeQueryBuilder(IQueryBuilder builder) {
if (builders != null) {
builders.remove(builder);
}
}
}
| mit |
low205/JavaTests | src/ru/sigma/test/learning/data/ExponentialDemo.java | 780 | package ru.sigma.test.learning.data;
/**
* Created with IntelliJ IDEA.
* User: emaltsev
* Date: 22.11.13
* Time: 10:37
* To change this template use File | Settings | File Templates.
*/
public class ExponentialDemo {
public static void main(String[] args) {
double x = 11.635;
double y = 2.76;
System.out.printf("The value of " + "e is %.4f%n",
Math.E);
System.out.printf("exp(%.3f) " + "is %.3f%n",
x, Math.exp(x));
System.out.printf("log(%.3f) is " + "%.3f%n",
x, Math.log(x));
System.out.printf("pow(%.3f, %.3f) " + "is %.3f%n",
x, y, Math.pow(x, y));
System.out.printf("sqrt(%.3f) is " + "%.3f%n",
x, Math.sqrt(x));
}
}
| mit |
kevmo314/canigraduate.uchicago.edu | backend/uchicago/scraper/src/main/java/com/canigraduate/uchicago/models/Activity.java | 73 | package com.canigraduate.uchicago.models;
public interface Activity {
}
| mit |
Yndal/ArduPilot-SensorPlatform | Tower_with_3drservices/dependencyLibs/Core/src/org/droidplanner/core/MAVLink/WaypointManager.java | 11062 | package org.droidplanner.core.MAVLink;
import com.MAVLink.Messages.MAVLinkMessage;
import com.MAVLink.common.msg_mission_ack;
import com.MAVLink.common.msg_mission_count;
import com.MAVLink.common.msg_mission_current;
import com.MAVLink.common.msg_mission_item;
import com.MAVLink.common.msg_mission_item_reached;
import com.MAVLink.common.msg_mission_request;
import org.droidplanner.core.drone.DroneInterfaces;
import org.droidplanner.core.drone.DroneInterfaces.OnWaypointManagerListener;
import org.droidplanner.core.drone.DroneVariable;
import org.droidplanner.core.model.Drone;
import java.util.ArrayList;
import java.util.List;
/**
* Class to manage the communication of waypoints to the MAV.
* <p/>
* Should be initialized with a MAVLink Object, so the manager can send messages
* via the MAV link. The function processMessage must be called with every new
* MAV Message.
*/
public class WaypointManager extends DroneVariable {
enum WaypointStates {
IDLE, READ_REQUEST, READING_WP, WRITING_WP_COUNT, WRITING_WP, WAITING_WRITE_ACK
}
public enum WaypointEvent_Type {
WP_UPLOAD, WP_DOWNLOAD, WP_RETRY, WP_CONTINUE, WP_TIMED_OUT
}
private static final long TIMEOUT = 15000; //ms
private static final int RETRY_LIMIT = 3;
private int retryTracker = 0;
private int readIndex;
private int writeIndex;
private int retryIndex;
private OnWaypointManagerListener wpEventListener;
WaypointStates state = WaypointStates.IDLE;
/**
* waypoint witch is currently being written
*/
private final DroneInterfaces.Handler watchdog;
private final Runnable watchdogCallback = new Runnable() {
@Override
public void run() {
if (processTimeOut(++retryTracker))
watchdog.postDelayed(this, TIMEOUT);
}
};
public WaypointManager(Drone drone, DroneInterfaces.Handler handler) {
super(drone);
this.watchdog = handler;
}
public void setWaypointManagerListener(OnWaypointManagerListener wpEventListener) {
this.wpEventListener = wpEventListener;
}
private void startWatchdog() {
stopWatchdog();
retryTracker = 0;
this.watchdog.postDelayed(watchdogCallback, TIMEOUT);
}
private void stopWatchdog() {
this.watchdog.removeCallbacks(watchdogCallback);
}
/**
* Try to receive all waypoints from the MAV.
* <p/>
* If all runs well the callback will return the list of waypoints.
*/
public void getWaypoints() {
// ensure that WPManager is not doing anything else
if (state != WaypointStates.IDLE)
return;
doBeginWaypointEvent(WaypointEvent_Type.WP_DOWNLOAD);
readIndex = -1;
state = WaypointStates.READ_REQUEST;
MavLinkWaypoint.requestWaypointsList(myDrone);
startWatchdog();
}
/**
* Write a list of waypoints to the MAV.
* <p/>
* The callback will return the status of this operation
*
* @param data waypoints to be written
*/
public void writeWaypoints(List<msg_mission_item> data) {
// ensure that WPManager is not doing anything else
if (state != WaypointStates.IDLE)
return;
if ((mission != null)) {
doBeginWaypointEvent(WaypointEvent_Type.WP_UPLOAD);
updateMsgIndexes(data);
mission.clear();
mission.addAll(data);
writeIndex = 0;
state = WaypointStates.WRITING_WP_COUNT;
MavLinkWaypoint.sendWaypointCount(myDrone, mission.size());
startWatchdog();
}
}
private void updateMsgIndexes(List<msg_mission_item> data) {
short index = 0;
for (msg_mission_item msg : data) {
msg.seq = index++;
}
}
/**
* Sets the current waypoint in the MAV
* <p/>
* The callback will return the status of this operation
*/
public void setCurrentWaypoint(int i) {
if ((mission != null)) {
MavLinkWaypoint.sendSetCurrentWaypoint(myDrone, (short) i);
}
}
/**
* Callback for when a waypoint has been reached
*
* @param wpNumber number of the completed waypoint
*/
public void onWaypointReached(int wpNumber) {
}
/**
* Callback for a change in the current waypoint the MAV is heading for
*
* @param seq number of the updated waypoint
*/
private void onCurrentWaypointUpdate(short seq) {
}
/**
* number of waypoints to be received, used when reading waypoints
*/
private short waypointCount;
/**
* list of waypoints used when writing or receiving
*/
private List<msg_mission_item> mission = new ArrayList<msg_mission_item>();
/**
* Try to process a Mavlink message if it is a mission related message
*
* @param msg Mavlink message to process
* @return Returns true if the message has been processed
*/
public boolean processMessage(MAVLinkMessage msg) {
switch (state) {
default:
case IDLE:
break;
case READ_REQUEST:
if (msg.msgid == msg_mission_count.MAVLINK_MSG_ID_MISSION_COUNT) {
waypointCount = ((msg_mission_count) msg).count;
mission.clear();
startWatchdog();
MavLinkWaypoint.requestWayPoint(myDrone, mission.size());
state = WaypointStates.READING_WP;
return true;
}
break;
case READING_WP:
if (msg.msgid == msg_mission_item.MAVLINK_MSG_ID_MISSION_ITEM) {
startWatchdog();
processReceivedWaypoint((msg_mission_item) msg);
doWaypointEvent(WaypointEvent_Type.WP_DOWNLOAD, readIndex + 1, waypointCount);
if (mission.size() < waypointCount) {
MavLinkWaypoint.requestWayPoint(myDrone, mission.size());
} else {
stopWatchdog();
state = WaypointStates.IDLE;
MavLinkWaypoint.sendAck(myDrone);
myDrone.getMission().onMissionReceived(mission);
doEndWaypointEvent(WaypointEvent_Type.WP_DOWNLOAD);
}
return true;
}
break;
case WRITING_WP_COUNT:
state = WaypointStates.WRITING_WP;
case WRITING_WP:
if (msg.msgid == msg_mission_request.MAVLINK_MSG_ID_MISSION_REQUEST) {
startWatchdog();
processWaypointToSend((msg_mission_request) msg);
doWaypointEvent(WaypointEvent_Type.WP_UPLOAD, writeIndex + 1, mission.size());
return true;
}
break;
case WAITING_WRITE_ACK:
if (msg.msgid == msg_mission_ack.MAVLINK_MSG_ID_MISSION_ACK) {
stopWatchdog();
myDrone.getMission().onWriteWaypoints((msg_mission_ack) msg);
state = WaypointStates.IDLE;
doEndWaypointEvent(WaypointEvent_Type.WP_UPLOAD);
return true;
}
break;
}
if (msg.msgid == msg_mission_item_reached.MAVLINK_MSG_ID_MISSION_ITEM_REACHED) {
onWaypointReached(((msg_mission_item_reached) msg).seq);
return true;
}
if (msg.msgid == msg_mission_current.MAVLINK_MSG_ID_MISSION_CURRENT) {
onCurrentWaypointUpdate(((msg_mission_current) msg).seq);
return true;
}
return false;
}
public boolean processTimeOut(int mTimeOutCount) {
// If max retry is reached, set state to IDLE. No more retry.
if (mTimeOutCount >= RETRY_LIMIT) {
state = WaypointStates.IDLE;
doWaypointEvent(WaypointEvent_Type.WP_TIMED_OUT, retryIndex, RETRY_LIMIT);
return false;
}
retryIndex++;
doWaypointEvent(WaypointEvent_Type.WP_RETRY, retryIndex, RETRY_LIMIT);
switch (state) {
default:
case IDLE:
break;
case READ_REQUEST:
MavLinkWaypoint.requestWaypointsList(myDrone);
break;
case READING_WP:
if (mission.size() < waypointCount) { // request last lost WP
MavLinkWaypoint.requestWayPoint(myDrone, mission.size());
}
break;
case WRITING_WP_COUNT:
MavLinkWaypoint.sendWaypointCount(myDrone, mission.size());
break;
case WRITING_WP:
// Log.d("TIMEOUT", "re Write Msg: " + String.valueOf(writeIndex));
if (writeIndex < mission.size()) {
myDrone.getMavClient().sendMavPacket(mission.get(writeIndex).pack());
}
break;
case WAITING_WRITE_ACK:
myDrone.getMavClient().sendMavPacket(mission.get(mission.size() - 1).pack());
break;
}
return true;
}
private void processWaypointToSend(msg_mission_request msg) {
/*
* Log.d("TIMEOUT", "Write Msg: " + String.valueOf(msg.seq));
*/
writeIndex = msg.seq;
msg_mission_item item = mission.get(writeIndex);
item.target_system = myDrone.getSysid();
item.target_component = myDrone.getCompid();
myDrone.getMavClient().sendMavPacket(item.pack());
if (writeIndex + 1 >= mission.size()) {
state = WaypointStates.WAITING_WRITE_ACK;
}
}
private void processReceivedWaypoint(msg_mission_item msg) {
/*
* Log.d("TIMEOUT", "Read Last/Curr: " + String.valueOf(readIndex) + "/"
* + String.valueOf(msg.seq));
*/
// in case of we receive the same WP again after retry
if (msg.seq <= readIndex)
return;
readIndex = msg.seq;
mission.add(msg);
}
private void doBeginWaypointEvent(WaypointEvent_Type wpEvent) {
retryIndex = 0;
if (wpEventListener == null)
return;
wpEventListener.onBeginWaypointEvent(wpEvent);
}
private void doEndWaypointEvent(WaypointEvent_Type wpEvent) {
if (retryIndex > 0)// if retry successful, notify that we now continue
doWaypointEvent(WaypointEvent_Type.WP_CONTINUE, retryIndex, RETRY_LIMIT);
retryIndex = 0;
if (wpEventListener == null)
return;
wpEventListener.onEndWaypointEvent(wpEvent);
}
private void doWaypointEvent(WaypointEvent_Type wpEvent, int index, int count) {
retryIndex = 0;
if (wpEventListener == null)
return;
wpEventListener.onWaypointEvent(wpEvent, index, count);
}
}
| mit |
markuswustenberg/jsense | jsense-protobuf/src/test/java/org/jsense/serialize/TestProtocolBuffersDeserializers.java | 3943 | package org.jsense.serialize;
import com.google.common.collect.ImmutableList;
import org.joda.time.Instant;
import org.joda.time.ReadableInstant;
import org.jsense.AccelerometerEvent;
import org.jsense.ModelFactory;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import static org.junit.Assert.*;
/**
* Tests the {@link org.jsense.serialize.PbAccelerometerEventDeserializer}.
*
* @author Markus Wüstenberg
*/
public class TestProtocolBuffersDeserializers {
private static final int SEED = 88951;
private static final ReadableInstant ABSOLUTE_TIMESTAMP = new Instant(123L);
private static final long RELATIVE_TIMESTAMP = 124L;
private static final float X = 0.1f;
private static final float Y = 0.2f;
private static final float Z = 0.3f;
private AccelerometerEvent event1, event2;
@Before
public void setUp() throws IOException {
ModelFactory.setSeed(SEED);
event1 = ModelFactory.newRandomAccelerometerEvent();
event2 = ModelFactory.newRandomAccelerometerEvent();
}
@Test
public void deserializeSingleAccelerometerEvent() throws IOException {
Deserializer<AccelerometerEvent> deserializer = new PbAccelerometerEventDeserializer(new ByteArrayInputStream(getByteArrayFrom(ImmutableList.of(event1))));
Iterable<AccelerometerEvent> events = deserializer.deserialize();
Iterator<AccelerometerEvent> eventsIterator = events.iterator();
assertTrue(eventsIterator.hasNext());
assertEquals(event1, eventsIterator.next());
}
@Test
public void deserializeMultipleAccelerometerEvents() throws IOException {
Deserializer<AccelerometerEvent> deserializer = new PbAccelerometerEventDeserializer(new ByteArrayInputStream(getByteArrayFrom(ImmutableList.of(event1, event2))));
Iterable<AccelerometerEvent> events = deserializer.deserialize();
Iterator<AccelerometerEvent> eventsIterator = events.iterator();
assertTrue(eventsIterator.hasNext());
assertEquals(event1, eventsIterator.next());
assertTrue(eventsIterator.hasNext());
assertEquals(event2, eventsIterator.next());
}
@Test(expected = NullPointerException.class)
public void sourceCantBeNull() throws IOException {
new PbAccelerometerEventDeserializer(null);
}
@Test
public void deserializeMultipleAccelerometerEventsAndDontKeepState() throws IOException {
AccelerometerEvent eventWithRelativeTimestamp = AccelerometerEvent.newBuilder()
.setAbsoluteTimestamp(ABSOLUTE_TIMESTAMP)
.setRelativeTimestamp(RELATIVE_TIMESTAMP)
.setX(X)
.setY(Y)
.setZ(Z)
.build();
AccelerometerEvent eventNoRelativeTimestamp = AccelerometerEvent.newBuilder()
.setAbsoluteTimestamp(ABSOLUTE_TIMESTAMP)
.setX(X)
.setY(Y)
.setZ(Z)
.build();
ByteArrayInputStream serialized = new ByteArrayInputStream(getByteArrayFrom(ImmutableList.of(eventWithRelativeTimestamp, eventNoRelativeTimestamp)));
Deserializer<AccelerometerEvent> deserializer = new PbAccelerometerEventDeserializer(serialized);
Iterable<AccelerometerEvent> events = deserializer.deserialize();
Iterator<AccelerometerEvent> eventsIterator = events.iterator();
assertTrue(eventsIterator.next().hasRelativeTimestamp());
assertFalse(eventsIterator.next().hasRelativeTimestamp());
}
private byte[] getByteArrayFrom(Iterable<AccelerometerEvent> events) throws IOException {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
new PbAccelerometerEventSerializer(out).serialize(events).flush();
return out.toByteArray();
}
}
| mit |
CS2103JAN2017-F11-B1/main | src/main/java/seedu/jobs/logic/commands/PathCommand.java | 1421 | package seedu.jobs.logic.commands;
import java.io.IOException;
import com.google.common.eventbus.Subscribe;
import seedu.jobs.commons.core.EventsCenter;
import seedu.jobs.commons.events.storage.SavePathChangedEventException;
/* Change save path
*/
//@@author A0130979U
public class PathCommand extends Command {
public static final String COMMAND_WORD = "path";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Change save path. "
+ "Parameters: path [filename] \n"
+ "Example: " + COMMAND_WORD
+ " taskbook.xml";
private String path;
private boolean isValid;
public static final String MESSAGE_SUCCESS = "Save path has been successfully updated \n";
public static final String MESSAGE_INVALID_FILE_PATH = "This path is invalid";
public PathCommand(String path) {
this.path = path;
this.isValid = true;
EventsCenter.getInstance().registerHandler(this);
}
@Override
public CommandResult execute() throws IOException {
assert model != null;
model.changePath(path);
if (!isValid) {
throw new IOException(MESSAGE_INVALID_FILE_PATH);
}
return new CommandResult(String.format(MESSAGE_SUCCESS));
}
@Subscribe
public void handleSavePathChangedEventException(SavePathChangedEventException event) {
isValid = false;
}
}
//@@author
| mit |
yizhuan/tradingac | src/main/java/mobi/qubits/tradingapp/query/QuoteEntity.java | 1859 | package mobi.qubits.tradingapp.query;
import java.util.Date;
import org.springframework.data.annotation.Id;
public class QuoteEntity {
@Id
private String id;
private String symbol;
private String name;
private float open;
private float prevClose;
private float currentQuote;
private float high;
private float low;
private String date;
private String quoteTime;
private Date timestamp;
public QuoteEntity() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getOpen() {
return open;
}
public void setOpen(float open) {
this.open = open;
}
public float getPrevClose() {
return prevClose;
}
public void setPrevClose(float prevClose) {
this.prevClose = prevClose;
}
public float getCurrentQuote() {
return currentQuote;
}
public void setCurrentQuote(float currentQuote) {
this.currentQuote = currentQuote;
}
public float getHigh() {
return high;
}
public void setHigh(float high) {
this.high = high;
}
public float getLow() {
return low;
}
public void setLow(float low) {
this.low = low;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getQuoteTime() {
return quoteTime;
}
public void setQuoteTime(String quoteTime) {
this.quoteTime = quoteTime;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
| mit |
axel-halin/Thesis-JHipster | FML-brute/jhipsters/uaa/src/main/java/io/variability/jhipster/security/SpringSecurityAuditorAware.java | 548 | package io.variability.jhipster.security;
import io.variability.jhipster.config.Constants;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
/**
* Implementation of AuditorAware based on Spring Security.
*/
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
String userName = SecurityUtils.getCurrentUserLogin();
return (userName != null ? userName : Constants.SYSTEM_ACCOUNT);
}
}
| mit |
Azure/azure-sdk-for-java | sdk/automation/azure-resourcemanager-automation/src/main/java/com/azure/resourcemanager/automation/models/ConnectionListResult.java | 2244 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.automation.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.automation.fluent.models.ConnectionInner;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The response model for the list connection operation. */
@Fluent
public final class ConnectionListResult {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ConnectionListResult.class);
/*
* Gets or sets a list of connection.
*/
@JsonProperty(value = "value")
private List<ConnectionInner> value;
/*
* Gets or sets the next link.
*/
@JsonProperty(value = "nextLink")
private String nextLink;
/**
* Get the value property: Gets or sets a list of connection.
*
* @return the value value.
*/
public List<ConnectionInner> value() {
return this.value;
}
/**
* Set the value property: Gets or sets a list of connection.
*
* @param value the value value to set.
* @return the ConnectionListResult object itself.
*/
public ConnectionListResult withValue(List<ConnectionInner> value) {
this.value = value;
return this;
}
/**
* Get the nextLink property: Gets or sets the next link.
*
* @return the nextLink value.
*/
public String nextLink() {
return this.nextLink;
}
/**
* Set the nextLink property: Gets or sets the next link.
*
* @param nextLink the nextLink value to set.
* @return the ConnectionListResult object itself.
*/
public ConnectionListResult withNextLink(String nextLink) {
this.nextLink = nextLink;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (value() != null) {
value().forEach(e -> e.validate());
}
}
}
| mit |
darevalor/Ecos-Tarea4 | src/main/java/co/edu/uniandes/ecos/tarea4/util/Constantes.java | 600 | /*
* Class Name: Constantes
* Name: Daniel Arevalo
* Date: 13/03/2016
* Version: 1.0
*/
package co.edu.uniandes.ecos.tarea4.util;
/**
* Clase utilitaria de constantes
* @author Daniel
*/
public class Constantes {
public static final String LOC_METHOD_DATA = "LOC/Method Data";
public static final String PGS_CHAPTER = "Pgs/Chapter";
public static final String CLASS_NAME = "Class Name";
public static final String PAGES = "Pages";
}
| mit |
butioy/webIM | butioy-framework-src/org/butioy/framework/security/XSSHttpServletRequestWrapper.java | 2507 | package org.butioy.framework.security;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* Created with IntelliJ IDEA.
* Author butioy
* Date 2015-09-18 22:33
*/
public class XSSHttpServletRequestWrapper extends HttpServletRequestWrapper {
HttpServletRequest orgRequest = null;
public XSSHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
orgRequest = request;
}
/**
* 覆盖getParameter方法,将参数名和参数值都做xss过滤。
* 如果需要获得原始的值,则通过super.getParameterValues(name)来获取
* getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
*/
@Override
public String getParameter(String name) {
String value = super.getParameter(xssEncode(name));
if(StringUtils.isNotBlank(value)) {
value = xssEncode(value);
}
return value;
}
/**
* 覆盖getHeader方法,将参数名和参数值都做xss过滤。
* 如果需要获得原始的值,则通过super.getHeaders(name)来获取
* getHeaderNames 也可能需要覆盖
*/
@Override
public String getHeader(String name) {
String value = super.getHeader(xssEncode(name));
if( StringUtils.isNotBlank(value) ) {
value = xssEncode(value);
}
return value;
}
/**
* 将容易引起xss漏洞的参数全部使用StringEscapeUtils转义
* @param value
* @return
*/
private static String xssEncode(String value) {
if (value == null || value.isEmpty()) {
return value;
}
value = StringEscapeUtils.escapeHtml4(value);
value = StringEscapeUtils.escapeEcmaScript(value);
return value;
}
/**
* 获取最原始的request
* @return
*/
public HttpServletRequest getOrgRequest() {
return orgRequest;
}
/**
* 获取最原始的request的静态方法
* @return
*/
public static HttpServletRequest getOrgRequest(HttpServletRequest request) {
if (request instanceof XSSHttpServletRequestWrapper) {
return ((XSSHttpServletRequestWrapper) request).getOrgRequest();
}
return request;
}
}
| mit |
felHR85/Pincho-Usb-Mass-Storage-for-Android | src/androidTest/java/com/felhr/usbmassstorageforandroid/bulkonlytests/UsbFacadeTest.java | 4796 | package com.felhr.usbmassstorageforandroid.bulkonlytests;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import com.felhr.usbmassstorageforandroid.bulkonly.UsbFacade;
import com.felhr.usbmassstorageforandroid.bulkonly.UsbFacadeInterface;
import android.hardware.usb.UsbEndpoint;
import android.test.InstrumentationTestCase;
import android.util.Log;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.junit.Before;
/**
* Created by Felipe Herranz(felhr85@gmail.com) on 17/12/14.
*/
public class UsbFacadeTest extends InstrumentationTestCase
{
private UsbFacade usbFacade;
// Mocked Usb objects
@Mock
private UsbDeviceConnection mConnection;
private UsbDevice mDevice;
private UsbInterface ifaceMocked;
private UsbEndpoint mockedInEndpoint;
private UsbEndpoint mockedOutEndpoint;
@Before
public void setUp()
{
System.setProperty("dexmaker.dexcache",
getInstrumentation().getTargetContext().getCacheDir().getPath());
initUsb(0);
}
@Test
public void testOpenDevice()
{
assertEquals(true, usbFacade.openDevice());
}
@Test
public void testSendCommand()
{
usbFacade.openDevice();
waitXtime(1000);
changeBulkMethod(31);
usbFacade.sendCommand(new byte[31]);
waitXtime(1000);
}
@Test
public void testSendData()
{
usbFacade.openDevice();
changeBulkMethod(10);
usbFacade.sendData(new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09});
}
@Test
public void testRequestCsw()
{
usbFacade.openDevice();
waitXtime(1000); // A handler must be declared inside a thread. This prevents a nullPointer
usbFacade.requestCsw();
}
@Test
public void testRequestData()
{
usbFacade.openDevice();
waitXtime(1000);
usbFacade.requestData(50);
}
private void initUsb(int bulkResponse)
{
mConnection = Mockito.mock(UsbDeviceConnection.class);
mDevice = Mockito.mock(UsbDevice.class);
// UsbInterface Mass storage device, Must be injected using a setter.
ifaceMocked = Mockito.mock(UsbInterface.class);
Mockito.when(ifaceMocked.getInterfaceClass()).thenReturn(UsbConstants.USB_CLASS_MASS_STORAGE);
Mockito.when(ifaceMocked.getInterfaceSubclass()).thenReturn(0x06);
Mockito.when(ifaceMocked.getInterfaceProtocol()).thenReturn(0x50);
Mockito.when(ifaceMocked.getEndpointCount()).thenReturn(0);
// UsbEndpoints IN,OUT. Must be injected using a setter
mockedInEndpoint = Mockito.mock(UsbEndpoint.class);
mockedOutEndpoint = Mockito.mock(UsbEndpoint.class);
// UsbDeviceConnection mocked methods
Mockito.when(mConnection.claimInterface(ifaceMocked, true)).thenReturn(true);
Mockito.when(mConnection.bulkTransfer(Mockito.any(UsbEndpoint.class), Mockito.any(byte[].class) ,Mockito.anyInt(), Mockito.anyInt())).thenReturn(bulkResponse);
// UsbDevice mocked methods
Mockito.when(mDevice.getInterfaceCount()).thenReturn(1);
// Initialize and inject dependencies
usbFacade = new UsbFacade(mDevice, mConnection);
usbFacade.setCallback(mCallback);
usbFacade.injectInterface(ifaceMocked);
usbFacade.injectInEndpoint(mockedInEndpoint);
usbFacade.injectOutEndpoint(mockedOutEndpoint);
}
private void changeBulkMethod(int response)
{
Mockito.when(mConnection.bulkTransfer(Mockito.any(UsbEndpoint.class), Mockito.any(byte[].class) , Mockito.anyInt(), Mockito.anyInt())).thenReturn(response);
}
private synchronized void waitXtime(long millis)
{
try
{
wait(millis);
}catch(InterruptedException e)
{
e.printStackTrace();
}
}
private UsbFacadeInterface mCallback = new UsbFacadeInterface()
{
@Override
public void cbwResponse(int response)
{
Log.d("UsbFacadeTest", "cbwResponse: " + String.valueOf(response));
}
@Override
public void cswData(byte[] data)
{
Log.d("UsbFacadeTest", "cswData: " + String.valueOf(data.length));
}
@Override
public void dataFromHost(int response)
{
Log.d("UsbFacadeTest", "Data from Host response: " + String.valueOf(response));
}
@Override
public void dataToHost(byte[] data)
{
Log.d("UsbFacadeTest", "Length buffer: " + String.valueOf(data.length));
}
};
}
| mit |
dohr-michael/storyline-character | src/main/java/org/mdo/storyline/character/config/WebConfigurer.java | 6892 | package org.mdo.storyline.character.config;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.servlet.InstrumentedFilter;
import com.codahale.metrics.servlets.MetricsServlet;
import org.mdo.storyline.character.web.filter.CachingHttpHeadersFilter;
import org.mdo.storyline.character.web.filter.StaticResourcesProductionFilter;
import org.mdo.storyline.character.web.filter.gzip.GZipServletFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.boot.context.embedded.ServletContextInitializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import javax.inject.Inject;
import javax.servlet.*;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* Configuration of web application with Servlet 3.0 APIs.
*/
@Configuration
@AutoConfigureAfter(CacheConfiguration.class)
public class WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer {
private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);
@Inject
private Environment env;
@Inject
private MetricRegistry metricRegistry;
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
log.info("Web application configuration, using profiles: {}", Arrays.toString(env.getActiveProfiles()));
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
initMetrics(servletContext, disps);
if (env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) {
initCachingHttpHeadersFilter(servletContext, disps);
initStaticResourcesProductionFilter(servletContext, disps);
}
initGzipFilter(servletContext, disps);
log.info("Web application fully configured");
}
/**
* Set up Mime types.
*/
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
// IE issue, see https://github.com/jhipster/generator-jhipster/pull/711
mappings.add("html", "text/html;charset=utf-8");
// CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
mappings.add("json", "text/html;charset=utf-8");
container.setMimeMappings(mappings);
}
/**
* Initializes the GZip filter.
*/
private void initGzipFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {
log.debug("Registering GZip Filter");
FilterRegistration.Dynamic compressingFilter = servletContext.addFilter("gzipFilter", new GZipServletFilter());
Map<String, String> parameters = new HashMap<>();
compressingFilter.setInitParameters(parameters);
compressingFilter.addMappingForUrlPatterns(disps, true, "*.css");
compressingFilter.addMappingForUrlPatterns(disps, true, "*.json");
compressingFilter.addMappingForUrlPatterns(disps, true, "*.html");
compressingFilter.addMappingForUrlPatterns(disps, true, "*.js");
compressingFilter.addMappingForUrlPatterns(disps, true, "/app/rest/*");
compressingFilter.addMappingForUrlPatterns(disps, true, "/metrics/*");
compressingFilter.setAsyncSupported(true);
}
/**
* Initializes the static resources production Filter.
*/
private void initStaticResourcesProductionFilter(ServletContext servletContext,
EnumSet<DispatcherType> disps) {
log.debug("Registering static resources production Filter");
FilterRegistration.Dynamic staticResourcesProductionFilter =
servletContext.addFilter("staticResourcesProductionFilter",
new StaticResourcesProductionFilter());
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/index.html");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/images/*");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/fonts/*");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/styles/*");
staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/views/*");
staticResourcesProductionFilter.setAsyncSupported(true);
}
/**
* Initializes the cachig HTTP Headers Filter.
*/
private void initCachingHttpHeadersFilter(ServletContext servletContext,
EnumSet<DispatcherType> disps) {
log.debug("Registering Caching HTTP Headers Filter");
FilterRegistration.Dynamic cachingHttpHeadersFilter =
servletContext.addFilter("cachingHttpHeadersFilter",
new CachingHttpHeadersFilter());
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/images/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/fonts/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/styles/*");
cachingHttpHeadersFilter.setAsyncSupported(true);
}
/**
* Initializes Metrics.
*/
private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) {
log.debug("Initializing Metrics registries");
servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE,
metricRegistry);
servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY,
metricRegistry);
log.debug("Registering Metrics Filter");
FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter",
new InstrumentedFilter());
metricsFilter.addMappingForUrlPatterns(disps, true, "/*");
metricsFilter.setAsyncSupported(true);
log.debug("Registering Metrics Servlet");
ServletRegistration.Dynamic metricsAdminServlet =
servletContext.addServlet("metricsServlet", new MetricsServlet());
metricsAdminServlet.addMapping("/metrics/metrics/*");
metricsAdminServlet.setAsyncSupported(true);
metricsAdminServlet.setLoadOnStartup(2);
}
}
| mit |
kanonirov/lanb-client | src/main/java/ru/lanbilling/webservice/wsdl/GetVgroupsAddonsStaffResponse.java | 2337 |
package ru.lanbilling.webservice.wsdl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ret" type="{urn:api3}soapVgroupsAddonsStaff" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"ret"
})
@XmlRootElement(name = "getVgroupsAddonsStaffResponse")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class GetVgroupsAddonsStaffResponse {
@XmlElement(required = true)
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected List<SoapVgroupsAddonsStaff> ret;
/**
* Gets the value of the ret property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ret property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRet().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SoapVgroupsAddonsStaff }
*
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public List<SoapVgroupsAddonsStaff> getRet() {
if (ret == null) {
ret = new ArrayList<SoapVgroupsAddonsStaff>();
}
return this.ret;
}
}
| mit |
liupangzi/codekata | leetcode/Algorithms/118.Pascal'sTriangle/Solution.java | 471 | public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
ArrayList<Integer> tmp = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
tmp.add(0, 1);
for (int j = 1; j < tmp.size() - 1; j++) {
tmp.set(j, tmp.get(j) + tmp.get(j + 1));
}
result.add(new ArrayList<>(tmp));
}
return result;
}
}
| mit |
ste-bo/designpatterns | src/test/java/de/v13dev/designpatterns/util/TestHelper.java | 705 | package de.v13dev.designpatterns.util;
import java.util.List;
/**
* Created by stebo on 22.03.17.
*/
public class TestHelper {
public static boolean isSortedAscending(List<Integer> list) {
if(list.size() < 2) return true;
for(int i = 1; i < list.size(); i++) {
if(list.get(i - 1) > list.get(i)) {
return false;
}
}
return true;
}
public static boolean isSortedDescending(List<Integer> list) {
if(list.size() < 2) return true;
for(int i = 1; i < list.size(); i++) {
if(list.get(i - 1) < list.get(i)) {
return false;
}
}
return true;
}
}
| mit |
aumgn/BukkitUtils | src/main/java/fr/aumgn/bukkitutils/geom/Vector.java | 6906 | package fr.aumgn.bukkitutils.geom;
import fr.aumgn.bukkitutils.geom.direction.VectorDirection;
import fr.aumgn.bukkitutils.geom.vector.VectorIterator;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import java.util.Iterator;
/**
* Immutable Vector class.
* Inspired from WorldEdit.
*/
public class Vector implements Iterable<Vector> {
private final double x, y, z;
public Vector() {
this.x = 0;
this.y = 0;
this.z = 0;
}
public Vector(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(Location loc) {
this(loc.getX(), loc.getY(), loc.getZ());
}
public Vector(Entity entity) {
this(entity.getLocation());
}
public Vector(Block block) {
this(block.getX(), block.getY(), block.getZ());
}
public double getX() {
return x;
}
public Vector setX(double x) {
return new Vector(x, y, z);
}
public int getBlockX() {
return (int) Math.round(x);
}
public double getY() {
return y;
}
public Vector setY(double y) {
return new Vector(x, y, z);
}
public int getBlockY() {
return (int) Math.round(y);
}
public double getZ() {
return z;
}
public Vector setZ(double z) {
return new Vector(x, y, z);
}
public int getBlockZ() {
return (int) Math.round(z);
}
public Vector add(double i) {
return new Vector(this.x + i, this.y + i, this.z + i);
}
public Vector add(double ox, double oy, double oz) {
return new Vector(x + ox, y + oy, z + oz);
}
public Vector add(Vector other) {
return new Vector(x + other.x, y + other.y, z + other.z);
}
public Vector addX(double ox) {
return new Vector(x + ox, y, z);
}
public Vector addY(double oy) {
return new Vector(x, y + oy, z);
}
public Vector addZ(double oz) {
return new Vector(x, y, z + oz);
}
public Vector subtract(double i) {
return new Vector(x - i, y - i, z - i);
}
public Vector subtract(double ox, double oy, double oz) {
return new Vector(x - ox, y - oy, z - oz);
}
public Vector subtract(Vector other) {
return new Vector(x - other.x, y - other.y, z - other.z);
}
public Vector subtractX(double ox) {
return new Vector(x - ox, y, z);
}
public Vector subtractY(double oy) {
return new Vector(x, y - oy, z);
}
public Vector subtractZ(double oz) {
return new Vector(x, y, z - oz);
}
public Vector multiply(double i) {
return new Vector(x * i, y * i, z * i);
}
public Vector multiply(double ox, double oy, double oz) {
return new Vector(x * ox, y * oy, z * oz);
}
public Vector multiply(Vector other) {
return new Vector(x * other.x, y * other.y, z * other.z);
}
public Vector divide(double i) {
return new Vector(x / i, y / i, z / i);
}
public Vector divide(double ox, double oy, double oz) {
return new Vector(x / ox, y / oy, z / oz);
}
public Vector divide(Vector other) {
return new Vector(x / other.x, y / other.y, z / other.z);
}
public Vector getMiddle(Vector other) {
return new Vector(
(x + other.x) / 2,
(y + other.y) / 2,
(z + other.z) / 2);
}
public boolean isInside(Vector min, Vector max) {
return x >= min.x && x <= max.x
&& y >= min.y && y <= max.y
&& z >= min.z && z <= max.z;
}
public boolean isZero() {
return x == 0.0 && y == 0.0 && z == 0;
}
public Vector positive() {
return new Vector(Math.abs(x), Math.abs(y), Math.abs(z));
}
public double lengthSq() {
return x * x + y * y + z * z;
}
public double length() {
return Math.sqrt(lengthSq());
}
public double distanceSq(Vector other) {
return subtract(other).lengthSq();
}
public double distance(Vector other) {
return subtract(other).length();
}
public Vector normalize() {
return divide(length());
}
public Vector2D to2D() {
return new Vector2D(x, z);
}
public Block toBlock(World world) {
return world.getBlockAt(getBlockX(), getBlockY(), getBlockZ());
}
public Direction toDirection() {
if (isZero()) {
return Direction.NONE;
}
return new VectorDirection(this);
}
public Direction towards(Vector to) {
return to.subtract(this).toDirection();
}
public org.bukkit.util.Vector toBukkit() {
return new org.bukkit.util.Vector(x, y, z);
}
public Location toLocation(World world) {
return toLocation(world, 0.0f, 0.0f);
}
public Location toLocation(World world, Vector2D direction) {
return toLocation(world, direction.toDirection());
}
public Location toLocation(World world, Direction dir) {
return toLocation(world, dir.getYaw(), dir.getPitch());
}
public Location toLocation(World world, float yaw, float pitch) {
return new Location(world, x, getBlockY() + 0.1, z, yaw, pitch);
}
@Override
public Iterator<Vector> iterator() {
return new VectorIterator(new Vector(), this);
}
public Iterable<Vector> rectangle(final Vector max) {
return new Iterable<Vector>() {
@Override
public Iterator<Vector> iterator() {
return new VectorIterator(Vector.this, max);
}
};
}
@Override
public String toString() {
return "(" + x + ", " + y + ", " + z + ")";
}
@Override
public int hashCode() {
return new HashCodeBuilder(23, 11)
.append(x)
.append(y)
.append(z)
.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Vector)) {
return false;
}
Vector o = (Vector) obj;
return x == o.x && y == o.y && z == o.z;
}
public boolean equalsBlock(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Vector)) {
return false;
}
Vector other = (Vector) obj;
return getBlockX() == other.getBlockX()
&& getBlockY() == other.getBlockY()
&& getBlockZ() == other.getBlockZ();
}
}
| mit |
ndal-eth/topobench | src/test/java/ch/ethz/topobench/graph/TestGraph.java | 799 | /* *******************************************************
* Released under the MIT License (MIT) --- see LICENSE
* Copyright (c) 2014 Ankit Singla, Sangeetha Abdu Jyothi,
* Chi-Yao Hong, Lucian Popa, P. Brighten Godfrey,
* Alexandra Kolla, Simon Kassing
* ******************************************************** */
package ch.ethz.topobench.graph;
public class TestGraph extends Graph {
public TestGraph(String name, int size) {
super(name, size);
}
public TestGraph(String name, int size, int uniformWeight) {
super(name, size, uniformWeight);
}
public boolean addBidirNeighbor(int n1, int n2) {
return super.addBidirNeighbor(n1, n2);
}
public void setNodeWeight(int i, int weight) {
super.setNodeWeight(i, weight);
}
}
| mit |
sadikovi/algorithms | careercup/company-structure.java | 1233 | package test;
/**
scala> map
res6: java.util.HashMap[String,java.util.List[String]] = {AAA=[BBB, CCC, EEE], CCC=[DDD]}
scala> test.Test.printCompany(map)
-AAA
-BBB
-CCC
-DDD
-EEE
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
public class Test {
public static void printCompany(HashMap<String, List<String>> graph) {
if (graph.size() == 0) return;
HashSet<String> roots = new HashSet<String>();
for (String v : graph.keySet()) {
roots.add(v);
}
for (String v : graph.keySet()) {
for (String l : graph.get(v)) {
roots.remove(l);
}
}
for (String v : roots) {
printCompany(graph, v, 0);
}
}
private static void printCompany(HashMap<String, List<String>> graph, String vertex, int depth) {
printVertex(vertex, depth);
if (graph.containsKey(vertex)) {
for (String v : graph.get(vertex)) {
printCompany(graph, v, depth + 1);
}
}
}
private static void printVertex(String vertex, int depth) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < depth; i++) {
sb.append(" ");
}
sb.append("-");
sb.append(vertex);
System.out.println(sb.toString());
}
}
| mit |
burakkose/libgdx-game-slicer | core/src/com/slicer/utils/AssetLoader.java | 1612 | package com.slicer.utils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
public class AssetLoader {
public static Texture bgGame, bgGameOver, bgFinish, score, soundOn, soundOff;
public static Sound gameOver, victory, slice, click;
public static FileHandle levelsFile;
public static boolean sound = true;
public static void load() {
bgGame = new Texture(Gdx.files.internal("data/images/bg1.jpeg"));
bgGameOver = new Texture(Gdx.files.internal("data/images/bg3.png"));
bgFinish = new Texture(Gdx.files.internal("data/images/bg2.png"));
soundOn = new Texture(Gdx.files.internal("data/images/on.png"));
soundOff = new Texture(Gdx.files.internal("data/images/off.png"));
score = new Texture(Gdx.files.internal("data/images/score.png"));
gameOver = Gdx.audio.newSound(Gdx.files.internal("data/sound/gameOver.wav"));
victory = Gdx.audio.newSound(Gdx.files.internal("data/sound/victory.wav"));
slice = Gdx.audio.newSound(Gdx.files.internal("data/sound/slice.wav"));
click = Gdx.audio.newSound(Gdx.files.internal("data/sound/click.wav"));
levelsFile = Gdx.files.internal("data/levels/levels.json");
}
public static void play(Sound s) {
if (sound)
s.play();
}
public static void dispose() {
bgGame.dispose();
bgGameOver.dispose();
bgFinish.dispose();
gameOver.dispose();
victory.dispose();
slice.dispose();
}
} | mit |
RaymondKwong/raymond_projects | services/jwtauth/src/main/java/com/raymond/entrypoint/GlobalExceptionHandler.java | 1163 | package com.raymond.entrypoint;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletResponse;
/**
* Created by Raymond Kwong on 12/1/2018.
*/
@Qualifier("handlerExceptionResolver")
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(AuthenticationException.class)
public ErrorResponseBean handleAuthenticationException(AuthenticationException exception, HttpServletResponse response){
ErrorResponseBean errorResponseBean = new ErrorResponseBean();
errorResponseBean.setError(HttpStatus.UNAUTHORIZED.getReasonPhrase());
errorResponseBean.setMessage(exception.getMessage());
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return errorResponseBean;
}
} | mit |
mattsoulanille/compSci | GiftList/GiftEntry.java | 1290 |
/**
* The GiftEntry class describes a gift in terms of three values:
* the gift name, the gift receipient, and whether the gift
* has been bought yet.
*
* @author Richard White
* @version 2013-12-05
*/
public class GiftEntry
{
/**
* Constructor for known recipient with blank Gift
* @param recipient The person who will receive an as yet unnamed gift
*/
/**
* Constructor for known recipient with known Gift
* @param recipient The person who will receive the gift
* @param gift The gift this person will receive
*/
/**
* setName establishes the giftName for a person's gift
* @param theGiftName the name of the gift
*/
/**
* setRecipient establishes the recipient of a gift
* @param theRecipient the name of the gift's receiver
*/
/**
* setAsPurchased checks the gift off as purchased
*/
/**
* getName returns giftName for a gift
* @return the name of the gift
*/
/**
* getRecipient identifies the recipient of a gift
* @return gift's receiver
*/
/**
* isPurchased identifies whether the gift has been purchased
* @return the value true if purchased, false if not yet purchased
*/
}
| mit |
fzheng/codejam | ccup/ch1/IsUnique.java | 1234 | public class IsUnique {
public static boolean isUnique1(String input) {
int checker = 0;
int n = input.length();
if (n <= 1) return true;
for (int i = 0; i < n; i++) {
int c = input.charAt(i) - 'a';
if ((checker & (1 << c)) > 0) return false;
checker |= (1 << c);
}
return true;
}
public static boolean isUnique2(String input) {
int N = 256;
int[] map = new int[N];
int n = input.length();
if (n <= 1) return true;
for (int i = 0; i < n; i++) {
int c = input.charAt(i);
if (map[c] == 1) return false;
map[c] = 1;
}
return true;
}
public static boolean isUnique3(String input) {
HashMap<Character, Boolean> map = new HashMap<Character, Boolean>();
int n = input.length();
if (n <= 1) return true;
for (int i = 0; i < n; i++) {
if (null != map.get(input.charAt(i))) return false;
else map.put(input.charAt(i), true);
}
return true;
}
public static void main(String[] args) {
String[] tester = {"", "a", "aa", "ab", "strong", "stronger", "Hello World"};
for (String s : tester) {
System.out.println(s + ": " + isUnique1(s) + " | " + isUnique2(s) + " | " + isUnique3(s));
}
}
} | mit |
HerbLuo/shop-api | src/main/java/cn/cloudself/dao/IAppJiyoujiaHeadDao.java | 887 | package cn.cloudself.dao;
import cn.cloudself.model.AppJiyoujiaHeadEntity;
import cn.cloudself.model.IntegerEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.Repository;
import java.util.List;
/**
* @author HerbLuo
* @version 1.0.0.d
* <p>
* change logs:
* 2017/5/19 HerbLuo 首次创建
*/
public interface IAppJiyoujiaHeadDao extends Repository<AppJiyoujiaHeadEntity, Integer> {
List<AppJiyoujiaHeadEntity> getDoubleColumn(int start, int length);
/**
* Max of 各类型(type 放置于左边还是右边)的记录数
* 如:type为0的记录数有3个,type为1的记录数有4个,返回结果就为4
*/
IntegerEntity maxCountOfDoubleColumn();
Page<AppJiyoujiaHeadEntity> findByType(byte type, Pageable pageable);
}
| mit |
zoltanvi/password-manager | src/view/PasswordManagerRegistration.java | 2435 | package view;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Font;
public class PasswordManagerRegistration {
JPanel regpanel;
private JTextField txtUsername;
private JPasswordField txtPass1;
private JPasswordField txtPass2;
private PasswordManagerGUI gui;
public PasswordManagerRegistration(PasswordManagerGUI gui) {
this.gui = gui;
regpanel = new JPanel();
regpanel.setLayout(new BorderLayout(0, 0));
JPanel panel_1 = new JPanel();
regpanel.add(panel_1, BorderLayout.NORTH);
JLabel lblRegistration = new JLabel(Labels.REG_REGISTRATION);
lblRegistration.setFont(new Font("Tahoma", Font.PLAIN, 38));
panel_1.add(lblRegistration);
JPanel panel_2 = new JPanel();
regpanel.add(panel_2, BorderLayout.CENTER);
panel_2.setLayout(null);
JLabel lblUsername = new JLabel(Labels.REG_USERNAME);
lblUsername.setBounds(74, 92, 132, 16);
panel_2.add(lblUsername);
JLabel lblPassword = new JLabel(Labels.REG_PASSWORD);
lblPassword.setBounds(74, 149, 173, 16);
panel_2.add(lblPassword);
JLabel lblPasswordAgain = new JLabel(Labels.REG_RE_PASSWORD);
lblPasswordAgain.setBounds(74, 204, 173, 16);
panel_2.add(lblPasswordAgain);
txtUsername = new JTextField();
txtUsername.setBounds(252, 89, 380, 22);
panel_2.add(txtUsername);
txtUsername.setColumns(10);
txtPass1 = new JPasswordField();
txtPass1.setBounds(252, 146, 380, 22);
panel_2.add(txtPass1);
txtPass2 = new JPasswordField();
txtPass2.setBounds(252, 201, 380, 22);
txtPass1.addActionListener(gui.getController());
txtPass1.setActionCommand(Labels.REG_PASS1FIELD);
txtPass2.addActionListener(gui.getController());
txtPass2.setActionCommand(Labels.REG_PASS2FIELD);
txtUsername.addActionListener(gui.getController());
txtUsername.setActionCommand(Labels.REG_USERFIELD);
panel_2.add(txtPass2);
JButton btnRegistration = new JButton(Labels.REG_REGBUTTON);
btnRegistration.addActionListener(gui.getController());
btnRegistration.setBounds(278, 288, 151, 25);
panel_2.add(btnRegistration);
}
public JTextField getTxtUsername() {
return txtUsername;
}
public JPasswordField getTxtPass1() {
return txtPass1;
}
public JPasswordField getTxtPass2() {
return txtPass2;
}
}
| mit |
Fumaloko92/MSc-Thesis | 17-05-2017/neuralturingmachines-master/src/com/anji_ahni/nn/activationfunction/PowerActivationFunction.java | 1453 | package com.anji_ahni.nn.activationfunction;
/**
* Square-root function.
*
* @author Oliver Coleman
*/
public class PowerActivationFunction implements ActivationFunction, ActivationFunctionNonIntegrating {
/**
* identifying string
*/
public final static String NAME = "power";
/**
* @see Object#toString()
*/
public String toString() {
return NAME;
}
/**
* This class should only be accessd via ActivationFunctionFactory.
*/
PowerActivationFunction() {
// no-op
}
/**
* Not used, returns 0.
*/
@Override
public double apply(double input) {
return 0;
}
/**
* Return first input raised to the power of the absolute value of the second input (or just first input if no second input).
*/
@Override
public double apply(double[] input, double bias) {
if (input.length < 2)
return input[0];
double v = Math.pow(input[0], Math.abs(input[1]));
if (Double.isNaN(v)) return 0;
if (Double.isInfinite(v)) return v < 0 ? -Double.MAX_VALUE / 2 : Double.MAX_VALUE / 2;
return v;
}
/**
* @see com.anji_ahni.nn.activationfunction.ActivationFunction#getMaxValue()
*/
public double getMaxValue() {
return Double.MAX_VALUE;
}
/**
* @see com.anji_ahni.nn.activationfunction.ActivationFunction#getMinValue()
*/
public double getMinValue() {
return -Double.MAX_VALUE;
}
/**
* @see com.anji_ahni.nn.activationfunction.ActivationFunction#cost()
*/
public long cost() {
return 75;
}
}
| mit |
edecisions/recapt | src/main/java/com/recapt/domain/IssueHistory.java | 1356 | /*
* Property of RECAPT http://recapt.com.ec/
* Chief Developer Ing. Eduardo Alfonso Sanchez eddie.alfonso@gmail.com
*/
package com.recapt.domain;
import java.time.LocalDateTime;
/**
*
* @author Eduardo
*/
public class IssueHistory {
private String name;
private String description;
private String reference;
private LocalDateTime created;
private Usuario createBy;
private Issue issue;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public LocalDateTime getCreated() {
return created;
}
public void setCreated(LocalDateTime created) {
this.created = created;
}
public Usuario getCreateBy() {
return createBy;
}
public void setCreateBy(Usuario createBy) {
this.createBy = createBy;
}
public Issue getIssue() {
return issue;
}
public void setIssue(Issue issue) {
this.issue = issue;
}
}
| mit |
danielmarcoto/ControleRemoto | app/src/main/java/br/com/command/comandos/PersianaSuiteAbrirCommand.java | 435 | package br.com.command.comandos;
import br.com.command.interfaces.Command;
import br.com.command.modelos.PersianaSuite;
/**
* Created by danielmarcoto on 17/11/15.
*/
public class PersianaSuiteAbrirCommand implements Command {
private PersianaSuite persiana;
public PersianaSuiteAbrirCommand(PersianaSuite persiana) {
this.persiana = persiana;
}
@Override
public void execute() {persiana.abrir();}
}
| mit |
kenyonduan/amazon-mws | src/main/java/com/elcuk/jaxb/OptionalWeightUnitOfMeasure.java | 740 | /* */ package com.elcuk.jaxb;
/* */
/* */ import javax.xml.bind.annotation.XmlEnum;
/* */ import javax.xml.bind.annotation.XmlType;
/* */
/* */ @XmlType(name="OptionalWeightUnitOfMeasure")
/* */ @XmlEnum
/* */ public enum OptionalWeightUnitOfMeasure
/* */ {
/* 30 */ GR,
/* 31 */ KG,
/* 32 */ OZ,
/* 33 */ LB,
/* 34 */ MG;
/* */
/* */ public String value() {
/* 37 */ return name();
/* */ }
/* */
/* */ public static OptionalWeightUnitOfMeasure fromValue(String v) {
/* 41 */ return valueOf(v);
/* */ }
/* */ }
/* Location: /Users/mac/Desktop/jaxb/
* Qualified Name: com.elcuk.jaxb.OptionalWeightUnitOfMeasure
* JD-Core Version: 0.6.2
*/ | mit |
vlsi1217/leetlint | src/nineChap5_DP2/RegularExpressionMatching.java | 2348 | package nineChap5_DP2;
/**
* http://www.lintcode.com/en/problem/regular-expression-matching/
* Created at 9:59 AM on 11/29/15.
*/
public class RegularExpressionMatching {
public static void main(String[] args) {
String s = "aaaab";
String p = "a*b";
boolean ans = new RegularExpressionMatching().isMatch(s,p);
System.out.println(ans);
}
/**
* @param s: A string
* @param p: A string includes "." and "*"
* @return: A boolean
*/
public boolean isMatch(String s, String p) {
// write your code here
// Ganker recursion
//return gankerRec(s,p,0,0);
// hehejun's DP
return heheDP(s, p);
}
/**
* Ganker's explanation is the best.
* @param s
* @param p
* @param i
* @param j
* @return
*/
private boolean gankerRec(String s, String p, int i, int j) {
if (j == p.length()) {
return i == s.length();
}
if (j == p.length()-1 || p.charAt(j+1) != '*') {
if (i == s.length() || s.charAt(i)!=p.charAt(j) && p.charAt(j) != '.') {
return false;
}
else {
return gankerRec(s,p,i+1,j+1);
}
}
// p.charAt(j+1) == '*'
while (i < s.length() && (p.charAt(j) == '.' || s.charAt(i) == p.charAt(j))) {
if (gankerRec(s,p,i,j+2)) {
return true;
}
i++;
}
return gankerRec(s,p,i,j+2);
}
/**
* http://hehejun.blogspot.com/2014/11/leetcoderegular-expression-matching_4.html
* So clean and elegant DP!
* @param s
* @param p
* @return
*/
private boolean heheDP(String s, String p) {
if (s == null || p == null) {
return false;
}
int lens = s.length();
int lenp = p.length();
boolean[][] F = new boolean[lenp+1][lens+1];
F[0][0] = true;
for (int i = 0; i < lenp; ++i) {
if (p.charAt(i) != '*') {
F[i+1][0] = false;
}
else {
F[i+1][0] = F[i-1][0];
}
}
for (int i = 0; i < lenp; ++i) {
for (int j = 0; j < lens; ++j) {
if (p.charAt(i) == s.charAt(j) || p.charAt(i) == '.') {
F[i+1][j+1] = F[i][j];
}
else if (p.charAt(i) == '*') {
F[i+1][j+1] = F[i][j+1] || F[i-1][j+1] ||
(F[i+1][j] && s.charAt(j) == p.charAt(i-1)
|| p.charAt(i-1) == '.');
}
}
}
return F[lenp][lens];
}
}
| mit |
Azure/azure-sdk-for-java | sdk/communication/azure-resourcemanager-communication/src/main/java/com/azure/resourcemanager/communication/models/LinkedNotificationHub.java | 796 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.communication.models;
import com.azure.resourcemanager.communication.fluent.models.LinkedNotificationHubInner;
/** An immutable client-side representation of LinkedNotificationHub. */
public interface LinkedNotificationHub {
/**
* Gets the resourceId property: The resource ID of the notification hub.
*
* @return the resourceId value.
*/
String resourceId();
/**
* Gets the inner com.azure.resourcemanager.communication.fluent.models.LinkedNotificationHubInner object.
*
* @return the inner object.
*/
LinkedNotificationHubInner innerModel();
}
| mit |
DragonSphereZ/DragonSphereZ | src/com/flowpowered/math/imaginary/Quaternionf.java | 29581 | package com.flowpowered.math.imaginary;
import java.io.Serializable;
import com.flowpowered.math.GenericMath;
import com.flowpowered.math.HashFunctions;
import com.flowpowered.math.TrigMath;
import com.flowpowered.math.matrix.Matrix3f;
import com.flowpowered.math.vector.Vector3f;
/**
* Represent a quaternion of the form <code>xi + yj + zk + w</code>. The x, y, z and w components are stored as floats. This class is immutable.
*/
public class Quaternionf implements Imaginaryf, Comparable<Quaternionf>, Serializable, Cloneable {
private static final long serialVersionUID = 1;
/**
* An immutable identity (0, 0, 0, 0) quaternion.
*/
public static final Quaternionf ZERO = new Quaternionf(0, 0, 0, 0);
/**
* An immutable identity (0, 0, 0, 1) quaternion.
*/
public static final Quaternionf IDENTITY = new Quaternionf(0, 0, 0, 1);
private final float x;
private final float y;
private final float z;
private final float w;
private transient volatile boolean hashed = false;
private transient volatile int hashCode = 0;
/**
* Constructs a new quaternion. The components are set to the identity (0, 0, 0, 1).
*/
public Quaternionf() {
this(0, 0, 0, 1);
}
/**
* Constructs a new quaternion from the double components.
*
* @param x The x (imaginary) component
* @param y The y (imaginary) component
* @param z The z (imaginary) component
* @param w The w (real) component
*/
public Quaternionf(double x, double y, double z, double w) {
this((float) x, (float) y, (float) z, (float) w);
}
/**
* Constructs a new quaternion from the float components.
*
* @param x The x (imaginary) component
* @param y The y (imaginary) component
* @param z The z (imaginary) component
* @param w The w (real) component
*/
public Quaternionf(float x, float y, float z, float w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Copy constructor.
*
* @param q The quaternion to copy
*/
public Quaternionf(Quaternionf q) {
this(q.x, q.y, q.z, q.w);
}
/**
* Gets the x (imaginary) component of this quaternion.
*
* @return The x (imaginary) component
*/
public float getX() {
return x;
}
/**
* Gets the y (imaginary) component of this quaternion.
*
* @return The y (imaginary) component
*/
public float getY() {
return y;
}
/**
* Gets the z (imaginary) component of this quaternion.
*
* @return The z (imaginary) component
*/
public float getZ() {
return z;
}
/**
* Gets the w (real) component of this quaternion.
*
* @return The w (real) component
*/
public float getW() {
return w;
}
/**
* Adds another quaternion to this one.
*
* @param q The quaternion to add
* @return A new quaternion, which is the sum of both
*/
public Quaternionf add(Quaternionf q) {
return add(q.x, q.y, q.z, q.w);
}
/**
* Adds the double components of another quaternion to this one.
*
* @param x The x (imaginary) component of the quaternion to add
* @param y The y (imaginary) component of the quaternion to add
* @param z The z (imaginary) component of the quaternion to add
* @param w The w (real) component of the quaternion to add
* @return A new quaternion, which is the sum of both
*/
public Quaternionf add(double x, double y, double z, double w) {
return add((float) x, (float) y, (float) z, (float) w);
}
/**
* Adds the float components of another quaternion to this one.
*
* @param x The x (imaginary) component of the quaternion to add
* @param y The y (imaginary) component of the quaternion to add
* @param z The z (imaginary) component of the quaternion to add
* @param w The w (real) component of the quaternion to add
* @return A new quaternion, which is the sum of both
*/
public Quaternionf add(float x, float y, float z, float w) {
return new Quaternionf(this.x + x, this.y + y, this.z + z, this.w + w);
}
/**
* Subtracts another quaternion from this one.
*
* @param q The quaternion to subtract
* @return A new quaternion, which is the difference of both
*/
public Quaternionf sub(Quaternionf q) {
return sub(q.x, q.y, q.z, q.w);
}
/**
* Subtracts the double components of another quaternion from this one.
*
* @param x The x (imaginary) component of the quaternion to subtract
* @param y The y (imaginary) component of the quaternion to subtract
* @param z The z (imaginary) component of the quaternion to subtract
* @param w The w (real) component of the quaternion to subtract
* @return A new quaternion, which is the difference of both
*/
public Quaternionf sub(double x, double y, double z, double w) {
return sub((float) x, (float) y, (float) z, (float) w);
}
/**
* Subtracts the float components of another quaternion from this one.
*
* @param x The x (imaginary) component of the quaternion to subtract
* @param y The y (imaginary) component of the quaternion to subtract
* @param z The z (imaginary) component of the quaternion to subtract
* @param w The w (real) component of the quaternion to subtract
* @return A new quaternion, which is the difference of both
*/
public Quaternionf sub(float x, float y, float z, float w) {
return new Quaternionf(this.x - x, this.y - y, this.z - z, this.w - w);
}
/**
* Multiplies the components of this quaternion by a double scalar.
*
* @param a The multiplication scalar
* @return A new quaternion, which has each component multiplied by the scalar
*/
public Quaternionf mul(double a) {
return mul((float) a);
}
/**
* Multiplies the components of this quaternion by a float scalar.
*
* @param a The multiplication scalar
* @return A new quaternion, which has each component multiplied by the scalar
*/
@Override
public Quaternionf mul(float a) {
return new Quaternionf(x * a, y * a, z * a, w * a);
}
/**
* Multiplies another quaternion with this one.
*
* @param q The quaternion to multiply with
* @return A new quaternion, which is the product of both
*/
public Quaternionf mul(Quaternionf q) {
return mul(q.x, q.y, q.z, q.w);
}
/**
* Multiplies the double components of another quaternion with this one.
*
* @param x The x (imaginary) component of the quaternion to multiply with
* @param y The y (imaginary) component of the quaternion to multiply with
* @param z The z (imaginary) component of the quaternion to multiply with
* @param w The w (real) component of the quaternion to multiply with
* @return A new quaternion, which is the product of both
*/
public Quaternionf mul(double x, double y, double z, double w) {
return mul((float) x, (float) y, (float) z, (float) w);
}
/**
* Multiplies the float components of another quaternion with this one.
*
* @param x The x (imaginary) component of the quaternion to multiply with
* @param y The y (imaginary) component of the quaternion to multiply with
* @param z The z (imaginary) component of the quaternion to multiply with
* @param w The w (real) component of the quaternion to multiply with
* @return A new quaternion, which is the product of both
*/
public Quaternionf mul(float x, float y, float z, float w) {
return new Quaternionf(
this.w * x + this.x * w + this.y * z - this.z * y,
this.w * y + this.y * w + this.z * x - this.x * z,
this.w * z + this.z * w + this.x * y - this.y * x,
this.w * w - this.x * x - this.y * y - this.z * z);
}
/**
* Divides the components of this quaternion by a double scalar.
*
* @param a The division scalar
* @return A new quaternion, which has each component divided by the scalar
*/
public Quaternionf div(double a) {
return div((float) a);
}
/**
* Divides the components of this quaternion by a float scalar.
*
* @param a The division scalar
* @return A new quaternion, which has each component divided by the scalar
*/
@Override
public Quaternionf div(float a) {
return new Quaternionf(x / a, y / a, z / a, w / a);
}
/**
* Divides this quaternions by another one.
*
* @param q The quaternion to divide with
* @return The quotient of the two quaternions
*/
public Quaternionf div(Quaternionf q) {
return div(q.x, q.y, q.z, q.w);
}
/**
* Divides this quaternions by the double components of another one.
*
* @param x The x (imaginary) component of the quaternion to divide with
* @param y The y (imaginary) component of the quaternion to divide with
* @param z The z (imaginary) component of the quaternion to divide with
* @param w The w (real) component of the quaternion to divide with
* @return The quotient of the two quaternions
*/
public Quaternionf div(double x, double y, double z, double w) {
return div((float) x, (float) y, (float) z, (float) w);
}
/**
* Divides this quaternions by the float components of another one.
*
* @param x The x (imaginary) component of the quaternion to divide with
* @param y The y (imaginary) component of the quaternion to divide with
* @param z The z (imaginary) component of the quaternion to divide with
* @param w The w (real) component of the quaternion to divide with
* @return The quotient of the two quaternions
*/
public Quaternionf div(float x, float y, float z, float w) {
final float d = x * x + y * y + z * z + w * w;
return new Quaternionf(
(this.x * w - this.w * x - this.z * y + this.y * z) / d,
(this.y * w + this.z * x - this.w * y - this.x * z) / d,
(this.z * w - this.y * x + this.x * y - this.w * z) / d,
(this.w * w + this.x * x + this.y * y + this.z * z) / d);
}
/**
* Returns the dot product of this quaternion with another one.
*
* @param q The quaternion to calculate the dot product with
* @return The dot product of the two quaternions
*/
public float dot(Quaternionf q) {
return dot(q.x, q.y, q.z, q.w);
}
/**
* Returns the dot product of this quaternion with the double components of another one.
*
* @param x The x (imaginary) component of the quaternion to calculate the dot product with
* @param y The y (imaginary) component of the quaternion to calculate the dot product with
* @param z The z (imaginary) component of the quaternion to calculate the dot product with
* @param w The w (real) component of the quaternion to calculate the dot product with
* @return The dot product of the two quaternions
*/
public float dot(double x, double y, double z, double w) {
return dot((float) x, (float) y, (float) z, (float) w);
}
/**
* Returns the dot product of this quaternion with the float components of another one.
*
* @param x The x (imaginary) component of the quaternion to calculate the dot product with
* @param y The y (imaginary) component of the quaternion to calculate the dot product with
* @param z The z (imaginary) component of the quaternion to calculate the dot product with
* @param w The w (real) component of the quaternion to calculate the dot product with
* @return The dot product of the two quaternions
*/
public float dot(float x, float y, float z, float w) {
return this.x * x + this.y * y + this.z * z + this.w * w;
}
/**
* Rotates a vector by this quaternion.
*
* @param v The vector to rotate
* @return The rotated vector
*/
public Vector3f rotate(Vector3f v) {
return rotate(v.getX(), v.getY(), v.getZ());
}
/**
* Rotates the double components of a vector by this quaternion.
*
* @param x The x component of the vector
* @param y The y component of the vector
* @param z The z component of the vector
* @return The rotated vector
*/
public Vector3f rotate(double x, double y, double z) {
return rotate((float) x, (float) y, (float) z);
}
/**
* Rotates the float components of a vector by this quaternion.
*
* @param x The x component of the vector
* @param y The y component of the vector
* @param z The z component of the vector
* @return The rotated vector
*/
public Vector3f rotate(float x, float y, float z) {
final float length = length();
if (Math.abs(length) < GenericMath.FLT_EPSILON) {
throw new ArithmeticException("Cannot rotate by the zero quaternion");
}
final float nx = this.x / length;
final float ny = this.y / length;
final float nz = this.z / length;
final float nw = this.w / length;
final float px = nw * x + ny * z - nz * y;
final float py = nw * y + nz * x - nx * z;
final float pz = nw * z + nx * y - ny * x;
final float pw = -nx * x - ny * y - nz * z;
return new Vector3f(
pw * -nx + px * nw - py * nz + pz * ny,
pw * -ny + py * nw - pz * nx + px * nz,
pw * -nz + pz * nw - px * ny + py * nx);
}
/**
* Returns a unit vector representing the direction of this quaternion, which is {@link Vector3f#FORWARD} rotated by this quaternion.
*
* @return The vector representing the direction this quaternion is pointing to
*/
public Vector3f getDirection() {
return rotate(Vector3f.FORWARD);
}
/**
* Returns the axis of rotation for this quaternion.
*
* @return The axis of rotation
*/
public Vector3f getAxis() {
final float q = (float) Math.sqrt(1 - w * w);
return new Vector3f(x / q, y / q, z / q);
}
/**
* Returns the angles in degrees around the x, y and z axes that correspond to the rotation represented by this quaternion.
*
* @return The angle in degrees for each axis, stored in a vector, in the corresponding component
*/
public Vector3f getAxesAnglesDeg() {
return getAxesAnglesRad().mul(TrigMath.RAD_TO_DEG);
}
/**
* Returns the angles in radians around the x, y and z axes that correspond to the rotation represented by this quaternion.
*
* @return The angle in radians for each axis, stored in a vector, in the corresponding component
*/
public Vector3f getAxesAnglesRad() {
final double roll;
final double pitch;
double yaw;
final double test = w * x - y * z;
if (Math.abs(test) < 0.4999) {
roll = TrigMath.atan2(2 * (w * z + x * y), 1 - 2 * (x * x + z * z));
pitch = TrigMath.asin(2 * test);
yaw = TrigMath.atan2(2 * (w * y + z * x), 1 - 2 * (x * x + y * y));
} else {
final int sign = (test < 0) ? -1 : 1;
roll = 0;
pitch = sign * Math.PI / 2;
yaw = -sign * 2 * TrigMath.atan2(z, w);
}
return new Vector3f(pitch, yaw, roll);
}
/**
* Conjugates the quaternion. <br> Conjugation of a quaternion <code>a</code> is an operation returning quaternion <code>a'</code> such that <code>a' * a = a * a' = |a|<sup>2</sup></code> where
* <code>|a|<sup>2<sup/></code> is squared length of <code>a</code>.
*
* @return the conjugated quaternion
*/
@Override
public Quaternionf conjugate() {
return new Quaternionf(-x, -y, -z, w);
}
/**
* Inverts the quaternion. <br> Inversion of a quaternion <code>a</code> returns quaternion <code>a<sup>-1</sup> = a' / |a|<sup>2</sup></code> where <code>a'</code> is {@link #conjugate()
* conjugation} of <code>a</code>, and <code>|a|<sup>2</sup></code> is squared length of <code>a</code>. <br> For any quaternions <code>a, b, c</code>, such that <code>a * b = c</code> equations
* <code>a<sup>-1</sup> * c = b</code> and <code>c * b<sup>-1</sup> = a</code> are true.
*
* @return the inverted quaternion
*/
@Override
public Quaternionf invert() {
final float lengthSquared = lengthSquared();
if (Math.abs(lengthSquared) < GenericMath.FLT_EPSILON) {
throw new ArithmeticException("Cannot invert a quaternion of length zero");
}
return conjugate().div(lengthSquared);
}
/**
* Returns the square of the length of this quaternion.
*
* @return The square of the length
*/
@Override
public float lengthSquared() {
return x * x + y * y + z * z + w * w;
}
/**
* Returns the length of this quaternion.
*
* @return The length
*/
@Override
public float length() {
return (float) Math.sqrt(lengthSquared());
}
/**
* Normalizes this quaternion.
*
* @return A new quaternion of unit length
*/
@Override
public Quaternionf normalize() {
final float length = length();
if (Math.abs(length) < GenericMath.FLT_EPSILON) {
throw new ArithmeticException("Cannot normalize the zero quaternion");
}
return new Quaternionf(x / length, y / length, z / length, w / length);
}
/**
* Converts this quaternion to a complex by extracting the rotation around
* the axis and returning it as a rotation in the plane perpendicular to the
* rotation axis.
*
* @return The rotation without the axis as a complex
*/
public Complexf toComplex() {
final float w2 = w * w;
return new Complexf(2 * w2 - 1, 2 * w * (float) Math.sqrt(1 - w2));
}
@Override
public Quaternionf toFloat() {
return new Quaternionf(x, y, z, w);
}
@Override
public Quaterniond toDouble() {
return new Quaterniond(x, y, z, w);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Quaternionf)) {
return false;
}
final Quaternionf quaternion = (Quaternionf) o;
if (Float.compare(quaternion.w, w) != 0) {
return false;
}
if (Float.compare(quaternion.x, x) != 0) {
return false;
}
if (Float.compare(quaternion.y, y) != 0) {
return false;
}
if (Float.compare(quaternion.z, z) != 0) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (!hashed) {
int result = (x != +0.0f ? HashFunctions.hash(x) : 0);
result = 31 * result + (y != +0.0f ? HashFunctions.hash(y) : 0);
result = 31 * result + (z != +0.0f ? HashFunctions.hash(z) : 0);
hashCode = 31 * result + (w != +0.0f ? HashFunctions.hash(w) : 0);
hashed = true;
}
return hashCode;
}
@Override
public int compareTo(Quaternionf q) {
return (int) Math.signum(lengthSquared() - q.lengthSquared());
}
@Override
public Quaternionf clone() {
return new Quaternionf(this);
}
@Override
public String toString() {
return "(" + x + ", " + y + ", " + z + ", " + w + ")";
}
/**
* Creates a new quaternion from the double angles in degrees around the x, y and z axes.
*
* @param pitch The rotation around x
* @param yaw The rotation around y
* @param roll The rotation around z
* @return The quaternion defined by the rotations around the axes
*/
public static Quaternionf fromAxesAnglesDeg(double pitch, double yaw, double roll) {
return fromAxesAnglesDeg((float) pitch, (float) yaw, (float) roll);
}
/**
* Creates a new quaternion from the double angles in radians around the x, y and z axes.
*
* @param pitch The rotation around x
* @param yaw The rotation around y
* @param roll The rotation around z
* @return The quaternion defined by the rotations around the axes
*/
public static Quaternionf fromAxesAnglesRad(double pitch, double yaw, double roll) {
return fromAxesAnglesRad((float) pitch, (float) yaw, (float) roll);
}
/**
* Creates a new quaternion from the float angles in degrees around the x, y and z axes.
*
* @param pitch The rotation around x
* @param yaw The rotation around y
* @param roll The rotation around z
* @return The quaternion defined by the rotations around the axes
*/
public static Quaternionf fromAxesAnglesDeg(float pitch, float yaw, float roll) {
return Quaternionf.fromAngleDegAxis(yaw, Vector3f.UNIT_Y).
mul(Quaternionf.fromAngleDegAxis(pitch, Vector3f.UNIT_X)).
mul(Quaternionf.fromAngleDegAxis(roll, Vector3f.UNIT_Z));
}
/**
* Creates a new quaternion from the float angles in radians around the x, y and z axes.
*
* @param pitch The rotation around x
* @param yaw The rotation around y
* @param roll The rotation around z
* @return The quaternion defined by the rotations around the axes
*/
public static Quaternionf fromAxesAnglesRad(float pitch, float yaw, float roll) {
return Quaternionf.fromAngleRadAxis(yaw, Vector3f.UNIT_Y).
mul(Quaternionf.fromAngleRadAxis(pitch, Vector3f.UNIT_X)).
mul(Quaternionf.fromAngleRadAxis(roll, Vector3f.UNIT_Z));
}
/**
* Creates a new quaternion from the angle-axis rotation defined from the first to the second vector.
*
* @param from The first vector
* @param to The second vector
* @return The quaternion defined by the angle-axis rotation between the vectors
*/
public static Quaternionf fromRotationTo(Vector3f from, Vector3f to) {
return Quaternionf.fromAngleRadAxis(TrigMath.acos(from.dot(to) / (from.length() * to.length())), from.cross(to));
}
/**
* Creates a new quaternion from the rotation double angle in degrees around the axis vector.
*
* @param angle The rotation angle in degrees
* @param axis The axis of rotation
* @return The quaternion defined by the rotation around the axis
*/
public static Quaternionf fromAngleDegAxis(double angle, Vector3f axis) {
return fromAngleRadAxis(Math.toRadians(angle), axis);
}
/**
* Creates a new quaternion from the rotation double angle in radians around the axis vector.
*
* @param angle The rotation angle in radians
* @param axis The axis of rotation
* @return The quaternion defined by the rotation around the axis
*/
public static Quaternionf fromAngleRadAxis(double angle, Vector3f axis) {
return fromAngleRadAxis((float) angle, axis);
}
/**
* Creates a new quaternion from the rotation float angle in degrees around the axis vector.
*
* @param angle The rotation angle in degrees
* @param axis The axis of rotation
* @return The quaternion defined by the rotation around the axis
*/
public static Quaternionf fromAngleDegAxis(float angle, Vector3f axis) {
return fromAngleRadAxis((float) Math.toRadians(angle), axis);
}
/**
* Creates a new quaternion from the rotation float angle in radians around the axis vector.
*
* @param angle The rotation angle in radians
* @param axis The axis of rotation
* @return The quaternion defined by the rotation around the axis
*/
public static Quaternionf fromAngleRadAxis(float angle, Vector3f axis) {
return fromAngleRadAxis(angle, axis.getX(), axis.getY(), axis.getZ());
}
/**
* Creates a new quaternion from the rotation double angle in degrees around the axis vector double components.
*
* @param angle The rotation angle in degrees
* @param x The x component of the axis vector
* @param y The y component of the axis vector
* @param z The z component of the axis vector
* @return The quaternion defined by the rotation around the axis
*/
public static Quaternionf fromAngleDegAxis(double angle, double x, double y, double z) {
return fromAngleRadAxis(Math.toRadians(angle), x, y, z);
}
/**
* Creates a new quaternion from the rotation double angle in radians around the axis vector double components.
*
* @param angle The rotation angle in radians
* @param x The x component of the axis vector
* @param y The y component of the axis vector
* @param z The z component of the axis vector
* @return The quaternion defined by the rotation around the axis
*/
public static Quaternionf fromAngleRadAxis(double angle, double x, double y, double z) {
return fromAngleRadAxis((float) angle, (float) x, (float) y, (float) z);
}
/**
* Creates a new quaternion from the rotation float angle in degrees around the axis vector float components.
*
* @param angle The rotation angle in degrees
* @param x The x component of the axis vector
* @param y The y component of the axis vector
* @param z The z component of the axis vector
* @return The quaternion defined by the rotation around the axis
*/
public static Quaternionf fromAngleDegAxis(float angle, float x, float y, float z) {
return fromAngleRadAxis((float) Math.toRadians(angle), x, y, z);
}
/**
* Creates a new quaternion from the rotation float angle in radians around the axis vector float components.
*
* @param angle The rotation angle in radians
* @param x The x component of the axis vector
* @param y The y component of the axis vector
* @param z The z component of the axis vector
* @return The quaternion defined by the rotation around the axis
*/
public static Quaternionf fromAngleRadAxis(float angle, float x, float y, float z) {
final float halfAngle = angle / 2;
final float q = TrigMath.sin(halfAngle) / (float) Math.sqrt(x * x + y * y + z * z);
return new Quaternionf(x * q, y * q, z * q, TrigMath.cos(halfAngle));
}
/**
* Creates a new quaternion from the rotation matrix. The matrix will be interpreted as a rotation matrix even if it is not.
*
* @param matrix The rotation matrix
* @return The quaternion defined by the rotation matrix
*/
public static Quaternionf fromRotationMatrix(Matrix3f matrix) {
final float trace = matrix.trace();
if (trace < 0) {
if (matrix.get(1, 1) > matrix.get(0, 0)) {
if (matrix.get(2, 2) > matrix.get(1, 1)) {
final float r = (float) Math.sqrt(matrix.get(2, 2) - matrix.get(0, 0) - matrix.get(1, 1) + 1);
final float s = 0.5f / r;
return new Quaternionf(
(matrix.get(2, 0) + matrix.get(0, 2)) * s,
(matrix.get(1, 2) + matrix.get(2, 1)) * s,
0.5f * r,
(matrix.get(1, 0) - matrix.get(0, 1)) * s);
} else {
final float r = (float) Math.sqrt(matrix.get(1, 1) - matrix.get(2, 2) - matrix.get(0, 0) + 1);
final float s = 0.5f / r;
return new Quaternionf(
(matrix.get(0, 1) + matrix.get(1, 0)) * s,
0.5f * r,
(matrix.get(1, 2) + matrix.get(2, 1)) * s,
(matrix.get(0, 2) - matrix.get(2, 0)) * s);
}
} else if (matrix.get(2, 2) > matrix.get(0, 0)) {
final float r = (float) Math.sqrt(matrix.get(2, 2) - matrix.get(0, 0) - matrix.get(1, 1) + 1);
final float s = 0.5f / r;
return new Quaternionf(
(matrix.get(2, 0) + matrix.get(0, 2)) * s,
(matrix.get(1, 2) + matrix.get(2, 1)) * s,
0.5f * r,
(matrix.get(1, 0) - matrix.get(0, 1)) * s);
} else {
final float r = (float) Math.sqrt(matrix.get(0, 0) - matrix.get(1, 1) - matrix.get(2, 2) + 1);
final float s = 0.5f / r;
return new Quaternionf(
0.5f * r,
(matrix.get(0, 1) + matrix.get(1, 0)) * s,
(matrix.get(2, 0) - matrix.get(0, 2)) * s,
(matrix.get(2, 1) - matrix.get(1, 2)) * s);
}
} else {
final float r = (float) Math.sqrt(trace + 1);
final float s = 0.5f / r;
return new Quaternionf(
(matrix.get(2, 1) - matrix.get(1, 2)) * s,
(matrix.get(0, 2) - matrix.get(2, 0)) * s,
(matrix.get(1, 0) - matrix.get(0, 1)) * s,
0.5f * r);
}
}
}
| mit |
mikoto2000/MiscellaneousStudy | java/SpringBoot/BuildingAnApplicationWithSpringBoot/src/test/java/hello/HelloControllerTest.java | 1188 | package hello;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
/**
* HelloControllerTest
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void testGetHello() throws Exception{
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
}
}
| mit |
tonikolaba/MrTower | src/al/artofsoul/data/TowerIce.java | 429 | package al.artofsoul.data;
import java.util.concurrent.CopyOnWriteArrayList;
public class TowerIce extends Tower {
public TowerIce(TowerType type, Pllaka filloPllaka, CopyOnWriteArrayList<Armiku> armiqt) {
super(type, filloPllaka, armiqt);
}
@Override
public void shoot (Armiku target) {
super.projectiles.add(new ProjectileIceball(super.type.projectileType, super.target, super.getX(), super.getY(), 32, 32));
}
}
| mit |
AndroidDevLog/AndroidDevLog | 94.StaticCalendarView/app/src/test/java/com/iosdevlog/a94staticcalendarview/ExampleUnitTest.java | 413 | package com.iosdevlog.a94staticcalendarview;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | mit |
Zippocat/JavaFX-MyVoip | src/components/HttpClientExample.java | 2204 | package components;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientExample {
private final String USER_AGENT = "Mozilla/5.0";
public String sendGet(String url) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
return result.toString();
}
public String sendPost(String url, Map<String, String> param) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : param.entrySet()) {
urlParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
return result.toString();
}
} | mit |
myid999/javademo | core/src/main/java/demo/java/v2c03network/InetAddressTest/InetAddressTest.java | 918 | package demo.java.v2c03network.InetAddressTest;
import java.net.*;
/**
* This program demonstrates the InetAddress class. Supply a host name as command line argument, or
* run without command line arguments to see the address of the local host.
* @version 1.01 2001-06-26
* @author Cay Horstmann
*/
public class InetAddressTest
{
public static void main(String[] args)
{
try
{
if (args.length > 0)
{
String host = args[0];
InetAddress[] addresses = InetAddress.getAllByName(host);
for (InetAddress a : addresses)
System.out.println(a);
}
else
{
InetAddress localHostAddress = InetAddress.getLocalHost();
System.out.println(localHostAddress);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
| mit |
kolboch/ClearSkyApp | app/src/main/java/com/example/kb/clearsky/model/api_specific/WeatherDescription.java | 1145 | package com.example.kb.clearsky.model.api_specific;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class WeatherDescription {
@SerializedName("id")
@Expose
private Integer weatherID;
@SerializedName("main")
@Expose
private String mainCategory;
@SerializedName("description")
@Expose
private String description;
@SerializedName("icon")
@Expose
private String iconCode;
public Integer getWeatherID() {
return weatherID;
}
public void setWeatherID(Integer weatherID) {
this.weatherID = weatherID;
}
public String getMainCategory() {
return mainCategory;
}
public void setMainCategory(String mainCategory) {
this.mainCategory = mainCategory;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIconCode() {
return iconCode;
}
public void setIconCode(String iconCode) {
this.iconCode = iconCode;
}
}
| mit |
Mariusrik/schoolprojects | Mobil utvikling eksamen/hotelapplikasjon/src/main/java/no/westerdals/eksamen/app2/LoginActivity.java | 8745 | package no.westerdals.eksamen.app2;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import no.westerdals.eksamen.app2.Model.User;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
EditText editTextUser;
EditText editTextPass;
Button loginButton;
TextView signUpLink;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextUser = (EditText) findViewById(R.id.email_address);
editTextPass = (EditText) findViewById(R.id.password_edit_text);
loginButton = (Button) findViewById(R.id.btn_login);
loginButton.setOnClickListener(this);
signUpLink = (TextView) findViewById(R.id.link_signup);
signUpLink.setOnClickListener(this);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
}
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
//opens main activity if already signed in
if (currentUser != null) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
LoginActivity.this.startActivity(intent);
finish();
}
}
private void signIn(String email, String password) {
if (!validateForm()) {
return;
}
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Signup is only with username and password.
* Room number will be connected to user id in the reception.
*/
private void createAccount(String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(LoginActivity.this, "User: " + user.getEmail() + " created",
Toast.LENGTH_SHORT).show();
registerUserDetails(user);
} else {
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void registerUserDetails(FirebaseUser user) {
writeNewUser(user.getUid(), user.getEmail(), "");
}
private void writeNewUser(String userId, String email, String roomNumber) {
User user = new User(email, roomNumber);
mDatabase.child("users").child(userId).setValue(user);
}
//TODO: make better validation on email etc
private boolean validateForm() {
boolean validLogin = true;
String email = editTextUser.getText().toString();
String password = editTextPass.getText().toString();
if (TextUtils.isEmpty(email)) {
editTextUser.setError("Email address is required");
validLogin = false;
} else
editTextUser.setError(null);
if (TextUtils.isEmpty(password)) {
editTextPass.setError(" Password is required");
validLogin = false;
} else
editTextPass.setError(null);
return validLogin;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_login) {
signIn(editTextUser.getText().toString(), editTextPass.getText().toString());
} else if (v.getId() == R.id.link_signup) {
//createAccount(editTextUser.getText().toString(), editTextPass.getText().toString());
signupForm();
}
}
public void signupForm() {
final AlertDialog.Builder signUpDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.sign_up_form,(ViewGroup) findViewById(R.id.sign_up_form));
signUpDialog.setView(layout);
final EditText emailAddress = (EditText) layout.findViewById(R.id.email_address);
final EditText repeatEmailAddress = (EditText) layout.findViewById(R.id.repeat_email_address);
final EditText password = (EditText) layout.findViewById(R.id.password_edit_text);
final EditText repeatPassword = (EditText) layout.findViewById(R.id.repeat_password_edit_text);
Button button = (Button) layout.findViewById(R.id.btn_sign_up);
signUpDialog.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
signUpDialog.create();
final AlertDialog d = signUpDialog.show();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(validateSignUpForm(password, repeatPassword, emailAddress, repeatEmailAddress)) {
createAccount(emailAddress.getText().toString(), password.getText().toString());
d.dismiss();
}
}
});
}
private boolean validateSignUpForm(EditText password, EditText repeatPassword, EditText emailAdress, EditText repeatEmailAdress){
boolean validated = true;
if (!TextUtils.equals(password.getText(), repeatPassword.getText())){
password.setError("Passwords not matching");
repeatPassword.setError("Passwords not matching");
validated = false;
} else if(TextUtils.isEmpty(password.getText())){
password.setError("Cannot be empty");
validated = false;
}else if(TextUtils.isEmpty(repeatPassword.getText())){
repeatPassword.setError("Cannot be empty");
validated = false;
} else {
password.setError(null);
repeatPassword.setError(null);
}
if (!TextUtils.equals(emailAdress.getText(), repeatEmailAdress.getText())){
emailAdress.setError("Email not matching");
repeatEmailAdress.setError("Email not matching");
validated = false;
} else if(TextUtils.isEmpty(emailAdress.getText())){
emailAdress.setError("Cannot be empty");
validated = false;
}else if(TextUtils.isEmpty(repeatEmailAdress.getText())){
repeatEmailAdress.setError("Cannot be empty");
validated = false;
} else {
emailAdress.setError(null);
repeatEmailAdress.setError(null);
}
return validated;
}
} | mit |
0704681032/Java8InAction | 清华大学邓俊辉老师数据结构资料/dsa/src/_java/dsa/splaytree.java | 8076 | /******************************************************************************************
* Data Structures in C++
* ISBN: 7-302-33064-6 & 7-302-33065-3 & 7-302-29652-2 & 7-302-26883-3
* Junhui DENG, deng@tsinghua.edu.cn
* Computer Science & Technology, Tsinghua University
* Copyright (c) 2006-2013. All rights reserved.
******************************************************************************************/
/*
* ÉìÕ¹Ê÷
* »ùÓÚBSTreeµÄÀ©³ä
*/
package dsa;
public class SplayTree extends BSTree implements Dictionary {
/**************************** ¹¹Ôì·½·¨ ****************************/
public SplayTree() { super(); }
public SplayTree(BinTreePosition r) { super(r); }
public SplayTree(BinTreePosition r, Comparator c) { super(r, c); }
/**************************** ´Êµä·½·¨£¨¸²¸Ç¸¸ÀàBSTree£© ****************************/
//Èô´ÊµäÖдæÔÚÒÔkeyΪ¹Ø¼üÂëµÄÌõÄ¿£¬Ôò·µ»ØÆäÖеÄÒ»¸öÌõÄ¿£»·ñÔò£¬·µ»Ønull
public Entry find(Object key) {
if (isEmpty()) return null;
BSTreeNode u = binSearch((BSTreeNode)root, key, C);
root = moveToRoot(u);
return (0 == C.compare(key, u.getKey())) ? (Entry)u.getElem() : null;
}
//²åÈëÌõÄ¿(key, value)£¬²¢·µ»Ø¸ÃÌõÄ¿
public Entry insert(Object key, Object value) {
Entry e = super.insert(key, value);//µ÷Óø¸Àà·½·¨Íê³É²åÈë
root = moveToRoot(lastV);//ÖØÐÂÆ½ºâ»¯
return e;
}
//Èô´ÊµäÖдæÔÚÒÔkeyΪ¹Ø¼üÂëµÄÌõÄ¿£¬Ôò½«Õª³ýÆäÖеÄÒ»¸ö²¢·µ»Ø£»·ñÔò£¬·µ»Ønull
public Entry remove(Object key) {
Entry e = super.remove(key);//µ÷Óø¸Àà·½·¨Íê³Éɾ³ý
if (null != e && null != lastV) root = moveToRoot(lastV);//ÖØÐÂÆ½ºâ»¯
return e;
}
/**************************** ¸¨Öú·½·¨ ****************************/
//´Ó½Úµãz¿ªÊ¼£¬×ÔÉ϶øÏÂÖØÐÂÆ½ºâ»¯
protected static BinTreePosition moveToRoot(BinTreePosition z) {
while (z.hasParent())
if (!z.getParent().hasParent())
if (z.isLChild()) z = zig(z);
else z = zag(z);
else if (z.isLChild())
if (z.getParent().isLChild()) z = zigzig(z);
else z = zigzag(z);
else if (z.getParent().isLChild()) z = zagzig(z);
else z = zagzag(z);
return z;
}
//vΪ×óº¢×Ó
//˳ʱÕëÐýתv£¬Ê¹Ö®ÉÏÉýÒ»²ã£¨ÉìÕ¹Ê÷£©
//·µ»ØÐµÄ×ÓÊ÷¸ù
protected static BinTreePosition zig(BinTreePosition v) {
if (null != v && v.isLChild()) {//v±ØÐëÓи¸Ç×£¬¶øÇÒ±ØÐëÊÇ×óº¢×Ó
BinTreePosition p = v.getParent();//¸¸Ç×
BinTreePosition g = p.getParent();//׿¸¸
boolean asLChild = p.isLChild();//¸¸Ç×ÊÇ·ñ׿¸¸µÄ×óº¢×Ó
v.secede();//Õª³öv£¨ÓÚÊÇpµÄ×óº¢×ÓΪ¿Õ£©
BinTreePosition c = v.getRChild();//½«vµÄÓÒº¢×Ó
if (null != c) p.attachL(c.secede());//×÷ΪpµÄ×óº¢×Ó
p.secede();//Õª³ö¸¸Ç×
v.attachR(p);//½«p×÷ΪvµÄÓÒº¢×Ó
if (null != g)//Èô׿¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó
if (asLChild) g.attachL(v);
else g.attachR(v);
}
return v;
}
//vΪÓÒº¢×Ó
//ÄæÊ±ÕëÐýתv£¬Ê¹Ö®ÉÏÉýÒ»²ã£¨ÉìÕ¹Ê÷£©
//·µ»ØÐµÄ×ÓÊ÷¸ù
protected static BinTreePosition zag(BinTreePosition v) {
if (null != v && v.isRChild()) {//v±ØÐëÓи¸Ç×£¬¶øÇÒ±ØÐëÊÇÓÒº¢×Ó
BinTreePosition p = v.getParent();//¸¸Ç×
BinTreePosition g = p.getParent();//׿¸¸
boolean asLChild = p.isLChild();//¸¸Ç×ÊÇ·ñ׿¸¸µÄ×óº¢×Ó
v.secede();//Õª³öv£¨ÓÚÊÇpµÄ×óº¢×ÓΪ¿Õ£©
BinTreePosition c = v.getLChild();//½«vµÄ×óº¢×Ó
if (null != c) p.attachR(c.secede());//×÷ΪpµÄÓÒº¢×Ó
p.secede();//Õª³ö¸¸Ç×
v.attachL(p);//½«p×÷ΪvµÄ×óº¢×Ó
if (null != g)//Èô׿¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó
if (asLChild) g.attachL(v);
else g.attachR(v);
}
return v;
}
//vΪ×óº¢×Ó£¬¸¸Ç×Ϊ×óº¢×Ó
//˳ʱÕëÐýתv£¬Ê¹Ö®ÉÏÉýÁ½²ã£¨ÉìÕ¹Ê÷£©
//·µ»ØÐµÄ×ÓÊ÷¸ù
protected static BinTreePosition zigzig(BinTreePosition v) {
if (null != v && v.isLChild() && v.hasParent() && v.getParent().isLChild()) {
BinTreePosition p = v.getParent();//¸¸Ç×
BinTreePosition g = p.getParent();//׿¸¸
BinTreePosition s = g.getParent();//Ôø×æ¸¸
boolean asLChild = g.isLChild();//׿¸¸ÊÇ·ñÔø×æ¸¸µÄ×óº¢×Ó
g.secede();
p.secede();
v.secede();
BinTreePosition c;//ÁÙʱ±äÁ¿£¬¸¨Öúº¢×ÓµÄÒÆ¶¯
c = p.getRChild(); if (null != c) g.attachL(c.secede());//pµÄÓÒº¢×Ó×÷ΪgµÄ×óº¢×Ó
c = v.getRChild(); if (null != c) p.attachL(c.secede());//vµÄÓÒº¢×Ó×÷ΪpµÄ×óº¢×Ó
p.attachR(g);//g×÷ΪpµÄÓÒº¢×Ó
v.attachR(p);//p×÷ΪvµÄÓÒº¢×Ó
if (null != s)//ÈôÔø×æ¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó
if (asLChild) s.attachL(v);
else s.attachR(v);
}
return v;
}
//vΪÓÒº¢×Ó£¬¸¸Ç×ΪÓÒº¢×Ó
//˳ʱÕëÐýתv£¬Ê¹Ö®ÉÏÉýÁ½²ã£¨ÉìÕ¹Ê÷£©
//·µ»ØÐµÄ×ÓÊ÷¸ù
protected static BinTreePosition zagzag(BinTreePosition v) {
if (null != v && v.isRChild() && v.hasParent() && v.getParent().isRChild()) {
BinTreePosition p = v.getParent();//¸¸Ç×
BinTreePosition g = p.getParent();//׿¸¸
BinTreePosition s = g.getParent();//Ôø×æ¸¸
boolean asLChild = g.isLChild();//׿¸¸ÊÇ·ñÔø×æ¸¸µÄ×óº¢×Ó
g.secede();
p.secede();
v.secede();
BinTreePosition c;//ÁÙʱ±äÁ¿£¬¸¨Öúº¢×ÓµÄÒÆ¶¯
c = p.getLChild(); if (null != c) g.attachR(c.secede());//pµÄ×óº¢×Ó×÷ΪgµÄÓÒº¢×Ó
c = v.getLChild(); if (null != c) p.attachR(c.secede());//vµÄ×óº¢×Ó×÷ΪpµÄÓÒº¢×Ó
p.attachL(g);//g×÷ΪpµÄ×óº¢×Ó
v.attachL(p);//p×÷ΪvµÄ×óº¢×Ó
if (null != s)//ÈôÔø×æ¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó
if (asLChild) s.attachL(v);
else s.attachR(v);
}
return v;
}
//vΪ×óº¢×Ó£¬¸¸Ç×ΪÓÒº¢×Ó
//˳ʱÕëÐýתv£¬Ê¹Ö®ÉÏÉýÁ½²ã£¨ÉìÕ¹Ê÷£©
//·µ»ØÐµÄ×ÓÊ÷¸ù
protected static BinTreePosition zigzag(BinTreePosition v) {
if (null != v && v.isLChild() && v.hasParent() && v.getParent().isRChild()) {
BinTreePosition p = v.getParent();//¸¸Ç×
BinTreePosition g = p.getParent();//׿¸¸
BinTreePosition s = g.getParent();//Ôø×æ¸¸
boolean asLChild = g.isLChild();//׿¸¸ÊÇ·ñÔø×æ¸¸µÄ×óº¢×Ó
g.secede();
p.secede();
v.secede();
BinTreePosition c;//ÁÙʱ±äÁ¿£¬¸¨Öúº¢×ÓµÄÒÆ¶¯
c = v.getLChild(); if (null != c) g.attachR(c.secede());//vµÄ×óº¢×Ó×÷ΪgµÄÓÒº¢×Ó
c = v.getRChild(); if (null != c) p.attachL(c.secede());//vµÄÓÒº¢×Ó×÷ΪpµÄ×óº¢×Ó
v.attachL(g);//g×÷ΪvµÄ×óº¢×Ó
v.attachR(p);//p×÷ΪvµÄÓÒº¢×Ó
if (null != s)//ÈôÔø×æ¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó
if (asLChild) s.attachL(v);
else s.attachR(v);
}
return v;
}
//vΪÓÒº¢×Ó£¬¸¸Ç×Ϊ×óº¢×Ó
//˳ʱÕëÐýתv£¬Ê¹Ö®ÉÏÉýÁ½²ã£¨ÉìÕ¹Ê÷£©
//·µ»ØÐµÄ×ÓÊ÷¸ù
protected static BinTreePosition zagzig(BinTreePosition v) {
if (null != v && v.isRChild() && v.hasParent() && v.getParent().isLChild()) {
BinTreePosition p = v.getParent();//¸¸Ç×
BinTreePosition g = p.getParent();//׿¸¸
BinTreePosition s = g.getParent();//Ôø×æ¸¸
boolean asLChild = g.isLChild();//׿¸¸ÊÇ·ñÔø×æ¸¸µÄ×óº¢×Ó
g.secede();
p.secede();
v.secede();
BinTreePosition c;//ÁÙʱ±äÁ¿£¬¸¨Öúº¢×ÓµÄÒÆ¶¯
c = v.getRChild(); if (null != c) g.attachL(c.secede());//vµÄÓÒº¢×Ó×÷ΪgµÄ×óº¢×Ó
c = v.getLChild(); if (null != c) p.attachR(c.secede());//vµÄ×óº¢×Ó×÷ΪpµÄÓÒº¢×Ó
v.attachR(g);//g×÷ΪvµÄÓÒº¢×Ó
v.attachL(p);//p×÷ΪvµÄ×óº¢×Ó
if (null != s)//ÈôÔø×æ¸¸´æÔÚ£¬Ôò½«v×÷ΪÆäº¢×Ó
if (asLChild) s.attachL(v);
else s.attachR(v);
}
return v;
}
} | mit |
MihawkHu/SimPl | src/simpl/typing/ListType.java | 1105 | package simpl.typing;
public final class ListType extends Type {
public Type t;
public ListType(Type t) {
this.t = t;
}
@Override
public boolean isEqualityType() {
// TODO Done
return t.isEqualityType();
}
@Override
public Substitution unify(Type t) throws TypeError {
// TODO Done
if (t instanceof TypeVar) {
return t.unify(this);
}
else if (t instanceof ListType) {
return this.t.unify(((ListType)t).t);
}
else {
throw new TypeMismatchError();
}
}
@Override
public boolean contains(TypeVar tv) {
// TODO Done
return t.contains(tv);
}
@Override
public Type replace(TypeVar a, Type t) {
// TODO Done
return new ListType(this.t.replace(a, t));
}
public String toString() {
return t + " list";
}
@Override
public boolean equals(Type t) {
if (t instanceof ListType) {
return this.t.equals(((ListType)t).t);
}
return false;
}
}
| mit |
felipecsl/GifImageView | app/src/main/java/com/felipecsl/gifimageview/app/GifGridAdapter.java | 1665 | package com.felipecsl.gifimageview.app;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.felipecsl.gifimageview.library.GifImageView;
import java.util.List;
public class GifGridAdapter extends BaseAdapter {
private final Context context;
private final List<String> imageUrls;
public GifGridAdapter(Context context, List<String> imageUrls) {
this.context = context;
this.imageUrls = imageUrls;
}
@Override
public int getCount() {
return imageUrls.size();
}
@Override
public Object getItem(int position) {
return imageUrls.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final GifImageView imageView;
if (convertView == null) {
imageView = new GifImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setPadding(10, 10, 10, 10);
int size = AbsListView.LayoutParams.WRAP_CONTENT;
AbsListView.LayoutParams layoutParams = new GridView.LayoutParams(size, size);
imageView.setLayoutParams(layoutParams);
} else {
imageView = (GifImageView) convertView;
imageView.clear();
}
new GifDataDownloader() {
@Override
protected void onPostExecute(final byte[] bytes) {
imageView.setBytes(bytes);
imageView.startAnimation();
}
}.execute(imageUrls.get(position));
return imageView;
}
}
| mit |
simokhov/schemas44 | src/main/java/ru/gov/zakupki/oos/signincoming/_1/BankGuaranteeReturnInvalid.java | 2353 | //
// 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: 2019.07.02 at 03:35:23 PM MSK
//
package ru.gov.zakupki.oos.signincoming._1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import ru.gov.zakupki.oos.types._1.ZfcsBankGuaranteeReturnInvalidType;
/**
* Пакет данных:
* Сведения о недействительности информации о возвращении банковской гарантии или об освобождении от обязательств по банковской гарантии
*
* <p>Java class for bankGuaranteeReturnInvalid complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="bankGuaranteeReturnInvalid">
* <complexContent>
* <extension base="{http://zakupki.gov.ru/oos/signIncoming/1}packetType">
* <sequence>
* <element name="data" type="{http://zakupki.gov.ru/oos/types/1}zfcs_bankGuaranteeReturnInvalidType"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "bankGuaranteeReturnInvalid", propOrder = {
"data"
})
public class BankGuaranteeReturnInvalid
extends PacketType
{
@XmlElement(required = true)
protected ZfcsBankGuaranteeReturnInvalidType data;
/**
* Gets the value of the data property.
*
* @return
* possible object is
* {@link ZfcsBankGuaranteeReturnInvalidType }
*
*/
public ZfcsBankGuaranteeReturnInvalidType getData() {
return data;
}
/**
* Sets the value of the data property.
*
* @param value
* allowed object is
* {@link ZfcsBankGuaranteeReturnInvalidType }
*
*/
public void setData(ZfcsBankGuaranteeReturnInvalidType value) {
this.data = value;
}
}
| mit |
NucleusPowered/Nucleus | nucleus-core/src/main/java/io/github/nucleuspowered/nucleus/core/scaffold/command/modifier/impl/RequiresEconomyModifier.java | 1279 | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.core.scaffold.command.modifier.impl;
import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandContext;
import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.CommandModifier;
import io.github.nucleuspowered.nucleus.core.scaffold.command.control.CommandControl;
import io.github.nucleuspowered.nucleus.core.scaffold.command.modifier.ICommandModifier;
import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection;
import net.kyori.adventure.text.Component;
import java.util.Optional;
public class RequiresEconomyModifier implements ICommandModifier {
@Override
public Optional<Component> testRequirement(final ICommandContext source, final CommandControl control,
final INucleusServiceCollection serviceCollection, final CommandModifier modifier) {
if (!serviceCollection.economyServiceProvider().serviceExists()) {
return Optional.of(serviceCollection.messageProvider().getMessageFor(source.cause().audience(), "command.economyrequired"));
}
return Optional.empty();
}
}
| mit |
mmithril/XChange | xchange-bitstamp/src/test/java/org/knowm/xchange/bitstamp/service/marketdata/TickerFetchIntegration.java | 929 | package org.knowm.xchange.bitstamp.service.marketdata;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.Test;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.bitstamp.BitstampExchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.service.polling.marketdata.PollingMarketDataService;
/**
* @author timmolter
*/
public class TickerFetchIntegration {
@Test
public void tickerFetchTest() throws Exception {
Exchange exchange = ExchangeFactory.INSTANCE.createExchange(BitstampExchange.class.getName());
PollingMarketDataService marketDataService = exchange.getPollingMarketDataService();
Ticker ticker = marketDataService.getTicker(new CurrencyPair("BTC", "USD"));
System.out.println(ticker.toString());
assertThat(ticker).isNotNull();
}
}
| mit |
gv2011/util | test/src/test/java/com/github/gv2011/util/bytes/DataTypeTest.java | 1762 | package com.github.gv2011.util.bytes;
import static com.github.gv2011.testutil.Assert.assertThat;
import static com.github.gv2011.testutil.Matchers.is;
import org.junit.Test;
import com.github.gv2011.util.BeanUtils;
import com.github.gv2011.util.icol.ICollections;
import com.github.gv2011.util.json.JsonUtils;
public class DataTypeTest {
@Test
public void test() {
final String encoded =
"multipart/related; boundary=example-2; start=\"<950118.AEBH@XIson.com>\"; type=\"Text/x-Okie\""
;
final DataType type = DataType.parse(encoded);
assertThat(type.getClass(), is(DataTypeImp.class));
assertThat(type.primaryType(), is("multipart"));
assertThat(type.subType(), is("related"));
assertThat(type.baseType(), is(DataType.parse("multipart/related")));
assertThat(type.parameters(), is(
ICollections.mapBuilder()
.put("boundary", "example-2")
.put("start", "<950118.AEBH@XIson.com>")
.put("type", "Text/x-Okie")
.build()
));
assertThat(type.toString(), is(encoded));
assertThat(
BeanUtils.typeRegistry().beanType(DataType.class).toJson(type),
is(JsonUtils.jsonFactory().primitive(encoded))
);
}
@Test(expected=IllegalStateException.class)
public void testValidation() {
BeanUtils.beanBuilder(DataType.class)
.set(DataType::primaryType).to("multipart")
.set(DataType::subType).to("@")
.build()
;
}
@Test//(expected=IllegalStateException.class)
public void testValidation2() {
BeanUtils.beanBuilder(DataType.class)
.set(DataType::primaryType).to("multipart")
.set(DataType::subType).to("related")
.build()
;
}
}
| mit |
a-ostrovsky/business_rules_kata | src/main/java/com/kata/businessrules/MainModule.java | 895 | package com.kata.businessrules;
import org.w3c.dom.Document;
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.kata.businessrules.products.Product;
public class MainModule extends AbstractModule {
@Override
protected void configure() {
installDummyModules();
bind(new TypeLiteral<RuleEngineLoader<Document>>() {
});
}
private void installDummyModules() {
bind(ReceiptGenerator.class).toInstance(new ReceiptGenerator() {
@Override
public Receipt generateReceipt(User customer, Product product) {
return null;
}
});
bind(UserRepository.class).toInstance(new UserRepository() {
@Override
public User getById(String id) {
return null;
}
});
bind(ProductRepository.class).toInstance(new ProductRepository() {
@Override
public <T extends Product> T getById(String id) {
return null;
}
});
}
}
| mit |
andyjko/whyline | edu/cmu/hcii/whyline/analysis/FindOverriders.java | 1239 | package edu.cmu.hcii.whyline.analysis;
import java.util.SortedSet;
import java.util.TreeSet;
import edu.cmu.hcii.whyline.bytecode.MethodInfo;
import edu.cmu.hcii.whyline.source.JavaSourceFile;
import edu.cmu.hcii.whyline.source.Line;
import edu.cmu.hcii.whyline.source.Token;
import edu.cmu.hcii.whyline.ui.WhylineUI;
/**
* @author Andrew J. Ko
*
*/
public class FindOverriders implements SearchResultsInterface {
private final MethodInfo method;
private final WhylineUI whylineUI;
private final SortedSet<Token> overriders = new TreeSet<Token>();
public FindOverriders(WhylineUI whylineUI, MethodInfo method) {
this.whylineUI = whylineUI;
this.method = method;
for(MethodInfo m : method.getOverriders()) {
JavaSourceFile source = m.getClassfile().getSourceFile();
if(source != null) {
Line line = source.getTokenForMethodName(m).getLine();
overriders.addAll(line.getTokensAfterFirstNonWhitespaceToken());
}
}
}
public String getResultsDescription() { return "overriders of " + method.getInternalName(); }
public String getCurrentStatus() { return "Done."; }
public SortedSet<Token> getResults() { return overriders; }
public boolean isDone() { return true; }
}
| mit |
StoyanVitanov/SoftwareUniversity | Java Web/Web Fundamentals/05.Handmade Web Server/servlet-containers/static-container/src/org/vitanov/container/ContainerConstants.java | 161 | package org.vitanov.container;
public class ContainerConstants {
public static String CONTAINER_ROOT_PATH =
System.getProperty("user.dir");
}
| mit |
project-capo/amber-java-clients | amber-java-examples/src/main/java/DriveToPointExample.java | 2273 | import pl.edu.agh.amber.common.AmberClient;
import pl.edu.agh.amber.drivetopoint.DriveToPointProxy;
import pl.edu.agh.amber.drivetopoint.Location;
import pl.edu.agh.amber.drivetopoint.Point;
import pl.edu.agh.amber.drivetopoint.Result;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
/**
* Drive to point proxy example.
*
* @author Pawel Suder <pawel@suder.info>
*/
public class DriveToPointExample {
public static void main(String[] args) {
(new DriveToPointExample()).runDemo();
}
public void runDemo() {
Scanner keyboard = new Scanner(System.in);
System.out.print("IP (default: 127.0.0.1): ");
String hostname = keyboard.nextLine();
if ("".equals(hostname)) {
hostname = "127.0.0.1";
}
AmberClient client;
try {
client = new AmberClient(hostname, 26233);
} catch (IOException e) {
System.out.println("Unable to connect to robot: " + e);
return;
}
DriveToPointProxy driveToPointProxy = new DriveToPointProxy(client, 0);
try {
List<Point> targets = Arrays.asList(
new Point(2.44725, 4.22125, 0.25),
new Point(1.46706, 4.14285, 0.25),
new Point(0.67389, 3.76964, 0.25),
new Point(0.47339, 2.96781, 0.25));
driveToPointProxy.setTargets(targets);
while (true) {
Result<List<Point>> resultNextTargets = driveToPointProxy.getNextTargets();
Result<List<Point>> resultVisitedTargets = driveToPointProxy.getVisitedTargets();
List<Point> nextTargets = resultNextTargets.getResult();
List<Point> visitedTargets = resultVisitedTargets.getResult();
System.out.println(String.format("next targets: %s, visited targets: %s", nextTargets.toString(), visitedTargets.toString()));
Thread.sleep(1000);
}
} catch (IOException e) {
System.out.println("Error in sending a command: " + e);
} catch (Exception e) {
e.printStackTrace();
} finally {
client.terminate();
}
}
}
| mit |
de-luxe/burstcoin-faucet | src/main/java/burstcoin/faucet/data/Account.java | 2187 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* 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 burstcoin.faucet.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Date;
@Entity
public class Account
implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String accountId;
@Column(nullable = true)
private Date lastClaim;
protected Account()
{
}
public Account(String accountId, Date lastClaim)
{
this.accountId = accountId;
this.lastClaim = lastClaim;
}
public Long getId()
{
return id;
}
public void setAccountId(String accountId)
{
this.accountId = accountId;
}
public void setLastClaim(Date lastClaim)
{
this.lastClaim = lastClaim;
}
public String getAccountId()
{
return accountId;
}
public Date getLastClaim()
{
return lastClaim;
}
}
| mit |
Crim/pardot-java-client | src/main/java/com/darksci/pardot/api/request/form/FormCreateRequest.java | 2672 | /**
* Copyright 2017, 2018, 2019, 2020 Stephen Powis https://github.com/Crim/pardot-java-client
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.darksci.pardot.api.request.form;
import com.darksci.pardot.api.request.BaseRequest;
/**
* For creating new Forms using Pardot's API.
*/
public class FormCreateRequest extends BaseRequest<FormCreateRequest> {
@Override
public String getApiEndpoint() {
return "form/do/create";
}
/**
* Define the name of the form.
* @param name The name of the form.
* @return FormCreateRequest builder.
*/
public FormCreateRequest withName(final String name) {
setParam("name", name);
return this;
}
/**
* Associate form with a campaign.
* @param campaignId Id of campaign to associate with form.
* @return FormCreateRequest builder.
*/
public FormCreateRequest withCampaignId(final Long campaignId) {
setParam("campaign_id", campaignId);
return this;
}
/**
* Associate form with a layout template.
* @param layoutTemplateId Id of layout template to associate with form.
* @return FormCreateRequest builder.
*/
public FormCreateRequest withLayoutTemplateId(final Long layoutTemplateId) {
setParam("layout_template_id", layoutTemplateId);
return this;
}
/**
* Associate form with a folder.
* @param folderId Id of folder to associate with form.
* @return FormCreateRequest builder.
*/
public FormCreateRequest withFolderId(final Long folderId) {
setParam("folder_id", folderId);
return this;
}
}
| mit |
CS2103JAN2017-T09-B4/main | src/main/java/seedu/tache/ui/UiManager.java | 6234 | package seedu.tache.ui;
import java.util.logging.Logger;
//import org.controlsfx.control.Notifications;
import com.google.common.eventbus.Subscribe;
import javafx.application.Platform;
//import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.image.Image;
//import javafx.scene.image.ImageView;
import javafx.stage.Stage;
//import javafx.util.Duration;
import seedu.tache.MainApp;
import seedu.tache.commons.core.ComponentManager;
import seedu.tache.commons.core.Config;
import seedu.tache.commons.core.LogsCenter;
import seedu.tache.commons.events.model.TaskManagerChangedEvent;
import seedu.tache.commons.events.storage.DataSavingExceptionEvent;
import seedu.tache.commons.events.ui.JumpToListRequestEvent;
import seedu.tache.commons.events.ui.PopulateRecurringGhostTaskEvent;
import seedu.tache.commons.events.ui.ShowHelpRequestEvent;
import seedu.tache.commons.events.ui.TaskPanelConnectionChangedEvent;
import seedu.tache.commons.util.StringUtil;
import seedu.tache.logic.Logic;
import seedu.tache.model.UserPrefs;
/**
* The manager of the UI component.
*/
public class UiManager extends ComponentManager implements Ui {
private static final Logger logger = LogsCenter.getLogger(UiManager.class);
private static final String ICON_APPLICATION = "/images/tache.png";
public static final String ALERT_DIALOG_PANE_FIELD_ID = "alertDialogPane";
private Logic logic;
private Config config;
private UserPrefs prefs;
private HotkeyManager hotkeyManager;
private NotificationManager notificationManager;
private MainWindow mainWindow;
public UiManager(Logic logic, Config config, UserPrefs prefs) {
super();
this.logic = logic;
this.config = config;
this.prefs = prefs;
}
@Override
public void start(Stage primaryStage) {
logger.info("Starting UI...");
primaryStage.setTitle(config.getAppTitle());
//Set the application icon.
primaryStage.getIcons().add(getImage(ICON_APPLICATION));
hotkeyManager = new HotkeyManager(primaryStage);
hotkeyManager.start();
try {
mainWindow = new MainWindow(primaryStage, config, prefs, logic);
mainWindow.show(); //This should be called before creating other UI parts
mainWindow.fillInnerParts();
} catch (Throwable e) {
logger.severe(StringUtil.getDetails(e));
showFatalErrorDialogAndShutdown("Fatal error during initializing", e);
}
notificationManager = new NotificationManager(logic);
notificationManager.start();
}
@Override
public void stop() {
prefs.updateLastUsedGuiSetting(mainWindow.getCurrentGuiSetting());
mainWindow.hide();
mainWindow.releaseResources();
hotkeyManager.stop();
notificationManager.stop();
}
private void showFileOperationAlertAndWait(String description, String details, Throwable cause) {
final String content = details + ":\n" + cause.toString();
showAlertDialogAndWait(AlertType.ERROR, "File Op Error", description, content);
}
private Image getImage(String imagePath) {
return new Image(MainApp.class.getResourceAsStream(imagePath));
}
void showAlertDialogAndWait(Alert.AlertType type, String title, String headerText, String contentText) {
showAlertDialogAndWait(mainWindow.getPrimaryStage(), type, title, headerText, contentText);
}
private static void showAlertDialogAndWait(Stage owner, AlertType type, String title, String headerText,
String contentText) {
final Alert alert = new Alert(type);
alert.getDialogPane().getStylesheets().add("view/TacheTheme.css");
alert.initOwner(owner);
alert.setTitle(title);
alert.setHeaderText(headerText);
alert.setContentText(contentText);
alert.getDialogPane().setId(ALERT_DIALOG_PANE_FIELD_ID);
alert.showAndWait();
}
private void showFatalErrorDialogAndShutdown(String title, Throwable e) {
logger.severe(title + " " + e.getMessage() + StringUtil.getDetails(e));
showAlertDialogAndWait(Alert.AlertType.ERROR, title, e.getMessage(), e.toString());
Platform.exit();
System.exit(1);
}
//==================== Event Handling Code ===============================================================
@Subscribe
private void handleDataSavingExceptionEvent(DataSavingExceptionEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
showFileOperationAlertAndWait("Could not save data", "Could not save data to file", event.exception);
}
@Subscribe
private void handleShowHelpEvent(ShowHelpRequestEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
mainWindow.handleHelp();
}
@Subscribe
private void handleJumpToListRequestEvent(JumpToListRequestEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
mainWindow.getTaskListPanel().scrollTo(event.targetIndex);
}
//@@author A0139925U
@Subscribe
private void handleTaskPanelConnectionChangedEvent(TaskPanelConnectionChangedEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
if (mainWindow.getTaskListPanel() != null) {
mainWindow.getTaskListPanel().resetConnections(event.getNewConnection());
}
}
@Subscribe
private void handlePopulateRecurringGhostTaskEvent(PopulateRecurringGhostTaskEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
if (mainWindow.getTaskListPanel() != null) {
mainWindow.getCalendarPanel().addAllEvents(event.getAllCompletedRecurringGhostTasks());
mainWindow.getCalendarPanel().addAllEvents(event.getAllUncompletedRecurringGhostTasks());
}
}
@Subscribe
public void handleUpdateNotificationsEvent(TaskManagerChangedEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
notificationManager.updateNotifications(event);
}
}
| mit |
gilz688/MIF-ImageEditor | MIFImageEditor/src/main/java/com/github/gilz688/mifeditor/MIEApplication.java | 1289 | package com.github.gilz688.mifeditor;
import com.github.gilz688.mifeditor.proto.MIEView;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class MIEApplication extends Application {
private Stage primaryStage;
private AnchorPane rootLayout;
public static final String APPLICATION_NAME = "MIF Image Editor";
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MIEApplication.class
.getResource("view/MIE.fxml"));
rootLayout = (AnchorPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
scene.getStylesheets().add(
getClass().getResource("application.css").toExternalForm());
primaryStage.setTitle(APPLICATION_NAME);
primaryStage.setScene(scene);
primaryStage.show();
final MIEView view = (MIEView) loader.getController();
view.setStage(primaryStage);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
| mit |