repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
smartnsoft/droid4me
library/src/main/java/com/smartnsoft/droid4me/cache/package-info.java
1333
// The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // 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. /** * Contains some caching features, based on RAM or/and the SD card (persistence) of the terminal. * * @author Édouard Mercier * @since 2010.07.09 */ package com.smartnsoft.droid4me.cache;
mit
lmarinov/Exercise-repo
Programming_Basics_Nov_2020/src/AdvancedConditionalStatements/Lab/AnymalType.java
620
package AdvancedConditionalStatements.Lab; import java.util.Scanner; public class AnymalType { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String animal = scanner.nextLine(); switch (animal){ case "dog": System.out.println("mammal"); break; case "crocodile": case "snake": case "tortoise": System.out.println("reptile"); break; default: System.out.println("unknown"); break; } } }
mit
DaanVanYperen/odb-little-fortune-planet
core/src/net/mostlyoriginal/game/system/planet/cells/OrganicCellSimulator.java
2061
package net.mostlyoriginal.game.system.planet.cells; import net.mostlyoriginal.game.component.PlanetCell; import net.mostlyoriginal.game.component.StatusMask; /** * @author Daan van Yperen */ public class OrganicCellSimulator implements CellSimulator { @Override public void color(CellDecorator c, float delta) { c.cell.color = c.planet.cellColor[c.cell.type.ordinal()]; } @Override public void process(CellDecorator c, float delta) { // spread. PlanetCell target = c.getRandomNeighbour(PlanetCell.CellType.AIR, 3); if (target != null && target.nextType == null && target.type == PlanetCell.CellType.AIR) { CellDecorator proxies = c.proxies(target); if (proxies.getNeighbour(PlanetCell.CellType.STATIC) != null) { // self on dirt? growww! target.nextType = PlanetCell.CellType.ORGANIC; target.nextColor = c.planet.cellColor[PlanetCell.CellType.ORGANIC.ordinal()]; } else { // parent on dirt? or random chance of growth? then we growww! if (c.getNeighbour(PlanetCell.CellType.STATIC) != null || FauxRng.random(2000) < 5 ) { target.nextType = PlanetCell.CellType.ORGANIC; target.nextColor = c.planet.cellColor[PlanetCell.CellType.ORGANIC.ordinal()]; } } } if (c.getNeighbour(PlanetCell.CellType.FIRE, PlanetCell.CellType.LAVA, PlanetCell.CellType.LAVA_CRUST) != null) { c.cell.nextType = PlanetCell.CellType.FIRE; } // die if no air. if (FauxRng.random(100 ) < 25 && c.getNeighbour(PlanetCell.CellType.AIR) == null) { c.cell.nextType = PlanetCell.CellType.AIR; } else { if ( FauxRng.random(1000 ) < 2 && c.countNeighbour(PlanetCell.CellType.AIR) > 6 ) { c.cell.nextType = PlanetCell.CellType.ORGANIC_SPORE; } } } @Override public void updateMask(CellDecorator c, float delta) { } }
mit
vanncho/DatabasesAdvancedHibernate
midtermExam/src/main/java/app/entities/anomalies/dto/exports/xml/AnomalyExportXMLDto.java
1360
package app.entities.anomalies.dto.exports.xml; import javax.xml.bind.annotation.*; import java.io.Serializable; import java.util.List; @XmlRootElement(name = "anomaly") @XmlAccessorType(XmlAccessType.FIELD) public class AnomalyExportXMLDto implements Serializable { @XmlAttribute(name = "id", required = true) private long id; @XmlAttribute(name = "origin-planet", required = true) private String originPlanet; @XmlAttribute(name = "teleport-planet", required = true) private String teleportPlanet; @XmlElementWrapper(name = "victims") @XmlElement(name = "victim") private List<VictimExportXMLDto> victims; public AnomalyExportXMLDto() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getOriginPlanet() { return originPlanet; } public void setOriginPlanet(String originPlanet) { this.originPlanet = originPlanet; } public String getTeleportPlanet() { return teleportPlanet; } public void setTeleportPlanet(String teleportPlanet) { this.teleportPlanet = teleportPlanet; } public List<VictimExportXMLDto> getVictims() { return victims; } public void setVictims(List<VictimExportXMLDto> victims) { this.victims = victims; } }
mit
BranchMetrics/Android-Deferred-Deep-Linking-SDK
Branch-SDK/src/main/java/io/branch/referral/ServerRequestIdentifyUserRequest.java
5545
package io.branch.referral; import android.app.Application; import android.content.Context; import org.json.JSONException; import org.json.JSONObject; /** * * <p> * The server request for identifying current user to Branch API. Handles request creation and execution. * </p> */ class ServerRequestIdentifyUserRequest extends ServerRequest { Branch.BranchReferralInitListener callback_; String userId_ = null; /** * <p>Create an instance of {@link ServerRequestIdentifyUserRequest} to Identify the current user to the Branch API * by supplying a unique identifier as a {@link String} value, with a callback specified to perform a * defined action upon successful response to request.</p> * * @param context Current {@link Application} context * @param userId A {@link String} value containing the unique identifier of the user. * @param callback A {@link Branch.BranchReferralInitListener} callback instance that will return * the data associated with the user id being assigned, if available. */ public ServerRequestIdentifyUserRequest(Context context, Branch.BranchReferralInitListener callback, String userId) { super(context, Defines.RequestPath.IdentifyUser); callback_ = callback; userId_ = userId; JSONObject post = new JSONObject(); try { post.put(Defines.Jsonkey.IdentityID.getKey(), prefHelper_.getIdentityID()); post.put(Defines.Jsonkey.DeviceFingerprintID.getKey(), prefHelper_.getDeviceFingerPrintID()); post.put(Defines.Jsonkey.SessionID.getKey(), prefHelper_.getSessionID()); if (!prefHelper_.getLinkClickID().equals(PrefHelper.NO_STRING_VALUE)) { post.put(Defines.Jsonkey.LinkClickID.getKey(), prefHelper_.getLinkClickID()); } post.put(Defines.Jsonkey.Identity.getKey(), userId); setPost(post); } catch (JSONException ex) { ex.printStackTrace(); constructError_ = true; } } public ServerRequestIdentifyUserRequest(Defines.RequestPath requestPath, JSONObject post, Context context) { super(requestPath, post, context); } public void onRequestSucceeded(ServerResponse resp, Branch branch) { try { if (getPost() != null && getPost().has(Defines.Jsonkey.Identity.getKey())) { prefHelper_.setIdentity(getPost().getString(Defines.Jsonkey.Identity.getKey())); } prefHelper_.setIdentityID(resp.getObject().getString(Defines.Jsonkey.IdentityID.getKey())); prefHelper_.setUserURL(resp.getObject().getString(Defines.Jsonkey.Link.getKey())); if (resp.getObject().has(Defines.Jsonkey.ReferringData.getKey())) { String params = resp.getObject().getString(Defines.Jsonkey.ReferringData.getKey()); prefHelper_.setInstallParams(params); } if (callback_ != null) { callback_.onInitFinished(branch.getFirstReferringParams(), null); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void handleFailure(int statusCode, String causeMsg) { if (callback_ != null) { JSONObject obj = new JSONObject(); try { obj.put("error_message", "Trouble reaching server. Please try again in a few minutes"); } catch (JSONException ex) { ex.printStackTrace(); } callback_.onInitFinished(obj, new BranchError("Trouble setting the user alias. " + causeMsg, statusCode)); } } @Override public boolean handleErrors(Context context) { if (!super.doesAppHasInternetPermission(context)) { if (callback_ != null) { callback_.onInitFinished(null, new BranchError("Trouble setting the user alias.", BranchError.ERR_NO_INTERNET_PERMISSION)); } return true; } else { try { String userId = getPost().getString(Defines.Jsonkey.Identity.getKey()); if (userId == null || userId.length() == 0 || userId.equals(prefHelper_.getIdentity())) { return true; } } catch (JSONException ignore) { return true; } } return false; } @Override public boolean isGetRequest() { return false; } /** * Return true if the user id provided for user identification is the same as existing id * * @return True if the user id refferes to the existing user */ public boolean isExistingID() { try { String userId= getPost().getString(Defines.Jsonkey.Identity.getKey()); return (userId != null && userId.equals(prefHelper_.getIdentity())); } catch (JSONException e) { e.printStackTrace(); return false; } } /* * Callback with existing first referral params. * * @param branch {@link Branch} instance. */ public void handleUserExist(Branch branch) { if (callback_ != null) { callback_.onInitFinished(branch.getFirstReferringParams(), null); } } @Override public void clearCallbacks() { callback_ = null; } @Override public boolean shouldRetryOnFail() { return true; //Identify user request need to retry on failure. } }
mit
IngotPowered/IngotAPI
src/com/ingotpowered/api/events/list/PlayerLoginEvent.java
628
package com.ingotpowered.api.events.list; import com.ingotpowered.api.Player; import com.ingotpowered.api.events.Event; public class PlayerLoginEvent implements Event { private Player player; private String joinMessage; public PlayerLoginEvent(Player player) { this.player = player; this.joinMessage = player.getUsername() + " connected to the server."; } public Player getPlayer() { return player; } public void setJoinMessage(String joinMessage) { this.joinMessage = joinMessage; } public String getJoinMessage() { return joinMessage; } }
mit
souravzzz/lispint
lispint/test/lispint/LexerTest.java
2040
package lispint; import static java.util.Arrays.asList; import static lispint.CommonTest.getLexer; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.junit.Test; public class LexerTest { @Test public void testEmpty() { String input = ""; testLexer(input, asList("")); } @Test public void testEmptyParens() { String input = "()"; testLexer(input, asList("(", ")")); } @Test public void testNil() { String input = "nil"; testLexer(input, asList("NIL")); } @Test public void testAtom() { String input = "a"; testLexer(input, asList("A")); } @Test public void testSimpleExp() { String input = "(a b)"; testLexer(input, asList("(", "A", "B", ")")); } @Test public void testSimpleList() { String input = "(a b c d)"; testLexer(input, asList("(", "A", "B", "C", "D", ")")); } @Test public void testMixedList() { String input = "(a -10 b 20 c +30)"; testLexer(input, asList("(", "A", "-10", "B", "20", "C", "+30", ")")); } @Test public void test1() { String input = "(times (plus 1 2) (minus 10 20))"; testLexer( input, asList("(", "TIMES", "(", "PLUS", "1", "2", ")", "(", "MINUS", "10", "20", ")", ")")); } @Test public void test2() { String input = "(quote (100 +200 -300))"; testLexer(input, asList("(", "QUOTE", "(", "100", "+200", "-300", ")", ")")); } @Test public void test3() { String input = "(defun double (x)\n (TIMES 2 x))"; testLexer( input, asList("(", "DEFUN", "DOUBLE", "(", "X", ")", "(", "TIMES", "2", "X", ")", ")")); } private static void testLexer(String input, List<String> expected) { Lexer l = getLexer(input); List<String> actual = new ArrayList<String>(); while (l.hasMoreTokens()) { Token token = l.getNextToken(); if (token != null) { actual.add(token.toString()); } } assertEquals(expected.toString(), actual.toString()); } }
mit
gin7758258/TinyMobileControlCenter
src/main/java/me/antinomy/hibernate/entity/BaseEntity.java
1586
package me.antinomy.hibernate.entity; import me.antinomy.util.DateUtil; import javax.persistence.*; import java.sql.Timestamp; import java.util.Date; /** * Created by ginvan on 15/10/9. */ @SuppressWarnings("serial") @MappedSuperclass public class BaseEntity { protected int id; protected String lastModifyModel; protected String lastModifyUser; protected Timestamp lastModifyDate; @Id @GeneratedValue(strategy = GenerationType.AUTO) public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "lastModifyModel") public String getLastModifyModel() { return lastModifyModel; } public void setLastModifyModel(String lastModifyModel) { this.lastModifyModel = lastModifyModel; } @Basic @Column(name = "lastModifyUser") public String getLastModifyUser() { return lastModifyUser; } public void setLastModifyUser(String lastModifyUser) { this.lastModifyUser = lastModifyUser; } @Basic @Column(name = "lastModifyDate") public Timestamp getLastModifyDate() { return lastModifyDate; } public void setLastModifyDate(Timestamp lastModifyDate) { this.lastModifyDate = lastModifyDate; } public boolean exist() { return id > 0; } public Object clone() { Object o = null; try { o = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return o; } }
mit
killermenpl/play-java
app/Filters.java
1450
import javax.inject.Inject; import javax.inject.Singleton; import filters.ExampleFilter; import play.Environment; import play.Mode; import play.http.HttpFilters; import play.mvc.EssentialFilter; /** * This class configures filters that run on every request. This * class is queried by Play to get a list of filters. * * Play will automatically use filters from any class called * <code>Filters</code> that is placed the root package. You can load filters * from a different class by adding a `play.http.filters` setting to * the <code>application.conf</code> configuration file. */ @Singleton public class Filters implements HttpFilters { private final Environment env; private final EssentialFilter exampleFilter; /** * @param env Basic environment settings for the current application. * @param exampleFilter A demonstration filter that adds a header to */ @Inject public Filters(Environment env, ExampleFilter exampleFilter) { this.env = env; this.exampleFilter = exampleFilter; } @Override public EssentialFilter[] filters() { // Use the example filter if we're running development mode. If // we're running in production or test mode then don't use any // filters at all. if (env.mode().equals(Mode.DEV)) { return new EssentialFilter[] { exampleFilter }; } else { return new EssentialFilter[] {}; } } }
mit
episode6/mockspresso
mockspresso-quick/src/main/java/com/episode6/hackit/mockspresso/quick/QuickMockspresso.java
7143
package com.episode6.hackit.mockspresso.quick; import com.episode6.hackit.mockspresso.api.InjectionConfig; import com.episode6.hackit.mockspresso.api.MockerConfig; import com.episode6.hackit.mockspresso.api.MockspressoPlugin; import com.episode6.hackit.mockspresso.extend.MockspressoExtension; import org.jetbrains.annotations.NotNull; /** * A mockspresso extension for bootstrapping / general use * * @deprecated see DEPRECATED.kt */ @Deprecated public interface QuickMockspresso extends MockspressoExtension<QuickMockspresso.Builder> { /** * @deprecated see DEPRECATED.kt */ @Deprecated interface Rule extends MockspressoExtension.Rule<QuickMockspresso.Builder> { } /** * @deprecated see DEPRECATED.kt */ @Deprecated interface Builder extends MockspressoExtension.Builder< QuickMockspresso, QuickMockspresso.Rule, QuickMockspresso.Builder> { /** * Apply one of the built-in {@link InjectionConfig}s to this builder. * @return A {@link InjectorPicker} that will apply an injectionConfig to this builder. */ @NotNull InjectorPicker injector(); /** * Apply one of the built-in {@link MockspressoPlugin}s to this builder. * @return A {@link PluginPicker} that will apply a plugin to this builder. */ @NotNull PluginPicker plugin(); /** * Apply one of the built-in {@link MockerConfig}s to this builder. * @return A {@link MockerPicker} that will apply a mockerConfig to this builder. */ @NotNull MockerPicker mocker(); } /** * A selector for one of the built in injection configs * @deprecated see DEPRECATED.kt */ @Deprecated interface InjectorPicker { /** * Applies the {@link InjectionConfig} for simple creation of objects via * their shortest constructor. * * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder simple(); /** * Applies the {@link InjectionConfig} for javax.inject based object creation * (looks for constructors, fields and methods annotated with @Inject). * * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder javax(); /** * Applies an {@link InjectionConfig} for dagger. This is the same as the * {@link #javax()} injector with additional support for dagger's Lazy interface. * Requires your project have a dependency on 'com.google.dagger:dagger' or * 'com.squareup.dagger:dagger' * * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder dagger(); } /** * A selector for one of the built-in mocker configs * @deprecated see DEPRECATED.kt */ @Deprecated interface MockerPicker { /** * Applies the {@link MockerConfig} for Mockito. * Requires your project have a dependency on 'org.mockito:mockito-core' v2.x * * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder mockito(); /** * Applies the {@link MockerConfig} for EasyMock. * Requires your project have a dependency on 'org.easymock:easymock' v3.4 * * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder easyMock(); /** * Applies the {@link MockerConfig} for Powermock + Mockito. * Requires your project have a dependency on org.mockito:mockito-core v2.x, * org.powermock:powermock-api-mockito2, and org.powermock:powermock-module-junit4 v1.7.0+. * Also requires your test be runWith the PowerMockRunner * * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder mockitoWithPowerMock(); /** * Applies the {@link MockerConfig} for Powermock + Mockito AND applies a PowerMockRule as * an outerRule to Mockspresso, so theres no need to use the PowerMockRunner * Requires your project have the same dependencies as {@link #mockitoWithPowerMock()} * PLUS org.powermock:powermock-module-junit4-rule and org.powermock:powermock-classloading-xstream * * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder mockitoWithPowerMockRule(); /** * Applies the {@link MockerConfig} for Powermock + EasyMock. * Requires your project have a dependency on org.easymock:easymock v3.4, * org.powermock:powermock-api-mockito2, and org.powermock:powermock-module-junit4 v1.7.0+. * Also requires your test be runWith the PowerMockRunner * <p> * WARNING, the @org.easymock.Mock annotation may not work correctly when using Mockspresso + * easymock + PowerMockRunner, as easymock overwrites Mockspresso's annotated mocks at the last minute. * To work around this problem, use powermock's @Mock, @MockNice and @MockStrict annotations instead. * * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder easyMockWithPowerMock(); /** * Applies the {@link MockerConfig} for Powermock + EasyMock AND applies a PowerMockRule as * an outerRule to Mockspresso, so theres no need to use the PowerMockRunner * Requires your project have the same dependencies as {@link #easyMockWithPowerMock()} * PLUS org.powermock:powermock-module-junit4-rule and org.powermock:powermock-classloading-xstream * * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder easyMockWithPowerMockRule(); } /** * A selector for one of the built in plugins * @deprecated see DEPRECATED.kt */ @Deprecated interface PluginPicker { /** * Applies a {@link MockspressoPlugin} thats adds special object handling * for some of the types provided by guava. * * Requires your project have a dependency on 'com.google.guava:guava' * * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder guava(); /** * Applies special object handling for the provided factory classes. The * applicable objects will be mocked by mockito, but with a default answer * that returns objects from mockspresso's dependency map (similar to how * the javax() injector automatically binds Providers, but applied to any * factory class, including generics). * <p> * Requires your project have a dependency on 'org.mockito:mockito-core' v2.x but * does NOT require using mockito as your mocker. * * @param factoryClasses The factory classes that should be auto-mocked and bound * if they are encountered in your test. * @return The {@link QuickMockspresso.Builder} for your mockspresso instance */ @NotNull QuickMockspresso.Builder automaticFactories(Class<?>... factoryClasses); } }
mit
hardikhirapara91/java-se-core
033_Interface/MultipleInheritance/src/main/java/com/hardik/javase/SecondTest.java
159
package com.hardik.javase; /** * Interface Second Test * * @author HARDIK HIRAPARA * */ public interface SecondTest { public void printSecondTest(); }
mit
ninepatch/IndoorMapView
library/src/main/java/indoormaps/ninepatch/com/library/Style.java
1039
package indoormaps.ninepatch.com.library; import android.content.Context; import androidx.annotation.ColorRes; /** * Created by luca on 07/09/16. */ public class Style { private boolean showLabel = true; private int labelPx = 18; private String labelColor = "#000"; private Context context; public Style(Context context) { this.context = context; } public boolean isShowLabel() { return showLabel; } public void setShowLabel(boolean showLabel) { this.showLabel = showLabel; } public double getLabelPx() { return labelPx; } public void setLabelPx(int labelPx) { this.labelPx = labelPx; } public String getLabelColor() { return labelColor; } @SuppressWarnings("ResourceType") public void setLabelColor(@ColorRes int labelColor) { this.labelColor = context.getResources().getString(labelColor); } public void setLabelColorHex(String labelColor) { this.labelColor = labelColor; } }
mit
BlockchainSociety/ethereumj-android
ethereumj-core/src/main/java/org/ethereum/net/eth/StatusMessage.java
3523
package org.ethereum.net.eth; import org.ethereum.util.ByteUtil; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import org.spongycastle.util.encoders.Hex; import static org.ethereum.net.eth.EthMessageCodes.STATUS; /** * Wrapper around an Ethereum Status message on the network * * @see org.ethereum.net.eth.EthMessageCodes#STATUS */ public class StatusMessage extends EthMessage { private byte protocolVersion; private byte networkId; /** * Total difficulty of the best chain as found in block header. */ private byte[] totalDifficulty; /** * The hash of the best (i.e. highest TD) known block. */ private byte[] bestHash; /** * The hash of the Genesis block */ private byte[] genesisHash; public StatusMessage(byte[] encoded) { super(encoded); } public StatusMessage(byte protocolVersion, byte networkId, byte[] totalDifficulty, byte[] bestHash, byte[] genesisHash) { this.protocolVersion = protocolVersion; this.networkId = networkId; this.totalDifficulty = totalDifficulty; this.bestHash = bestHash; this.genesisHash = genesisHash; this.parsed = true; } private void parse() { RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); this.protocolVersion = paramsList.get(0).getRLPData()[0]; byte[] networkIdBytes = paramsList.get(1).getRLPData(); this.networkId = networkIdBytes == null ? 0 : networkIdBytes[0]; this.totalDifficulty = paramsList.get(2).getRLPData(); this.bestHash = paramsList.get(3).getRLPData(); this.genesisHash = paramsList.get(4).getRLPData(); parsed = true; } private void encode() { byte[] protocolVersion = RLP.encodeByte(this.protocolVersion); byte[] networkId = RLP.encodeByte(this.networkId); byte[] totalDifficulty = RLP.encodeElement(this.totalDifficulty); byte[] bestHash = RLP.encodeElement(this.bestHash); byte[] genesisHash = RLP.encodeElement(this.genesisHash); this.encoded = RLP.encodeList( protocolVersion, networkId, totalDifficulty, bestHash, genesisHash); } @Override public byte[] getEncoded() { if (encoded == null) encode(); return encoded; } @Override public Class<?> getAnswerMessage() { return null; } public byte getProtocolVersion() { if (!parsed) parse(); return protocolVersion; } public byte getNetworkId() { if (!parsed) parse(); return networkId; } public byte[] getTotalDifficulty() { if (!parsed) parse(); return totalDifficulty; } public byte[] getBestHash() { if (!parsed) parse(); return bestHash; } public byte[] getGenesisHash() { if (!parsed) parse(); return genesisHash; } @Override public EthMessageCodes getCommand() { return STATUS; } @Override public String toString() { if (!parsed) parse(); return "[" + this.getCommand().name() + " protocolVersion=" + this.protocolVersion + " networkId=" + this.networkId + " totalDifficulty=" + ByteUtil.toHexString(this.totalDifficulty) + " bestHash=" + Hex.toHexString(this.bestHash) + " genesisHash=" + Hex.toHexString(this.genesisHash) + "]"; } }
mit
csarnataro/interactivebusinesscard
android/interactivebusinesscard/app/src/main/java/it/inefficienza/interactivebusinesscard/chs/ResizeAnimation.java
1264
package it.inefficienza.interactivebusinesscard.chs; import android.content.res.Resources; import android.util.TypedValue; import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; /** * @author Christian Sarnataro */ public class ResizeAnimation extends Animation { final int startWidth; final float targetWidth; View view; public ResizeAnimation(View view, int targetWidth) { this.view = view; // this.targetWidth = targetWidth; Resources r = view.getResources(); this.targetWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, targetWidth, r.getDisplayMetrics()); startWidth = view.getWidth(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { int newWidth = (int) (startWidth + (targetWidth - startWidth) * interpolatedTime); view.getLayoutParams().width = newWidth; view.requestLayout(); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override public boolean willChangeBounds() { return true; } }
mit
waylau/spring-boot-tutorial
samples/blog-prototype/src/main/java/com/waylau/spring/boot/blog/controller/UserController.java
645
package com.waylau.spring.boot.blog.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; /** * 用户控制器. * * @author <a href="https://waylau.com">Way Lau</a> * @date 2017年2月26日 */ @RestController @RequestMapping("/users") public class UserController { /** * 查询所用用户 * @return */ @GetMapping public ModelAndView list() { return new ModelAndView("users/list"); } }
mit
lichader/Alfred
src/main/java/com/lichader/alfred/metroapi/v3/model/DisruptionRoute.java
495
package com.lichader.alfred.metroapi.v3.model; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by lichader on 14/6/17. */ public class DisruptionRoute { @JsonProperty("route_type") public int Routetype; @JsonProperty("route_id") public int RouteId; @JsonProperty("route_name") public String RouteName; @JsonProperty("route_number") public String RouteNumber; @JsonProperty("direction") public DisruptionDirection Direction; }
mit
karnik/jips-core
jips/src/main/java/de/karnik/jips/gui/GUIObjectHelper.java
22101
/* * JIPS - JIPS Image Processing Software * Copyright (C) 2006 - 2017 Markus Karnik (markus.karnik@gmail.com) * * This file is licensed to you under the MIT license. * See the LICENSE file in the project root for more information. * */ package de.karnik.jips.gui; import de.karnik.fonts.MyFont; import de.karnik.jips.common.JIPSException; import de.karnik.jips.common.config.JIPSVariables; import de.karnik.jips.common.lang.Translator; import de.karnik.jips.gui.objects.Borders; import javax.swing.*; import javax.swing.text.PlainDocument; import java.awt.*; import java.awt.event.ActionListener; /** * The GUIObjectHelper class contains class fields and methods for easyer graphical usage of components. * * @author <a href="mailto:markus.karnik@my-design.org">Markus Karnik</a> * @version 1.0 * @since v.0.0.3 */ public class GUIObjectHelper { public static final int FONT_TYPE_NORMAL = 0; public static final int FONT_TYPE_BOLD = 1; public static final int FONT_TYPE_ITALIC = 2; private static GUIObjectHelper instance = null; /** * The object to hold the GridBagLayout. */ protected GridBagLayout gbl = null; /** * The object to hold the GridBagConstraints. */ protected GridBagConstraints gbc = null; /** * A dimension object with a height and width of 0. */ protected Dimension nullDim = new Dimension( 0, 0 ); /** * The object to hold the translator functions. */ private Translator trans = null; // ============================================================= // Labels // ============================================================= /** * The object to hold the JIPS variables and functions. */ private JIPSVariables vars = null; /** * Constructs a new GUIObjectHelper object. */ private GUIObjectHelper() throws JIPSException { trans = Translator.getInstance(); vars = JIPSVariables.getInstance(); gbl = new GridBagLayout(); gbc = new GridBagConstraints( 0, 0, 0, 0, 0, 0, GridBagConstraints.BOTH, GridBagConstraints.NORTHWEST, new Insets( 2, 2, 2, 2 ), 0, 0); } /** * Returns the mainframe instance. * * @return the main frame object. */ public static GUIObjectHelper getInstance() throws JIPSException { if (instance == null) { instance = new GUIObjectHelper(); } return instance; } /** * Returns a bold label with the specified values and options. * * @param text the text to show * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @param append some text to append. maybe a ":" in lists * @return the bold label */ public JLabel getBoldLabel( String text, boolean t, String append ) { JLabel jl = null; if ( t ) text = trans.getTranslation( text ); jl = new JLabel( text + append ); MyFont jlFont = new MyFont( jl.getFont(), MyFont.BOLD ); jl.setFont( jlFont ); if( vars.graphicalDebugMode ) jl.setBorder( Borders.L1R_BORDER ); return jl; } /** * Returns a label with light gray text and the specified values and options. * * @param text the text to show * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @return the label */ public JLabel getLightLabel( String text, boolean t ) { JLabel jl = null; if ( t ) text = trans.getTranslation( text ); jl = new JLabel( text ); jl.setForeground( Color.DARK_GRAY ); if( vars.graphicalDebugMode ) jl.setBorder( Borders.L1R_BORDER ); return jl; } // ============================================================= // RadioButtons // ============================================================= /** * Returns a label with light gray and italic text. * * @param text the text to show * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @param append some text to append. maybe a ":" in lists * @return the label */ public JLabel getLightItalicLabel( String text, boolean t, String append ) { JLabel jl = null; if ( t ) text = trans.getTranslation( text ); jl = new JLabel( text + append ); MyFont jlFont = new MyFont( jl.getFont(), MyFont.ITALIC ); jl.setFont( jlFont ); jl.setForeground( Color.DARK_GRAY ); if( vars.graphicalDebugMode ) jl.setBorder( Borders.L1R_BORDER ); return jl; } /** * Returns a label with light gray and italic text. The is also the option to * put n blanks in front of the text. * * @param text the text to show * @param blanks the counter for the leading blanks * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @return the label */ public JLabel getLightItalicLabel( String text, int blanks, boolean t ) { JLabel jl = null; String blankString = ""; for( int i = 0; i < blanks; i++ ) blankString += "&nbsp;"; if ( t ) text = trans.getTranslation( text ); jl = new JLabel( blankString + text ); MyFont jlFont = new MyFont( jl.getFont(), MyFont.ITALIC ); jl.setFont( jlFont ); jl.setForeground( Color.DARK_GRAY ); if( vars.graphicalDebugMode ) jl.setBorder( Borders.L1R_BORDER ); return jl; } // ============================================================= // Buttons // ============================================================= /** * Returns a label with the specified values and options. * * @param text the text to show * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @param append some text to append. maybe a ":" in lists * @return the label */ public JLabel getLabel( String text, boolean t, String append ) { JLabel jl = null; if ( t ) text = trans.getTranslation( text ); jl = new JLabel( text + append ); if( vars.graphicalDebugMode ) jl.setBorder( Borders.L1R_BORDER ); return jl; } /** * Returns a radio button with the specified options. * * @param text the text for the radio button * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @param status if <strong>true</strong> the button is selected * @param al the action listener for this object * @return the radio button */ public JRadioButton getRadioButton( String text, boolean t, boolean status, ActionListener al ) { JRadioButton jrb = null; if( t ) text = trans.getTranslation( text ); jrb = new JRadioButton( text, status ); if( al != null ) jrb.addActionListener( al ); if( vars.graphicalDebugMode ) jrb.setBorderPainted( true ); if( vars.graphicalDebugMode ) jrb.setBorder( Borders.L1R_BORDER ); return jrb; } /** * Returns a radio button with the specified options an bold text. * * @param text the text for the radio button * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @param status if <strong>true</strong> the button is selected * @param al the action listener for this object * @return the radio button */ public JRadioButton getBoldRadioButton( String text, boolean t, boolean status, ActionListener al ) { JRadioButton jrb = null; if( t ) text = trans.getTranslation( text ); jrb = new JRadioButton( text, status ); MyFont jlFont = new MyFont( jrb.getFont(), MyFont.BOLD ); jrb.setFont( jlFont ); if( al != null ) jrb.addActionListener( al ); if( vars.graphicalDebugMode ) jrb.setBorderPainted( true ); if( vars.graphicalDebugMode ) jrb.setBorder( Borders.L1R_BORDER ); return jrb; } /** * Returns a button with the specified options. * * @param text the text for the button * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @return the button */ public JButton getButton( String text, boolean t ) { JButton jb = null; if( t ) text = trans.getTranslation( text ); jb = new JButton( text ); return jb; } // ============================================================= // ComboBoxes // ============================================================= /** * Returns a button with the specified options. * * @param text the text for the button * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @param al the action listener for the button * @param actionCommand the actionCommand for the Button. if null, the text will be used * @return the button */ public JButton getButton( String text, boolean t, ActionListener al, String actionCommand ) { JButton jb = null; if( t ) text = trans.getTranslation( text ); jb = new JButton( text ); if( al != null ) jb.addActionListener( al ); if( actionCommand != null ) jb.setActionCommand( actionCommand ); return jb; } // ============================================================= // TextAreas // ============================================================= /** * Returns a button with the specified options, no border and underlined blue text. * * @param text the text for the button * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @param al the action listener for the button * @param actionCommand the actionCommand for the Button. if null, the text will be used * @return the button */ public JButton getLinkButton( String text, boolean t, ActionListener al, String actionCommand ) { JButton jb = null; if( t ) text = trans.getTranslation( text ); jb = new JButton( text ); jb.setBorder( Borders.E3_BORDER ); jb.setContentAreaFilled( false ); jb.setForeground( Color.BLUE ); jb.setAlignmentX( JButton.LEFT_ALIGNMENT ); if( al != null ) jb.addActionListener( al ); if( actionCommand != null ) jb.setActionCommand( actionCommand ); return jb; } /** * Returns a button with the specified options and bold text. * * @param text the text for the button * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @return the button */ public JButton getBoldButton( String text, boolean t ) { JButton jb = null; if( t ) text = trans.getTranslation( text ); jb = new JButton( text ); MyFont jlFont = new MyFont( jb.getFont(), MyFont.BOLD ); jb.setFont( jlFont ); return jb; } /** * Returns a combo box with the specified values. * * @param values the values for the combo box * @param selected the index of the selected value * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @return the combo box */ public JComboBox getComboBox( String[] values, int selected, boolean t, ActionListener al ) { JComboBox jcb = null; if( t ) { for( int i = 0; i < values.length; i++) values[ i ] = trans.getTranslation( values[ i ] ); } jcb = new JComboBox( values ); jcb.setSelectedIndex( selected ); if( al != null ) jcb.addActionListener( al ); if( vars.graphicalDebugMode ) jcb.setBorder( Borders.L1R_BORDER ); jcb.setPreferredSize( nullDim ); jcb.setMaximumSize( nullDim ); return jcb; } /** * Returns a scroll pane with an embedded text area. * * @param text the text to show * @param rows the rows of the text area * @param cols tje cols of the text area * @param edit the edit option. if <strong>true</strong>, the text is editable * @param jta reference to the text area * @return the JScrollPane */ public JScrollPane getTextArea( String text, int rows, int cols, boolean edit, JTextArea jta ) { if( jta != null ) { jta.setRows( rows ); jta.setColumns( cols ); jta.setText( text ); jta.setEditable( edit ); JScrollPane jsp = new JScrollPane( jta ); return jsp; } return null; } /** * Returns a scroll pane with an embedded text area. * * @param text the text to show * @param rows the rows of the text area * @param cols tje cols of the text area * @param edit the edit option. if <strong>true</strong>, the text is editable * @return the JScrollPane */ public JScrollPane getTextArea( String text, int rows, int cols, boolean edit ) { JTextArea jta = new JTextArea( text, rows, cols); jta.setEditable( edit ); JScrollPane jsp = new JScrollPane( jta ); return jsp; } /** * Returns a JTextArea with Background <strong>null</strong> and * normal text. Text is becomes wrapped. * * @param text the text to show * @param type the font type * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @param color the foregroundcolor * @return the JLabel */ public JLabel getMultiLabel( String text, int type, boolean t, Color color ) { MyFont jlFont = null; if( t ) text = trans.getTranslation( text ); StringBuffer sb = new StringBuffer( "<html><body><font face=arial size=2>" ); sb.append( text ); sb.append( "</font></body></html>" ); JLabel jl = new JLabel ( sb.toString() ); switch( type ) { case FONT_TYPE_BOLD: jlFont = new MyFont( jl.getFont(), MyFont.BOLD ); break; case FONT_TYPE_ITALIC: jlFont = new MyFont( jl.getFont(), MyFont.ITALIC ); break; case ( FONT_TYPE_ITALIC | FONT_TYPE_BOLD ): jlFont = new MyFont( jl.getFont(), ( MyFont.BOLD | MyFont.ITALIC ) ); break; } if( jl != null ) jl.setFont( jlFont ); if( color != null ) jl.setForeground( color ); if( vars.graphicalDebugMode ) jl.setBorder( Borders.L1R_BORDER ); return jl; } /** * Returns a JTextArea with Background <strong>null</strong> and * bold text. Text is becomes wrapped. * * @param text the text to show * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @return the JLabel */ public JLabel getBoldMultiLabel( String text, boolean t ) { JLabel jl = getMultiLabel( text, FONT_TYPE_BOLD, t, null ); return jl; } /** * Returns a JTextArea with Background <strong>null</strong> and * light gray italic text. Text becomes wrapped. * * @param text the text to show * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @return the JLabel */ public JLabel getLightItalicMultiLabel( String text, boolean t ) { JLabel jl = getMultiLabel( text, FONT_TYPE_ITALIC, t, Color.DARK_GRAY ); return jl; } // ============================================================= // JTextField // ============================================================= /** * Returns a JTextField with the specified text. * * @param text the text to show * @param l the length of the TextField * @param t the translate option. if <strong>true</strong>, the text is going to be translated * @param v * @return the JTextField */ public JTextField getTextField( String text, int l, boolean t, PlainDocument v ) { if( t ) text = trans.getTranslation( text ); JTextField jtf = new JTextField( text, l ); if( v != null ) jtf.setDocument( v ); jtf.setText( text ); if( vars.graphicalDebugMode ) jtf.setBorder( Borders.L1R_BORDER ); return jtf; } // ============================================================= // GridBagLayout // ============================================================= /** * Adds a component with the specified GridBagConstraint values to the specified container. * * @param cont the container * @param gbl the layout object * @param c the component to set the constraint * @param p the point for the grid values * @param d the dimension of tge grid * @param a the align of the grid * @param f the fill type of the grid */ public void addComponent( Container cont, GridBagLayout gbl, Component c, Point p, Dimension d, int a, int f ) { addComponent( cont, gbl, c, p.x, p.y, d.width, d.height, a, f, new Insets( 1, 1, 1, 1), 0, 0, 1.0, 1.0 ); } /** * Adds a component with the specified GridBagConstraint values to the specified container. * * @param cont the container * @param gbl the layout object * @param c the component to set the constraint * @param x the gridx value * @param y the gridy value * @param width the gridwidth value * @param height the gridheight value */ public void addComponent( Container cont, GridBagLayout gbl, Component c, int x, int y, int width, int height ) { addComponent( cont, gbl, c, x, y, width, height, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets( 1, 1, 1, 1), 0, 0, 1.0, 1.0 ); } /** * Adds a component with the specified GridBagConstraint values to the specified container. * * @param cont the container * @param gbl the layout object * @param c the component to set the constraint * @param x the gridx value * @param y the gridy value * @param width the gridwidth value * @param height the gridheight value */ public void addFillComponent( Container cont, GridBagLayout gbl, Component c, int x, int y, int width, int height ) { addComponent( cont, gbl, c, x, y, width, height, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets( 1, 1, 1, 1), 0, 0, 40.0, 40.0 ); } /** * Adds a component with the specified GridBagConstraint values to the specified container. * * @param cont the container * @param gbl the layout object * @param c the component to set the constraint * @param x the gridx value * @param y the gridy value * @param width the gridwidth value * @param height the gridheight value * @param a the align of the grid * @param f the fill type of the grid */ public void addComponent( Container cont, GridBagLayout gbl, Component c, int x, int y, int width, int height, int a, int f ) { addComponent( cont, gbl, c, x, y, width, height, a, f, new Insets( 1, 1, 1, 1), 0, 0, 40.0, 40.0 ); } /** * Adds a component with the specified GridBagConstraint values to the specified container. * * @param cont the container * @param gbl the layout object * @param c the component to set the constraint * @param x the gridx value * @param y the gridy value * @param width the gridwidth value * @param height the gridheight value * @param weightx the weightx value * @param weighty the weighty value */ public void addComponent( Container cont, GridBagLayout gbl, Component c, int x, int y, int width, int height, double weightx, double weighty ) { addComponent( cont, gbl, c, x, y, width, height, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets( 1, 1, 1, 1), 0, 0, weightx, weighty ); } /** * Adds a component with the specified GridBagConstraint values to the specified container. * * @param cont the container * @param gbl the layout object * @param c the component to set the constraint * @param x the gridx value * @param y the gridy value * @param width the gridwidth value * @param height the gridheight value * @param a the align of the grid * @param f the fill type of the grid * @param i the insets of the grid * @param ipadx * @param ipady * @param weightx the weightx value * @param weighty the weighty value */ public void addComponent( Container cont, GridBagLayout gbl, Component c, int x, int y, int width, int height, int a, int f, Insets i, int ipadx, int ipady, double weightx, double weighty ) { GridBagConstraints gbc = new GridBagConstraints( x, y, width, height, weightx, weighty, a, f, i, ipadx, ipady ); gbl.setConstraints( c, gbc ); cont.add( c ); } }
mit
JonathanCSmith/Overhauled
src/main/java/me/jonathansmith/overhauled/core/CoreProperties.java
996
package me.jonathansmith.overhauled.core; import tv.twitch.Core; /** * Created by Jonathan Charles Smith on 25/08/15. * * Properties for the core infrastructure of the mod */ public class CoreProperties { public static final String ID = "overhauled"; public static final String NAME = "Overhauled"; public static final String VERSION = "0.0.0"; public static final String CONFIGURATION_GUI_CLASS = "me.jonathansmith.overhauled.core.configuration.ConfigurationGUIFactory"; public static final String SERVER_DELEGATE_CLASS = "me.jonathansmith.overhauled.core.delegate.ServerDelegate"; public static final String CLIENT_DELEGATE_CLASS = "me.jonathansmith.overhauled.core.delegate.ClientDelegate"; // ************************ RUNTIME ARGUMENTS ********************** public static final boolean IS_DEBUG_MODE_FORCED = true; public static final String NETWORK_NAME = CoreProperties.ID; }
mit
ONSdigital/tredegar
src/main/java/com/github/onsdigital/json/partial/Link.java
110
package com.github.onsdigital.json.partial; public class Link { public String text; public String href; }
mit
adnanaziz/epicode
java/src/main/java/com/epi/BinaryTreeLevelOrder.java
2192
package com.epi; import com.epi.BinaryTreePrototypeTemplate.BinaryTreeNode; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class BinaryTreeLevelOrder { // @include public static List<List<Integer>> binaryTreeDepthOrder( BinaryTreeNode<Integer> tree) { Queue<BinaryTreeNode<Integer>> currDepthNodes = new LinkedList<>(); currDepthNodes.add(tree); List<List<Integer>> result = new ArrayList<>(); while (!currDepthNodes.isEmpty()) { Queue<BinaryTreeNode<Integer>> nextDepthNodes = new LinkedList<>(); List<Integer> thisLevel = new ArrayList<>(); while (!currDepthNodes.isEmpty()) { BinaryTreeNode<Integer> curr = currDepthNodes.poll(); if (curr != null) { thisLevel.add(curr.data); // Defer the null checks to the null test above. nextDepthNodes.add(curr.left); nextDepthNodes.add(curr.right); } } if (!thisLevel.isEmpty()) { result.add(thisLevel); } currDepthNodes = nextDepthNodes; } return result; } // @exclude public static void main(String[] args) { // 3 // 2 5 // 1 4 6 // 10 // 13 BinaryTreeNode<Integer> tree = new BinaryTreeNode<>(3); tree.left = new BinaryTreeNode<>(2); tree.left.left = new BinaryTreeNode<>(1); tree.left.left.left = new BinaryTreeNode<>(10); tree.left.left.left.right = new BinaryTreeNode<>(13); tree.right = new BinaryTreeNode<>(5); tree.right.left = new BinaryTreeNode<>(4); tree.right.right = new BinaryTreeNode<>(6); List<List<Integer>> result = binaryTreeDepthOrder(tree); List<List<Integer>> goldenRes = Arrays.asList( Arrays.asList(3), Arrays.asList(2, 5), Arrays.asList(1, 4, 6), Arrays.asList(10), Arrays.asList(13)); if (!goldenRes.equals(result)) { System.err.println("Failed on input " + tree); System.err.println("Expected " + goldenRes); System.err.println("Your code produced " + result); System.exit(-1); } else { System.out.println("You passed all tests."); } } }
mit
anderson-uchoa/DyMMer
src/br/ufc/lps/view/trees/adaptation/CheckBoxNodeData.java
955
package br.ufc.lps.view.trees.adaptation; import br.ufc.lps.model.adaptation.ValueQuantification; public class CheckBoxNodeData { private String text; private boolean checked; private ValueQuantification valueQuantification = new ValueQuantification(); public CheckBoxNodeData(final String text, final boolean checked) { this.text = text; this.checked = checked; } public boolean isChecked() { return checked; } public void setChecked(final boolean checked) { this.checked = checked; } public String getText() { return text; } public void setText(final String text) { this.text = text; } public ValueQuantification getValueQuantification() { return valueQuantification; } public void setValueQuantification(ValueQuantification valueQuantification) { this.valueQuantification = valueQuantification; } @Override public String toString() { return getClass().getName() + "[" + text + "/" + checked + "]"; } }
mit
Menkachev/Java
Java DB Fundamentals/Java Introduction/01. Java Basics/CompareCharArrays.java
946
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; /** * Compare two char arrays lexicographically (letter by letter). * Print the them in alphabetical order, each on separate line. */ public class CompareCharArrays { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] arr1 = reader.readLine().split("\\s"); String[] arr2 = reader.readLine().split("\\s"); String firstWord = String.join("", Arrays.asList(arr1)); String secondWord = String.join("", Arrays.asList(arr2)); if (firstWord.compareTo(secondWord) >= 0){ System.out.println(secondWord); System.out.println(firstWord); } else { System.out.println(firstWord); System.out.println(secondWord); } } }
mit
bacta/swg
game-server/src/main/java/com/ocdsoft/bacta/swg/server/game/message/object/MessageQueueString.java
1008
package com.ocdsoft.bacta.swg.server.game.message.object; import com.ocdsoft.bacta.engine.utils.BufferUtil; import com.ocdsoft.bacta.swg.server.game.controller.object.GameControllerMessage; import lombok.AllArgsConstructor; import lombok.Getter; import java.nio.ByteBuffer; /** * Created by crush on 5/30/2016. * <p> * A generic message queue data that contains a simple payload of one String. * The meaning of the String is context and message dependant. */ @Getter @AllArgsConstructor @GameControllerMessage({ GameControllerMessageType.ATTACH_SCRIPT, GameControllerMessageType.DETACH_SCRIPT, GameControllerMessageType.ANIMATION_ACTION }) public final class MessageQueueString implements MessageQueueData { private final String string; public MessageQueueString(final ByteBuffer buffer) { string = BufferUtil.getAscii(buffer); } @Override public void writeToBuffer(final ByteBuffer buffer) { BufferUtil.putAscii(buffer, string); } }
mit
larsq/knapsack
src/main/java/local/laer/app/knapsack/support/OffsetBinaryMatrix.java
11620
/* * 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 local.laer.app.knapsack.support; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.databind.util.Converter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import static java.util.stream.Collectors.toList; import local.laer.app.knapsack.domain.Cell; import local.laer.app.knapsack.domain.ImmutablePosition; import local.laer.app.knapsack.domain.support.Matrix; import local.laer.app.knapsack.domain.Position; import static local.laer.app.knapsack.support.IntFunctions.col; import static local.laer.app.knapsack.support.IntFunctions.partial; import local.laer.app.knapsack.support.matrix.BoolMatrix; import local.laer.app.knapsack.support.matrix.IntMatrix; /** * * @author Lars Eriksson (larsq.eriksson@gmail.com) */ @JsonSerialize(converter = OffsetBinaryMatrix.JsonConverter.class) public class OffsetBinaryMatrix implements BoolMatrix, IntMatrix { public static class JsonConverter implements Converter<OffsetBinaryMatrix, Matrix> { private static Matrix.Stripe defineRowStripe(OffsetBinaryMatrix matrix, int row) { Matrix.Stripe stripe = new Matrix.Stripe(); stripe.setDirection(Matrix.Direction.Row); stripe.setOffset(new ImmutablePosition(row, matrix.colOffset)); int[] rowData = matrix.extractRow(matrix.colOffset, matrix.cols(), row); String[] converted = Arrays.stream(rowData) .mapToObj(String::valueOf) .collect(toList()).toArray(new String[0]); stripe.setData(converted); return stripe; } @Override public JavaType getInputType(TypeFactory typeFactory) { return typeFactory.constructType(OffsetBinaryMatrix.class); } @Override public JavaType getOutputType(TypeFactory typeFactory) { return typeFactory.constructType(Matrix.class); } @Override public Matrix convert(OffsetBinaryMatrix value) { List<Matrix.Stripe> stripes = new ArrayList<>(); value.consume(partial(col(value.colOffset), cell -> stripes.add(defineRowStripe(value, cell.getRow())))); Matrix m = new Matrix(); m.setContent(stripes.toArray(new Matrix.Stripe[stripes.size()])); m.setDefaultValue(0); return m; } } protected static boolean within(int val, int lowerInclusive, int upperInclusive) { return lowerInclusive <= val && val <= upperInclusive; } protected static boolean[][] copy(boolean[][] value) { boolean[][] clone = new boolean[value.length][value[0].length]; for (int i = 0; i < clone.length; i++) { System.arraycopy(value[i], 0, clone[i], 0, value[i].length); } return clone; } public static OffsetBinaryMatrix fillWith(OffsetBinaryMatrix matrix, boolean value) { return matrix.transform(IntFunctions.booleanFunction(__ -> value)); } private final int colOffset; private final int rowOffset; private final boolean[][] value; public OffsetBinaryMatrix(int row, int col, int rows, int cols) { value = new boolean[rows][cols]; this.colOffset = col; this.rowOffset = row; } protected OffsetBinaryMatrix(int newRow, int newCol, boolean[][] value) { this.colOffset = newCol; this.rowOffset = newRow; this.value = OffsetBinaryMatrix.this.copy(value); } public OffsetBinaryMatrix copy() { return new OffsetBinaryMatrix(rowOffset, colOffset, value); } public OffsetBinaryMatrix translateTo(Position position) { return translate(position.getRow(), position.getCol()); } public OffsetBinaryMatrix translate(int row, int col) { return new OffsetBinaryMatrix(row, col, value); } public OffsetBinaryMatrix transform(Function<Cell<Integer>, Integer> callback) { OffsetBinaryMatrix matrix = new OffsetBinaryMatrix(rowOffset, colOffset, value); matrix.mutableTransform(callback); return matrix; } public void consume(Consumer<Cell<Integer>> callback) { SimpleCell<Integer> cell = new SimpleCell<>(); for (int row = 0; row < rows(); row++) { for (int col = 0; col < cols(); col++) { cell.col = col + colOffset; cell.row = row + rowOffset; cell.value = convertToInt(value[row][col]); callback.accept(cell); } } } protected int[] extractCol(int lowerRowIndexInclusive, int nRows, int col) { int[] data = new int[nRows]; for (int i = 0; i < nRows; i++) { data[i] = getInt(i + lowerRowIndexInclusive, col); } return data; } protected int[] extractRow(int lowerColIndexInclusive, int nCols, int row) { int[] data = new int[nCols]; for (int i = 0; i < nCols; i++) { data[i] = getInt(row, i + lowerColIndexInclusive); } return data; } protected static Integer convertToInt(Boolean b) { if (b == null) { return 0; } return b ? 1 : 0; } protected static Boolean convertToBool(Integer i) { if (i == null) { return false; } return !Objects.equals(i, 0); } protected void mutableTransform(Function<Cell<Integer>, Integer> callback) { SimpleCell<Integer> cell = new SimpleCell<>(); for (int row = 0; row < rows(); row++) { for (int col = 0; col < cols(); col++) { cell.col = col + colOffset; cell.row = row + rowOffset; cell.value = convertToInt(value[row][col]); Integer newValue = callback.apply(cell); value[row][col] = convertToBool((newValue == null) ? 0 : newValue); } } } public boolean matchAll(Predicate<Cell<Integer>> callback) { SimpleCell cell = new SimpleCell(); for (int row = 0; row < rows(); row++) { for (int col = 0; col < cols(); col++) { cell.col = col; cell.row = row; cell.value = convertToInt(value[row][col]); if (!callback.test(cell)) { return false; } } } return true; } boolean relative(int row, int col) { if (rows() <= row) { return false; } if (cols() <= col) { return false; } return value[row][col]; } @Override public int getInt(int row, int col) { return getBool(row, col) ? 1 : 0; } protected int lowerCol() { return colOffset; } protected int lowerRow() { return rowOffset; } protected int cols() { return value[0].length; } protected int rows() { return value.length; } protected int upperColIndexInclusive() { return colOffset + cols() - 1; } protected int upperRowIndexInclusive() { return rowOffset + rows() - 1; } public boolean defines(int row, int col) { return within(col, lowerCol(), upperColIndexInclusive()) && within(row, lowerRow(), upperRowIndexInclusive()); } @Override public boolean getBool(int row, int col) { if (!defines(row, col)) { return false; } return value[row - lowerRow()][col - lowerCol()]; } public OffsetBinaryMatrix intersection(OffsetBinaryMatrix otherMatrix, Mode mode) { if (!intersectsWith(otherMatrix)) { return null; } int lowerX = Math.max(lowerCol(), otherMatrix.lowerCol()); int lowerY = Math.max(lowerRow(), otherMatrix.lowerRow()); int upperX = Math.min(upperColIndexInclusive(), otherMatrix.upperColIndexInclusive()); int upperY = Math.min(upperRowIndexInclusive(), otherMatrix.upperRowIndexInclusive()); int cols = upperX - lowerX + 1; int rows = upperY - lowerY + 1; OffsetBinaryMatrix matrix = new OffsetBinaryMatrix(lowerY, lowerX, rows, cols); for (int col = 0; col < cols; col++) { for (int row = 0; row < rows; row++) { boolean val = getBool(lowerY + row, lowerX + col); boolean otherVal = otherMatrix.getBool(lowerY + row, lowerX + col); matrix.value[row][col] = mode.apply(val, otherVal); } } return matrix; } public boolean zero() { for (boolean[] row : value) { for (boolean col : row) { if (col == true) { return false; } } } return true; } public boolean one() { for (boolean[] row : value) { for (boolean col : row) { if (col == false) { return false; } } } return true; } private int size() { return value.length * value[0].length; } public int sum() { int sum = 0; for (boolean[] row : value) { for (boolean col : row) { if (col == true) { sum += 1; } } } return sum; } public double ratio() { return ((double) sum()) / ((double) size()); } public boolean intersectsWith(OffsetBinaryMatrix otherMatrix) { if (otherMatrix == this) { return true; } if (upperColIndexInclusive() < otherMatrix.lowerCol() || otherMatrix.upperColIndexInclusive() < lowerCol()) { return false; } if (upperRowIndexInclusive() < otherMatrix.lowerRow() || otherMatrix.upperRowIndexInclusive() < lowerRow()) { return false; } return true; } @Override public String toString() { return String.format("[%s,%s]-[%s,%s]", lowerCol(), lowerRow(), upperColIndexInclusive(), upperRowIndexInclusive()); } public static enum Mode implements BiFunction<Boolean, Boolean,Boolean> { AND { @Override public Boolean apply(Boolean first, Boolean second) { return first && second; } }, OR { @Override public Boolean apply(Boolean first, Boolean second) { return first || second; } }, NOT_SAME { @Override public Boolean apply(Boolean first, Boolean second) { return !Objects.equals(first, second); } }, SAME { @Override public Boolean apply(Boolean first, Boolean second) { return Objects.equals(first, second); } }; } }
mit
eyeshot/2dianmarket
server/xcx/src/core/service/Service.java
4726
package core.service; import java.io.Serializable; import java.util.List; import java.util.Map; import core.support.BaseParameter; import core.support.QueryResult; public interface Service<E> { /** * Persist object * * @param entity */ public void persist(E entity); /** * @param id * @return */ public boolean deleteByPK(Serializable... id); /** * Remove a persistent instance * * @param entity */ public void delete(E entity); /** * delete entity by property though hql * * @param propName * @param propValue */ public void deleteByProperties(String propName, Object propValue); /** * delete entity by properties though hql * * @param propName * @param propValue */ public void deleteByProperties(String[] propName, Object[] propValue); /** * Update the persistent instance with the identifier of the given detached instance. * * @param entity */ public void update(E entity); /** * update property batch * * @param conditionName where clause condiction property name * @param conditionValue where clause condiction property value * @param propertyName update clause property name array * @param propertyValue update clase property value array */ public void updateByProperties(String[] conditionName, Object[] conditionValue, String[] propertyName, Object[] propertyValue); public void updateByProperties(String[] conditionName, Object[] conditionValue, String propertyName, Object propertyValue); public void updateByProperties(String conditionName, Object conditionValue, String[] propertyName, Object[] propertyValue); public void updateByProperties(String conditionName, Object conditionValue, String propertyName, Object propertyValue); /** * cautiously use this method, through delete then insert to update an entity when need to update primary key value (unsupported) use this method * * @param entity updated entity * @param oldId already existed primary key */ public void update(E entity, Serializable oldId); /** * Merge the state of the given entity into the current persistence context. * * @param entity */ public E merge(E entity); /** * Get persistent object * * @param id * @return */ public E get(Serializable id); /** * load persistent object * * @param id * @return */ public E load(Serializable id); /** * get an entity by properties * * @param propName * @param propValue * @return */ public E getByProerties(String[] propName, Object[] propValue); public E getByProerties(String[] propName, Object[] propValue, Map<String, String> sortedCondition); /** * get an entity by property * * @param propName * @param propValue * @return */ public E getByProerties(String propName, Object propValue); public E getByProerties(String propName, Object propValue, Map<String, String> sortedCondition); /** * query by property * * @param propName * @param propValue * @return */ public List<E> queryByProerties(String[] propName, Object[] propValue, Map<String, String> sortedCondition, Integer top); public List<E> queryByProerties(String[] propName, Object[] propValue, Map<String, String> sortedCondition); public List<E> queryByProerties(String[] propName, Object[] propValue, Integer top); public List<E> queryByProerties(String[] propName, Object[] propValue); public List<E> queryByProerties(String propName, Object propValue, Map<String, String> sortedCondition, Integer top); public List<E> queryByProerties(String propName, Object propValue, Map<String, String> sortedCondition); public List<E> queryByProerties(String propName, Object propValue, Integer top); public List<E> queryByProerties(String propName, Object propValue); /** * Completely clear the session. */ public void clear(); /** * Remove this instance from the session cache. */ public void evict(E entity); /** * count all * * @return */ public Long countAll(); /** * Query all * * @return */ public List<E> doQueryAll(); public List<E> doQueryAll(Map<String, String> sortedCondition, Integer top); public List<E> doQueryAll(Integer top); public Long doCount(BaseParameter parameter); public List<E> doQuery(BaseParameter parameter); public QueryResult<E> doPaginationQuery(BaseParameter parameter); public QueryResult<E> doPaginationQuery(BaseParameter parameter, boolean bool); public List<Object[]> doExecuteSql(String sql); public int doInsertUpdateSql(String sql); }
mit
iyybpatrick/LeetCode
JAVA/Tag order/Backtracking/_51N_Queens.java
1525
/** * Created by YuebinYang on 9/18/17. */ import java.util.*; public class _51N_Queens { public List<List<String>> solveNQueens(int n) { List<List<String>> result = new ArrayList<>(); if (n <= 0) return result; char[][] board= new char[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { board[i][j] = '.'; } } DFS(board, result, 0); return result; } public void DFS(char[][] board, List<List<String>> result, int rowIdx) { if (rowIdx == board.length) { result.add(construct(board)); return; } for (int colIdx = 0; colIdx < board.length; colIdx++) { if (valid(board, rowIdx, colIdx)) { board[rowIdx][colIdx] = 'Q'; DFS(board, result, rowIdx + 1); board[rowIdx][colIdx] = '.'; } } } public boolean valid(char[][]board, int x, int y) { for (int i = 0; i < x; i++) { for (int j = 0; j <board.length; j++) { if (board[i][j] == 'Q' && (j == y || y + i == j + x || x + y == i + j)) { return false; } } } return true; } public List<String> construct(char[][]board) { List<String> strList = new LinkedList<>(); for (int i = 0; i < board.length; i++) { strList.add(new String(board[i])); } return strList; } }
mit
kaflu/Top-Down-Go-Kart-Game
Go Kart Game/src/Octopus.java
1085
import java.util.ArrayList; import org.newdawn.slick.SlickException; public class Octopus extends AIKart { /* Starting Position */ public final int StartX = (int) WorldCoordinates.Octopus.getPosX(); public final int StartY = (int) WorldCoordinates.Octopus.getPosY(); /** Constants specific to octopus */ public final int octopusStartChase = 100; public final int octopusEndChase = 250; /** Initializing the bot with the appropriate image sprite */ public Octopus(String kartAssetLocation, String kartName, ArrayList<Point2D> waypoints) throws SlickException { createSprite(kartAssetLocation, kartName); updateStartLocation(StartX, StartY); } /** Logic for the kart */ public void move(World world, int delta) { octopusStrategy(world); update(world, delta); } /** Logic for the strategy */ public void octopusStrategy(World world) { if(this.distanceTo(world.getPlayer()) >= octopusStartChase && this.distanceTo(world.getPlayer()) <= octopusEndChase) this.setDontFollowWaypoint(true); else this.setDontFollowWaypoint(false); } }
mit
hakandilek/wordclock-layout
layout/src/test/java/me/dilek/wordclock/layout/AppTest.java
653
package me.dilek.wordclock.layout; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
mit
KROKIteam/KROKI-CERIF-Model
CerifModel/WebApp/src_gen/ejb_generated/CfProj_FacilConstraints.java
300
package ejb_generated; import adapt.exceptions.InvariantException; public class CfProj_FacilConstraints extends CfProj_Facil{ private String objectName; public String getObjectName() { return objectName; } public void setObjectName(String objectName) { this.objectName = objectName; } }
mit
CNGL-repo/r2rml
src/r2rml/engine/Configuration.java
3435
package r2rml.engine; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import org.apache.log4j.Logger; /** * Configuration Class. * * @author Christophe Debruyne * @version 0.1 * */ public class Configuration { private static Logger logger = Logger.getLogger(Configuration.class.getName()); private String connectionURL = null; private String user = null; private String password = null; private String mappingFile = null; private String outputFile = null; private String format = null; private String baseIRI = null; private boolean filePerGraph = false; private List<String> CSVFiles = new ArrayList<String>(); public Configuration(String path) throws R2RMLException { Properties properties = new Properties(); try { properties.load(new FileInputStream(new File(path))); } catch (IOException e) { throw new R2RMLException(e.getMessage(), e); } connectionURL = properties.getProperty("connectionURL"); user = properties.getProperty("user"); password = properties.getProperty("password"); mappingFile = properties.getProperty("mappingFile"); outputFile = properties.getProperty("outputFile"); format = properties.getProperty("format", "TURTLE"); setFilePerGraph("true".equals(properties.getProperty("filePerGraph", "false").toLowerCase())); baseIRI = properties.getProperty("baseIRI"); String files = properties.getProperty("CSVFiles"); if(files != null && !"".equals(files)) { StringTokenizer tk = new StringTokenizer(files, ";"); while(tk.hasMoreTokens()) { CSVFiles.add(tk.nextToken()); } } } public Configuration() { } public String getConnectionURL() { return connectionURL; } public void setConnectionURL(String connectionURL) { this.connectionURL = connectionURL; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getMappingFile() { return mappingFile; } public void setMappingFile(String mappingFile) { this.mappingFile = mappingFile; } public String getOutputFile() { return outputFile; } public void setOutputFile(String outputFile) { this.outputFile = outputFile; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public String getBaseIRI() { return baseIRI; } public void setBaseIRI(String baseIRI) { if(baseIRI.contains("#")) logger.warn("Base IRIs should not contain a \"#\"."); if(baseIRI.contains("?")) logger.warn("Base IRIs should not contain a \"?\"."); if(!baseIRI.endsWith("/")) logger.warn("Base IRIs should end with a \"/\"."); this.baseIRI = baseIRI; } public boolean isFilePerGraph() { return filePerGraph; } public void setFilePerGraph(boolean filePerGraph) { this.filePerGraph = filePerGraph; } public List<String> getCSVFiles() { return CSVFiles; } public void setCSVFiles(List<String> cSVFiles) { CSVFiles = cSVFiles; } public boolean hasConnectionURL() { return connectionURL != null && !"".equals(connectionURL); } public boolean hasCSVFiles() { return CSVFiles != null && CSVFiles.size() > 0; } }
mit
RogueLogic/Parallel
src/main/java/net/roguelogic/mods/parallel/internal/Updater.java
1038
package net.roguelogic.mods.parallel.internal; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; final class Updater { private boolean firstTick = true; Updater() { MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onWorldTick(final TickEvent.WorldTickEvent event) { if (TickEvent.Phase.START == event.phase && Thread.currentThread().getName().equals("Server thread")) { if (firstTick) { firstTick = false; Management.init(); } Management.update(); } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onWorldUnload(final WorldEvent.Unload unloadWorldEvent) { Management.worldUnload(); } }
mit
redraiment/jactiverecord
src/main/java/me/zzp/ar/ex/SqlExecuteException.java
272
package me.zzp.ar.ex; /** * 执行SQL时遇到任何问题抛出此异常。 * * @since 1.0 * @author redraiment */ public class SqlExecuteException extends RuntimeException { public SqlExecuteException(String sql, Throwable cause) { super(sql, cause); } }
mit
wszdwp/AlgorithmPractice
src/main/java/com/codingpan/ms/OTS20190803.java
1097
package com.codingpan.ms; import edu.princeton.cs.algs4.StdOut; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class OTS20190803 { public int solution(String S) { // write your code in Java SE 8 int[] count = new int[26]; for (int i = 0; i < S.length(); i++) { char c = S.charAt(i); count[c - 'a'] += 1; } Arrays.sort(count); Set<Integer> seen = new HashSet<>(); int ans = 0; for (int i = 25; i >= 0; i--) { if (count[i] > 0) { if (seen.contains(count[i])) { ans += seen.contains(count[i] - 1) ? count[i] : 1; seen.add(count[i] - 1); } seen.add(count[i]); } } return ans; } public static void main(String[] args) { OTS20190803 solu = new OTS20190803(); String[] ss = {"ccaaffddecee"}; for (String s : ss) { int ans = solu.solution(s); StdOut.println("ans " + ans); } } }
mit
unbroken-dome/siren-java
siren-ap/src/main/java/org/unbrokendome/siren/ap/codegeneration/method/contributors/LinkTitleBuilderMethodContributor.java
1498
package org.unbrokendome.siren.ap.codegeneration.method.contributors; import com.google.auto.service.AutoService; import com.squareup.javapoet.CodeBlock; import org.unbrokendome.siren.ap.codegeneration.title.TitleCodeGenerationUtils; import org.unbrokendome.siren.ap.codegeneration.method.BuilderMethodContributor; import org.unbrokendome.siren.ap.model.affordance.link.LinkTemplate; import javax.annotation.Nullable; @AutoService(BuilderMethodContributor.class) public class LinkTitleBuilderMethodContributor extends AbstractLinkBuilderMethodContributor { @Nullable @Override protected CodeBlock doGenerateBuilderSetterStatement(LinkTemplate linkTemplate, String builderVariableName) { CodeBlock titleCode = getTitleCode(linkTemplate, builderVariableName); if (titleCode != null) { return CodeBlock.of(".setTitle($L)", titleCode); } else { return null; } } @Nullable private CodeBlock getTitleCode(LinkTemplate linkTemplate, String builderVariableName) { if (linkTemplate.hasTitleMap() || linkTemplate.hasResolvableTitles()) { String titleMapFieldName = TitleCodeGenerationUtils.getTitlesFieldName(linkTemplate); return CodeBlock.of("$L.get($L.getRels())", titleMapFieldName, builderVariableName); } else if (linkTemplate.getTitle() != null) { return CodeBlock.of("$S", linkTemplate.getTitle()); } else { return null; } } }
mit
kana2011/mcShopAndroid
app/src/main/java/xyz/paphonb/mcshop/SelectAccountActivity.java
12626
package xyz.paphonb.mcshop; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.TwoLineListItem; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import java.util.ArrayList; import java.util.List; import xyz.paphonb.mcshop.libs.McShop; import xyz.paphonb.mcshop.utils.Util; public class SelectAccountActivity extends AppCompatActivity { public String PREFS_NAME = "xyz.paphonb.mcShop"; public static SharedPreferences settings; public static int currentCredential = 0; private JSONArray credentials; private ArrayList<Account> accounts; private AccountAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_account); final ListView listview = (ListView) findViewById(R.id.listview); ImageButton addButton = (ImageButton) findViewById(R.id.addButton); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent loginIntent = new Intent(SelectAccountActivity.this, LoginActivity.class); startActivity(loginIntent); finish(); } }); accounts = new ArrayList<>(); settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); JSONParser parser = new JSONParser(); loadCredentials(); adapter = new AccountAdapter(this, accounts); listview.setAdapter(adapter); listview.setDivider(null); listview.setDividerHeight(0); listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { new AlertDialog.Builder(SelectAccountActivity.this) .setTitle(R.string.account_delete) .setMessage(R.string.settings_signout_content) .setPositiveButton(R.string.account_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { deleteCredential(position); loadCredentials(); adapter.setData(accounts); adapter.notifyDataSetChanged(); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .show(); return false; } }); listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) { final Account account = accounts.get(position); final ProgressDialog progress = ProgressDialog.show(SelectAccountActivity.this, "Please wait...", "Switching account", true, false); new Thread(new Runnable() { @Override public void run() { String token = account.getToken(); String res = checkAuth(token); if(res.equals("success")) { SharedPreferences.Editor editor = settings.edit(); editor.putInt("currentCredential", position); editor.commit(); List<NameValuePair> nameValuePairList = new ArrayList<>(); final String userInfo = McShop.postData(McShop.getCurrentCredential(SelectAccountActivity.this), "/api/user:shop", nameValuePairList); runOnUiThread(new Runnable() { @Override public void run() { progress.dismiss(); Intent homeIntent = new Intent(SelectAccountActivity.this, HomeActivity.class); homeIntent.putExtra("userInfo", userInfo); startActivity(homeIntent); finish(); MainActivity.getInstance().finish(); } }); } else if(res.equals("error")) { runOnUiThread(new Runnable() { @Override public void run() { progress.dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(SelectAccountActivity.this); builder.setMessage("No connection.") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); } }); } else { runOnUiThread(new Runnable() { @Override public void run() { progress.dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(SelectAccountActivity.this); builder.setMessage("Session expired.") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { deleteCredential(position); loadCredentials(); adapter.setData(accounts); adapter.notifyDataSetChanged(); } }); AlertDialog alert = builder.create(); alert.show(); } }); } } }).start(); } }); } private void loadCredentials() { JSONParser parser = new JSONParser(); accounts = new ArrayList<>(); try { credentials = (JSONArray) parser.parse(settings.getString("credentials", "[]")); for (int i = 0; i < credentials.size(); i++) { Account account = new Account((String) ((JSONObject) credentials.get(i)).get("username"), (String) ((JSONObject) credentials.get(i)).get("address"), (String) ((JSONObject) credentials.get(i)).get("token")); accounts.add(account); } } catch (Exception e) { } } class Account { private String username; private String address; private String token; public Account(String username, String address, String token) { this.username = username; this.address = address; this.token = token; } public String getUsername() { return username; } public String getAddress() { return address; } public String getToken() { return token; } } class AccountAdapter extends BaseAdapter { private Context context; private ArrayList<Account> accounts; public AccountAdapter(Context context, ArrayList<Account> accounts) { this.context = context; this.accounts = accounts; } @Override public int getCount() { return accounts.size(); } @Override public Object getItem(int position) { return accounts.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { TwoLineListItem twoLineListItem; LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); twoLineListItem = (TwoLineListItem) inflater.inflate( android.R.layout.simple_list_item_2, null); if(position == McShop.getCurrentCredentialIndex(SelectAccountActivity.this)) { twoLineListItem.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark)); } TextView text1 = twoLineListItem.getText1(); TextView text2 = twoLineListItem.getText2(); text1.setTextColor(getResources().getColor(R.color.md_white_1000)); text2.setTextColor(getResources().getColor(R.color.md_white_1000)); text1.setText(accounts.get(position).getUsername()); text2.setText(accounts.get(position).getAddress()); return twoLineListItem; } public void setData(ArrayList<Account> data) { this.accounts = data; } } public String checkAuth(String token) { try { JSONParser parser = new JSONParser(); JSONArray credentials = (JSONArray)parser.parse(settings.getString("credentials", "[]")); String address = (String)((JSONObject)credentials.get(settings.getInt("currentCredential", 0))).get("address"); List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(2); nameValuePairList.add(new BasicNameValuePair("token", token)); JSONObject res = (JSONObject)parser.parse(Util.postData(address + "/api/auth:tokenLogin", nameValuePairList)); if((Boolean)((JSONObject)parser.parse(Util.postData(address + "/api/auth:tokenLogin", nameValuePairList))).get("status")) { return "success"; } else { return "failed"; } } catch (Exception e) { return "error"; } } private void deleteCredential(int position) { JSONArray list = new JSONArray(); JSONArray jsonArray = credentials; int len = jsonArray.size(); if (jsonArray != null) { for (int i = 0; i < len; i++) { //Excluding the item at position if (i != position) { list.add(jsonArray.get(i)); } } } SharedPreferences.Editor editor = settings.edit(); editor.putString("credentials", list.toString()); if(position == McShop.getCurrentCredentialIndex(SelectAccountActivity.this)) { editor.putInt("currentCredential", 0); } editor.commit(); } }
mit
MGautier/Programacion
Android/M4Podometro-Studio/app/src/main/java/apps/curso/podometro/StepListener.java
132
package apps.curso.podometro; public interface StepListener { public void onStep(); public void passValue(); }
mit
byhieg/easyweather
app/src/main/java/com/weather/byhieg/easyweather/city/CityContract.java
1215
package com.weather.byhieg.easyweather.city; import com.weather.byhieg.easyweather.BasePresenter; import com.weather.byhieg.easyweather.BaseView; import com.weather.byhieg.easyweather.citymanage.CityManageContract; import com.weather.byhieg.easyweather.data.source.local.entity.CityEntity; import com.weather.byhieg.easyweather.data.source.local.entity.ProvinceEntity; import java.util.List; /** * Created by byhieg on 17/5/30. * Contact with byhieg@gmail.com */ public interface CityContract { interface ProvincePresenter extends BasePresenter{ void loadData(); } interface ProvinceView extends BaseView<ProvincePresenter>{ void showProvinceData(List<ProvinceEntity> data); } interface CityPresenter extends BasePresenter { void loadCityData(String provinceName); void insertLoveCity(String cityName); void cancelCity(String cityName); void getCityWeather(String cityName); boolean isExist(String cityName); } interface CityView extends BaseView<CityPresenter> { void showNoData(); void showCityData(List<CityEntity> data); void cancelRefresh(); void setNetWork(); } }
mit
mezz/JustEnoughItems
src/main/java/mezz/jei/ingredients/IngredientBlacklistInternal.java
1443
package mezz.jei.ingredients; import java.util.HashSet; import java.util.Set; import mezz.jei.api.ingredients.IIngredientHelper; import mezz.jei.api.ingredients.ITypedIngredient; import mezz.jei.api.ingredients.subtypes.UidContext; public class IngredientBlacklistInternal { private final Set<String> ingredientBlacklist = new HashSet<>(); public <V> void addIngredientToBlacklist(ITypedIngredient<V> typedIngredient, IIngredientHelper<V> ingredientHelper) { V ingredient = typedIngredient.getIngredient(); String uniqueName = ingredientHelper.getUniqueId(ingredient, UidContext.Ingredient); ingredientBlacklist.add(uniqueName); } public <V> void removeIngredientFromBlacklist(ITypedIngredient<V> typedIngredient, IIngredientHelper<V> ingredientHelper) { V ingredient = typedIngredient.getIngredient(); String uniqueName = ingredientHelper.getUniqueId(ingredient, UidContext.Ingredient); ingredientBlacklist.remove(uniqueName); } public <V> boolean isIngredientBlacklistedByApi(ITypedIngredient<V> typedIngredient, IIngredientHelper<V> ingredientHelper) { V ingredient = typedIngredient.getIngredient(); String uid = ingredientHelper.getUniqueId(ingredient, UidContext.Ingredient); String uidWild = ingredientHelper.getWildcardId(ingredient); if (uid.equals(uidWild)) { return ingredientBlacklist.contains(uid); } return ingredientBlacklist.contains(uid) || ingredientBlacklist.contains(uidWild); } }
mit
xross-criss/STM
src/main/java/pl/morecraft/dev/stm/rest/CategoryResource.java
1623
package pl.morecraft.dev.stm.rest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import pl.morecraft.dev.stm.dto.CategoryDTO; import pl.morecraft.dev.stm.dto.TaskDTO; import pl.morecraft.dev.stm.service.CategoryService; import pl.morecraft.dev.stm.service.TaskService; import java.io.IOException; @Slf4j @RestController @RequestMapping("/api/category") public class CategoryResource { private final CategoryService categoryService; @Autowired public CategoryResource(CategoryService categoryService) { this.categoryService = categoryService; } @RequestMapping( value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity<CategoryDTO> getCategory(@RequestParam(value = "id") Long id) throws IOException { return new ResponseEntity<>( categoryService.getCategory(id), HttpStatus.OK ); } @RequestMapping( value = "", method = {RequestMethod.POST, RequestMethod.PUT}, produces = MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity<CategoryDTO> saveCategory(@ModelAttribute CategoryDTO category) throws IOException { return new ResponseEntity<>( categoryService.saveCategory(category), HttpStatus.OK ); } }
mit
wipu/iwant
private/iwant-mock-wsroot/essential/iwant-entry3/src/main/java/org/fluentjava/iwant/api/ClassToTestDebugInformation.java
236
package org.fluentjava.iwant.api; public class ClassToTestDebugInformation { public String methodToTestDebugInformation(String parameterVariable) { final String localVariable = ""; return localVariable + parameterVariable; } }
mit
venanciolm/afirma-ui-miniapplet_x_x
afirma_ui_miniapplet/src/main/java/es/gob/jmulticard/card/cwa14890/Cwa14890Card.java
7143
/* * Controlador Java de la Secretaria de Estado de Administraciones Publicas * para el DNI electronico. * * El Controlador Java para el DNI electronico es un proveedor de seguridad de JCA/JCE * que permite el acceso y uso del DNI electronico en aplicaciones Java de terceros * para la realizacion de procesos de autenticacion, firma electronica y validacion * de firma. Para ello, se implementan las funcionalidades KeyStore y Signature para * el acceso a los certificados y claves del DNI electronico, asi como la realizacion * de operaciones criptograficas de firma con el DNI electronico. El Controlador ha * sido disenado para su funcionamiento independiente del sistema operativo final. * * Copyright (C) 2012 Direccion General de Modernizacion Administrativa, Procedimientos * e Impulso de la Administracion Electronica * * Este programa es software libre y utiliza un licenciamiento dual (LGPL 2.1+ * o EUPL 1.1+), lo cual significa que los usuarios podran elegir bajo cual de las * licencias desean utilizar el codigo fuente. Su eleccion debera reflejarse * en las aplicaciones que integren o distribuyan el Controlador, ya que determinara * su compatibilidad con otros componentes. * * El Controlador puede ser redistribuido y/o modificado bajo los terminos de la * Lesser GNU General Public License publicada por la Free Software Foundation, * tanto en la version 2.1 de la Licencia, o en una version posterior. * * El Controlador puede ser redistribuido y/o modificado bajo los terminos de la * European Union Public License publicada por la Comision Europea, * tanto en la version 1.1 de la Licencia, o en una version posterior. * * Deberia recibir una copia de la GNU Lesser General Public License, si aplica, junto * con este programa. Si no, consultelo en <http://www.gnu.org/licenses/>. * * Deberia recibir una copia de la European Union Public License, si aplica, junto * con este programa. Si no, consultelo en <http://joinup.ec.europa.eu/software/page/eupl>. * * Este programa es distribuido con la esperanza de que sea util, pero * SIN NINGUNA GARANTIA; incluso sin la garantia implicita de comercializacion * o idoneidad para un proposito particular. */ package es.gob.jmulticard.card.cwa14890; import java.io.IOException; import java.security.cert.CertificateException; import java.security.interfaces.RSAPrivateKey; import es.gob.jmulticard.apdu.connection.ApduConnectionException; /** Interfaz con los m&eacute;todos necesarios para la operaci&oacute;n de las tarjetas * acordes a la especificaci&oacute;n CWA-14890. * @author Carlos Gamuci */ public interface Cwa14890Card { /** Verifica la CA intermedia del certificado de componente de la tarjeta. * @throws CertificateException Cuando ocurre alg&uacute;n problema en la * validaci&oacute;n del certificado * @throws IOException Cuando ocurre alg&uacute;n problema en la selecci&oacute;n * y lectura del certificado * @throws SecurityException Si falla la validaci&oacute;n de la CA */ void verifyCaIntermediateIcc() throws CertificateException, IOException; /** Verifica el certificado de componente de la tarjeta. * @throws CertificateException Cuando ocurre alg&uacute;n problema en la * validaci&oacute;n del certificado * @throws IOException Cuando ocurre alg&uacute;n problema en la selecci&oacute;n * y lectura del certificado * @throws SecurityException Si falla la validaci&oacute;n del certificado */ void verifyIcc() throws CertificateException, IOException; /** Recupera el certificado de componente codificado. * @return Certificado codificado * @throws IOException Cuando ocurre alg&uacute;n problema en la selecci&oacute;n * y lectura del certificado */ byte[] getIccCertEncoded() throws IOException; /** Verifica que los certificados declarados por el controlador (certificados de * Terminal) sean v&aacute;lidos para el uso de la tarjeta. * @throws ApduConnectionException Cuando ocurre alg&iacute;n error en la * comunicaci&oacute;n con la tarjeta * @throws es.gob.jmulticard.apdu.connection.cwa14890.SecureChannelException Cuando ocurre alg&uacute;n error en la * verificaci&oacute;n de los certificados */ void verifyIfdCertificateChain() throws ApduConnectionException; /** Obtiene el mensaje de autenticaci&oacute;n interna de la tarjeta. * @param randomIfd Bytes aleatorios generados * @param chrCCvIfd CHR de la clave p&uacute;blica del certificado de Terminal * @return Mensaje cifrado con la clave privada de componente de la tarjeta * @throws ApduConnectionException Cuando ocurre un error de comunicaci&oacute;n con la tarjeta */ byte[] getInternalAuthenticateMessage(final byte[] randomIfd, final byte[] chrCCvIfd) throws ApduConnectionException; /** Envia el mensaje de autenticaci&oacute;n externa. * @param extAuthenticationData Mensaje de autenticaci&oacute;n externa * @return {@code true} si la autenticaci&oacute;n finaliz&oacute; correctamente, {@code false} en caso contrario * @throws ApduConnectionException Cuando ocurre un error en la comunicaci&oacute;n con * la tarjeta */ boolean externalAuthentication(final byte[] extAuthenticationData) throws ApduConnectionException; /** Establece una clave p&uacute;blica y otra privada para la autenticaci&oacute;n * interna y externa de la tarjeta. * @param refPublicKey Referencia a la clave publica * @param refPrivateKey Referencia a la clave privada * @throws es.gob.jmulticard.apdu.connection.cwa14890.SecureChannelException Cuando ocurre un error durante el proceso de autenticaci&oacute;n * @throws ApduConnectionException Cuando ocurre un error de comunicaci&oacute;n con la tarjeta */ void setKeysToAuthentication(final byte[] refPublicKey, final byte[] refPrivateKey) throws ApduConnectionException; /** Solicita un desaf&iacute;o de 8 bytes a la tarjeta. * @return Array de 8 bytes aleatorios * @throws ApduConnectionException Cuando ocurre un error de comunicaci&oacute;n con la tarjeta */ byte[] getChallenge() throws ApduConnectionException; /** Recupera el numero de serie de la tarjeta. * @return N&uacute;mero de serie * @throws ApduConnectionException Cuando ocurre un error en la comunicaci&oacute;n con * la tarjeta */ byte[] getSerialNumber() throws ApduConnectionException; /** Recupera la referencia a la clave privada del certificado de Componente. * @return Referencia a clave privada */ byte[] getRefIccPrivateKey(); /** Recupera el CHR de la clave publica del certificado de Terminal. * @return Referencia a clave p&uacute;blica */ byte[] getChrCCvIfd(); /** Recupera la clave privada del certificado de componente de la tarjeta. * @return Clave privada */ RSAPrivateKey getIfdPrivateKey(); }
mit
iiED-csumb/hackmb-smartphone-controller
GameController 2 2/app/src/main/java/edu/csumb/gamecontroller/IOBeat.java
566
package edu.csumb.gamecontroller; import java.util.TimerTask; public class IOBeat extends TimerTask { private IOWebSocket socket; private boolean running = false; public IOBeat(IOWebSocket socket){ this.socket = socket; } @Override public void run() { // TODO Auto-generated method stub if(running){ socket.send("2::"); //send heartbeat; System.out.println("HeartBeat Written to server"); } } public void start(){ running = true; } public void stop(){ running = false; } public boolean isRunning(){ return running; } }
mit
Slushy/goldendragon
src/main/java/engine/common/Component.java
1876
package engine.common; import engine.scenes.Scene; /** * Represents the base class for all components * * @author Brandon Porter * */ public abstract class Component extends Entity { private GameObject _gameObject; /** * Constructs a new component entity * * @param componentName * name of the component */ public Component(String componentName) { super(componentName); } /** * @return the game object owning this component */ public final GameObject getGameObject() { return _gameObject; } /** * @return the transform of the game object owning this component */ public Transform getTransform() { return _gameObject != null ? _gameObject.getTransform() : null; } /** * Stores a reference to the game object containing this component * * @param gameObject */ protected void setGameObject(GameObject gameObject) { this._gameObject = gameObject; } /** * @return the scene of the component */ protected Scene getScene() { return _gameObject != null ? _gameObject.getScene() : null; } /** * @return true or false if this component should destroy the game object * when the component is disposed. This is only used for "required" * components. A required component should override this method and * return true, because when a required component is destroyed we * SHOULD also destroy the game object */ protected boolean destroyGameObjectOnDispose() { return false; } /** * Disposes the component by removing itself from the game object */ @Override protected void onDispose() { if (_gameObject == null) return; // We have a valid game object so lets remove this component and check // if we should also dispose the game object _gameObject.removeComponent(this); if (destroyGameObjectOnDispose()) _gameObject.dispose(); } }
mit
InnovateUKGitHub/innovation-funding-service
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/review/security/ReviewInvitePermissionRules.java
942
package org.innovateuk.ifs.review.security; import org.innovateuk.ifs.commons.security.PermissionRule; import org.innovateuk.ifs.commons.security.PermissionRules; import org.innovateuk.ifs.review.domain.ReviewInvite; import org.innovateuk.ifs.security.BasePermissionRules; import org.innovateuk.ifs.user.resource.UserResource; import org.springframework.stereotype.Component; /** * Provides the permissions around CRUD operations for {@link ReviewInvite} resources. */ @Component @PermissionRules public class ReviewInvitePermissionRules extends BasePermissionRules { @PermissionRule(value = "READ_ASSESSMENT_PANEL_INVITES", description = "An assessor may only view their own invites to assessment panels") public boolean userCanViewInvites(UserResource inviteUser, UserResource loggedInUser) { return inviteUser != null && loggedInUser != null && inviteUser.equals(loggedInUser); } }
mit
jamiestevenson/fsm-lab
fsm-lab/fsm-lab/src/main/model/Loom.java
1596
package main.model; import java.awt.Dimension; public interface Loom { /** * Gets the dimensions of the Loom, note that this is an indication of capacity, not the number * FSMs present in the Loom. * @return Dimension indicating the size of this Loom */ public abstract Dimension dimension(); /** * Add a FSM to this collection * @param fsm - a FSM * @return - true if added, otherwise false * * NB - the FSM will be added on a best effort basis, near the origin (0,0) (top left), if * there is no room, or the input is null, the input will not be added to this collection. */ public abstract boolean add(FSM fsm); /** * Puts a FSM in a specific location in the Loom * @param fsm - a FiniteStateMachine to add * @param x - the column to add the FSM * @param y - the row to add the FSM * @return - true if the FSM is added, otherwise false */ public abstract boolean put(FSM fsm, int x, int y); /** * Get the FSM at the specified coordinates * @param x - the column * @param y - the row * @return - the FSM at the location (x,y) or null if the location is empty * * NB - some FSM configurations may use some form of null object */ public abstract FSM getCellContents(int x, int y); /** * Executes one 'tick' of the simulation on all FSMs on the loom. Makes no guarantees about * ordering or edge-of-grid behaviour. * * @return boolean - true if all FSMs in the loom are asked to tick and all FSMs ticked FSMs * report back a successful tick, otherwise false. */ public abstract boolean tick(); }
mit
hypery2k/cordova-hotspot-plugin
test/android/unit/api/WifiAddressesTest.java
1621
package unit.api; import com.mady.wifi.api.WifiAddresses; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Created by mreinhardt on 16.02.16. */ public class WifiAddressesTest { @Test public void shouldGetAllDevices() throws Exception { WifiAddresses wifiAddresses = new WifiAddresses(null); List<String> devices = wifiAddresses.getAllDevicesIp(); assertTrue(devices.size() > 0); } @Test public void shouldSucceedWithValidAddress() throws Exception { WifiAddresses wifiAddresses = new WifiAddresses(null); boolean success = wifiAddresses.pingCmd("8.8.8.8"); String result = wifiAddresses.getPingResulta("8.8.8.8"); assertTrue(success); assertTrue(result.length() > 0); } @Test public void shouldNotWorkWithPrivateIP() throws Exception { WifiAddresses wifiAddresses = new WifiAddresses(null); boolean success = wifiAddresses.pingCmd("192.168.255.250"); String result = wifiAddresses.getPingResulta("192.168.255.250"); assertFalse(success); assertTrue(result.length() > 0); assertTrue(result.contains("Request timeout")); } //@Test public void shouldFailWithInvalidAddress() throws Exception { WifiAddresses wifiAddresses = new WifiAddresses(null); boolean success = wifiAddresses.pingCmd("8.8.8.811"); String result = wifiAddresses.getPingResulta("8.8.8.811"); assertFalse(success); assertTrue(result.length() == 0); } }
mit
christopherfebles/FeedOrganizer
src/main/java/com/cjf/twitterlistmanager/dao/impl/UserDAOImpl.java
3351
package com.cjf.twitterlistmanager.dao.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import com.cjf.twitterlistmanager.dao.UserDAO; import com.cjf.twitterlistmanager.model.User; @Repository public class UserDAOImpl implements UserDAO { private NamedParameterJdbcTemplate jdbcTemplate; @Autowired public void setDataSource(DataSource dataSource) { jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); } @Override public User getUserById(int userId) { String query = "Select * From TwitterListManager.Users Where user_id = :userId"; SqlParameterSource namedParameters = new MapSqlParameterSource("userId", Integer.valueOf(userId)); User retVal = null; try { retVal = jdbcTemplate.queryForObject(query, namedParameters, new UserRowMapper()); } catch (EmptyResultDataAccessException e) { } return retVal; } @Override public User getUserByName(String screenName) { String query = "Select * From TwitterListManager.Users Where screen_name = :screenName"; SqlParameterSource namedParameters = new MapSqlParameterSource("screenName", screenName); User retVal = null; try { retVal = jdbcTemplate.queryForObject(query, namedParameters, new UserRowMapper()); } catch (EmptyResultDataAccessException e) { } return retVal; } @Override public void saveUser(User user) { String query = "Update TwitterListManager.Users " + "Set user_id = :userId, screen_name = :screenName, access_token = :accessToken, " + "token_secret = :tokenSecret, token_raw = :tokenRaw " + "Where user_id = :userId"; // Check if Update or Insert User tmpUser = this.getUserById(user.getUserId()); if (tmpUser == null) { // Insert query = "Insert Into TwitterListManager.Users( user_id, screen_name, access_token, token_secret, token_raw) " + "Values( :userId, :screenName, :accessToken, :tokenSecret, :tokenRaw )"; } Map<String, Object> namedParameters = new HashMap<String, Object>(); namedParameters.put("userId", Integer.valueOf(user.getUserId())); namedParameters.put("screenName", user.getScreenName()); namedParameters.put("accessToken", user.getAccessToken()); namedParameters.put("tokenSecret", user.getTokenSecret()); namedParameters.put("tokenRaw", user.getTokenRaw()); jdbcTemplate.update(query, namedParameters); } private class UserRowMapper implements RowMapper<User> { @Override public User mapRow(ResultSet resultSet, int rowNum) throws SQLException { return new User(resultSet.getInt("user_id"), resultSet.getString("screen_name"), resultSet.getString("access_token"), resultSet.getString("token_secret"), resultSet.getString("token_raw")); } } }
mit
Playtika/testcontainers-spring-boot
embedded-clickhouse/src/main/java/com/playtika/test/clickhouse/EmbeddedClickHouseBootstrapConfiguration.java
3602
package com.playtika.test.clickhouse; import com.playtika.test.common.spring.DockerPresenceBootstrapConfiguration; import com.playtika.test.common.utils.ContainerUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.testcontainers.containers.ClickHouseContainer; import org.testcontainers.shaded.com.google.common.base.Strings; import java.util.LinkedHashMap; import static com.playtika.test.clickhouse.ClickHouseProperties.BEAN_NAME_EMBEDDED_CLICK_HOUSE; import static com.playtika.test.common.utils.ContainerUtils.configureCommonsAndStart; @Slf4j @Configuration @ConditionalOnExpression("${embedded.containers.enabled:true}") @AutoConfigureAfter(DockerPresenceBootstrapConfiguration.class) @ConditionalOnProperty(name = "embedded.clickhouse.enabled", havingValue = "true", matchIfMissing = true) @EnableConfigurationProperties(ClickHouseProperties.class) public class EmbeddedClickHouseBootstrapConfiguration { @Bean(name = BEAN_NAME_EMBEDDED_CLICK_HOUSE, destroyMethod = "stop") public ClickHouseContainer clickHouseContainer(ConfigurableEnvironment environment, ClickHouseProperties properties) { ClickHouseContainer clickHouseContainer = new ClickHouseContainer(ContainerUtils.getDockerImageName(properties)); String username = Strings.isNullOrEmpty(properties.getUser()) ? clickHouseContainer.getUsername() : properties.getUser(); String password = Strings.isNullOrEmpty(properties.getPassword()) ? clickHouseContainer.getPassword() : properties.getPassword(); clickHouseContainer.addEnv("CLICKHOUSE_USER", username); clickHouseContainer.addEnv("CLICKHOUSE_PASSWORD", Strings.nullToEmpty(password)); clickHouseContainer = (ClickHouseContainer) configureCommonsAndStart(clickHouseContainer, properties, log); registerClickHouseEnvironment(clickHouseContainer, environment, properties, username, password); return clickHouseContainer; } private void registerClickHouseEnvironment(ClickHouseContainer clickHouseContainer, ConfigurableEnvironment environment, ClickHouseProperties properties, String username, String password) { Integer mappedPort = clickHouseContainer.getMappedPort(properties.port); String host = clickHouseContainer.getContainerIpAddress(); LinkedHashMap<String, Object> map = new LinkedHashMap<>(); map.put("embedded.clickhouse.schema", "default"); map.put("embedded.clickhouse.host", host); map.put("embedded.clickhouse.port", mappedPort); map.put("embedded.clickhouse.user", username); map.put("embedded.clickhouse.password", password); log.info("Started ClickHouse server. Connection details: {}", map); MapPropertySource propertySource = new MapPropertySource("embeddedClickHouseInfo", map); environment.getPropertySources().addFirst(propertySource); } }
mit
przodownikR1/java8features
src/test/java/pl/java/scalatech/design_pattern/RepConwithPoly/newPolyApproach/OrdinaryEngine.java
200
package pl.java.scalatech.design_pattern.RepConwithPoly.newPolyApproach; public class OrdinaryEngine extends EngineNew{ @Override double getMultiplier() { return 1.0d; } }
mit
justnero-ru/university
semestr.06/КГ/Lab.04/code/src/ru/justnero/study/s6/cg/e4/gui/ShowForm.java
7515
package ru.justnero.study.s6.cg.e4.gui; import com.jogamp.opengl.awt.GLCanvas; import java.awt.*; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragSource; import java.util.function.Supplier; import javax.swing.*; import ru.justnero.study.s6.cg.e2.gui.Animation; import ru.justnero.study.s6.cg.e2.main.figures.AnimableQuad; import ru.justnero.study.s6.cg.e4.Main; import ru.justnero.study.s6.cg.e4.main.ClipBox; import ru.justnero.study.s6.cg.e4.main.Lab4Scene; import ru.justnero.study.s6.cg.e4.main.Labyrinth; import ru.justnero.study.s6.cg.e4.main.Parallelogram; import ru.justnero.study.s6.cg.e4.main.Quad; import ru.justnero.study.s6.cg.e4.main.Trapeze; import ru.justnero.study.s6.cg.e4.util.TransformMatrix; import ru.justnero.study.s6.cg.e4.util.Vector2D; public class ShowForm extends JPanel { protected static final float speedScale = 400f; protected static final float sizeScale = 1000f; protected final TransformMatrix transformationMatrix = new TransformMatrix(); protected final AnimableQuad temp = new AnimableQuad(); protected final AnimableQuad origin = new AnimableQuad(); protected final Quad tempQuad = new Quad(); protected Animation animation; protected Animation animationVertex; protected Animation animationRotate; DropTargetListener dropTargetListener; float globalSpeedScale = 10e3f; private JPanel rootPanel; private JPanel showPanel; private JPanel inputPanel; private JPanel checkBoxPanel; private JPanel buttonPanel; private JButton btnStart; private JButton btnClear; private JCheckBox checkBoxFill; private JButton btnPause; private JTabbedPane tabbedPane1; private JSlider sliderGlobaalSpeed; private JLabel lblRhombus; private JLabel lblTrapeze; private JColorChooser colorChooser; private JSlider sliderMoveSpeed; private JSlider sliderAngle; private JSlider sliderSize; private JLabel lblLabyrinth; private JLabel lblClipBox; // protected final AnimableVector3f vertexE; private ButtonGroup buttonGroup = new ButtonGroup(); private ButtonGroup buttonGroup2 = new ButtonGroup(); private Lab4Scene scene; private Main jogl; private GLCanvas canvas; // private ImageIcon parallelogram; private ImageIcon parallelogram = new ImageIcon("resource/parallelogram.png"); private ImageIcon trapeze = new ImageIcon("resource/trapeze.png"); private ImageIcon labyrinth = new ImageIcon("resource/labyrinth.png"); private ImageIcon clipBox = new ImageIcon("resource/clipBox.png"); public ShowForm() { super(); colorChooser.setColor(Color.white); // TransferHandler transferHandler = new TransferHandler("icon"); // transferHandler.setDragImage(new ImageIcon("plain.jpg").getImage()); int iconSize = 64; Image temp = parallelogram.getImage(); temp = temp.getScaledInstance(iconSize, iconSize, java.awt.Image.SCALE_SMOOTH); parallelogram.setImage(temp); temp = trapeze.getImage(); temp = temp.getScaledInstance(iconSize, iconSize, java.awt.Image.SCALE_SMOOTH); trapeze.setImage(temp); labyrinth.setImage(labyrinth.getImage().getScaledInstance(iconSize, iconSize, java.awt.Image.SCALE_SMOOTH)); clipBox.setImage(clipBox.getImage().getScaledInstance(iconSize, iconSize, java.awt.Image.SCALE_SMOOTH)); lblRhombus.setIcon(parallelogram); lblTrapeze.setIcon(trapeze); lblLabyrinth.setIcon(labyrinth); lblClipBox.setIcon(clipBox); dropTargetListener = new DropTargetListener(showPanel, scene); Supplier<Vector2D> velocityGetter = () -> { int angle = sliderAngle.getValue(); int speed = sliderMoveSpeed.getValue(); Vector2D velocity = new Vector2D( (float) Math.cos(Math.toRadians(angle)), (float) Math.sin(Math.toRadians(angle))); velocity.multiply(speed / speedScale); return velocity; }; DragSource ds = new DragSource(); ds.createDefaultDragGestureRecognizer(lblRhombus.getParent(), DnDConstants.ACTION_COPY, new DragListener( (this::createQuad), Figure.PARALLELOGRAM, velocityGetter)); ds = new DragSource(); ds.createDefaultDragGestureRecognizer(lblTrapeze.getParent(), DnDConstants.ACTION_COPY, new DragListener( (this::createQuad), Figure.TRAPEZE, velocityGetter)); ds = new DragSource(); ds.createDefaultDragGestureRecognizer(lblLabyrinth.getParent(), DnDConstants.ACTION_COPY, new DragListener( (this::createQuad), Figure.LABYRINTH, velocityGetter)); ds = new DragSource(); ds.createDefaultDragGestureRecognizer(lblClipBox.getParent(), DnDConstants.ACTION_COPY, new DragListener( (this::createQuad), Figure.CLIP_BOX, velocityGetter)); addListeners(); add(rootPanel); } public static void main(String[] args) { JOptionPane.showMessageDialog(null, new ShowForm(), "Лабораторная работа 4", JOptionPane.PLAIN_MESSAGE); } private void createUIComponents() { canvas = Main.createCanvas(); jogl = (Main) canvas.getGLEventListener(0); scene = jogl.getScene(); new Thread(() -> { while (true) { canvas.repaint(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); showPanel = new JPanel(new GridLayout(1, 1)); showPanel.add(canvas); } protected Quad createQuad(Figure figure) { Quad resultFigure = null; switch (figure) { case PARALLELOGRAM: resultFigure = new Parallelogram(); break; case TRAPEZE: resultFigure = new Trapeze(); break; case LABYRINTH: resultFigure = new Labyrinth(); break; case CLIP_BOX: resultFigure = new ClipBox(); break; } transformationMatrix.scale(sliderSize.getValue() / sizeScale, sliderSize.getValue() / sizeScale, ((figure == Figure.LABYRINTH || figure == Figure.CLIP_BOX) ? 0.5f : 1f)); resultFigure.setResult(tempQuad); resultFigure.transform(transformationMatrix); resultFigure.applyChange(); resultFigure.setColor(colorChooser.getColor()); return resultFigure; } private void addListeners() { btnStart.addActionListener(l -> { scene.setAnimation(true); }); btnPause.addActionListener(l -> { scene.setAnimation(false); }); btnClear.addActionListener(l -> { scene.clear(); }); sliderGlobaalSpeed.addChangeListener(l -> { scene.getGlobalParameters().value = sliderGlobaalSpeed.getValue() / globalSpeedScale; }); checkBoxFill.addChangeListener(l -> { scene.getGlobalParameters().fill = checkBoxFill.isSelected(); }); } public enum Figure { PARALLELOGRAM, TRAPEZE, CLIP_BOX, LABYRINTH } }
mit
jamesporter/MPofTheDay
cordovaMP/platforms/android/gen/org/complexview/mps/R.java
617
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package org.complexview.mps; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; public static final int notif=0x7f020001; } public static final class string { public static final int app_name=0x7f040000; } public static final class xml { public static final int config=0x7f030000; } }
mit
MummyDing/YM-Mobile-Security-Manager
src/main/java/com/github/mummyding/ymsecurity/view/YMMainItem.java
1809
package com.github.mummyding.ymsecurity.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.support.v7.widget.CardView; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.github.mummyding.ymsecurity.R; /** * Created by MummyDing on 2017/3/23. */ public class YMMainItem extends LinearLayout implements IView { private ImageView mItemImage; private TextView mItemName; public YMMainItem(Context context) { this(context, null); } public YMMainItem(Context context, AttributeSet attrs) { this(context, attrs, 0); } public YMMainItem(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutInflater.from(context).inflate(R.layout.item_main, this); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.YMMainItem, defStyleAttr, 0); initView(a); } private void initView(TypedArray a) { int src = a.getResourceId(R.styleable.YMMainItem_mi_src, 0); String name = a.getString(R.styleable.YMMainItem_mi_text); int color = a.getColor(R.styleable.YMMainItem_mi_backgroundColor, Color.WHITE); mItemImage = (ImageView) findViewById(R.id.item_image); mItemName = (TextView) findViewById(R.id.item_name); if (src != 0) { mItemImage.setBackgroundResource(src); } ((CardView)findViewById(R.id.card_view)).setCardBackgroundColor(color); mItemName.setText(name); } @Override public void bindViewModel(Object viewModel) { } @Override public void update() { } }
mit
JabRef/jabref
src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModel.java
10835
package org.jabref.gui.fieldeditors; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.jabref.gui.DialogService; import org.jabref.gui.autocompleter.SuggestionProvider; import org.jabref.gui.externalfiles.AutoSetFileLinksUtil; import org.jabref.gui.externalfiletype.CustomExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.externalfiletype.UnknownExternalFileType; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.BindingsHelper; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.bibtex.FileFieldWriter; import org.jabref.logic.importer.FulltextFetchers; import org.jabref.logic.importer.util.FileFieldParser; import org.jabref.logic.integrity.FieldCheckers; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.field.Field; import org.jabref.model.util.FileHelper; import org.jabref.preferences.PreferencesService; public class LinkedFilesEditorViewModel extends AbstractEditorViewModel { private final ListProperty<LinkedFileViewModel> files = new SimpleListProperty<>(FXCollections.observableArrayList(LinkedFileViewModel::getObservables)); private final BooleanProperty fulltextLookupInProgress = new SimpleBooleanProperty(false); private final DialogService dialogService; private final BibDatabaseContext databaseContext; private final TaskExecutor taskExecutor; private final PreferencesService preferences; private final ExternalFileTypes externalFileTypes = ExternalFileTypes.getInstance(); public LinkedFilesEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, DialogService dialogService, BibDatabaseContext databaseContext, TaskExecutor taskExecutor, FieldCheckers fieldCheckers, PreferencesService preferences) { super(field, suggestionProvider, fieldCheckers); this.dialogService = dialogService; this.databaseContext = databaseContext; this.taskExecutor = taskExecutor; this.preferences = preferences; BindingsHelper.bindContentBidirectional( files, text, LinkedFilesEditorViewModel::getStringRepresentation, this::parseToFileViewModel); } private static String getStringRepresentation(List<LinkedFileViewModel> files) { // Only serialize linked files, not the ones that are automatically found List<LinkedFile> filesToSerialize = files.stream() .filter(file -> !file.isAutomaticallyFound()) .map(LinkedFileViewModel::getFile) .collect(Collectors.toList()); return FileFieldWriter.getStringRepresentation(filesToSerialize); } /** * Creates an instance of {@link LinkedFile} based on the given file. * We try to guess the file type and relativize the path against the given file directories. * * TODO: Move this method to {@link LinkedFile} as soon as {@link CustomExternalFileType} lives in model. */ public static LinkedFile fromFile(Path file, List<Path> fileDirectories, ExternalFileTypes externalFileTypesFile) { String fileExtension = FileHelper.getFileExtension(file).orElse(""); ExternalFileType suggestedFileType = externalFileTypesFile .getExternalFileTypeByExt(fileExtension) .orElse(new UnknownExternalFileType(fileExtension)); Path relativePath = FileUtil.relativize(file, fileDirectories); return new LinkedFile("", relativePath, suggestedFileType.getName()); } public LinkedFileViewModel fromFile(Path file) { List<Path> fileDirectories = databaseContext.getFileDirectories(preferences.getFilePreferences()); LinkedFile linkedFile = fromFile(file, fileDirectories, externalFileTypes); return new LinkedFileViewModel( linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences, externalFileTypes); } public boolean isFulltextLookupInProgress() { return fulltextLookupInProgress.get(); } private List<LinkedFileViewModel> parseToFileViewModel(String stringValue) { return FileFieldParser.parse(stringValue).stream() .map(linkedFile -> new LinkedFileViewModel( linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences, externalFileTypes)) .collect(Collectors.toList()); } public ObservableList<LinkedFileViewModel> getFiles() { return files.get(); } public ListProperty<LinkedFileViewModel> filesProperty() { return files; } public void addNewFile() { Path workingDirectory = databaseContext.getFirstExistingFileDir(preferences.getFilePreferences()) .orElse(preferences.getFilePreferences().getWorkingDirectory()); FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .withInitialDirectory(workingDirectory) .build(); List<Path> fileDirectories = databaseContext.getFileDirectories(preferences.getFilePreferences()); dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(newFile -> { LinkedFile newLinkedFile = fromFile(newFile, fileDirectories, externalFileTypes); files.add(new LinkedFileViewModel( newLinkedFile, entry, databaseContext, taskExecutor, dialogService, preferences, externalFileTypes)); }); } @Override public void bindToEntry(BibEntry entry) { super.bindToEntry(entry); if (entry != null) { BackgroundTask<List<LinkedFileViewModel>> findAssociatedNotLinkedFiles = BackgroundTask .wrap(() -> findAssociatedNotLinkedFiles(entry)) .onSuccess(files::addAll); taskExecutor.execute(findAssociatedNotLinkedFiles); } } /** * Find files that are probably associated to the given entry but not yet linked. */ private List<LinkedFileViewModel> findAssociatedNotLinkedFiles(BibEntry entry) { List<LinkedFileViewModel> result = new ArrayList<>(); AutoSetFileLinksUtil util = new AutoSetFileLinksUtil( databaseContext, preferences.getFilePreferences(), preferences.getAutoLinkPreferences(), ExternalFileTypes.getInstance()); try { List<LinkedFile> linkedFiles = util.findAssociatedNotLinkedFiles(entry); for (LinkedFile linkedFile : linkedFiles) { LinkedFileViewModel newLinkedFile = new LinkedFileViewModel( linkedFile, entry, databaseContext, taskExecutor, dialogService, preferences, externalFileTypes); newLinkedFile.markAsAutomaticallyFound(); result.add(newLinkedFile); } } catch (IOException e) { dialogService.showErrorDialogAndWait("Error accessing the file system", e); } return result; } public void fetchFulltext() { FulltextFetchers fetcher = new FulltextFetchers(preferences.getImportFormatPreferences()); BackgroundTask .wrap(() -> fetcher.findFullTextPDF(entry)) .onRunning(() -> fulltextLookupInProgress.setValue(true)) .onFinished(() -> fulltextLookupInProgress.setValue(false)) .onSuccess(url -> { if (url.isPresent()) { addFromURL(url.get()); } else { dialogService.notify(Localization.lang("No full text document found")); } }) .executeWith(taskExecutor); } public void addFromURL() { Optional<String> urlText = dialogService.showInputDialogAndWait( Localization.lang("Download file"), Localization.lang("Enter URL to download")); if (urlText.isPresent()) { try { URL url = new URL(urlText.get()); addFromURL(url); } catch (MalformedURLException exception) { dialogService.showErrorDialogAndWait( Localization.lang("Invalid URL"), exception); } } } private void addFromURL(URL url) { LinkedFileViewModel onlineFile = new LinkedFileViewModel( new LinkedFile(url, ""), entry, databaseContext, taskExecutor, dialogService, preferences, externalFileTypes); files.add(onlineFile); onlineFile.download(); } public void deleteFile(LinkedFileViewModel file) { if (file.getFile().isOnlineLink()) { removeFileLink(file); } else { boolean deleteSuccessful = file.delete(); if (deleteSuccessful) { files.remove(file); } } } public void removeFileLink(LinkedFileViewModel file) { files.remove(file); } }
mit
mistankovic/fer-tiger
src/main/java/hr/fer/zari/rasip/tiger/service/impl/UserRoleServiceImpl.java
1990
package hr.fer.zari.rasip.tiger.service.impl; import hr.fer.zari.rasip.tiger.dao.jpa.UserRoleRepository; import hr.fer.zari.rasip.tiger.domain.AppUser; import hr.fer.zari.rasip.tiger.domain.UserRole; import hr.fer.zari.rasip.tiger.rest.model.UserRoleRestModel; import hr.fer.zari.rasip.tiger.service.UserRoleService; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserRoleServiceImpl implements UserRoleService { private UserRoleRepository userRoleRepository; @Autowired public UserRoleServiceImpl(UserRoleRepository userRoleRepository) { this.userRoleRepository = userRoleRepository; } @Override public UserRole getByName(String name) { return userRoleRepository.findByName(name); } @Override public Collection<UserRole> getAll() { Iterable<UserRole> all = userRoleRepository.findAll(); if (all instanceof Collection) { return (Collection<UserRole>) all; } Collection<UserRole> roles = new HashSet<>(); for (UserRole userRole : all) { roles.add(userRole); } return roles; } @Override public UserRole save(UserRole userRole) { return userRoleRepository.save(userRole); } @Override public Collection<UserRoleRestModel> convert(Collection<UserRole> roles) { Set<UserRoleRestModel> models = new LinkedHashSet<>(roles.size()); for (UserRole userRole : roles) { models.add(convert(userRole)); } return models; } private UserRoleRestModel convert(UserRole role) { return new UserRoleRestModel(role.getName(), role.getDescription()); } @Override public boolean hasAppUserRoleWithName(AppUser appUser, String userRoleName) { boolean hasRoleWithName = false; for (UserRole role : appUser.getRoles()) { if(role.getName().equals(userRoleName)){ hasRoleWithName = true; break; } } return hasRoleWithName; } }
mit
caelum/tubaina
src/main/java/br/com/caelum/tubaina/chunk/NoteChunk.java
339
package br.com.caelum.tubaina.chunk; import java.util.List; import br.com.caelum.tubaina.Chunk; import br.com.caelum.tubaina.CompositeChunk; public class NoteChunk extends CompositeChunk<NoteChunk> { private final List<Chunk> title; public NoteChunk(List<Chunk> title, List<Chunk> body) { super(body); this.title = title; } }
mit
camsys/onebusaway-siri-api-v20
src/main/java/eu/datex2/schema/_2_0rc1/_2_0/RoadsideReferencePoint.java
10362
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // 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: 2014.11.22 at 01:45:09 PM EST // package eu.datex2.schema._2_0rc1._2_0; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for RoadsideReferencePoint complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="RoadsideReferencePoint"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="roadsideReferencePointIdentifier" type="{http://datex2.eu/schema/2_0RC1/2_0}String"/> * &lt;element name="administrativeArea" type="{http://datex2.eu/schema/2_0RC1/2_0}MultilingualString" minOccurs="0"/> * &lt;element name="roadName" type="{http://datex2.eu/schema/2_0RC1/2_0}MultilingualString" minOccurs="0"/> * &lt;element name="roadNumber" type="{http://datex2.eu/schema/2_0RC1/2_0}String" minOccurs="0"/> * &lt;element name="directionBound" type="{http://datex2.eu/schema/2_0RC1/2_0}DirectionEnum" minOccurs="0"/> * &lt;element name="directionRelative" type="{http://datex2.eu/schema/2_0RC1/2_0}ReferencePointDirectionEnum" minOccurs="0"/> * &lt;element name="distanceFromPrevious" type="{http://datex2.eu/schema/2_0RC1/2_0}MetresAsFloat" minOccurs="0"/> * &lt;element name="distanceToNext" type="{http://datex2.eu/schema/2_0RC1/2_0}MetresAsFloat" minOccurs="0"/> * &lt;element name="elevatedRoadSection" type="{http://datex2.eu/schema/2_0RC1/2_0}Boolean" minOccurs="0"/> * &lt;element name="roadsideReferencePointDescription" type="{http://datex2.eu/schema/2_0RC1/2_0}MultilingualString" minOccurs="0"/> * &lt;element name="roadsideReferencePointDistance" type="{http://datex2.eu/schema/2_0RC1/2_0}MetresAsFloat" minOccurs="0"/> * &lt;element name="roadsideReferencePointExtension" type="{http://datex2.eu/schema/2_0RC1/2_0}ExtensionType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RoadsideReferencePoint", propOrder = { "roadsideReferencePointIdentifier", "administrativeArea", "roadName", "roadNumber", "directionBound", "directionRelative", "distanceFromPrevious", "distanceToNext", "elevatedRoadSection", "roadsideReferencePointDescription", "roadsideReferencePointDistance", "roadsideReferencePointExtension" }) public class RoadsideReferencePoint { @XmlElement(required = true) protected String roadsideReferencePointIdentifier; protected MultilingualString administrativeArea; protected MultilingualString roadName; protected String roadNumber; protected DirectionEnum directionBound; protected ReferencePointDirectionEnum directionRelative; protected Float distanceFromPrevious; protected Float distanceToNext; protected Boolean elevatedRoadSection; protected MultilingualString roadsideReferencePointDescription; protected Float roadsideReferencePointDistance; protected ExtensionType roadsideReferencePointExtension; /** * Gets the value of the roadsideReferencePointIdentifier property. * * @return * possible object is * {@link String } * */ public String getRoadsideReferencePointIdentifier() { return roadsideReferencePointIdentifier; } /** * Sets the value of the roadsideReferencePointIdentifier property. * * @param value * allowed object is * {@link String } * */ public void setRoadsideReferencePointIdentifier(String value) { this.roadsideReferencePointIdentifier = value; } /** * Gets the value of the administrativeArea property. * * @return * possible object is * {@link MultilingualString } * */ public MultilingualString getAdministrativeArea() { return administrativeArea; } /** * Sets the value of the administrativeArea property. * * @param value * allowed object is * {@link MultilingualString } * */ public void setAdministrativeArea(MultilingualString value) { this.administrativeArea = value; } /** * Gets the value of the roadName property. * * @return * possible object is * {@link MultilingualString } * */ public MultilingualString getRoadName() { return roadName; } /** * Sets the value of the roadName property. * * @param value * allowed object is * {@link MultilingualString } * */ public void setRoadName(MultilingualString value) { this.roadName = value; } /** * Gets the value of the roadNumber property. * * @return * possible object is * {@link String } * */ public String getRoadNumber() { return roadNumber; } /** * Sets the value of the roadNumber property. * * @param value * allowed object is * {@link String } * */ public void setRoadNumber(String value) { this.roadNumber = value; } /** * Gets the value of the directionBound property. * * @return * possible object is * {@link DirectionEnum } * */ public DirectionEnum getDirectionBound() { return directionBound; } /** * Sets the value of the directionBound property. * * @param value * allowed object is * {@link DirectionEnum } * */ public void setDirectionBound(DirectionEnum value) { this.directionBound = value; } /** * Gets the value of the directionRelative property. * * @return * possible object is * {@link ReferencePointDirectionEnum } * */ public ReferencePointDirectionEnum getDirectionRelative() { return directionRelative; } /** * Sets the value of the directionRelative property. * * @param value * allowed object is * {@link ReferencePointDirectionEnum } * */ public void setDirectionRelative(ReferencePointDirectionEnum value) { this.directionRelative = value; } /** * Gets the value of the distanceFromPrevious property. * * @return * possible object is * {@link Float } * */ public Float getDistanceFromPrevious() { return distanceFromPrevious; } /** * Sets the value of the distanceFromPrevious property. * * @param value * allowed object is * {@link Float } * */ public void setDistanceFromPrevious(Float value) { this.distanceFromPrevious = value; } /** * Gets the value of the distanceToNext property. * * @return * possible object is * {@link Float } * */ public Float getDistanceToNext() { return distanceToNext; } /** * Sets the value of the distanceToNext property. * * @param value * allowed object is * {@link Float } * */ public void setDistanceToNext(Float value) { this.distanceToNext = value; } /** * Gets the value of the elevatedRoadSection property. * * @return * possible object is * {@link Boolean } * */ public Boolean isElevatedRoadSection() { return elevatedRoadSection; } /** * Sets the value of the elevatedRoadSection property. * * @param value * allowed object is * {@link Boolean } * */ public void setElevatedRoadSection(Boolean value) { this.elevatedRoadSection = value; } /** * Gets the value of the roadsideReferencePointDescription property. * * @return * possible object is * {@link MultilingualString } * */ public MultilingualString getRoadsideReferencePointDescription() { return roadsideReferencePointDescription; } /** * Sets the value of the roadsideReferencePointDescription property. * * @param value * allowed object is * {@link MultilingualString } * */ public void setRoadsideReferencePointDescription(MultilingualString value) { this.roadsideReferencePointDescription = value; } /** * Gets the value of the roadsideReferencePointDistance property. * * @return * possible object is * {@link Float } * */ public Float getRoadsideReferencePointDistance() { return roadsideReferencePointDistance; } /** * Sets the value of the roadsideReferencePointDistance property. * * @param value * allowed object is * {@link Float } * */ public void setRoadsideReferencePointDistance(Float value) { this.roadsideReferencePointDistance = value; } /** * Gets the value of the roadsideReferencePointExtension property. * * @return * possible object is * {@link ExtensionType } * */ public ExtensionType getRoadsideReferencePointExtension() { return roadsideReferencePointExtension; } /** * Sets the value of the roadsideReferencePointExtension property. * * @param value * allowed object is * {@link ExtensionType } * */ public void setRoadsideReferencePointExtension(ExtensionType value) { this.roadsideReferencePointExtension = value; } }
mit
novirael/school-codebase
java/algorithms/src/lists3/Iterators/LinkedListIterator.java
769
package lists3.Iterators; import lists3.LinkedList; public class LinkedListIterator implements Iterator { private LinkedList singleLinkedList; private int current = -1; private int first; private int last; public LinkedListIterator(LinkedList linkedList) { this.singleLinkedList = linkedList; first = 0; last = linkedList.size() - 1; } @Override public void next() { current++; } @Override public boolean isDone() { return current < first || current > last; } @Override public void first() { current = first; } @Override public void last() { current = last; } @Override public Object current() throws IndexOutOfBoundsException { return singleLinkedList.get(current); } @Override public void previous() { current--; } }
mit
PATRONAS/opuxl
demos/java/src/main/java/de/patronas/opus/opuxl/server/ExcelType.java
651
/******************************************************************************* * Copyright 2016 PATRONAS Financial Systems GmbH. All rights reserved. ******************************************************************************/ package de.patronas.opus.opuxl.server; /** * @author stepan */ public enum ExcelType { CURRENCY("currency"), // SQL Numerical DATETIME("datetime"), // SQL Timestamp LOGICAL("logical"), // SQL Bit NUMBER("number"), // SQL Double TEXT("text"); // SQL Varchar private final String type; private ExcelType(final String type) { this.type = type; } public String get() { return type; } }
mit
xgp/kannel-java
protocol/src/main/java/org/kannel/protocol/gateway/KannelGateway.java
4375
package org.kannel.protocol.gateway; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import org.kannel.protocol.exceptions.NotEnoughPropertiesException; import org.kannel.protocol.exceptions.WrongPropertieException; import org.kannel.protocol.kbinds.KannelBinding; /** * Base class for creating Kannel gateways. * * @author garth */ public class KannelGateway extends Thread { public static final String props_inBound = "kjGateway.inBound"; public static final String props_outBound = "kjGateway.outBound"; protected boolean inBoundThreadOn = true; protected boolean outBoundThreadOn = true; protected Properties properties = null; protected KannelBinding kannelBind = null; protected KjWritingThread outBoundThread = null; protected KjReadingThread inBoundThread = null; protected AckCycleThread ackAdminThread = null; protected long ackTTL = 0; protected long ackFrecuency = 0; public KannelGateway() {} public KannelGateway(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { parseArgs(args); } private void parseArgs(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { if (args.length < 1) { throw new IllegalArgumentException(); } else { this.properties = new Properties(); this.properties.load(new FileInputStream(new File(args[0]))); String swap = this.properties.getProperty(this.props_inBound); if (swap.equalsIgnoreCase("true")) { this.inBoundThreadOn = true; } else { this.inBoundThreadOn = false; } swap = this.properties.getProperty(this.props_outBound); if (swap.equalsIgnoreCase("true")) { this.outBoundThreadOn = true; } else { this.outBoundThreadOn = false; } // ack ttl swap = this.properties.getProperty(AckCycleThread.prop_waitForAckTTL); ackTTL = Long.parseLong(swap); // ack frecuency swap = this.properties.getProperty(AckCycleThread.prop_acknowledgementCycleRate); ackFrecuency = Long.parseLong(swap); } } public void terminate() {} public void run() { try { if (this.kannelBind == null) { this.kannelBind = new KannelBinding(this.properties); } else if (!this.kannelBind.isConnected()) { this.kannelBind.connect(); } if (this.ackAdminThread == null) { this.ackAdminThread = new AckCycleThread(this.outBoundThread, ackFrecuency); this.ackAdminThread.setAckTTL(ackTTL); } this.ackAdminThread.start(); // Start reading thread if (this.inBoundThreadOn) { this.inBoundThread.addAckCycleThread(this.ackAdminThread); this.inBoundThread.start(); } // Start writing thread if (this.outBoundThreadOn) { this.outBoundThread.addAckCycleThread(this.ackAdminThread); this.outBoundThread.start(); } } catch (NotEnoughPropertiesException e) { // } catch (WrongPropertieException e) { // } catch (IOException e) { // } } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public KannelBinding getKannelBind() { return kannelBind; } public void setKannelBind(KannelBinding kannelBind) { this.kannelBind = kannelBind; } public KjWritingThread getOutBoundThread() { return outBoundThread; } public void setOutBoundThread(KjWritingThread outBoundThread) { this.outBoundThread = outBoundThread; } public boolean getOutBoundThreadOn() { return outBoundThreadOn; } public void setOutBoundThreadOn(boolean outBoundThreadOn) { this.outBoundThreadOn = outBoundThreadOn; } public KjReadingThread getInBoundThread() { return inBoundThread; } public void setInBoundThread(KjReadingThread inBoundThread) { this.inBoundThread = inBoundThread; } public boolean getInBoundThreadOn() { return inBoundThreadOn; } public void setInBoundThreadOn(boolean inBoundThreadOn) { this.inBoundThreadOn = inBoundThreadOn; } }
mit
harrietrc/Mapster
app/src/main/java/com/mapster/places/autocomplete/AutoCompletePlaces.java
3667
package com.mapster.places.autocomplete; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; /** * Created by tommyngo on 19/03/15. */ public class AutoCompletePlaces { private static final String LOG_TAG = "Mapster"; private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place"; private static final String TYPE_AUTOCOMPLETE = "/autocomplete"; private static final String OUT_JSON = "/json"; private String _apiKey; public AutoCompletePlaces(String apiKey) { this._apiKey = apiKey; } public ArrayList<String> autocomplete(String input) { HttpURLConnection conn = null; ArrayList<String> resultList = null; StringBuilder jsonResults; URL url = null; InputStreamReader in = null; try { StringBuilder sb = formURLString(input); try { url = new URL(sb.toString()); conn = (HttpURLConnection) url.openConnection(); in = new InputStreamReader(conn.getInputStream()); } catch (MalformedURLException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } jsonResults = convertJsonResultsToStringBuilder(in); resultList = extractPlaceDescriptionsFromResults(jsonResults); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Error processing Places API URL", e); return resultList; } catch (IOException e) { Log.e(LOG_TAG, "Error connecting to Places API", e); return resultList; } finally { if (conn != null) { conn.disconnect(); } } return resultList; } private StringBuilder formURLString(String input){ StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON); try { sb.append("?input=" + URLEncoder.encode(input, "utf8")); sb.append("&key=" + _apiKey); } catch (UnsupportedEncodingException e){ e.printStackTrace(); } return sb; } private StringBuilder convertJsonResultsToStringBuilder(InputStreamReader in) throws IOException{ StringBuilder jsonResults = new StringBuilder(); int read; char[] buff = new char[1024]; while ((read = in.read(buff)) != -1) { jsonResults.append(buff, 0, read); } return jsonResults; } private ArrayList<String> extractPlaceDescriptionsFromResults(StringBuilder jsonResults) { ArrayList<String> resultList = null; try { // Create a JSON object hierarchy from the results JSONObject jsonObj = new JSONObject(jsonResults.toString()); JSONArray predsJsonArray = jsonObj.getJSONArray("predictions"); // Extract the Place descriptions from the results resultList = new ArrayList<String>(predsJsonArray.length()); for (int i = 0; i < predsJsonArray.length(); i++) { resultList.add(predsJsonArray.getJSONObject(i).getString("description")); } } catch (JSONException e) { Log.e(LOG_TAG, "Cannot process JSON results", e); } return resultList; } }
mit
luisparravicini/caliboro
src/main/java/ar/com/ktulu/caliboro/ui/MainFrame.java
13850
package ar.com.ktulu.caliboro.ui; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.FileDialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.net.URISyntaxException; import javax.swing.DropMode; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSplitPane; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import ar.com.ktulu.caliboro.BonesStore; import ar.com.ktulu.caliboro.Exporter; import ar.com.ktulu.caliboro.Previewer; import ar.com.ktulu.caliboro.model.Bone; import ar.com.ktulu.caliboro.model.BoneImage; import ar.com.ktulu.caliboro.ui.dnd.BonesTransferHandler; import ar.com.ktulu.caliboro.ui.images.ImageException; import ar.com.ktulu.caliboro.ui.images.ImageManager; import ar.com.ktulu.caliboro.ui.images.ImageMouseListener; import ar.com.ktulu.caliboro.ui.images.ImageView; import ar.com.ktulu.caliboro.ui.treeModel.BaseBoneTreeNode; import ar.com.ktulu.caliboro.ui.treeModel.BoneImageTreeNode; import ar.com.ktulu.caliboro.ui.treeModel.BoneTreeNode; @SuppressWarnings("serial") public class MainFrame extends JFrame implements TreeModelListener, TreeSelectionListener { private JPanel contentPane; private JTree bonesTree; private JToolBar toolBar; private JButton btnAgregar; private JScrollPane scrollPane; private JButton btnAddImages; private JButton btnRemove; private JButton btnBonePoints; private boolean bonePointAdding = true; private JButton btnExportar; private JButton btnPrevisualizar; private JPanel panel; private JPanel panel_1; private ImageManager imageManager; private JButton btnAbrir; /** * Launch the application. */ public static void main(String[] args) { MainFrame.startup(); } public static void startup() { EventQueue.invokeLater(new Runnable() { public void run() { EventQueueErrorCatcher.install(); try { MainFrame frame = new MainFrame(); frame.setInitialStoreFolder(); BonesStore.getInstance().load(); frame.setup(); frame.setVisible(true); } catch (Exception e) { EventQueueErrorCatcher.logError(e); } } }); } private void setInitialStoreFolder() { File path; while ((path = Util.askForFolder()) == null) { JOptionPane.showMessageDialog(null, "Debe seleccionar una carpeta para guardar los datos", null, JOptionPane.INFORMATION_MESSAGE); } BonesStore.getInstance().setPath(path); } /** * Create the frame. */ public MainFrame() { imageManager = new ImageManager(this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 578, 337); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JSplitPane splitPane = new JSplitPane(); splitPane.setDividerLocation(180); contentPane.add(splitPane, BorderLayout.CENTER); bonesTree = new JTree(); bonesTree.setShowsRootHandles(true); JScrollPane bonesScrollPane = new JScrollPane(); bonesScrollPane.setViewportView(bonesTree); splitPane.setLeftComponent(bonesScrollPane); panel = new JPanel(); splitPane.setRightComponent(panel); panel.setLayout(new BorderLayout(0, 0)); panel_1 = new JPanel(); panel.add(panel_1, BorderLayout.SOUTH); panel_1.setLayout(new BorderLayout(0, 0)); imageManager.imageInfo = new JLabel(); panel_1.add(imageManager.imageInfo, BorderLayout.WEST); JSlider imageZoom = new JSlider(); imageZoom.setToolTipText("Nivel de zoom de la imagen"); imageZoom.setMaximum(150); imageZoom.setMinimum(20); imageZoom.setValue(100); imageZoom.setMajorTickSpacing(10); imageZoom.setSnapToTicks(true); imageZoom.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent event) { imageManager.sliderChangedValue(); } }); panel_1.add(imageZoom, BorderLayout.EAST); imageManager.imageZoom = imageZoom; scrollPane = new JScrollPane(); panel.add(scrollPane); imageManager.imageView = new ImageView(); scrollPane.setViewportView(imageManager.imageView); toolBar = new JToolBar(); contentPane.add(toolBar, BorderLayout.NORTH); btnAbrir = new JButton("Abrir"); toolBar.add(btnAbrir); btnAbrir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { openData(); } }); btnAgregar = new JButton("Agregar hueso"); toolBar.add(btnAgregar); btnRemove = new JButton("Borrar"); btnRemove.setEnabled(false); toolBar.add(btnRemove); btnAddImages = new JButton("Agregar fotos"); btnAddImages.setEnabled(false); toolBar.add(btnAddImages); btnBonePoints = new JButton(getBonePointButtonLabel()); toolBar.add(btnBonePoints); btnExportar = new JButton("Exportar"); toolBar.add(btnExportar); btnExportar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { export(); } }); btnPrevisualizar = new JButton("Previsualizar"); toolBar.add(btnPrevisualizar); btnPrevisualizar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { preview(); } }); btnBonePoints.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { bonePointAdding = !bonePointAdding; btnBonePoints.setText(getBonePointButtonLabel()); } }); btnAgregar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { addBone(); } }); btnAddImages.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addBoneImages(); } }); btnRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { removeNode(); } }); imageManager.hideImage(); } protected void openData() { File path = Util.askForFolder(); if (path != null) { BonesStore store = BonesStore.getInstance(); store.setPath(path); store.load(); loadBones(); imageManager.hideImage(); } } protected void export() { Exporter exporter = new Exporter(); try { File exportPath = Util.askForFolder(); if (exportPath == null) return; BonesStore store = BonesStore.getInstance(); exporter.export(exportPath, store.dataNode().getBones(), store.getPath()); // TODO mostrar un dialogo que diga que terminó // TODO abrir la carpeta donde se exporto // if (!Util.openFolder(exportPath)) // Util.showError("No se pudo abrir la carpeta de exportación"); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } protected void preview() { Previewer previewer = new Previewer(); try { BonesStore store = BonesStore.getInstance(); previewer.deploy(store.dataNode().getBones(), store.getPath()); String indexPath = previewer.getIndexPath(); if (!Util.open(indexPath)) Util.showError("No se pudo abrir el archivo de previsualizacion"); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } } private String getBonePointButtonLabel() { return "Puntos: " + (bonePointAdding ? "Agregar" : "Borrar"); } protected void setup() { bonesTree.setRootVisible(false); bonesTree.setModel(createTreeModel()); bonesTree.setEditable(true); bonesTree.addTreeSelectionListener(this); bonesTree.setDragEnabled(true); bonesTree.setDropMode(DropMode.ON); bonesTree.setTransferHandler(new BonesTransferHandler()); ImageMouseListener mouseListener = new ImageMouseListener(imageManager); scrollPane.addMouseListener(mouseListener); scrollPane.addMouseMotionListener(mouseListener); loadBones(); } private TreeModel createTreeModel() { DefaultTreeModel model = new DefaultTreeModel( new DefaultMutableTreeNode()); model.addTreeModelListener(this); return model; } private void loadBones() { bonesTree.setModel(createTreeModel()); BonesStore store = BonesStore.getInstance(); store.freeze(); try { for (Bone bone : BonesStore.getInstance().data()) addBone(bone); } finally { store.unfreeze(); } } protected void removeNode() { DefaultTreeModel model = (DefaultTreeModel) bonesTree.getModel(); TreePath[] selection = bonesTree.getSelectionPaths(); if (selection != null) { if (JOptionPane.showConfirmDialog(this, "¿está seguro de borrar los elementos seleccionados?", "Borrar", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) return; for (TreePath path : selection) { MutableTreeNode node = (MutableTreeNode) path .getLastPathComponent(); // TODO esta mal esto asi if (BaseBoneTreeNode.class.isInstance(node)) { TreeNode parent = node.getParent(); ((BaseBoneTreeNode) node).removeDataNode(); model.reload(parent); } } } } protected void addBoneImages() { FileDialog fileDlg = new FileDialog(this); fileDlg.setMode(FileDialog.LOAD); fileDlg.setFilenameFilter(new FilenameFilter() { @Override public boolean accept(File dir, String name) { boolean isFile = new File(dir, name).isFile(); return isFile && knownImageType(name); } }); fileDlg.setVisible(true); // TODO recien en jdk7 puedo seleccionar varios archivos a la vez String filename = fileDlg.getFile(); if (filename != null) { // en windows no corre la validacion de FilenameFilter, asi que // chequeo aca también if (!knownImageType(filename)) Util.showError("Tipo de imagen no reconocida"); else addBoneImage(new File(fileDlg.getDirectory(), filename)); } } private boolean knownImageType(String name) { name = name.toLowerCase(); final String[] accepted = { ".jpg", ".png", ".jpeg" }; for (String ext : accepted) if (name.endsWith(ext)) return true; return false; } private void addBoneImage(File filePath) { DefaultTreeModel model = (DefaultTreeModel) bonesTree.getModel(); TreePath path = bonesTree.getSelectionPath(); if (path != null) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path .getLastPathComponent(); if (isBoneImageNode(selectedNode)) selectedNode = (DefaultMutableTreeNode) selectedNode .getParent(); BoneTreeNode node = (BoneTreeNode) selectedNode; node.addBoneImage(filePath.getAbsolutePath()); model.reload(selectedNode); bonesTree.expandPath(path); } } protected void addBone() { addBone(new Bone("Nombre del hueso")); } private void addBone(Bone bone) { BoneTreeNode node = new BoneTreeNode(bone); DefaultTreeModel model = (DefaultTreeModel) bonesTree.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); root.add(node); model.reload(); } public void treeNodesChanged(TreeModelEvent e) { updateButtonsStatus((DefaultTreeModel) e.getSource()); } public void treeNodesInserted(TreeModelEvent e) { updateButtonsStatus((DefaultTreeModel) e.getSource()); } public void treeNodesRemoved(TreeModelEvent e) { updateButtonsStatus((DefaultTreeModel) e.getSource()); } public void treeStructureChanged(TreeModelEvent e) { updateButtonsStatus((DefaultTreeModel) e.getSource()); } private void updateButtonsStatus() { updateButtonsStatus((DefaultTreeModel) bonesTree.getModel()); } private void updateButtonsStatus(DefaultTreeModel model) { DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); boolean bonesExist = root.getChildCount() > 0; boolean boneSelected = (bonesTree.getSelectionCount() > 0); btnAddImages.setEnabled(bonesExist && boneSelected); btnRemove.setEnabled(bonesExist && boneSelected); } @Override public void valueChanged(TreeSelectionEvent event) { updateButtonsStatus(); updateBoneImageView(event.getPath()); } private void updateBoneImageView(TreePath path) { if (path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path .getLastPathComponent(); if (!isBoneImageNode(node)) { imageManager.hideImage(); updateButtonsStatus(); return; } BoneImageTreeNode imgNode = (BoneImageTreeNode) node; try { imageManager.loadBoneImage(imgNode); updateButtonsStatus(); } catch (ImageException e) { EventQueueErrorCatcher.logToFile(e); Util.showError(e.getMessage()); } } } private boolean isBoneImageNode(DefaultMutableTreeNode node) { return (BoneImageTreeNode.class.isInstance(node)); } public BoneImage getImageSelected() { BoneImage result = null; TreePath path = bonesTree.getSelectionPath(); if (path != null) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path .getLastPathComponent(); if (isBoneImageNode(selectedNode)) result = (BoneImage) selectedNode.getUserObject(); } return result; } public boolean isAddingPoints() { return bonePointAdding; } }
mit
jay006/SmartQLabs
app/src/main/java/com/example/joker/smartqlabs/ListAdapter.java
4928
package com.example.joker.smartqlabs; import android.content.Context; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.util.ArrayList; /** * Created by joker on 22/9/17. */ public class ListAdapter extends BaseAdapter { private static final String TAG = ListAdapter.class.getSimpleName(); private ArrayList<QueueModel> queues; private Context context; private Handler handler; private int lastPosition = -1; private EditContactDetailsCallBack callback; public ListAdapter(ArrayList<QueueModel> queues, Context context, Handler uihandler) { this.queues = queues; this.context = context; this.handler = uihandler; } @Override public int getCount() { return queues == null ? 0 : queues.size(); } @Override public Object getItem(int position) { return queues.size() == 0 ? null : queues.get(position); } @Override public long getItemId(int position) { return queues.get(position).hashCode(); } @Override public View getView(final int position, View convertView, final ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); viewHolder = new ViewHolder(); viewHolder.id = (TextView) convertView.findViewById(R.id.idTV); viewHolder.time = (TextView) convertView.findViewById(R.id.timeTV); viewHolder.qno = (TextView) convertView.findViewById(R.id.qnoTV); viewHolder.shopImage = (ImageView) convertView.findViewById(R.id.shopImgae); viewHolder.shop_name = (TextView) convertView.findViewById(R.id.shopName); viewHolder.shop_info = (TextView) convertView.findViewById(R.id.shopInfo); viewHolder.navBtn = (Button) convertView.findViewById(R.id.navBtn); viewHolder.cancleBtn = (Button) convertView.findViewById(R.id.cancelBtn); viewHolder.otpTV = (TextView)convertView.findViewById(R.id.otp_codeTV); viewHolder.qCodeTV = (TextView)convertView.findViewById(R.id.q_codeTV); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } //setting up the queue details to the card ,,,,,, viewHolder.id.setText("Counter No."+ queues.get(position).getCounter_no()); viewHolder.time.setText(queues.get(position).getTime() +"min left"); viewHolder.qno.setText(queues.get(position).getQueue_no()+"th position"); viewHolder.shop_name.setText(queues.get(position).getShop_name()); viewHolder.shop_info.setText(queues.get(position).getShop_info()); viewHolder.otpTV.setText("OTP: "+queues.get(position).getOtp()); viewHolder.qCodeTV.setText("Q-Code: "+queues.get(position).getqCode()); Glide.with(parent.getContext()) .load(queues.get(position).getUrl()) .crossFade() .diskCacheStrategy(DiskCacheStrategy.ALL) .into(viewHolder.shopImage); //on cancel button click viewHolder.cancleBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (callback != null) { callback.cancelQueue(queues.get(position)); } } }); viewHolder.navBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(callback!=null){ callback.navPlace(queues.get(position)); } } }); //for the animation of the list items. // Animation animation = AnimationUtils.loadAnimation(parent.getContext(), (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top); // convertView.startAnimation(animation); // lastPosition = position; return convertView; } public void setCallback(EditContactDetailsCallBack callback) { this.callback = callback; } //making an interface to update the ListAdapter interface EditContactDetailsCallBack { void cancelQueue(QueueModel contact); void navPlace(QueueModel contact); } //ViewHolder class private class ViewHolder { TextView id = null, shop_name = null, shop_info = null, time = null, qno = null,otpTV=null,qCodeTV; Button cancleBtn = null, navBtn = null; ImageView shopImage = null; } }
mit
ai-ku/langvis
src/edu/cmu/cs/stage3/alice/authoringtool/WorldTreeComponent.java
23697
/* * Copyright (c) 1999-2003, Carnegie Mellon University. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. Products derived from the software may not be called "Alice", * nor may "Alice" appear in their name, without prior written * permission of Carnegie Mellon University. * * 4. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes software developed by Carnegie Mellon University" */ package edu.cmu.cs.stage3.alice.authoringtool; import java.awt.*; import javax.swing.*; import javax.swing.border.*; import ai.ku.util.Palette; import edu.cmu.cs.stage3.util.StringObjectPair; /** * @author Jason Pratt */ public class WorldTreeComponent extends javax.swing.JPanel { /** * */ private static final long serialVersionUID = -1580076609121991922L; protected edu.cmu.cs.stage3.alice.core.World world; protected edu.cmu.cs.stage3.alice.core.Element bogusRoot = new edu.cmu.cs.stage3.alice.core.Transformable(); protected edu.cmu.cs.stage3.alice.authoringtool.util.WorldTreeModel worldTreeModel = new edu.cmu.cs.stage3.alice.authoringtool.util.WorldTreeModel(); protected edu.cmu.cs.stage3.alice.authoringtool.util.ElementTreeCellRenderer cellRenderer = new edu.cmu.cs.stage3.alice.authoringtool.util.ElementTreeCellRenderer(); protected edu.cmu.cs.stage3.alice.authoringtool.util.ElementTreeCellEditor cellEditor = new edu.cmu.cs.stage3.alice.authoringtool.util.ElementTreeCellEditor(); protected edu.cmu.cs.stage3.alice.core.Element selectedElement; protected edu.cmu.cs.stage3.alice.authoringtool.util.Configuration authoringtoolConfig; protected java.awt.dnd.DragSource dragSource = new java.awt.dnd.DragSource(); protected java.util.HashSet elementSelectionListeners = new java.util.HashSet(); protected WorldTreeDropTargetListener worldTreeDropTargetListener = new WorldTreeDropTargetListener(); protected AuthoringTool authoringTool; public WorldTreeComponent( AuthoringTool authoringTool ) { this.authoringTool = authoringTool; modelInit(); jbInit(); treeInit(); dndInit(); selectionInit(); } private void modelInit() { worldTreeModel.setRoot( bogusRoot ); } private void treeInit() { worldTree.setModel( worldTreeModel ); worldTree.addTreeSelectionListener( worldSelectionListener ); worldTree.setCellEditor( cellEditor ); worldTree.setCellRenderer( cellRenderer ); CustomTreeUI treeUI = new CustomTreeUI(); worldTree.setUI( treeUI ); worldTree.putClientProperty( "Tree.lineStyle", "Angled" ); worldTree.putClientProperty( "Tree.line", Color.black ); treeUI.setExpandedIcon( AuthoringToolResources.getIconForString( "minus" ) ); treeUI.setCollapsedIcon( AuthoringToolResources.getIconForString( "plus" ) ); worldTree.setEditable( true ); worldTree.addMouseListener( worldTreeMouseListener ); worldTree.addTreeWillExpandListener( new javax.swing.event.TreeWillExpandListener() { public void treeWillCollapse( javax.swing.event.TreeExpansionEvent ev ) throws javax.swing.tree.ExpandVetoException { if( ev.getPath().getLastPathComponent() == worldTreeModel.getRoot() ) { throw new javax.swing.tree.ExpandVetoException( ev ); } } public void treeWillExpand( javax.swing.event.TreeExpansionEvent ev ) {} } ); treeScrollPane.setBorder( null ); } private void dndInit() { dragSource.createDefaultDragGestureRecognizer( worldTree, java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE | java.awt.dnd.DnDConstants.ACTION_LINK, new ElementTreeDragGestureListener( worldTree ) ); worldTree.setDropTarget( new java.awt.dnd.DropTarget( worldTree, worldTreeDropTargetListener ) ); } private void selectionInit() { authoringTool.addElementSelectionListener( new edu.cmu.cs.stage3.alice.authoringtool.event.ElementSelectionListener() { public void elementSelected( edu.cmu.cs.stage3.alice.core.Element element ) { WorldTreeComponent.this.setSelectedElement( element ); } } ); } public void startListening( AuthoringTool authoringTool ) { authoringTool.addAuthoringToolStateListener( worldTreeModel ); } public edu.cmu.cs.stage3.alice.core.World getWorld() { return world; } public void setWorld( edu.cmu.cs.stage3.alice.core.World world ) { this.world = world; if( world == null ) { worldTreeModel.setRoot( bogusRoot ); setCurrentScope( bogusRoot ); } else { worldTreeModel.setRoot( world ); setCurrentScope( world ); worldTree.setSelectionRow( 0 ); } revalidate(); repaint(); } public void setCurrentScope( edu.cmu.cs.stage3.alice.core.Element element ) { worldTreeModel.setCurrentScope( element ); } public void setSelectedElement( edu.cmu.cs.stage3.alice.core.Element element ) { if( element != selectedElement ) { selectedElement = element; if( element == null ) { worldTree.clearSelection(); } else { while( true ) { Object[] path = worldTreeModel.getPath( element ); if( path == null || path.length == 0 ) { try { Thread.sleep( 10 ); } catch( InterruptedException ie ) { break; } } else { javax.swing.tree.TreePath selectedPath = new javax.swing.tree.TreePath( path ); worldTree.setSelectionPath( selectedPath ); worldTree.scrollPathToVisible( selectedPath ); break; } } } } } public edu.cmu.cs.stage3.alice.core.Element getSelectedElement() { return selectedElement; } private javax.swing.event.TreeSelectionListener worldSelectionListener = new javax.swing.event.TreeSelectionListener() { public void valueChanged( javax.swing.event.TreeSelectionEvent ev ) { javax.swing.tree.TreePath path = ev.getNewLeadSelectionPath(); if( path != null ) { Object o = path.getLastPathComponent(); if( o instanceof edu.cmu.cs.stage3.alice.core.Element ) { selectedElement = (edu.cmu.cs.stage3.alice.core.Element)o; if( selectedElement == worldTreeModel.HACK_getOriginalRoot() ) { //pass } else { WorldTreeComponent.this.authoringTool.setSelectedElement( selectedElement ); } } } else { WorldTreeComponent.this.setSelectedElement( (edu.cmu.cs.stage3.alice.core.Element)WorldTreeComponent.this.worldTreeModel.getRoot() ); } } }; //////////////////// // Drag and Drop //////////////////// public class ElementTreeDragGestureListener implements java.awt.dnd.DragGestureListener { protected javax.swing.JTree tree; protected edu.cmu.cs.stage3.alice.authoringtool.util.WorldTreeModel treeModel; public ElementTreeDragGestureListener( javax.swing.JTree tree ) { this.tree = tree; this.treeModel = (edu.cmu.cs.stage3.alice.authoringtool.util.WorldTreeModel)tree.getModel(); } public void dragGestureRecognized( java.awt.dnd.DragGestureEvent dge ) { edu.cmu.cs.stage3.alice.authoringtool.util.DnDManager.fireDragGestureRecognized( dge ); if( tree.isEditing() ) { return; } /* do we need to avoid double-click drags? java.awt.event.InputEvent triggerEvent = dge.getTriggerEvent(); if( triggerEvent instanceof java.awt.event.MouseEvent ) { if( ((java.awt.event.MouseEvent)triggerEvent).getClickCount() > 1 ) { return; } } */ java.awt.Point p = dge.getDragOrigin(); javax.swing.tree.TreePath path = tree.getPathForLocation( (int)p.getX(), (int)p.getY() ); if( path != null ) { Object element = path.getLastPathComponent(); if( element instanceof edu.cmu.cs.stage3.alice.core.Element ) { if( treeModel.isElementInScope( (edu.cmu.cs.stage3.alice.core.Element)element ) ) { java.awt.datatransfer.Transferable transferable = edu.cmu.cs.stage3.alice.authoringtool.datatransfer.TransferableFactory.createTransferable( element ); dragSource.startDrag( dge, java.awt.dnd.DragSource.DefaultMoveDrop, transferable, edu.cmu.cs.stage3.alice.authoringtool.util.DnDManager.getInternalListener() ); edu.cmu.cs.stage3.alice.authoringtool.util.DnDManager.fireDragStarted( transferable, WorldTreeComponent.this ); } } } } } public class WorldTreeDropTargetListener implements java.awt.dnd.DropTargetListener { protected boolean checkDrag( java.awt.dnd.DropTargetDragEvent dtde ) { if( AuthoringToolResources.safeIsDataFlavorSupported(dtde, AuthoringToolResources.getReferenceFlavorForClass( edu.cmu.cs.stage3.alice.core.Model.class ) ) ) { dtde.acceptDrag( java.awt.dnd.DnDConstants.ACTION_MOVE ); return true; } dtde.rejectDrag(); return false; } public void dragEnter( java.awt.dnd.DropTargetDragEvent dtde ) { if( checkDrag( dtde ) ) { worldTree.setDropLinesActive( true ); } } public void dragOver( java.awt.dnd.DropTargetDragEvent dtde ) { if( checkDrag( dtde ) ) { worldTree.setCursorLocation( dtde.getLocation() ); javax.swing.tree.TreePath parentPath = worldTree.getParentPath(); edu.cmu.cs.stage3.alice.core.Element parent = (edu.cmu.cs.stage3.alice.core.Element)parentPath.getLastPathComponent(); java.awt.datatransfer.Transferable transferable = edu.cmu.cs.stage3.alice.authoringtool.util.DnDManager.getCurrentTransferable(); edu.cmu.cs.stage3.alice.core.Element child = null; if( (transferable != null) && AuthoringToolResources.safeIsDataFlavorSupported(transferable, AuthoringToolResources.getReferenceFlavorForClass( edu.cmu.cs.stage3.alice.core.Model.class ) ) ) { try { child = (edu.cmu.cs.stage3.alice.core.Element)transferable.getTransferData( AuthoringToolResources.getReferenceFlavorForClass( edu.cmu.cs.stage3.alice.core.Model.class ) ); } catch( Exception e ) { AuthoringTool.showErrorDialog( "Error encountered extracting drop transferable.", e ); } } if( child != null ) { if( isAcceptableDrop( parent, child ) ) { // worldTree.setSelectionPath( parentPath ); worldTree.setShowDropLines( true ); } else { //TODO setCursor //if( (!invalidCursorShown) && (invalidCursor != null) ) { // worldTree.setCursor( invalidCursor ); //} worldTree.setShowDropLines( false ); } } else { worldTree.setShowDropLines( true ); } } } public void dropActionChanged( java.awt.dnd.DropTargetDragEvent dtde ) { checkDrag( dtde ); } public void dragExit( java.awt.dnd.DropTargetEvent dte ) { worldTree.setDropLinesActive( false ); } public void drop( java.awt.dnd.DropTargetDropEvent dtde ) { boolean succeeded = true; //DEBUG System.out.println( "drop" ); worldTree.setCursorLocation( dtde.getLocation() ); try { Object o = null; if( AuthoringToolResources.safeIsDataFlavorSupported(dtde, AuthoringToolResources.getReferenceFlavorForClass( edu.cmu.cs.stage3.alice.core.Model.class ) ) ) { java.awt.datatransfer.Transferable transferable = dtde.getTransferable(); final edu.cmu.cs.stage3.alice.core.Model model = (edu.cmu.cs.stage3.alice.core.Model)transferable.getTransferData( AuthoringToolResources.getReferenceFlavorForClass( edu.cmu.cs.stage3.alice.core.Model.class ) ); javax.swing.tree.TreePath parentPath = worldTree.getParentPath(); final edu.cmu.cs.stage3.alice.core.Element parent = (edu.cmu.cs.stage3.alice.core.Element)parentPath.getLastPathComponent(); if( isAcceptableDrop( parent, model ) ) { dtde.acceptDrop( java.awt.dnd.DnDConstants.ACTION_MOVE ); javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run() { try { insertChild( parent, model, worldTree.getParentToPredecessorPaths() ); } catch( Throwable t ) { AuthoringTool.showErrorDialog( "Error moving child.", t ); } } } ); succeeded = true; } else { dtde.rejectDrop(); succeeded = false; } } else { dtde.rejectDrop(); succeeded = false; } } catch( java.awt.datatransfer.UnsupportedFlavorException e ) { AuthoringTool.showErrorDialog( "Drop didn't work: bad flavor", e ); succeeded = false; } catch( java.io.IOException e ) { AuthoringTool.showErrorDialog( "Drop didn't work: IOException", e ); succeeded = false; } catch( Throwable t ) { AuthoringTool.showErrorDialog( "Drop didn't work.", t ); succeeded = false; } worldTree.setDropLinesActive( false ); dtde.dropComplete( succeeded ); } private boolean isAcceptableDrop( edu.cmu.cs.stage3.alice.core.Element parent, edu.cmu.cs.stage3.alice.core.Element child ) { if( parent instanceof edu.cmu.cs.stage3.alice.core.Group ) { edu.cmu.cs.stage3.alice.core.Group group = (edu.cmu.cs.stage3.alice.core.Group)parent; Class childValueClass = child.getClass(); if( child instanceof edu.cmu.cs.stage3.alice.core.Expression ) { childValueClass = ((edu.cmu.cs.stage3.alice.core.Expression)child).getValueClass(); } if( ! group.valueClass.getClassValue().isAssignableFrom( childValueClass ) ) { return false; } } if( (parent instanceof edu.cmu.cs.stage3.alice.core.Group) || (parent instanceof edu.cmu.cs.stage3.alice.core.World) ) { if( child.getParent() instanceof edu.cmu.cs.stage3.alice.core.World ) { return true; } else if( child.getParent() instanceof edu.cmu.cs.stage3.alice.core.Group ) { return true; } else if( child.getParent() == null ) { return true; } } return false; } private void insertChild( edu.cmu.cs.stage3.alice.core.Element parent, edu.cmu.cs.stage3.alice.core.Element child, javax.swing.tree.TreePath[] parentToPredecessor ) { int index; javax.swing.tree.TreePath parentPath = parentToPredecessor[0]; javax.swing.tree.TreePath predecessorPath = parentToPredecessor[parentToPredecessor.length-1]; edu.cmu.cs.stage3.alice.core.property.ObjectArrayProperty oap = null; if( parent instanceof edu.cmu.cs.stage3.alice.core.World ) { oap = ((edu.cmu.cs.stage3.alice.core.World)parent).sandboxes; } else if( parent instanceof edu.cmu.cs.stage3.alice.core.Group ) { oap = ((edu.cmu.cs.stage3.alice.core.Group)parent).values; } if( predecessorPath == parentPath ) { index = 0; } else { int i = parentToPredecessor.length - 1; while( (i >= 0) && (parentToPredecessor[i] != null) && (! parentToPredecessor[i].getParentPath().equals( parentPath )) ) { i--; } edu.cmu.cs.stage3.alice.core.Element predecessor = (edu.cmu.cs.stage3.alice.core.Element)parentToPredecessor[i].getLastPathComponent(); index = 1 + oap.indexOf( predecessor ); } if( isAcceptableDrop( parent, child ) ) { int currentIndex = oap.indexOf( child ); if( (currentIndex > -1) && (currentIndex < index) ) { index--; } authoringTool.getUndoRedoStack().startCompound(); // child.removeFromParent(); child.removeFromParentsProperties(); // parent.addChild( child ); child.setParent( parent ); oap.add( index, child ); authoringTool.getUndoRedoStack().stopCompound(); } } } // avoid editing on drag... and other mouse enhancements public class CustomTreeUI extends javax.swing.plaf.basic.BasicTreeUI { protected java.awt.event.MouseListener createMouseListener() { return new CustomMouseHandler(); } protected boolean startEditing( javax.swing.tree.TreePath path, java.awt.event.MouseEvent ev ) { boolean result = super.startEditing( path, ev ); if( result ) { WorldTreeComponent.this.cellEditor.selectText(); } return result; } public class CustomMouseHandler extends java.awt.event.MouseAdapter { // we'll do our own click detection protected long pressTime; protected java.awt.Point pressPoint; protected long clickDelay = 300; protected double clickDistance = 8.0; public void mousePressed( java.awt.event.MouseEvent ev ) { pressTime = ev.getWhen(); pressPoint = ev.getPoint(); if( (tree != null) && tree.isEnabled() ) { tree.requestFocus(); javax.swing.tree.TreePath path = getClosestPathForLocation( tree, ev.getX(), ev.getY() ); if( path != null ) { java.awt.Rectangle bounds = getPathBounds( tree, path ); if( ev.getY() > (bounds.y + bounds.height) ) { return; } if( javax.swing.SwingUtilities.isLeftMouseButton( ev ) ) { checkForClickInExpandControl( path, ev.getX(), ev.getY() ); } } } } public void mouseReleased( java.awt.event.MouseEvent ev ) { if( (tree != null) && tree.isEnabled() ) { tree.requestFocus(); javax.swing.tree.TreePath path = getClosestPathForLocation( tree, ev.getX(), ev.getY() ); if( path != null ) { edu.cmu.cs.stage3.alice.core.Element element = (edu.cmu.cs.stage3.alice.core.Element)path.getLastPathComponent(); boolean elementInScope = ((edu.cmu.cs.stage3.alice.authoringtool.util.WorldTreeModel)tree.getModel()).isElementInScope( element ); if( elementInScope ) { java.awt.Rectangle bounds = getPathBounds( tree, path ); if( ev.getY() > (bounds.y + bounds.height) ) { return; } int x = ev.getX(); if( x > bounds.x && (x <= (bounds.x + bounds.width)) ) { if( isClick( ev ) ) { if( startEditing( path, ev ) ) { return; } } //System.out.println( element + " in scope of " + ((edu.cmu.cs.stage3.alice.authoringtool.util.ScopedElementTreeModel)tree.getModel()).getCurrentScope() ); selectPathForEvent( path, ev ); } } } } } protected boolean isClick( java.awt.event.MouseEvent ev ) { if( ev.getClickCount() > 1 ) { return true; } long time = ev.getWhen(); java.awt.Point p = ev.getPoint(); if( (time - pressTime) <= clickDelay ) { double dx = p.getX() - pressPoint.getX(); double dy = p.getY() - pressPoint.getY(); double dist = Math.sqrt( dx*dx + dy*dy ); if( dist <= clickDistance ) { return true; } } return false; } } } ///////////////////////////// // Mouse event handling ///////////////////////////// protected final java.awt.event.MouseListener worldTreeMouseListener = new edu.cmu.cs.stage3.alice.authoringtool.util.CustomMouseAdapter() { protected java.util.Vector<StringObjectPair> defaultStructure; protected void popupResponse( java.awt.event.MouseEvent ev ) { javax.swing.JTree tree = (javax.swing.JTree)ev.getSource(); javax.swing.tree.TreePath path = tree.getPathForLocation( ev.getX(), ev.getY() ); if( path != null ) { Object node = path.getLastPathComponent(); if( node instanceof edu.cmu.cs.stage3.alice.core.Element ) { javax.swing.JPopupMenu popup = createPopup( (edu.cmu.cs.stage3.alice.core.Element)node, path ); if( popup != null ) { popup.show( ev.getComponent(), ev.getX(), ev.getY() ); edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.ensurePopupIsOnScreen( popup ); } } } else { edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.createAndShowPopupMenu( getDefaultStructure(), ev.getComponent(), ev.getX(), ev.getY() ); } } private javax.swing.JPopupMenu createPopup( final edu.cmu.cs.stage3.alice.core.Element element, javax.swing.tree.TreePath path ) { java.util.Vector structure = edu.cmu.cs.stage3.alice.authoringtool.util.ElementPopupUtilities.getDefaultStructure( element, worldTreeModel.isElementInScope( element ), authoringTool, worldTree, path ); return edu.cmu.cs.stage3.alice.authoringtool.util.ElementPopupUtilities.makeElementPopupMenu( element, structure ); } protected java.util.Vector getDefaultStructure() { if( defaultStructure == null ) { defaultStructure = new java.util.Vector(); defaultStructure.add( new edu.cmu.cs.stage3.util.StringObjectPair( "create new group", new Runnable() { public void run() { edu.cmu.cs.stage3.alice.core.Group newGroup = new edu.cmu.cs.stage3.alice.core.Group(); String name = AuthoringToolResources.getNameForNewChild( "Group", world ); newGroup.name.set( name ); newGroup.valueClass.set( edu.cmu.cs.stage3.alice.core.Model.class ); world.addChild( newGroup ); world.groups.add( newGroup ); } } ) ); } return defaultStructure; } }; ////////////////////////// // GUI ////////////////////////// BorderLayout borderLayout2 = new BorderLayout(); TitledBorder titledBorder1; JScrollPane treeScrollPane = new JScrollPane(); JPanel treePanel = new JPanel(); BorderLayout borderLayout4 = new BorderLayout(); WorldTree worldTree = new WorldTree(); //JTree charactersTree = new javax.swing.JTree(); public void jbInit() { titledBorder1 = new TitledBorder(""); setLayout( borderLayout2 ); /* if (authoringtoolConfig != null){ int fontSize = Integer.parseInt(authoringtoolConfig.getValue("fontSize")); worldTree.setFont(new java.awt.Font("Dialog", 0, (int)(14*fontSize/12.0))); } else{ worldTree.setFont(new java.awt.Font("Dialog", 0, 14)); } */ worldTree.setFont(new java.awt.Font("Dialog", 0, 14)); // this.setSize(20, 30); // this.setPreferredSize(getPreferredSize()); this.setMinimumSize( new Dimension(10, 32) ); treePanel.setLayout(borderLayout4); worldTree.setBorder(new JScrollPane().getViewportBorder()); worldTree.setBackground(Palette.gray); //charactersTree.setFont(new java.awt.Font("Dialog", 0, 14)); //charactersTree.setRootVisible(false); this.add(treeScrollPane, BorderLayout.CENTER); treeScrollPane.getViewport().add(treePanel, null); treePanel.add(worldTree, BorderLayout.CENTER); UIManager.put("Tree.line", Color.black); worldTree.putClientProperty( "Tree.line", Color.red ); //treePanel.add(charactersTree, BorderLayout.CENTER); } public static class HackBorder extends AbstractBorder { // a hack to simulate a Metal ScrollPane border private static final long serialVersionUID = -754378921915147679L; private static final Insets insets = new Insets( 1, 1, 2, 2 ); public void paintBorder( Component c, Graphics g, int x, int y, int w, int h ) { g.translate( x, y ); g.setColor( javax.swing.plaf.metal.MetalLookAndFeel.getControlDarkShadow() ); g.drawRect( 0, 0, w-2, h-2 ); g.setColor( javax.swing.plaf.metal.MetalLookAndFeel.getControlHighlight() ); g.drawLine( w-1, 1, w-1, h-1 ); g.drawLine( 1, h-1, w-1, h-1 ); g.setColor( javax.swing.plaf.metal.MetalLookAndFeel.getControl() ); g.drawLine( w-2, 2, w-2, 2 ); g.drawLine( 1, h-2, 1, h-2 ); g.translate( -x, -y ); } public Insets getBorderInsets( Component c ) { return insets; } } }
mit
magic-bus/BlueBus
src/edu/umich/pts/mbus/bluebus/feed/FeedParser.java
555
package edu.umich.pts.mbus.bluebus.feed; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; public final class FeedParser { protected static InputStream getInputStream(String url) { final URL feedUrl; try { feedUrl = new URL(url); return feedUrl.openConnection().getInputStream(); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }
mit
craterdog/java-collection-framework
src/main/java/craterdog/collections/abstractions/Sequence.java
4396
/************************************************************************ * Copyright (c) Crater Dog Technologies(TM). All Rights Reserved. * ************************************************************************ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * * * This code is free software; you can redistribute it and/or modify it * * under the terms of The MIT License (MIT), as published by the Open * * Source Initiative. (See http://opensource.org/licenses/MIT) * ************************************************************************/ package craterdog.collections.abstractions; import craterdog.core.Iterator; import craterdog.core.Sequential; import craterdog.smart.SmartObject; import craterdog.utils.NaturalComparator; import java.lang.reflect.Array; import java.util.Comparator; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /** * This abstract class defines the invariant methods that all sequences must inherit. * * @author Derk Norton * @param <E> The type of elements that are in the sequence. */ public abstract class Sequence<E> extends SmartObject<Sequence<E>> implements Sequential<E> { static private final XLogger logger = XLoggerFactory.getXLogger(Sequence.class); @Override public int hashCode() { logger.entry(); int hash = 5; for (E element : this) { hash = 11 * hash + element.hashCode(); } logger.exit(hash); return hash; } @Override public boolean equals(Object object) { logger.entry(object); boolean result = false; if (object != null && getClass() == object.getClass()) { @SuppressWarnings("unchecked") final Sequence<E> that = (Sequence<E>) object; if (this.getSize() == that.getSize()) { result = true; // so far anyway... Iterator<E> thisIterator = this.createIterator(); Iterator<E> thatIterator = that.createIterator(); while (thisIterator.hasNext()) { E thisElement = thisIterator.getNext(); E thatElement = thatIterator.getNext(); if (!thisElement.equals(thatElement)) { result = false; // oops, found a difference break; } } } } logger.exit(result); return result; } @Override public int compareTo(Sequence<E> that) { logger.entry(that); if (that == null) return 1; if (this == that) return 0; // same object int result = 0; Comparator<Object> comparator = new NaturalComparator<>(); Iterator<E> thisIterator = this.createIterator(); Iterator<E> thatIterator = that.createIterator(); while (thisIterator.hasNext() && thatIterator.hasNext()) { E thisElement = thisIterator.getNext(); E thatElement = thatIterator.getNext(); result = comparator.compare(thisElement, thatElement); if (result != 0) break; } if (result == 0) { // same so far, check for different lengths result = Integer.compare(this.getSize(), that.getSize()); } logger.exit(result); return result; } @SuppressWarnings("unchecked") @Override public E[] toArray() { logger.entry(); E[] array = (E[]) new Object[0]; // OK to use type Object array since it is empty int size = this.getSize(); if (size > 0) { // Requires a TOTAL HACK since we cannot instantiate a parameterized array explicitly! Iterator<E> iterator = createIterator(); E template = iterator.getNext(); // we know there must be at least one element array = (E[]) Array.newInstance(template.getClass(), size); array[0] = template; // copy in the first element for (int index = 1; index < size; index++) { array[index] = iterator.getNext(); // copy the rest of the elements } } logger.exit(array); return array; } @Override public Iterator<E> iterator() { return createIterator(); } }
mit
blckshrk/MavenDataExtraction
src/main/java/fr/lille1/maven_data_extraction/core/exceptions/MavenDataExtractionException.java
930
package fr.lille1.maven_data_extraction.core.exceptions; public class MavenDataExtractionException extends RuntimeException { private static final long serialVersionUID = -3950552488615943947L; /** * */ public MavenDataExtractionException() { super(); } /** * @param message * @param cause * @param enableSuppression * @param writableStackTrace */ public MavenDataExtractionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } /** * @param message * @param cause */ public MavenDataExtractionException(String message, Throwable cause) { super(message, cause); } /** * @param message */ public MavenDataExtractionException(String message) { super(message); } /** * @param cause */ public MavenDataExtractionException(Throwable cause) { super(cause); } }
mit
Bernardo-MG/jpa-example
src/test/java/com/bernardomg/example/jpa/test/integration/inheritance/multiple/ITMultipleTableInheritanceValueEntityQueryCriteriaApi.java
3173
/** * The MIT License (MIT) * <p> * Copyright (c) 2016-2021 the the original author or authors. * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * 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.bernardomg.example.jpa.test.integration.inheritance.multiple; import javax.persistence.EntityManager; import javax.persistence.Query; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import com.bernardomg.example.jpa.test.config.annotation.PersistenceIntegrationTest; import com.bernardomg.example.jpa.test.config.criteria.inheritance.multiple.MultipleTableInheritanceValueEntityCriteriaFactory; /** * Integration tests for a {@code MultipleTableInheritanceValueEntity} testing * it loads values correctly by using the criteria API. * * @author Bernardo Mart&iacute;nez Garrido */ @PersistenceIntegrationTest public class ITMultipleTableInheritanceValueEntityQueryCriteriaApi extends AbstractJUnit4SpringContextTests { /** * The persistence entity manager. */ @Autowired private EntityManager entityManager; /** * Default constructor. */ public ITMultipleTableInheritanceValueEntityQueryCriteriaApi() { super(); } /** * Tests that retrieving all the entities with a specific enum, through the * ordinal value, gives the correct number of them. */ @Test public final void testAllWithValue() { final Integer readCount; readCount = getQuery().getResultList().size(); // Reads the expected number of entities Assertions.assertEquals(1, readCount); } /** * Returns the query for the test. * * @return the query for the test */ private final Query getQuery() { final Integer value; // Value to find // Queried value value = 11; return entityManager .createQuery(MultipleTableInheritanceValueEntityCriteriaFactory .findAllWithValue(entityManager, value)); } }
mit
dfslima/portalCliente
src/main/java/br/com/portalCliente/enumeration/MaritalStatus.java
503
package br.com.portalCliente.enumeration; public enum MaritalStatus { SINGLE(0), MARRIED(1), DIVORCED(2), SEPARATED(4), WIDOWED(5); private final int value; private MaritalStatus(int value) { this.value = value; } public int getValue() { return value; } public static MaritalStatus getName(int value){ MaritalStatus result = null; for(MaritalStatus mt : MaritalStatus.values()){ if(mt.value == value){ result = mt; break; } } return result; } }
mit
karim/adila
database/src/main/java/adila/db/silversmart5fumts_xt303.java
238
// This file is automatically generated. package adila.db; /* * Motorola Motosmart * * DEVICE: silversmart_umts * MODEL: XT303 */ final class silversmart5fumts_xt303 { public static final String DATA = "Motorola|Motosmart|"; }
mit
Samuel-Oliveira/Java_CTe
src/main/java/br/com/swconsultoria/cte/schema_300/evCCeCTe/TUFSemEX.java
2321
// // Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802 // Consulte <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem. // Gerado em: 2019.09.22 às 07:47:55 PM BRT // package br.com.swconsultoria.cte.schema_300.evCCeCTe; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java de TUF_sem_EX. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * <p> * <pre> * &lt;simpleType name="TUF_sem_EX"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="AC"/> * &lt;enumeration value="AL"/> * &lt;enumeration value="AM"/> * &lt;enumeration value="AP"/> * &lt;enumeration value="BA"/> * &lt;enumeration value="CE"/> * &lt;enumeration value="DF"/> * &lt;enumeration value="ES"/> * &lt;enumeration value="GO"/> * &lt;enumeration value="MA"/> * &lt;enumeration value="MG"/> * &lt;enumeration value="MS"/> * &lt;enumeration value="MT"/> * &lt;enumeration value="PA"/> * &lt;enumeration value="PB"/> * &lt;enumeration value="PE"/> * &lt;enumeration value="PI"/> * &lt;enumeration value="PR"/> * &lt;enumeration value="RJ"/> * &lt;enumeration value="RN"/> * &lt;enumeration value="RO"/> * &lt;enumeration value="RR"/> * &lt;enumeration value="RS"/> * &lt;enumeration value="SC"/> * &lt;enumeration value="SE"/> * &lt;enumeration value="SP"/> * &lt;enumeration value="TO"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "TUF_sem_EX", namespace = "http://www.portalfiscal.inf.br/cte") @XmlEnum public enum TUFSemEX { AC, AL, AM, AP, BA, CE, DF, ES, GO, MA, MG, MS, MT, PA, PB, PE, PI, PR, RJ, RN, RO, RR, RS, SC, SE, SP, TO; public String value() { return name(); } public static TUFSemEX fromValue(String v) { return valueOf(v); } }
mit
phase/Sponge
src/main/java/org/spongepowered/mod/service/scheduler/ScheduledTask.java
5918
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.service.scheduler; import com.google.common.base.Optional; import org.spongepowered.api.plugin.PluginContainer; import org.spongepowered.api.service.scheduler.Task; import java.util.UUID; /** * <p> * ScheduledTask is an internal representation of a Task created by the Plugin * through one of the Scheduler interfaces. * </p> */ public class ScheduledTask implements Task { protected long offset; protected long period; protected PluginContainer owner; protected Runnable runnableBody; protected long timestamp; protected ScheduledTaskState state; protected UUID id; protected String name; protected TaskSynchroncity syncType; // Internal Task state. Not for user-service use. public enum ScheduledTaskState { WAITING, RUNNING, CANCELED, } // No c'tor without arguments. This prevents internal Sponge code from accidentally trying to // instantiate a ScheduledTask incorrectly. @SuppressWarnings("unused") private ScheduledTask() { } // This c'tor is OK for internal Sponge use. APIs do not expose the c'tor. protected ScheduledTask(long x, long t, TaskSynchroncity syncType) { // All tasks begin waiting. this.state = ScheduledTaskState.WAITING; // Values assigned to offset and period are always interpreted by the internal // Sponge implementation as in milliseconds for scaleDecriptors that are not Tick based. this.offset = x; this.period = t; this.owner = null; this.runnableBody = null; this.id = UUID.randomUUID(); this.syncType = syncType; } // Builder method protected ScheduledTask setState(ScheduledTaskState state) { this.state = state; return this; } // Builder method protected ScheduledTask setOffset(long x) { this.offset = x; return this; } // Builder method protected ScheduledTask setPeriod(long t) { this.period = t; return this; } // Builder method protected ScheduledTask setTimestamp(long ts) { this.timestamp = ts; return this; } // Builder method protected ScheduledTask setPluginContainer(PluginContainer owner) { this.owner = owner; return this; } // Builder method protected ScheduledTask setRunnableBody(Runnable body) { this.runnableBody = body; return this; } @Override public PluginContainer getOwner() { return this.owner; } @Override public Optional<Long> getDelay() { Optional<Long> result = Optional.absent(); if (this.offset > 0) { result = Optional.of(this.offset); } return result; } @Override public Optional<Long> getInterval() { Optional<Long> result = Optional.absent(); if (this.period > 0) { result = Optional.of(this.period); } return result; } @Override public boolean cancel() { boolean bResult = false; // When a task is canceled, it is removed from the map // Even if the task is a repeating task, by removing it from the map of tasks // known in the Scheduler, the task will not repeat. // // A successful cancel() occurs when the opportunity is present where // the task can be canceled. If it is, then the result is true. // If the task is already canceled, or already running, the task cannot // be canceled. if (this.state == ScheduledTask.ScheduledTaskState.WAITING) { bResult = true; } this.state = ScheduledTask.ScheduledTaskState.CANCELED; return bResult; } @Override public Optional<Runnable> getRunnable() { Optional<Runnable> result = Optional.absent(); if (this.runnableBody != null) { result = Optional.of(this.runnableBody); } return result; } @Override public UUID getUniqueId() { return this.id; } @Override public Optional<String> getName() { Optional<String> result = Optional.absent(); if (this.name != null) { result = Optional.of(this.name); } return result; } @Override public boolean isSynchronous() { return this.syncType == TaskSynchroncity.SYNCHRONOUS; } @Override public String setName(String name) { this.name = name; return this.name; } public enum TaskSynchroncity { SYNCHRONOUS, ASYNCHRONOUS } }
mit
karim/adila
database/src/main/java/adila/db/soul4na_alcatel20one20touch204037r.java
266
// This file is automatically generated. package adila.db; /* * Alcatel ONETOUCH 4037R * * DEVICE: SOUL4NA * MODEL: ALCATEL ONE TOUCH 4037R */ final class soul4na_alcatel20one20touch204037r { public static final String DATA = "Alcatel|ONETOUCH 4037R|"; }
mit
hpiasg/desij
src/main/java/net/strongdesign/desij/gui/STGEditorNavigationPopUp.java
924
package net.strongdesign.desij.gui; import javax.swing.BorderFactory; import javax.swing.JPopupMenu; public class STGEditorNavigationPopUp extends JPopupMenu { private static final long serialVersionUID = 2993881479268447533L; public STGEditorNavigationPopUp(STGEditorNavigation listener) { super(); setBorder(BorderFactory.createRaisedBevelBorder()); add(listener.DELETE_SELECTED); add(listener.PARALLEL_COMPOSITION); add(listener.SYNCHRONOUS_PRODUCT); add(listener.DUMMY_SURROUNDING); add(listener.RELAX_INJECTIVE); add(listener.RELAX_INJECTIVE2); add(listener.SIMPLE_DUMMY_REMOVAL); add(listener.PETRIFY); add(listener.PETRIFY_CSC); add(listener.MPSAT_CSC); add(listener.REPORT_IMPLEMENTABLE); add(listener.REPORT_IMPLEMENTABLE_SW); add(listener.REPORT_PROBLEMATIC_TRIGGERS); add(listener.DUMMIFY_RECURRING_SIGNALS); add(listener.REMOVE_DEAD_TRANSITIONS); } }
mit
smarr/SOMns-vscode
server/org.eclipse.lsp4j.jsonrpc/org/eclipse/lsp4j/jsonrpc/json/adapters/EitherTypeAdapterFactory.java
1157
/****************************************************************************** * Copyright (c) 2016 TypeFox and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, * or the Eclipse Distribution License v. 1.0 which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause ******************************************************************************/ package org.eclipse.lsp4j.jsonrpc.json.adapters; import org.eclipse.lsp4j.jsonrpc.messages.Either; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * @deprecated Use {@link EitherTypeAdapter.Factory} instead. */ @Deprecated public class EitherTypeAdapterFactory extends EitherTypeAdapter.Factory { /** * @deprecated Use {@link EitherTypeAdapter} instead. */ @Deprecated protected static class Adapter<L, R> extends EitherTypeAdapter<L, R> { public Adapter(Gson gson, TypeToken<Either<L, R>> typeToken) { super(gson, typeToken); } } }
mit
Woogis/SisatongPodcast
app/src/main/java/net/sisatong/podcast/fragment/gpodnet/TagListFragment.java
5259
package net.sisatong.podcast.fragment.gpodnet; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.TextView; import net.sisatong.podcast.adapter.gpodnet.TagListAdapter; import net.sisatong.podcast.core.gpoddernet.GpodnetService; import net.sisatong.podcast.core.gpoddernet.GpodnetServiceException; import net.sisatong.podcast.core.gpoddernet.model.GpodnetTag; import net.sisatong.podcast.menuhandler.MenuItemUtils; import java.util.List; import net.sisatong.podcast.activity.MainActivity; public class TagListFragment extends ListFragment { private static final String TAG = "TagListFragment"; private static final int COUNT = 50; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(net.sisatong.podcast.R.menu.gpodder_podcasts, menu); MenuItem searchItem = menu.findItem(net.sisatong.podcast.R.id.action_search); final SearchView sv = (SearchView) MenuItemCompat.getActionView(searchItem); MenuItemUtils.adjustTextColor(getActivity(), sv); sv.setQueryHint(getString(net.sisatong.podcast.R.string.gpodnet_search_hint)); sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { Activity activity = getActivity(); if (activity != null) { sv.clearFocus(); ((MainActivity) activity).loadChildFragment(SearchListFragment.newInstance(s)); } return true; } @Override public boolean onQueryTextChange(String s) { return false; } }); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { GpodnetTag tag = (GpodnetTag) getListAdapter().getItem(position); MainActivity activity = (MainActivity) getActivity(); activity.loadChildFragment(TagFragment.newInstance(tag)); } }); startLoadTask(); } @Override public void onResume() { super.onResume(); ((MainActivity) getActivity()).getMainActivtyActionBar().setTitle(net.sisatong.podcast.R.string.add_feed_label); } @Override public void onDestroyView() { super.onDestroyView(); cancelLoadTask(); } private AsyncTask<Void, Void, List<GpodnetTag>> loadTask; private void cancelLoadTask() { if (loadTask != null && !loadTask.isCancelled()) { loadTask.cancel(true); } } private void startLoadTask() { cancelLoadTask(); loadTask = new AsyncTask<Void, Void, List<GpodnetTag>>() { private Exception exception; @Override protected List<GpodnetTag> doInBackground(Void... params) { GpodnetService service = new GpodnetService(); try { return service.getTopTags(COUNT); } catch (GpodnetServiceException e) { e.printStackTrace(); exception = e; return null; } finally { service.shutdown(); } } @Override protected void onPreExecute() { super.onPreExecute(); setListShown(false); } @Override protected void onPostExecute(List<GpodnetTag> gpodnetTags) { super.onPostExecute(gpodnetTags); final Context context = getActivity(); if (context != null) { if (gpodnetTags != null) { setListAdapter(new TagListAdapter(context, android.R.layout.simple_list_item_1, gpodnetTags)); } else if (exception != null) { TextView txtvError = new TextView(getActivity()); txtvError.setText(exception.getMessage()); getListView().setEmptyView(txtvError); } setListShown(true); } } }; if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) { loadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { loadTask.execute(); } } }
mit
danielabar/framegen
FramegenCore/src/main/java/com/framegen/core/framehandler/option/FadeFrameHandler.java
3449
package com.framegen.core.framehandler.option; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.concurrent.*; import com.framegen.api.response.FrameHandlerVO; import com.framegen.api.response.TaskResultVO; import com.framegen.api.service.IFrameHandler; import com.framegen.api.settings.SettingsVO; import com.framegen.api.settings.option.FadeSettingsVO; import com.framegen.core.framehandler.FrameHandlerBase; import com.framegen.core.task.OffsetFilterTask; import com.framegen.core.taskvo.OffsetFilterTaskVO; public class FadeFrameHandler extends FrameHandlerBase implements IFrameHandler { private static final Float MULTIPLIER = Float.valueOf("1.0"); private static final Float OFFSET_START = Float.valueOf("0"); private static final Float OFFSET_END = Float.valueOf("230"); private final ExecutorService taskExecutor; private final CompletionService<TaskResultVO> taskCompletionService; public FadeFrameHandler() { super(); this.taskExecutor = Executors.newFixedThreadPool(getNumberOfThreads()); this.taskCompletionService = new ExecutorCompletionService<TaskResultVO>(taskExecutor); } @Override public Integer getNumberOfFrames(SettingsVO settings) throws IOException { FadeSettingsVO fadeSettings = settings.getFadeSettings(); return fadeSettings.getSteps() + 1; } @Override public FrameHandlerVO generateFrames(SettingsVO settings) throws IOException, InterruptedException { BufferedImage baseImage = getBaseImage(settings); FadeSettingsVO fadeSettings = settings.getFadeSettings(); Integer steps = fadeSettings.getSteps(); Float offsetIncrement = (OFFSET_END - OFFSET_START) / steps; for (int i=0; i<steps; i++) { OffsetFilterTaskVO vo = new OffsetFilterTaskVO(baseImage, settings.getProgramSettings().getOutputDir(), MULTIPLIER, getOffset(i, offsetIncrement), settings.getProgramSettings().getGeneratedImageNamePrefix(), i, NUMBER_OF_PAD_CHARS, steps); Callable<TaskResultVO> task = new OffsetFilterTask<TaskResultVO>(vo); taskCompletionService.submit(task); } OffsetFilterTaskVO offsetFilterTaskVO = new OffsetFilterTaskVO(baseImage, settings.getProgramSettings().getOutputDir(), MULTIPLIER, OFFSET_END, settings.getProgramSettings().getGeneratedImageNamePrefix(), steps, NUMBER_OF_PAD_CHARS, steps); Callable<TaskResultVO> task = new OffsetFilterTask<TaskResultVO>(offsetFilterTaskVO); taskCompletionService.submit(task); return buildFrameHandlerResponse(taskCompletionService, steps+1); } protected Float getOffset(int i, Float offsetIncrement) { return OFFSET_START + (i * offsetIncrement); } @Override public Double getAllFrameSize(SettingsVO settings) throws Exception { BufferedImage baseImage = getBaseImage(settings); FadeSettingsVO negativeSettings = settings.getFadeSettings(); Integer steps = negativeSettings.getSteps(); Float offsetIncrement = (OFFSET_END - OFFSET_START) / steps; OffsetFilterTaskVO offsetFilterTaskVO = new OffsetFilterTaskVO(baseImage, settings.getProgramSettings().getOutputDir(), MULTIPLIER, getOffset(1, offsetIncrement), settings.getProgramSettings().getGeneratedImageNamePrefix(), 1, NUMBER_OF_PAD_CHARS, steps); OffsetFilterTask<TaskResultVO> task = new OffsetFilterTask<TaskResultVO>(offsetFilterTaskVO); TaskResultVO overlayResultVO = task.overlay(); return overlayResultVO.getFrameSize() * getNumberOfFrames(settings); } }
mit
CrystalshardCA/Ruby
src/main/java/ca/crystalshard/adapter/web/JobApiController.java
1613
package ca.crystalshard.adapter.web; import ca.crystalshard.adapter.web.handlers.JobApiDeleteHandler; import ca.crystalshard.adapter.web.handlers.JobApiGetAllHandler; import ca.crystalshard.adapter.web.handlers.JobApiGetHandler; import ca.crystalshard.adapter.web.handlers.JobApiPostHandler; import ca.crystalshard.adapter.web.handlers.JobApiPutHandler; import com.google.inject.Inject; import spark.ResponseTransformer; public class JobApiController extends RubyApiController { private JobApiGetHandler getHandler; private JobApiPostHandler postHandler; private JobApiPutHandler putHandler; private JobApiDeleteHandler deleteHandler; private JobApiGetAllHandler getAllHandler; @Inject public JobApiController(ResponseTransformer transformer, JobApiGetHandler getHandler, JobApiPostHandler postHandler, JobApiPutHandler putHandler, JobApiDeleteHandler deleteHandler, JobApiGetAllHandler getAllHandler) { super(transformer); this.getHandler = getHandler; this.postHandler = postHandler; this.putHandler = putHandler; this.deleteHandler = deleteHandler; this.getAllHandler = getAllHandler; } @Override public void register() { path("/api/v1/job", () -> { get("/:jobId", getHandler); get("", getAllHandler); post("", postHandler); put("/:jobId", putHandler); delete("/:jobId", deleteHandler); }); } }
mit
dominikschreiber/underscore.java
src/test/java/com/dominikschreiber/underscore/_Test.java
29981
package com.dominikschreiber.underscore; import com.dominikschreiber.underscore.java.util.function.BiFunction; import com.dominikschreiber.underscore.java.util.function.BiPredicate; import com.dominikschreiber.underscore.java.util.function.Consumer; import com.dominikschreiber.underscore.java.util.function.Function; import com.dominikschreiber.underscore.java.util.function.Predicate; import org.junit.Test; import java.util.AbstractMap; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class _Test { private Function<Integer, Integer> square = new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { return input * input; } }; private Predicate<Integer> isEven = new Predicate<Integer>() { @Override public boolean test(Integer input) { return input % 2 == 0; } }; private BiFunction<Integer, Integer, Integer> sum = new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer current, Integer sum) { return current + sum; } }; private BiPredicate<String, String> stringEquals = new BiPredicate<String, String>() { @Override public boolean test(String a, String b) { return a.equals(b); } }; private Function<String, Long> length = new Function<String, Long>() { @Override public Long apply(String s) { return (long) s.length(); } }; // ----- _.each -------------------------------------------------------------------------------- @Test public void staticEachWithStringBuilder() { final StringBuilder result = new StringBuilder(); _.each(_.range(1, 6), new Consumer<Integer>() { @Override public void accept(Integer input) { result.append(Integer.toString(input, 10)); } }); assertEquals("12345", result.toString()); } @Test public void staticEachNullInput() { _.each(null, new Consumer<Object>() { @Override public void accept(Object input) { } }); // tests pass if no exception is thrown -- no need to Assert.pass() } @Test public void chainedEachWithStringBuilder() { final StringBuilder result = new StringBuilder(); new _<Integer>(_.range(1, 6)) .each(new Consumer<Integer>() { @Override public void accept(Integer input) { result.append(Integer.toString(input, 10)); } }); assertEquals("12345", result.toString()); } // ----- _.map --------------------------------------------------------------------------------- @Test public void staticMapWithSquare() { List<Integer> result = _.map(_.range(1, 6), square); assertEquals(_.list(1, 4, 9, 16, 25), result); } @Test public void staticMapWithNullInput() { assertEquals(Collections.emptyList(), _.map(null, square)); } @Test public void chainedMapWithSquare() { Iterable<Integer> result = new _<Integer>(_.range(1, 6)) .map(square) .value(); assertEquals(Arrays.asList(new Integer[] {1, 4, 9, 16, 25}), result); } @Test public void staticMapMap() { Map<String, Integer> lengths = new HashMap<String, Integer>(); lengths.put("foo", "foo".length()); lengths.put("quux", "quux".length()); Map<Long, String> expected = new HashMap<Long, String>(); expected.put((long) "foo".length(), "foo"); expected.put((long) "quux".length(), "quux"); Map<Long, String> actual = _.map(lengths, new BiFunction<String, Integer, Map.Entry<Long, String>>() { @Override public Map.Entry<Long, String> apply(String s, Integer integer) { return new AbstractMap.SimpleEntry<Long, String>((long) integer, s); } }); assertEquals(expected, actual); } // ----- _.filter ------------------------------------------------------------------------------ @Test public void staticFilterWithIsEven() { List<Integer> result = _.filter(_.range(1, 6), isEven); assertEquals(Arrays.asList(new Integer[] {2, 4}), result); } @Test public void staticFilterWithNullInput() { assertEquals(Collections.emptyList(), _.filter(null, isEven)); } @Test public void chainedFilterWithIsEven() { Iterable<Integer> result = new _<Integer>(_.range(1, 6)) .filter(isEven) .value(); assertEquals(_.list(2, 4), result); } // ----- _.find -------------------------------------------------------------------------------- @Test public void staticFindWithIsEven() { assertEquals( 2, (int) _.find(_.range(1, 6), isEven) ); } @Test public void staticFindWithNullInput() { assertEquals(null, _.find(null, isEven)); } @Test public void chainedFindWithIsEven() { assertEquals( 2, (int) new _<Integer>(_.range(1, 6)).find(isEven) ); } // ----- _.reduce ------------------------------------------------------------------------------ @Test public void staticReduceWithSum() { Integer result = _.reduce(_.range(1, 6), sum, 0); assertTrue(1 + 2 + 3 + 4 + 5 == result); } @Test public void staticReduceWithNullInput() { assertEquals( 5, (int) _.reduce(null, sum, 5) ); } @Test public void chainedReduceWithSum() { Integer result = new _<Integer>(_.range(1, 6)) .reduce(sum, 0); assertTrue(1 + 2 + 3 + 4 + 5 == result); } @Test public void chainedComplexWithSumOfEvenSquares() { Integer sumOfEvenSquares = new _<Integer>(_.range(1, 11)) .map(square) .filter(isEven) .reduce(sum, 0); assertTrue(4 + 16 + 36 + 64 + 100 == sumOfEvenSquares); } // ---- _.contains ----------------------------------------------------------------------------- @Test public void staticContainsWithIntegers() { assertTrue(_.contains(_.range(1, 6), 4)); assertFalse(_.contains(_.range(1, 4), 6)); } @Test public void staticContainsWithNullInput() { assertFalse(_.contains(null, "foo")); } @Test public void chainedContainsWithIntegers() { assertTrue(new _<Integer>(_.range(1, 6)).contains(4)); assertFalse(new _<Integer>(_.range(1, 4)).contains(6)); } @Test public void staticContainsWithStringEquals() { assertTrue(_.contains(_.list("foo", "bar", "baz"), "foo", stringEquals)); assertFalse(_.contains(_.list("foo", "bar"), "baz", stringEquals)); } @Test public void chainedContainsWithStringEquals() { assertTrue(new _<String>(_.list("foo", "bar", "baz")).contains("foo", stringEquals)); assertFalse(new _<String>(_.list("foo", "bar")).contains("baz", stringEquals)); } // ----- _.sortBy ------------------------------------------------------------------------------ @Test public void staticSortBy() { assertEquals(_.list("foo", "test", "qwert", "zuiopü"), _.sortBy(_.list("test", "zuiopü", "foo", "qwert"), length)); } @Test public void staticSortByNullInput() { assertEquals(Collections.emptyList(), _.sortBy(null, length)); } @Test public void chainedSortBy() { assertEquals(_.list("foo", "test", "qwert", "zuiopü"), new _<String>(_.list("test", "zuiopü", "foo", "qwert")).sortBy(length).value()); } @Test public void chainedSortByNullInput() { assertEquals(Collections.emptyList(), new _<String>(null).sortBy(length).value()); } // ----- _.groupBy ----------------------------------------------------------------------------- @Test public void staticGroupBy() { Map<Integer, List<String>> expected = new HashMap<Integer, List<String>>(); expected.put(3, _.list("foo", "bar", "baz")); expected.put(4, _.list("this", "shit")); assertEquals(expected, _.groupBy(_.list("foo", "bar", "baz", "this", "shit"), new Function<String, Integer>() { public Integer apply(String s) { return s.length(); } })); } @Test public void staticGroupByNullInput() { assertEquals(Collections.emptyMap(), _.groupBy(null, _.identity(Integer.class))); } @Test public void chainedGroupBy() { Map<Integer, List<String>> expected = new HashMap<Integer, List<String>>(); expected.put(3, _.list("foo", "bar", "baz")); expected.put(4, _.list("this", "shit")); assertEquals(expected, new _<String>(_.list("foo", "bar", "baz", "this", "shit")) .groupBy(new Function<String, Integer>() { public Integer apply(String s) { return s.length(); } }) ); } @Test public void chainedGroupNullInput() { assertEquals(Collections.emptyMap(), new _<Integer>(null).groupBy(_.identity(Integer.class))); } // ----- _.reject ------------------------------------------------------------------------------ @Test public void staticRejectWithIsEven() { assertEquals(_.list(1,3,5), _.reject(_.range(1, 6), isEven)); } @Test public void staticRejectWithIsEvenWithNullInput() { assertEquals(Collections.emptyList(), _.reject(null, isEven)); } @Test public void chainedRejectWithIsEven() { assertEquals(_.list(1,3,5), new _<Integer>(_.range(1, 6)).reject(isEven).value()); } @Test public void chainedRejectWithIsEvenWithNullInput() { assertEquals(Collections.emptyList(), new _<Integer>(null).reject(isEven).value()); } // ----- _.every ------------------------------------------------------------------------------- @Test public void staticEvery() { assertTrue(_.every(_.list(2,4,6), isEven)); assertFalse(_.every(_.range(1, 6), isEven)); } @Test public void staticEveryWithNullInput() { assertTrue(_.every(null, isEven)); } @Test public void chainedEvery() { assertTrue(new _<Integer>(_.list(2,4,6)).every(isEven)); assertFalse(new _<Integer>(_.range(1, 6)).every(isEven)); } @Test public void chainedEveryWithNullInput() { assertTrue(new _<Integer>(null).every(isEven)); } // ----- _.some -------------------------------------------------------------------------------- @Test public void staticSome() { assertTrue(_.some(_.range(1, 6), isEven)); assertFalse(_.some(_.list(1,3), isEven)); } @Test public void staticSomeWithNullInput() { assertFalse(_.some(null, isEven)); } @Test public void chainedSome() { assertTrue(new _<Integer>(_.range(1, 6)).some(isEven)); assertFalse(new _<Integer>(_.list(1,3)).some(isEven)); } @Test public void chainedSomeWithNullInput() { assertFalse(new _<Integer>(null).some(isEven)); } // ----- _.size -------------------------------------------------------------------------------- @Test public void staticSize() { assertEquals(3, _.size(_.range(1, 4))); } @Test public void staticSizeWithNullInput() { assertEquals(0, _.size(null)); } @Test public void chainedSize() { assertEquals(3, new _<Integer>(_.range(1, 4)).size()); } // ----- _.first ------------------------------------------------------------------------------- @Test public void staticFirst() { assertEquals(_.range(1, 4), _.first(_.range(1, 5), 3)); } @Test public void staticFirstWithNullInput() { assertEquals(Collections.emptyList(), _.first(null, 3)); } @Test public void staticFirstDefaultN() { assertTrue(1 == _.first(_.range(1, 5))); } @Test public void chainedFirst() { assertEquals(_.range(1, 4),new _<Integer>(_.range(1, 5)).first(3).value()); } @Test public void chainedFirstDefaultN() { assertTrue(1 == new _<Integer>(_.range(1, 5)).first()); } // ----- _.initial ----------------------------------------------------------------------------- @Test public void staticInitial() { assertEquals(_.list("foo"), _.initial(_.list("foo", "bar", "baz"), 2)); } @Test public void staticInitialWithNullInput() { assertEquals(Collections.emptyList(), _.initial(null, 2)); } @Test public void staticInitialDefaultN() { assertEquals(_.list("foo", "bar"), _.initial(_.list("foo", "bar", "baz"))); } @Test public void chainedInitial() { assertEquals(_.list("foo"), new _<String>(_.list("foo", "bar", "baz")).initial(2).value()); } @Test public void chainedInitialDefaultN() { assertEquals(_.list("foo", "bar"), new _<String>(_.list("foo", "bar", "baz")).initial().value()); } // ----- _.last -------------------------------------------------------------------------------- @Test public void staticLast() { assertEquals(_.range(4, 6), _.last(_.range(1, 6), 2)); } @Test public void staticLastDefaultN() { assertTrue(4 == _.last(_.range(1, 5))); } @Test public void chainedLast() { assertEquals(_.range(4, 6), new _<Integer>(_.range(1, 6)).last(2).value()); } @Test public void chainedLastDefaultN() { assertTrue(4 == new _<Integer>(_.range(1, 5)).last()); } // ----- _.rest -------------------------------------------------------------------------------- @Test public void staticRest() { assertEquals(_.range(3, 5), _.rest(_.range(1, 5), 2)); } @Test public void staticRestWithNullInput() { assertEquals(Collections.emptyList(), _.rest(null, 2)); } @Test public void staticRestDefaultN() { assertEquals(_.range(2, 5), _.rest(_.range(1, 5))); } @Test public void chainedRest() { assertEquals(_.range(3, 5), new _<Integer>(_.range(1, 5)).rest(2).value()); } @Test public void chainedRestDefaultN() { assertEquals(_.range(2, 5), new _<Integer>(_.range(1, 5)).rest().value()); } // ----- _.zip --------------------------------------------------------------------------------- @Test public void staticZipSameLengths() { assertEquals(_.list(_.entry(0,3), _.entry(1,4), _.entry(2,5)), _.zip(_.range(3), _.range(3,6))); } @Test public void staticZipFirstIsLonger() { assertEquals(_.list(_.entry(0,3), _.entry(1,4)), _.zip(_.range(3), _.range(3,5))); } @Test public void staticZipSecondIsLonger() { assertEquals(_.list(_.entry(0,3), _.entry(1,4), _.entry(2,5)), _.zip(_.range(3), _.range(3,9))); } @Test public void staticZipNullInput() { assertEquals(Collections.emptyList(), _.zip(null, _.range(4))); assertEquals(Collections.emptyList(), _.zip(_.range(4), null)); } @Test public void chainedZipSameLengths() { assertEquals(_.list(_.entry(0,4), _.entry(1,5), _.entry(2,6), _.entry(3,7)), new _<Integer>(_.range(4)).zip(_.range(4,8)).value()); } @Test public void chainedZipFirstIsLonger() { assertEquals(_.list(_.entry(0,3), _.entry(1,4)), new _<Integer>(_.range(4)).zip(_.range(3,5)).value()); } @Test public void chainedZipSecondIsLonger() { assertEquals(_.list(_.entry(0,3), _.entry(1,4)), new _<Integer>(_.range(2)).zip(_.range(3,9)).value()); } @Test public void chainedZipNullInput() { assertEquals(Collections.emptyList(), new _<Integer>(_.range(10)).zip(null).value()); } // ----- _.range ------------------------------------------------------------------------------- @Test public void rangeOptimisticInputs() { assertEquals(_.list(1,2,3,4,5), _.range(1, 6, 1)); } @Test public void rangeNegativeStep() { assertEquals(_.list(0,-1,-2,-3,-4), _.range(0, -5, -1)); } @Test public void rangeOddStep() { assertEquals(_.list(0, 2, 4), _.range(0, 5, 2)); assertEquals(_.list(0, -2, -4), _.range(0, -5, -2)); } @Test public void rangeSameStartStop() { List<Integer> empty = Collections.emptyList(); assertEquals(empty, _.range(0, 0, 1)); } @Test public void rangeZeroStep() { List<Integer> empty = Collections.emptyList(); assertEquals(empty, _.range(0, 100, 0)); } @Test public void rangeStartGreaterStopPositiveStep() { List<Integer> empty = Collections.emptyList(); assertEquals(empty, _.range(5, 0, 1)); } @Test public void rangeDefaultStep() { assertEquals(_.list(0,1,2,3,4), _.range(0, 5)); } @Test public void rangeDefaultStepStartGreaterStop() { List<Integer> empty = Collections.emptyList(); assertEquals(empty, _.range(0, -5)); } @Test public void rangeDefaultStart() { assertEquals(_.list(0,1,2,3,4), _.range(5)); } // ----- _.wrap -------------------------------------------------------------------------------- @Test public void wrap() { final String before = "before ++ "; final String after = " ++ after"; final Function<String, String> expected = new Function<String, String>() { @Override public String apply(String s) { return before + s + after; } }; final Function<String, String> actual = _.wrap(_.identity(String.class), new Function<Function<String, String>, Function<String, String>>() { public Function<String, String> apply(final Function<String, String> wrapped) { return new Function<String, String>() { public String apply(String s){ return before + wrapped.apply(s) + after; } }; } }); _.each(_.list("foo", "bar", "baz"), new Consumer<String>() { @Override public void accept(String s) { assertEquals(expected.apply(s), actual.apply(s)); } }); } // ----- _.negate ------------------------------------------------------------------------------ @Test public void negatePredicate() { final Predicate<String> ofEvenLength = new Predicate<String>() { @Override public boolean test(String s) { return s.length() % 2 == 0; } }; final Predicate<String> ofOddLength = _.negate(ofEvenLength); _.each(_.list("foo", "lorem", "quux"), new Consumer<String>() { @Override public void accept(String s) { assertTrue(ofEvenLength.test(s) ^ ofOddLength.test(s)); } }); } @Test public void negateBiPredicate() { final BiPredicate<String, Integer> isOfLength = new BiPredicate<String, Integer>() { @Override public boolean test(String s, Integer integer) { return s.length() == integer; } }; final BiPredicate<String, Integer> isNotOfLength = _.negate(isOfLength); _.each(_.list("foo:3", "lorem:2", "quux:12"), new Consumer<String>() { @Override public void accept(String s) { String[] unzip = s.split(":"); assertTrue(isOfLength.test(unzip[0], Integer.parseInt(unzip[1])) ^ isNotOfLength.test(unzip[0], Integer.parseInt(unzip[1]))); } }); } // ----- _.extend ------------------------------------------------------------------------------ @Test public void extendWithNothing() { Datastore defaults = datastore(0, 1); Datastore options = datastore(null, null); Datastore expected = datastore(defaults.a, defaults.b); try { Datastore result = _.extend(defaults, options); assertEquals(expected.a, result.a); assertEquals(expected.b, result.b); } catch (Exception e) { fail(e.getMessage()); } } @Test public void extendWithOverrides() { Datastore defaults = datastore(0, 1); Datastore options = datastore(2, 3); Datastore expected = datastore(options.a, options.b); try { Datastore result = _.extend(defaults, options); assertEquals(expected.a, result.a); assertEquals(expected.b, result.b); } catch (Exception e) { fail(e.getMessage()); } } @Test public void extendWithPartialOverrides() { Datastore defaults = datastore(0, 1); Datastore options = datastore(null, 3); Datastore expected = datastore(defaults.a, options.b); try { Datastore result = _.extend(defaults, options); assertEquals(expected.a, result.a); assertEquals(expected.b, result.b); } catch (Exception e) { fail(e.getMessage()); } } private Datastore datastore(Integer a, Integer b) { Datastore result = new Datastore(); result.a = a; result.b = b; return result; } private static class Datastore { public Integer a; public Integer b; } @Test public void extendWithPartialOverridesAndMethodsInDatastore() { MethodDatastore defaults = methodDatastore(0, 1); MethodDatastore options = methodDatastore(null, 3); MethodDatastore expected = methodDatastore(defaults.a, options.b); try { MethodDatastore result = _.extend(defaults, options); assertEquals(expected.a, result.a); assertEquals(expected.b, result.b); } catch (Exception e) { fail(e.getMessage()); } } private MethodDatastore methodDatastore(Integer a, Integer b) { MethodDatastore result = new MethodDatastore(); result.a = a; result.b = b; return result; } private static class MethodDatastore extends Datastore { public void foo() {} } @Test public void extendWithPartialOverridesAndBuilderInDatastore() { BuilderDatastore defaults = new BuilderDatastore.Builder() .setA(0) .setB(1) .build(); BuilderDatastore options = new BuilderDatastore.Builder() .setA(null) .setB(2) .build(); BuilderDatastore expected = new BuilderDatastore.Builder() .setA(defaults.a) .setB(options.b) .build(); try { BuilderDatastore result = _.extend(defaults, options); assertEquals(expected.a, result.a); assertEquals(expected.b, result.b); } catch (Exception e) { fail(e.getMessage()); } } private static class BuilderDatastore extends Datastore { public static class Builder { private BuilderDatastore store = new BuilderDatastore(); public Builder setA(Integer a) { store.a = a; return this; } public Builder setB(Integer b) { store.b = b; return this; } public BuilderDatastore build() { return store; } } } // ----- _.list -------------------------------------------------------------------------------- @Test public void list() { assertTrue(_.list("foo", "bar", "baz") instanceof List); assertEquals(Arrays.asList(new String[] {"foo", "bar"}), _.list(new String[] {"foo", "bar"})); } @Test public void listWithNullInput() { assertEquals(Collections.emptyList(), _.list()); } // ----- _.dictionary -------------------------------------------------------------------------- @Test public void dictionary() { Map<String, Integer> expected = new HashMap<String, Integer>(); expected.put("foo", "foo".length()); expected.put("bar", "bar".length()); Map<String, Integer> actual = _.dictionary( _.entry("foo", "foo".length()), _.entry("bar", "bar".length()) ); assertEquals(expected, actual); } @Test public void dictionaryWithNullInput() { assertEquals(Collections.emptyMap(), _.dictionary(null)); } // ----- _.entry ------------------------------------------------------------------------------- @Test public void entry() { assertEquals(new AbstractMap.SimpleEntry<String,Integer>("foo", 3), _.entry("foo", 3)); } // ----- _.join -------------------------------------------------------------------------------- @Test public void staticJoin() { assertEquals("foo::bar", _.join(_.list("foo", "bar"), "::")); } @Test public void staticJoinDefaultSeparator() { assertEquals("foo,bar", _.join(_.list("foo", "bar"))); } @Test public void staticJoinWithNullInput() { assertEquals("", _.join(null, ",")); } @Test public void staticJoinDefaultSeparatorWithNullInput() { // need to cast -- otherwise multiple methods match _.join(null) assertEquals("", _.join((Iterable<String>) null)); } @Test public void chainedJoin() { assertEquals("foo::bar", new _<String>(_.list("foo", "bar")).join("::")); } @Test public void chainedJoinDefaultSeparator() { assertEquals("foo,bar", new _<String>(_.list("foo", "bar")).join()); } @Test public void chainedJoinWithNullInput() { assertEquals("", new _<String>(null).join("::")); } @Test public void chainedJoinDefaultSeparatorWithNullInput() { assertEquals("", new _<String>(null).join()); } // ----- _.stringify --------------------------------------------------------------------------- @Test public void staticStringifyTerminalCases() { assertEquals("1", _.stringify(1)); assertEquals("1.0", _.stringify(1.0)); assertEquals("true", _.stringify(true)); assertEquals("\"foo\"", _.stringify("foo")); } @Test public void staticStringifyListCase() { assertEquals("[0,1,2,3]", _.stringify(_.range(4))); } @Test public void staticStringifyMapCase() { Map<String, Integer> json = new HashMap<String, Integer>(); json.put("0", 1); json.put("1", 5); json.put("2", 9); assertEquals("{\"0\":1,\"1\":5,\"2\":9}", _.stringify(json)); } @Test public void staticStringifyComplexCase() { Map<String, Integer> frequencies = new HashMap<String, Integer>(); frequencies.put("a", 20); frequencies.put("b", 4); frequencies.put("c", 12); Map<String, String> complex = new HashMap<String, String>(); complex.put("name", _.stringify(_.list("foo", "bar"))); complex.put("frequencies", _.stringify(frequencies)); assertEquals("{\"name\":[\"foo\",\"bar\"],\"frequencies\":{\"a\":20,\"b\":4,\"c\":12}}", _.stringify(complex)); } @Test public void staticStringifyComplexListCase() { Map<String, String> json1 = new HashMap<String, String>(); json1.put("1foo", "[\"bar\"]"); json1.put("2goo", "[\"gl\"]"); Map<String, String> json2 = new HashMap<String, String>(); json2.put("3oo", "[\"ps\"]"); json2.put("4no", "[\"oo\"]"); assertEquals("[{\"1foo\":[\"bar\"],\"2goo\":[\"gl\"]},{\"3oo\":[\"ps\"],\"4no\":[\"oo\"]}]", _.stringify(_.list(json1, json2))); } @Test public void staticStringifyComplexMixedCase() { Map<String, Object> json = new HashMap<String, Object>(); json.put("string", "thisIsAString"); json.put("number", 1337); json.put("list", _.list(1,2,3,4,5)); Map<String, Object> nested = new HashMap<String, Object>(); nested.put("string", "thisIsAnotherString"); nested.put("number", 12345); json.put("map", nested); assertEquals("{\"number\":1337,\"string\":\"thisIsAString\",\"list\":[1,2,3,4,5],\"map\":{\"number\":12345,\"string\":\"thisIsAnotherString\"}}", _.stringify(json)); } // ----- _.identity ---------------------------------------------------------------------------- @Test public void identity() { final Function<String, String> expected = new Function<String, String>() { public String apply(String s) { return s; } }; final Function<String, String> actual = _.identity(String.class); _.each(_.list("foo", "bar", "baz"), new Consumer<String>() { @Override public void accept(String s) { assertEquals(expected.apply(s), actual.apply(s)); } }); } // ----- _.constant ---------------------------------------------------------------------------- @Test public void constant() { assertEquals("foo", _.constant("foo").get()); } }
mit
kalessil/yii2inspections
src/main/java/com/kalessil/phpStorm/yii2inspections/inspectors/utils/InheritanceChainExtractUtil.java
1936
package com.kalessil.phpStorm.yii2inspections.inspectors.utils; import com.jetbrains.php.lang.psi.elements.PhpClass; import org.jetbrains.annotations.NotNull; import java.security.InvalidParameterException; import java.util.HashSet; import java.util.Set; /* * This file is part of the Yii2 Inspections package. * * Author: Vladimir Reznichenko <kalessil@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ final public class InheritanceChainExtractUtil { @NotNull public static Set<PhpClass> collect(@NotNull PhpClass clazz) { final Set<PhpClass> processedItems = new HashSet<>(); if (clazz.isInterface()) { processInterface(clazz, processedItems); } else { processClass(clazz, processedItems); } return processedItems; } private static void processClass(@NotNull PhpClass clazz, @NotNull Set<PhpClass> processed) { if (clazz.isInterface()) { throw new InvalidParameterException("Interface shall not be provided"); } processed.add(clazz); /* re-delegate interface handling */ for (PhpClass anInterface : clazz.getImplementedInterfaces()) { processInterface(anInterface, processed); } /* handle parent class */ if (null != clazz.getSuperClass()) { processClass(clazz.getSuperClass(), processed); } } private static void processInterface(@NotNull PhpClass clazz, @NotNull Set<PhpClass> processed) { if (!clazz.isInterface()) { throw new InvalidParameterException("Class shall not be provided"); } if (processed.add(clazz)) { for (PhpClass parentInterface : clazz.getImplementedInterfaces()) { processInterface(parentInterface, processed); } } } }
mit
dersoncheng/OpenAtlas
OpenAtlasCore/src/com/openatlas/runtime/RuntimeVariables.java
1811
/** * OpenAtlasForAndroid Project The MIT License (MIT) Copyright (OpenAtlasForAndroid) 2015 Bunny Blue,achellies 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 BunnyBlue * **/ package com.openatlas.runtime; import android.app.Application; import android.content.res.Resources; import android.util.Log; public class RuntimeVariables { public static Application androidApplication; public static DelegateClassLoader delegateClassLoader; private static Resources delegateResources; public static Resources getDelegateResources() { return delegateResources; } public static void setDelegateResources(Resources delegateResources) { Log.e("bunny", "setDelegateResources" + delegateResources.toString()); RuntimeVariables.delegateResources = delegateResources; } }
mit
IsaiasSantana/CarGame
core/src/com/cargame/gameWorld/GameWorld.java
7073
package com.cargame.gameWorld; import com.cargame.gameObjects.Car; import com.cargame.gameObjects.EnemyCar; import com.cargame.gameObjects.PlayerCar; import com.cargame.gameObjects.RoadControl; import com.cargame.helpers.AssetLoader; import java.util.ArrayList; import java.util.Iterator; /** * Created by isaias on 19/11/16. * updating objects game. */ public class GameWorld { private static int countLevel; private static ArrayList<Float> distance; private static int highScore; private static int level; private static ArrayList<EnemyCar> rival; private static GameWorld world; private States currentState; private PlayerCar player; private RoadControl roadControl; private float runTime; public enum States { OPENING, READY, RUNNING, GAME_OVER, HIGH_SCORE, ABOUT, CREDITS } private GameWorld() { this.player = new PlayerCar(Car.INI_POSITION_X, Car.INI_POSITION_Y, 30, 30, 0.0f, 0.0f); rival = new ArrayList(); distance = new ArrayList(); this.roadControl = RoadControl.getInstance(); this.currentState = States.OPENING; this.runTime = 0.0f; highScore = 0; level = 1; } public void dispose() { this.player.dispose(); rival.clear(); rival = null; distance.clear(); distance = null; this.currentState = null; this.roadControl.dispose(); } public void update(float delta) { switch (currentState) { case OPENING: opening(); break; case READY: ready(delta); break; case RUNNING: running(delta); break; case GAME_OVER: gameOver(); break; } } private void opening() { if (!AssetLoader.intro.isPlaying()) { AssetLoader.intro.play(); AssetLoader.intro.setLooping(true); AssetLoader.intro.setVolume(0.2f); } } public boolean isAbout() { return this.currentState == States.ABOUT; } public boolean isOpening() { return this.currentState == States.OPENING; } public boolean isReady() { return this.currentState == States.READY; } public boolean isRunning() { return this.currentState == States.RUNNING; } public boolean isGameOver() { return this.currentState == States.GAME_OVER; } public boolean isHighScore() { return this.currentState == States.HIGH_SCORE; } public void setCurrentState(States state) { this.currentState = state; } public States getCurrentState() { return this.currentState; } private void ready(float delta) { if (AssetLoader.intro.isPlaying()) { AssetLoader.intro.stop(); } else if (!AssetLoader.musicPlayGame.isPlaying()) { AssetLoader.musicPlayGame.play(); AssetLoader.musicPlayGame.setLooping(true); AssetLoader.musicPlayGame.setVolume(0.2f); } this.roadControl.update(delta); } private void running(float delta) { this.player.update(delta); this.roadControl.update(delta); Iterator it = rival.iterator(); while (it.hasNext()) { EnemyCar car = (EnemyCar) it.next(); car.update(delta); if (testCollision(car) && this.player.isAlive()) { this.player.setIsAlive(false); this.player.stop(); this.roadControl.setVelocity(0.0f); AssetLoader.explosion.play(); break; } } if (!this.player.isAlive() && this.runTime < 1.03f) { this.runTime = this.runTime + 0.005f; } if (this.runTime > 1.03f) { this.runTime = 0.0f; if (AssetLoader.musicPlayGame.isPlaying()) { AssetLoader.musicPlayGame.stop(); } this.currentState = States.GAME_OVER; } } private void gameOver() { if (AssetLoader.musicPlayGame.isPlaying()) { AssetLoader.musicPlayGame.stop(); } else if (!AssetLoader.musicGameOver.isPlaying()) { AssetLoader.musicGameOver.play(); AssetLoader.musicGameOver.setVolume(0.2f); AssetLoader.musicGameOver.setLooping(false); } this.runTime = this.runTime + 0.005f; if (this.runTime > 0.5f) { this.runTime = 0.0f; this.currentState = States.HIGH_SCORE; } this.roadControl.reset(); this.player.reset(); for (int i = 0; i < rival.size(); i++) { rival.get(i).reset(distance.get(i)); } level = 1; countLevel = 1; } public static GameWorld getInstanceWorld() { if (world == null) { world = new GameWorld(); } return world; } public PlayerCar getPlayerCar() { return this.player; } public RoadControl getRoad() { return this.roadControl; } public ArrayList<EnemyCar> getRivalsCars() { return rival; } public void initCarsRivals(float posX1, float posX2, float width, float height) { float positionY = -90.0f; for (int i = 0; i < 30; i++) { if (i % 2 == 0) { distance.add(positionY); rival.add(new EnemyCar(posX1, positionY, RoadControl.getVelocity(), width, height)); } else { distance.add(positionY); rival.add(new EnemyCar(posX2, positionY, RoadControl.getVelocity(), width, height)); } positionY -= 70.0f; } } public boolean testCollision(EnemyCar car) { if (!Car.collision(this.player, car)) { return false; } car.setCollide(true); return true; } public static void countHighScore() { highScore++; } public static void setHighScore(int highScore) { highScore = highScore; } public static int getHighScore() { return highScore; } public static void setLevel(int level) { level = level; } public static int getCountLevel() { return countLevel; } public static void resetScoreAndLevel(){ highScore = 0; level = 1; } public static void setCountLevel(int level) { countLevel = level; } public static int getLevel() { return level; } public static int getTotalRivalCars() { return rival.size(); } public static ArrayList<Float> getDistances() { return distance; } }
mit
Shaojia/ZHCarPocket
MaintainService/src/com/coortouch/app/wcf/listener/GetOneRecordListener.java
143
package com.coortouch.app.wcf.listener; public interface GetOneRecordListener<T> { void onFinish(T data); void onFailed(String Message); }
mit
roxan/letsgo
code/src/edu/mum/waa/group9/DaoImp/RideDaoImpl.java
1808
package edu.mum.waa.group9.DaoImp; import java.sql.Connection; import java.sql.PreparedStatement; import edu.mum.waa.group9.beanInterfaces.RideInterface; import edu.mum.waa.group9.daoFacade.RideDaoFacade; import edu.mum.waa.group9.utils.ConnectionManager; import edu.mum.waa.group9.utils.DateUtil; public class RideDaoImpl implements RideDaoFacade { private String INSERT_RECORD = "INSERT INTO RIDE (person_id,source,destination,depart_date,depart_time," + "return_date,return_time,description,capacity,vehicle_description," + "expected_expense,ride_type) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)"; private boolean insert_success = false; @Override public boolean createRide(RideInterface rideBean) { System.out.println("Inside RideDaoImpl--createRide"); PreparedStatement ps; Connection con; try { con = ConnectionManager.getConnection(); try { System.out.println("rideBean.getSource-->"+rideBean.getSource()); ps = con.prepareStatement(INSERT_RECORD); ps.setInt(1, rideBean.getPerson().getId()); ps.setString(2, rideBean.getSource()); ps.setString(3, rideBean.getDestination()); ps.setDate(4, DateUtil.sqlDate(rideBean.getDepartDate())); ps.setString(5, rideBean.getDepartTime()); ps.setDate(6, DateUtil.sqlDate(rideBean.getReturnDate())); ps.setString(7, rideBean.getReturnTime()); ps.setString(8, rideBean.getDescription()); ps.setInt(9, rideBean.getCapacity()); ps.setString(10, rideBean.getVehicleDescription()); ps.setBigDecimal(11, rideBean.getExpectedExpense()); ps.setString(12, rideBean.getRideType()); ps.executeUpdate(); insert_success = true; ps.close(); } finally { ConnectionManager.closeConnection(con); } } catch (Exception e) { e.printStackTrace(); } return insert_success; } }
mit
lehmann/ArtigoMSM_UFSC
artigo/src/test/java/br/ufsc/lehmann/classifier/MSTPClassifierTest.java
577
package br.ufsc.lehmann.classifier; import br.ufsc.core.IMeasureDistance; import br.ufsc.core.trajectory.SemanticTrajectory; import br.ufsc.lehmann.EnumProblem; import br.ufsc.lehmann.method.MSTPTest; import br.ufsc.lehmann.msm.artigo.Problem; public class MSTPClassifierTest extends AbstractClassifierTest implements MSTPTest { public MSTPClassifierTest(EnumProblem problemDescriptor) { super(problemDescriptor); } @Override public IMeasureDistance<SemanticTrajectory> measurer(Problem problem) { return MSTPTest.super.measurer(problem); } }
mit
hindsightsoftware/upkeep-jira-cloudformation-maven-plugin
src/main/java/com/hindsightsoftware/upkeep/JiraRestoreUtils.java
6038
package com.hindsightsoftware.upkeep; import org.apache.maven.plugin.logging.Log; import java.io.IOException; import java.util.Arrays; import java.util.List; public class JiraRestoreUtils { public static boolean uploadCredentials(SecuredShellClient ssh, String s3AwsCredentials, String s3AwsConfig){ List<SecuredShellClient.FilePair> files = Arrays.asList( new SecuredShellClient.FilePair(s3AwsCredentials, ".aws/"), new SecuredShellClient.FilePair(s3AwsConfig, ".aws/") ); return ssh.execute("mkdir -p .aws") == 0 && ssh.uploadFile(files); } public static boolean getPsqlFromBucket(SecuredShellClient ssh, String bucketName, String psqlFileName){ return ssh.execute("aws s3 cp s3://" + bucketName + "/" + psqlFileName + " .") == 0; } public static boolean stopJira(SecuredShellClient ssh){ List<String> commands = Arrays.asList( // Stop "(sudo /opt/atlassian/jira/bin/shutdown.sh > /dev/null 2>&1 || true)", // Wait until is down "while pgrep -u root java > /dev/null; do echo \'Waiting for JIRA to shutdown...\' & sleep 10 & (sudo /opt/atlassian/jira/bin/shutdown.sh > /dev/null 2>&1 || true); done; echo \'JIRA is down.\'" ); return ssh.execute(commands) == 0; } public static boolean startJira(SecuredShellClient ssh){ List<String> commands = Arrays.asList( // Sometimes JIRA complains about this... //"sudo rm -f /opt/atlassian/jira/work/catalina.pid", // Start "sudo su -c \"exec env USE_NOHUP=true /opt/atlassian/jira/bin/startup.sh > /dev/null\"; sleep 10", // Check if PID is alive "ps cax | grep $(sudo cat /opt/atlassian/jira/work/catalina.pid) || (echo \"No active JIRA PID found! JIRA did not start!\" & exit 1)" ); return ssh.execute(commands) == 0; } public static boolean uploadSetenv(SecuredShellClient ssh, String setenvPath){ List<SecuredShellClient.FilePair> files = Arrays.asList( new SecuredShellClient.FilePair(setenvPath, "/home/ec2-user/") ); if(!ssh.uploadFile(files)){ return false; } return ssh.execute("sudo mv /home/ec2-user/setenv.sh /opt/atlassian/jira/bin/setenv.sh") == 0; } public static boolean restoreFromPsql(Log log, SecuredShellClient ssh, String endpoint, String password, String psqlFileName){ if(ssh.execute("PGPASSWORD=\'" + password + "\' createdb -h " + endpoint + " -p 5432 -U postgres jira") != 0){ log.info("Database has been already created... Terminating all connections..."); List<String> commands = Arrays.asList( // Terminate all connections "PGPASSWORD=\'" + password + "\' psql -h " + endpoint + " -p 5432 -U postgres jira -c \"SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid();\"", // Drop the database "PGPASSWORD=\'" + password + "\' dropdb -h " + endpoint + " --if-exists -p 5432 -U postgres jira", // Create new one "PGPASSWORD=\'" + password + "\' createdb -h " + endpoint + " -p 5432 -U postgres jira" ); if(ssh.execute(commands) != 0){ return false; } } // Restore data return ssh.execute("PGPASSWORD=\'" + password + "\' pg_restore -j 4 -v -n public -h " + endpoint + " -p 5432 -U postgres -d jira \"" + psqlFileName + "\"") == 0; } public static boolean getIndexesFromBucket(SecuredShellClient ssh, String bucketName, String indexesFileName){ List<String> commands = Arrays.asList( // Download xml/zip file from S3 bucket "aws s3 cp s3://" + bucketName + "/" + indexesFileName + " .", // Copy to destination "sudo tar -xzvf " + indexesFileName + " -C /var/atlassian/application-data/jira/caches/indexes", // Make jira as owner of the extracted indexes "sudo chown -R jira /var/atlassian/application-data/jira/caches/indexes/" ); return ssh.execute(commands) == 0; } private static boolean checkResponse(Log log, Http.Response response) throws IOException { if(response.getStatusCode() == 302){ return true; } String body = response.getBody(); if(body.contains("Could not find file at this location")){ log.error("Unable to restore JIRA, file not found"); } else if(body.contains("JIRA has already been set up")){ log.error("JIRA has already been set up"); } else { log.error("Incorrect response code returned: " + response.getStatusCode() + " but expected 302"); log.error("Has your JIRA already been set up?"); } return false; } public static boolean waitForJiraToBeAlive(SecuredShellClient ssh, Log log, int maxWaitTime){ return new TimeoutBlock(maxWaitTime, 10000) {@Override public boolean block(){ return ssh.execute("curl -sS --fail --connect-timeout 5 --max-time 5 -o /dev/null localhost:8080") == 0; }}.run(); } public static boolean waitForUrlToBeAlive(Log log, String host, int maxWaitTime){ return new TimeoutBlock(maxWaitTime, 10000) {@Override public boolean block() { try { Http.Response response = Http.GET(host).timeout(5).send(); log.info("GET \"" + host + "\" returned " + response.getStatusCode()); return response.getStatusCode() >= 200 && response.getStatusCode() < 500; } catch (IOException e) { log.info("GET \"" + host + "\" timeout"); return false; } }}.run(); } }
mit
devdebonair/acme
HourType.java
78
enum HourType { Regular, Callback, Holiday, Vacation, JuryDuty, Bereavement }
mit
accelazh/EngineV2
EngineV2_Branch/src/com/accela/TestCases/synchronizeSupport/TestingConfigViewLock.java
363
package com.accela.TestCases.synchronizeSupport; public class TestingConfigViewLock { /** * ConfigViewLockµÄ²âÊÔÊÇ»ùÓÚ¶ÔÏ̵߳ģ¬ÎÞ·¨×Ô¶¯²âÊÔ¡£ * Äã¿ÉÒÔʹÓÃConfigViewLockTester£¬¸ù¾ÝÆä×¢ÊÍÖеÄ˵ * Ã÷´ó¸ÙÊÖ¶¯²âÊÔ */ public void test() { ConfigViewLockTester t=new ConfigViewLockTester(); t.startTestThreads(); t.bombTest(); } }
mit
dromelvan/dromelvan-core
src/main/java/org/dromelvan/modell/TillgangligSpelare.java
1615
package org.dromelvan.modell; /** * @author macke */ public class TillgangligSpelare extends PersistentObjekt { /** * */ private static final long serialVersionUID = 5856908650562800720L; private DeByteOmgang deByteOmgang; private Spelare spelare; private Deltagare deltagare; private boolean ny; public TillgangligSpelare() {} public DeByteOmgang getDeByteOmgang() { return deByteOmgang; } public void setDeByteOmgang(DeByteOmgang deByteOmgang) { this.deByteOmgang = deByteOmgang; } public Spelare getSpelare() { return spelare; } public void setSpelare(Spelare spelare) { this.spelare = spelare; } public Deltagare getDeltagare() { return deltagare; } public void setDeltagare(Deltagare deltagare) { this.deltagare = deltagare; } public boolean isNy() { return ny; } public void setNy(boolean ny) { this.ny = ny; } public int compareTo(PersistentObjekt persistentObjekt) { TillgangligSpelare tillgangligSpelare = ((TillgangligSpelare)persistentObjekt); int compare = 0; if(getDeltagare() != null) { if(getDeltagare().getId() == 1 && tillgangligSpelare.getDeltagare().getId() > 1) { return 1; } else if(getDeltagare().getId() > 1 && tillgangligSpelare.getDeltagare().getId() == 1) { return -1; } compare = getDeltagare().compareTo(tillgangligSpelare.getDeltagare()); } if(compare == 0) { compare = getSpelare().getPosition().compareTo(tillgangligSpelare.getSpelare().getPosition()); } if(compare == 0) { compare = getSpelare().compareTo(tillgangligSpelare.getSpelare()); } return compare; } }
mit
iitc/access
src/main/java/com/iancaffey/access/google/maps/TravelMode.java
341
package com.iancaffey.access.google.maps; import com.iancaffey.access.util.QueryToken; /** * TravelMode * * @author Ian Caffey * @since 1.0 */ public enum TravelMode implements QueryToken { DRIVING, WALKING, BICYCLING, TRANSIT; @Override public String toToken() { return name().toLowerCase(); } }
mit
webfolderio/cormorant
cormorant-core/src/main/java/io/webfolder/cormorant/api/SQLiteDataSourceFactory.java
1954
/** * The MIT License * Copyright © 2017, 2019 WebFolder OÜ * * 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 io.webfolder.cormorant.api; import static java.io.File.separator; import static java.lang.String.format; import static org.sqlite.SQLiteConfig.Encoding.UTF8; import java.nio.file.Path; import javax.sql.DataSource; import org.sqlite.SQLiteConfig; import org.sqlite.SQLiteDataSource; public class SQLiteDataSourceFactory implements DataSourceFactory { private final SQLiteDataSource ds; public SQLiteDataSourceFactory(final Path metadataStore) { SQLiteConfig config = new SQLiteConfig(); config.setEncoding(UTF8); config.setSharedCache(true); ds = new SQLiteDataSource(config); ds.setUrl(format("jdbc:sqlite:%s%scormorant.db", metadataStore.toAbsolutePath(), separator)); } @Override public DataSource get() { return ds; } }
mit
biddyweb/devicehive-java-server
src/main/java/com/devicehive/service/DeviceCommandService.java
3183
package com.devicehive.service; import com.devicehive.auth.HivePrincipal; import com.devicehive.messages.bus.MessageBus; import com.devicehive.model.Device; import com.devicehive.model.DeviceCommand; import com.devicehive.model.User; import com.devicehive.model.wrappers.DeviceCommandWrapper; import com.devicehive.service.time.TimestampService; import com.devicehive.util.HiveValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.Date; import java.util.Random; @Service public class DeviceCommandService extends AbstractHazelcastEntityService { @Autowired private TimestampService timestampService; @Autowired private HiveValidator hiveValidator; @Autowired private MessageBus messageBus; public DeviceCommand find(Long id, String guid) { return find(id, guid, DeviceCommand.class); } public Collection<DeviceCommand> find(Collection<String> devices, Collection<String> names, Date timestamp, String status, Integer take, Boolean isUpdated, HivePrincipal principal) { return find(devices, names, timestamp, status, take, isUpdated, principal, DeviceCommand.class); } public DeviceCommand convertToDeviceCommand(DeviceCommandWrapper commandWrapper, Device device, User user, Long commandId) { DeviceCommand command = new DeviceCommand(); command.setTimestamp(timestampService.getTimestamp()); if (commandId == null) { //TODO: Replace with UUID command.setId(Math.abs(new Random().nextInt())); } else { command.setId(commandId); } command.setDeviceGuid(device.getGuid()); command.setCommand(commandWrapper.getCommand()); if (user != null) { command.setUserId(user.getId()); } if (commandWrapper.getParameters() != null) { command.setParameters(commandWrapper.getParameters()); } if (commandWrapper.getLifetime() != null) { command.setLifetime(commandWrapper.getLifetime()); } if (commandWrapper.getStatus() != null) { command.setStatus(commandWrapper.getStatus()); } if (commandWrapper.getResult() != null) { command.setResult(commandWrapper.getResult()); } hiveValidator.validate(command); return command; } public void store(DeviceCommand command) { command.setIsUpdated(false); store(command, DeviceCommand.class); } //FIXME: temporary added, need to understand necessity of this method public void submitDeviceCommandUpdate(DeviceCommand command) { final DeviceCommand existing = find(command.getId(), command.getDeviceGuid()); if(existing != null) { if(command.getCommand() == null) { command.setCommand(existing.getCommand()); } command.setIsUpdated(true); store(command); } messageBus.publishDeviceCommandUpdate(command); } }
mit
anassinator/dpm
Lab 1/Printer.java
1029
import lejos.nxt.Button; import lejos.nxt.LCD; import lejos.nxt.Motor; public class Printer extends Thread { private UltrasonicController cont; private final int option; public Printer(int option, UltrasonicController cont) { this.cont = cont; this.option = option; } public void run() { while (true) { LCD.clear(); LCD.drawString("Controller Type is... ", 0, 0); if (this.option == Button.ID_LEFT) LCD.drawString("BangBang", 0, 1); else if (this.option == Button.ID_RIGHT) LCD.drawString("P type", 0, 1); LCD.drawString("US Distance: " + cont.readUSDistance(), 0, 1 ); // UNCOMMENT TO PRINT MAX SPEED OF A MOTOR. FOR TESTING PURPOSES ONLY // LCD.drawString(String.valueOf(Motor.A.getMaxSpeed()), 0, 2 ); try { Thread.sleep(200); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } } public static void printMainMenu() { LCD.clear(); LCD.drawString("left = bangbang", 0, 0); LCD.drawString("right = p type", 0, 1); } }
mit
danielvilas/ArduinoCurrentMonitor
SomAnalisys/src/main/java/es/daniel/somanalisys/data/CustomData.java
149
package es.daniel.somanalisys.data; import java.util.Date; public interface CustomData { public String getFile(); public Date getDate(); }
mit
bcvsolutions/CzechIdMng
Realization/backend/core/core-impl/src/test/java/eu/bcvsolutions/idm/core/bulk/action/impl/script/ScriptRedeployBulkActionIntegrationTest.java
5913
package eu.bcvsolutions.idm.core.bulk.action.impl.script; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import eu.bcvsolutions.idm.core.api.bulk.action.dto.IdmBulkActionDto; import eu.bcvsolutions.idm.core.api.domain.CoreResultCode; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto; import eu.bcvsolutions.idm.core.api.dto.IdmScriptDto; import eu.bcvsolutions.idm.core.api.dto.ResultModel; import eu.bcvsolutions.idm.core.api.dto.ResultModels; import eu.bcvsolutions.idm.core.api.dto.filter.IdmScriptFilter; import eu.bcvsolutions.idm.core.api.service.IdmScriptService; import eu.bcvsolutions.idm.core.api.service.Recoverable; import eu.bcvsolutions.idm.core.model.entity.IdmScript; import eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission; import eu.bcvsolutions.idm.test.api.AbstractBulkActionTest; /** * Integration tests for {@link ScriptRedeployBulkAction} * * @author Ondrej Husnik * */ public class ScriptRedeployBulkActionIntegrationTest extends AbstractBulkActionTest { private static final String TEST_SCRIPT_CODE_1 = "testScript1"; private static final String TEST_BACKUP_FOLDER = "/tmp/idm_test_backup/"; private static final String CHANGED_TEST_DESC = "CHANGED_TEST_DESC"; @Autowired private IdmScriptService scriptService; @Before public void login() { IdmIdentityDto adminIdentity = this.createUserWithAuthorities(IdmBasePermission.UPDATE); loginAsNoAdmin(adminIdentity.getUsername()); configurationService.setValue(Recoverable.BACKUP_FOLDER_CONFIG, TEST_BACKUP_FOLDER); cleanUp(); } @After public void logout() { super.logout(); } @Test public void processBulkActionByIds() { IdmScriptDto script1 = scriptService.getByCode(TEST_SCRIPT_CODE_1); Set<UUID> scripts = new HashSet<UUID>(); scripts.add(script1.getId()); String origDesc = script1.getDescription(); script1.setDescription(CHANGED_TEST_DESC); script1 = scriptService.save(script1); assertNotEquals(script1.getDescription(), origDesc); IdmBulkActionDto bulkAction = this.findBulkAction(IdmScript.class, ScriptRedeployBulkAction.NAME); bulkAction.setIdentifiers(scripts); IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, 1l, null, null); script1 = scriptService.get(script1.getId()); assertEquals(script1.getDescription(), origDesc); } @Test public void processBulkActionByFilter() { IdmScriptDto script1 = scriptService.getByCode(TEST_SCRIPT_CODE_1); Set<UUID> scripts = new HashSet<UUID>(); scripts.add(script1.getId()); String origDesc = script1.getDescription(); script1.setDescription(CHANGED_TEST_DESC); script1 = scriptService.save(script1); assertNotEquals(script1.getDescription(), origDesc); IdmScriptFilter filter = new IdmScriptFilter(); filter.setCode(TEST_SCRIPT_CODE_1); List<IdmScriptDto> checkScripts = scriptService.find(filter, null).getContent(); assertEquals(1, checkScripts.size()); IdmBulkActionDto bulkAction = this.findBulkAction(IdmScript.class, ScriptRedeployBulkAction.NAME); bulkAction.setTransformedFilter(filter); bulkAction.setFilter(toMap(filter)); IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, 1l, null, null); script1 = scriptService.get(script1.getId()); assertEquals(script1.getDescription(), origDesc); } @Test public void prevalidationBulkActionByIds() { IdmScriptDto script1 = scriptService.getByCode(TEST_SCRIPT_CODE_1); IdmBulkActionDto bulkAction = this.findBulkAction(IdmScript.class, ScriptRedeployBulkAction.NAME); bulkAction.getIdentifiers().add(script1.getId()); // None info results ResultModels resultModels = bulkActionManager.prevalidate(bulkAction); List<ResultModel> results = resultModels.getInfos(); Assert.assertEquals(2, results.size()); Assert.assertTrue(results.stream().anyMatch(n -> n.getStatusEnum().equals(CoreResultCode.BACKUP_FOLDER_FOUND.toString()))); Assert.assertTrue(results.stream().anyMatch(n -> n.getStatusEnum().equals(CoreResultCode.DEPLOY_SCRIPT_FOLDER_FOUND.toString()))); } @Test public void processBulkActionWithoutPermission() { IdmScriptDto script1 = scriptService.getByCode(TEST_SCRIPT_CODE_1); Set<UUID> scripts = new HashSet<UUID>(); scripts.add(script1.getId()); String origDesc = script1.getDescription(); script1.setDescription(CHANGED_TEST_DESC); script1 = scriptService.save(script1); assertNotEquals(script1.getDescription(), origDesc); // user hasn't permission for script update IdmIdentityDto readerIdentity = this.createUserWithAuthorities(IdmBasePermission.READ); loginAsNoAdmin(readerIdentity.getUsername()); IdmBulkActionDto bulkAction = this.findBulkAction(IdmScript.class, ScriptRedeployBulkAction.NAME); bulkAction.setIdentifiers(scripts); IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, 0l, null, null); script1 = scriptService.get(script1.getId()); assertEquals(script1.getDescription(), CHANGED_TEST_DESC); } /** * Cleans backup directory after every test */ private void cleanUp() { String bckFolderName = configurationService.getValue(Recoverable.BACKUP_FOLDER_CONFIG); File path = new File(bckFolderName); if (path.exists() && path.isDirectory()) { try { FileUtils.deleteDirectory(path); } catch (IOException e) { fail("Unable to clean up backup directory!"); } } } }
mit
digitalheir/lombok
test/transform/resource/before/ValLessSimple.java
468
import lombok.val; public class ValLessSimple { private short field2 = 5; private String method() { return "method"; } private double method2() { return 2.0; } { System.out.println("Hello"); val z = 20; val x = 10; val a = z; val y = field2; } private void testVal(String param) { val fieldV = field; val a = 10; val b = 20; { val methodV = method(); val foo = fieldV + methodV; } } private String field = "field"; }
mit
nnest/sparrow
sparrow-api/src/main/java/com/github/nnest/sparrow/ElasticCommand.java
551
/** * */ package com.github.nnest.sparrow; /** * elastic command * * @author brad.wu * @since 0.0.1 * @version 0.0.1 */ public interface ElasticCommand { /** * get command kind * * @return command kind */ ElasticCommandKind getCommandKind(); /** * analysis current command by given analyzer * * @param documentAnalyzer * document analyzer * @return returns myself or a new command if want, according to * implementation */ ElasticCommand analysis(ElasticDocumentAnalyzer documentAnalyzer); }
mit
Ruben-Sten/TeXiFy-IDEA
gen/nl/hannahsten/texifyidea/psi/LatexEndCommand.java
309
// This is a generated file. Not intended for manual editing. package nl.hannahsten.texifyidea.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface LatexEndCommand extends PsiElement { @NotNull List<LatexParameter> getParameterList(); }
mit
debrecenics/PropertyBasedLockingEvaluation
evaluation/org.mondo.collaboration.security.lock.eval/src/org/mondo/collaboration/security/lock/eval/distribution/IDistribution.java
137
package org.mondo.collaboration.security.lock.eval.distribution; public interface IDistribution { public double getNext(); }
mit
PotatoSauceMC/Graphics-Testing
src/com/potatosaucevfx/Boxy.java
764
package com.potatosaucevfx; import java.awt.Color; import java.awt.Graphics; public class Boxy { static int x; static int y; int size = 10; int speedMod = 2; static boolean goingLeft = false; static boolean goingRight = false; static boolean goingUp = false; static boolean goingDown = false; @SuppressWarnings("static-access") public Boxy(int x, int y){ this.x = x * speedMod; this.y = y * speedMod; } public void tick(Main main) { if(goingUp && y > 0){ y--; } if(goingDown && y < Main.HEIGHT){ y++; } if(goingRight && x < Main.WIDTH) { x++; } if(goingLeft && x > 0){ x--; } } public void render(Graphics g) { g.setColor(Color.white); g.fillRect(Main.fx, Main.fy, size, size); } }
mit
equus52/algorithm-sample
src/main/java/equus/independent/data/Tuple.java
1388
package equus.independent.data; public class Tuple<T1, T2> { private final T1 value1; private final T2 value2; public Tuple(T1 value1, T2 value2) { this.value1 = value1; this.value2 = value2; } public T1 getValue1() { return value1; } public T2 getValue2() { return value2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value1 == null) ? 0 : value1.hashCode()); result = prime * result + ((value2 == null) ? 0 : value2.hashCode()); return result; } @SuppressWarnings("rawtypes") @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Tuple other = (Tuple) obj; if (value1 == null) { if (other.value1 != null) { return false; } } else if (!value1.equals(other.value1)) { return false; } if (value2 == null) { if (other.value2 != null) { return false; } } else if (!value2.equals(other.value2)) { return false; } return true; } }
mit