repo_name
stringlengths
7
104
file_path
stringlengths
11
238
context
list
import_statement
stringlengths
103
6.85k
code
stringlengths
60
38.4k
next_line
stringlengths
10
824
gold_snippet_index
int32
0
8
sastix/cms
server/src/main/java/com/sastix/cms/server/services/content/impl/ZipHandlerServiceImpl.java
[ "@Getter @Setter @NoArgsConstructor @ToString\npublic class CreateResourceDTO {\n\n /**\n * The media-type of this new resource.\n */\n @NotNull\n private String resourceMediaType;\n\n /**\n * The author creating this resource.\n */\n @NotNull\n private String resourceAuthor;\n\n ...
import com.sastix.cms.common.content.CreateResourceDTO; import com.sastix.cms.common.content.ResourceDTO; import com.sastix.cms.common.content.exceptions.ResourceAccessError; import com.sastix.cms.server.domain.entities.Resource; import com.sastix.cms.server.services.content.DistributedCacheService; import com.sastix.cms.server.services.content.HashedDirectoryService; import com.sastix.cms.server.services.content.ResourceService; import com.sastix.cms.server.services.content.ZipHandlerService; import org.apache.tika.Tika; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Parser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.json.GsonJsonParser; import org.springframework.stereotype.Service; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
/* * Copyright(c) 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sastix.cms.server.services.content.impl; @Slf4j @Service public class ZipHandlerServiceImpl implements ZipHandlerService { public static final String METADATA_XML_FILE = "imsmanifest.xml"; public static final String METADATA_JSON_FILE = "info.json"; public static final String METADATA_STARTPAGE = "startpage"; public static final String METADATA_STARTPAGE_CAMEL = "startPage"; private final GsonJsonParser gsonJsonParser = new GsonJsonParser(); @Autowired DistributedCacheService distributedCacheService; @Autowired
HashedDirectoryService hashedDirectoryService;
5
melloc/roguelike
game/src/main/java/edu/brown/cs/roguelike/game/GUIApp.java
[ "public final class Vec2i implements Serializable {\r\n\tprivate static final long serialVersionUID = 5659632794862666943L;\r\n\t\r\n\t/**\r\n\t * Since {@link Vec2i} instances are immutable, their x and y fields may be accessed without getters.\r\n\t */\r\n\tpublic final int x, y;\r\n\t\r\n\t/**\r\n\t * Creates a ...
import cs195n.Vec2i; import edu.brown.cs.roguelike.engine.config.ConfigurationException; import edu.brown.cs.roguelike.engine.game.CumulativeTurnManager; import edu.brown.cs.roguelike.engine.game.Game; import edu.brown.cs.roguelike.engine.graphics.Application; import edu.brown.cs.roguelike.engine.proc.BSPLevelGenerator; import edu.brown.cs.roguelike.engine.save.SaveManager;
package edu.brown.cs.roguelike.game; public class GUIApp extends Application { private final static Vec2i SCREEN_SIZE = new Vec2i(80,30); private final static int POINTS_PER_TURN = 10; private SaveManager sm;
private CumulativeTurnManager tm;
2
IncQueryLabs/smarthome-cep-demonstrator
runtime/com.incquerylabs.smarthome.eventbus.api/src/main/java/com/incquerylabs/smarthome/eventbus/api/IEventSubscriber.java
[ "public class GroupItemStateChangedEvent extends ItemStateChangedEvent {\n\n\tpublic GroupItemStateChangedEvent(Item item, State newState, State oldState) {\n\t\tsuper(item, newState, oldState);\n\t}\n\t\n @Override\n public String toString() {\n return String.format(\"%s group state changed from %s to...
import java.util.Collection; import org.eclipse.smarthome.core.items.Item; import com.incquerylabs.smarthome.eventbus.api.events.GroupItemStateChangedEvent; import com.incquerylabs.smarthome.eventbus.api.events.ItemAddedEvent; import com.incquerylabs.smarthome.eventbus.api.events.ItemCommandEvent; import com.incquerylabs.smarthome.eventbus.api.events.ItemRemovedEvent; import com.incquerylabs.smarthome.eventbus.api.events.ItemStateChangedEvent; import com.incquerylabs.smarthome.eventbus.api.events.ItemStateEvent; import com.incquerylabs.smarthome.eventbus.api.events.ItemUpdatedEvent;
package com.incquerylabs.smarthome.eventbus.api; public interface IEventSubscriber { public void stateUpdated(ItemStateEvent event); public void stateChanged(ItemStateChangedEvent event); public void groupStateChanged(GroupItemStateChangedEvent event); public void commandReceived(ItemCommandEvent event); public void initItems(Collection<Item> items); public void itemAdded(ItemAddedEvent event);
public void itemRemoved(ItemRemovedEvent event);
3
integeruser/jgltut
src/integeruser/jgltut/tut13/GeomImpostor.java
[ "public enum MouseButtons {\n MB_LEFT_BTN,\n MB_RIGHT_BTN,\n MB_MIDDLE_BTN\n}", "public static class ViewData {\n public Vector3f targetPos;\n public Quaternionf orient;\n public float radius;\n public float degSpinRotation;\n\n public ViewData(Vector3f targetPos, Quaternionf orient, float...
import integeruser.jglsdk.glutil.MousePoles.MouseButtons; import integeruser.jglsdk.glutil.MousePoles.ViewData; import integeruser.jglsdk.glutil.MousePoles.ViewPole; import integeruser.jglsdk.glutil.MousePoles.ViewScale; import integeruser.jgltut.Tutorial; import integeruser.jgltut.commons.*; import integeruser.jgltut.framework.Framework; import integeruser.jgltut.framework.Mesh; import integeruser.jgltut.framework.MousePole; import integeruser.jgltut.framework.Timer; import org.joml.*; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL15; import java.lang.Math; import java.nio.ByteBuffer; import java.util.ArrayList; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL30.*; import static org.lwjgl.opengl.GL31.*; import static org.lwjgl.opengl.GL32.*;
package integeruser.jgltut.tut13; /** * Visit https://github.com/integeruser/jgltut for info and updates. * Original: https://bitbucket.org/alfonse/gltut/src/default/Tut%2013%20Impostors/GeomImpostor.cpp * <p> * Part III. Illumination * Chapter 13. Lies and Impostors * <p> * W,A,S,D - move the cameras forward/backwards and left/right, relative to the camera's current orientation. Holding * SHIFT with these keys will move in smaller increments. * Q,E - raise and lower the camera, relative to its current orientation. Holding SHIFT with these keys will move * in smaller increments. * P - toggle pausing on/off. * -,= - rewind/jump forward time by 0.5 second (of real-time). * T - toggle viewing the look-at point. * G - toggle the drawing of the light source. * <p> * LEFT CLICKING and DRAGGING - rotate the camera around the target point, both horizontally and vertically. * LEFT CLICKING and DRAGGING + CTRL - rotate the camera around the target point, either horizontally or vertically. * LEFT CLICKING and DRAGGING + ALT - change the camera's up direction. * WHEEL SCROLLING - move the camera closer to it's target point or farther away. */ public class GeomImpostor extends Tutorial { public static void main(String[] args) { Framework.CURRENT_TUTORIAL_DATAPATH = "/integeruser/jgltut/tut13/data/"; new GeomImpostor().start(500, 500); } @Override protected void init() { initializePrograms(); planeMesh = new Mesh("LargePlane.xml"); cubeMesh = new Mesh("UnitCube.xml"); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CW); final float depthZNear = 0.0f; final float depthZFar = 1.0f; glEnable(GL_DEPTH_TEST); glDepthMask(true); glDepthFunc(GL_LEQUAL); glDepthRange(depthZNear, depthZFar); glEnable(GL_DEPTH_CLAMP); // Setup our Uniform Buffers lightUniformBuffer = glGenBuffers(); glBindBuffer(GL_UNIFORM_BUFFER, lightUniformBuffer); GL15.glBufferData(GL_UNIFORM_BUFFER, LightBlock.BYTES, GL_DYNAMIC_DRAW); projectionUniformBuffer = glGenBuffers(); glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer); glBufferData(GL_UNIFORM_BUFFER, ProjectionBlock.BYTES, GL_DYNAMIC_DRAW); // Bind the static buffers. glBindBufferRange(GL_UNIFORM_BUFFER, lightBlockIndex, lightUniformBuffer, 0, LightBlock.BYTES); glBindBufferRange(GL_UNIFORM_BUFFER, projectionBlockIndex, projectionUniformBuffer, 0, ProjectionBlock.BYTES); glBindBuffer(GL_UNIFORM_BUFFER, 0); imposterVBO = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, imposterVBO); glBufferData(GL_ARRAY_BUFFER, NUMBER_OF_SPHERES * 4 * Float.BYTES, GL_STREAM_DRAW); imposterVAO = glGenVertexArrays(); glBindVertexArray(imposterVAO); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, false, 16, 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 1, GL_FLOAT, false, 16, 12); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glEnable(GL_PROGRAM_POINT_SIZE); createMaterials(); glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> { if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_P: sphereTimer.togglePause(); break; case GLFW_KEY_MINUS: sphereTimer.rewind(0.5f); break; case GLFW_KEY_EQUAL: sphereTimer.fastForward(0.5f); break; case GLFW_KEY_T: drawCameraPos = !drawCameraPos; break; case GLFW_KEY_G: drawLights = !drawLights; break; case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, true); break; } } }); glfwSetMouseButtonCallback(window, (window, button, action, mods) -> { boolean pressed = action == GLFW_PRESS; glfwGetCursorPos(window, mouseBuffer1, mouseBuffer2); int x = (int) mouseBuffer1.get(0); int y = (int) mouseBuffer2.get(0);
MousePole.forwardMouseButton(window, viewPole, button, pressed, x, y);
7
CagataySonmez/EdgeCloudSim
src/edu/boun/edgecloudsim/applications/sample_app2/SampleNetworkModel.java
[ "public class SimManager extends SimEntity {\r\n\tprivate static final int CREATE_TASK = 0;\r\n\tprivate static final int CHECK_ALL_VM = 1;\r\n\tprivate static final int GET_LOAD_LOG = 2;\r\n\tprivate static final int PRINT_PROGRESS = 3;\r\n\tprivate static final int STOP_SIMULATION = 4;\r\n\t\r\n\tprivate String s...
import org.cloudbus.cloudsim.core.CloudSim; import edu.boun.edgecloudsim.core.SimManager; import edu.boun.edgecloudsim.core.SimSettings; import edu.boun.edgecloudsim.edge_client.Task; import edu.boun.edgecloudsim.network.NetworkModel; import edu.boun.edgecloudsim.utils.Location; import edu.boun.edgecloudsim.utils.SimLogger;
/* * Title: EdgeCloudSim - Network Model * * Description: * SampleNetworkModel uses * -> the result of an empirical study for the WLAN and WAN delays * The experimental network model is developed * by taking measurements from the real life deployments. * * -> MMPP/MMPP/1 queue model for MAN delay * MAN delay is observed via a single server queue model with * Markov-modulated Poisson process (MMPP) arrivals. * * Licence: GPL - http://www.gnu.org/copyleft/gpl.html * Copyright (c) 2017, Bogazici University, Istanbul, Turkey */ package edu.boun.edgecloudsim.applications.sample_app2; public class SampleNetworkModel extends NetworkModel { public static enum NETWORK_TYPE {WLAN, LAN}; public static enum LINK_TYPE {DOWNLOAD, UPLOAD}; public static double MAN_BW = 1300*1024; //Kbps @SuppressWarnings("unused") private int manClients; private int[] wanClients; private int[] wlanClients; private double lastMM1QueueUpdateTime; private double ManPoissonMeanForDownload; //seconds private double ManPoissonMeanForUpload; //seconds private double avgManTaskInputSize; //bytes private double avgManTaskOutputSize; //bytes //record last n task statistics during MM1_QUEUE_MODEL_UPDATE_INTEVAL seconds to simulate mmpp/m/1 queue model private double totalManTaskInputSize; private double totalManTaskOutputSize; private double numOfManTaskForDownload; private double numOfManTaskForUpload; public static final double[] experimentalWlanDelay = { /*1 Client*/ 88040.279 /*(Kbps)*/, /*2 Clients*/ 45150.982 /*(Kbps)*/, /*3 Clients*/ 30303.641 /*(Kbps)*/, /*4 Clients*/ 27617.211 /*(Kbps)*/, /*5 Clients*/ 24868.616 /*(Kbps)*/, /*6 Clients*/ 22242.296 /*(Kbps)*/, /*7 Clients*/ 20524.064 /*(Kbps)*/, /*8 Clients*/ 18744.889 /*(Kbps)*/, /*9 Clients*/ 17058.827 /*(Kbps)*/, /*10 Clients*/ 15690.455 /*(Kbps)*/, /*11 Clients*/ 14127.744 /*(Kbps)*/, /*12 Clients*/ 13522.408 /*(Kbps)*/, /*13 Clients*/ 13177.631 /*(Kbps)*/, /*14 Clients*/ 12811.330 /*(Kbps)*/, /*15 Clients*/ 12584.387 /*(Kbps)*/, /*15 Clients*/ 12135.161 /*(Kbps)*/, /*16 Clients*/ 11705.638 /*(Kbps)*/, /*17 Clients*/ 11276.116 /*(Kbps)*/, /*18 Clients*/ 10846.594 /*(Kbps)*/, /*19 Clients*/ 10417.071 /*(Kbps)*/, /*20 Clients*/ 9987.549 /*(Kbps)*/, /*21 Clients*/ 9367.587 /*(Kbps)*/, /*22 Clients*/ 8747.625 /*(Kbps)*/, /*23 Clients*/ 8127.663 /*(Kbps)*/, /*24 Clients*/ 7907.701 /*(Kbps)*/, /*25 Clients*/ 7887.739 /*(Kbps)*/, /*26 Clients*/ 7690.831 /*(Kbps)*/, /*27 Clients*/ 7393.922 /*(Kbps)*/, /*28 Clients*/ 7297.014 /*(Kbps)*/, /*29 Clients*/ 7100.106 /*(Kbps)*/, /*30 Clients*/ 6903.197 /*(Kbps)*/, /*31 Clients*/ 6701.986 /*(Kbps)*/, /*32 Clients*/ 6500.776 /*(Kbps)*/, /*33 Clients*/ 6399.565 /*(Kbps)*/, /*34 Clients*/ 6098.354 /*(Kbps)*/, /*35 Clients*/ 5897.143 /*(Kbps)*/, /*36 Clients*/ 5552.127 /*(Kbps)*/, /*37 Clients*/ 5207.111 /*(Kbps)*/, /*38 Clients*/ 4862.096 /*(Kbps)*/, /*39 Clients*/ 4517.080 /*(Kbps)*/, /*40 Clients*/ 4172.064 /*(Kbps)*/, /*41 Clients*/ 4092.922 /*(Kbps)*/, /*42 Clients*/ 4013.781 /*(Kbps)*/, /*43 Clients*/ 3934.639 /*(Kbps)*/, /*44 Clients*/ 3855.498 /*(Kbps)*/, /*45 Clients*/ 3776.356 /*(Kbps)*/, /*46 Clients*/ 3697.215 /*(Kbps)*/, /*47 Clients*/ 3618.073 /*(Kbps)*/, /*48 Clients*/ 3538.932 /*(Kbps)*/, /*49 Clients*/ 3459.790 /*(Kbps)*/, /*50 Clients*/ 3380.649 /*(Kbps)*/, /*51 Clients*/ 3274.611 /*(Kbps)*/, /*52 Clients*/ 3168.573 /*(Kbps)*/, /*53 Clients*/ 3062.536 /*(Kbps)*/, /*54 Clients*/ 2956.498 /*(Kbps)*/, /*55 Clients*/ 2850.461 /*(Kbps)*/, /*56 Clients*/ 2744.423 /*(Kbps)*/, /*57 Clients*/ 2638.386 /*(Kbps)*/, /*58 Clients*/ 2532.348 /*(Kbps)*/, /*59 Clients*/ 2426.310 /*(Kbps)*/, /*60 Clients*/ 2320.273 /*(Kbps)*/, /*61 Clients*/ 2283.828 /*(Kbps)*/, /*62 Clients*/ 2247.383 /*(Kbps)*/, /*63 Clients*/ 2210.939 /*(Kbps)*/, /*64 Clients*/ 2174.494 /*(Kbps)*/, /*65 Clients*/ 2138.049 /*(Kbps)*/, /*66 Clients*/ 2101.604 /*(Kbps)*/, /*67 Clients*/ 2065.160 /*(Kbps)*/, /*68 Clients*/ 2028.715 /*(Kbps)*/, /*69 Clients*/ 1992.270 /*(Kbps)*/, /*70 Clients*/ 1955.825 /*(Kbps)*/, /*71 Clients*/ 1946.788 /*(Kbps)*/, /*72 Clients*/ 1937.751 /*(Kbps)*/, /*73 Clients*/ 1928.714 /*(Kbps)*/, /*74 Clients*/ 1919.677 /*(Kbps)*/, /*75 Clients*/ 1910.640 /*(Kbps)*/, /*76 Clients*/ 1901.603 /*(Kbps)*/, /*77 Clients*/ 1892.566 /*(Kbps)*/, /*78 Clients*/ 1883.529 /*(Kbps)*/, /*79 Clients*/ 1874.492 /*(Kbps)*/, /*80 Clients*/ 1865.455 /*(Kbps)*/, /*81 Clients*/ 1833.185 /*(Kbps)*/, /*82 Clients*/ 1800.915 /*(Kbps)*/, /*83 Clients*/ 1768.645 /*(Kbps)*/, /*84 Clients*/ 1736.375 /*(Kbps)*/, /*85 Clients*/ 1704.106 /*(Kbps)*/, /*86 Clients*/ 1671.836 /*(Kbps)*/, /*87 Clients*/ 1639.566 /*(Kbps)*/, /*88 Clients*/ 1607.296 /*(Kbps)*/, /*89 Clients*/ 1575.026 /*(Kbps)*/, /*90 Clients*/ 1542.756 /*(Kbps)*/, /*91 Clients*/ 1538.544 /*(Kbps)*/, /*92 Clients*/ 1534.331 /*(Kbps)*/, /*93 Clients*/ 1530.119 /*(Kbps)*/, /*94 Clients*/ 1525.906 /*(Kbps)*/, /*95 Clients*/ 1521.694 /*(Kbps)*/, /*96 Clients*/ 1517.481 /*(Kbps)*/, /*97 Clients*/ 1513.269 /*(Kbps)*/, /*98 Clients*/ 1509.056 /*(Kbps)*/, /*99 Clients*/ 1504.844 /*(Kbps)*/, /*100 Clients*/ 1500.631 /*(Kbps)*/ }; public static final double[] experimentalWanDelay = { /*1 Client*/ 20703.973 /*(Kbps)*/, /*2 Clients*/ 12023.957 /*(Kbps)*/, /*3 Clients*/ 9887.785 /*(Kbps)*/, /*4 Clients*/ 8915.775 /*(Kbps)*/, /*5 Clients*/ 8259.277 /*(Kbps)*/, /*6 Clients*/ 7560.574 /*(Kbps)*/, /*7 Clients*/ 7262.140 /*(Kbps)*/, /*8 Clients*/ 7155.361 /*(Kbps)*/, /*9 Clients*/ 7041.153 /*(Kbps)*/, /*10 Clients*/ 6994.595 /*(Kbps)*/, /*11 Clients*/ 6653.232 /*(Kbps)*/, /*12 Clients*/ 6111.868 /*(Kbps)*/, /*13 Clients*/ 5570.505 /*(Kbps)*/, /*14 Clients*/ 5029.142 /*(Kbps)*/, /*15 Clients*/ 4487.779 /*(Kbps)*/, /*16 Clients*/ 3899.729 /*(Kbps)*/, /*17 Clients*/ 3311.680 /*(Kbps)*/, /*18 Clients*/ 2723.631 /*(Kbps)*/, /*19 Clients*/ 2135.582 /*(Kbps)*/, /*20 Clients*/ 1547.533 /*(Kbps)*/, /*21 Clients*/ 1500.252 /*(Kbps)*/, /*22 Clients*/ 1452.972 /*(Kbps)*/, /*23 Clients*/ 1405.692 /*(Kbps)*/, /*24 Clients*/ 1358.411 /*(Kbps)*/, /*25 Clients*/ 1311.131 /*(Kbps)*/ }; public SampleNetworkModel(int _numberOfMobileDevices, String _simScenario) { super(_numberOfMobileDevices, _simScenario); } @Override public void initialize() { wanClients = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()]; //we have one access point for each datacenter wlanClients = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()]; //we have one access point for each datacenter int numOfApp = SimSettings.getInstance().getTaskLookUpTable().length; SimSettings SS = SimSettings.getInstance(); for(int taskIndex=0; taskIndex<numOfApp; taskIndex++) { if(SS.getTaskLookUpTable()[taskIndex][0] == 0) { SimLogger.printLine("Usage percentage of task " + taskIndex + " is 0! Terminating simulation..."); System.exit(0); } else{ double weight = SS.getTaskLookUpTable()[taskIndex][0]/(double)100; //assume half of the tasks use the MAN at the beginning ManPoissonMeanForDownload += ((SS.getTaskLookUpTable()[taskIndex][2])*weight) * 4; ManPoissonMeanForUpload = ManPoissonMeanForDownload; avgManTaskInputSize += SS.getTaskLookUpTable()[taskIndex][5]*weight; avgManTaskOutputSize += SS.getTaskLookUpTable()[taskIndex][6]*weight; } } ManPoissonMeanForDownload = ManPoissonMeanForDownload/numOfApp; ManPoissonMeanForUpload = ManPoissonMeanForUpload/numOfApp; avgManTaskInputSize = avgManTaskInputSize/numOfApp; avgManTaskOutputSize = avgManTaskOutputSize/numOfApp; lastMM1QueueUpdateTime = SimSettings.CLIENT_ACTIVITY_START_TIME; totalManTaskOutputSize = 0; numOfManTaskForDownload = 0; totalManTaskInputSize = 0; numOfManTaskForUpload = 0; } /** * source device is always mobile device in our simulation scenarios! */ @Override public double getUploadDelay(int sourceDeviceId, int destDeviceId, Task task) { double delay = 0; //special case for man communication if(sourceDeviceId == destDeviceId && sourceDeviceId == SimSettings.GENERIC_EDGE_DEVICE_ID){ return delay = getManUploadDelay(); }
Location accessPointLocation = SimManager.getInstance().getMobilityModel().getLocation(sourceDeviceId,CloudSim.clock());
4
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/Executions.java
[ "public abstract class Execution {\n\n public enum ExecutionState {\n UNKNOWN,\n BEGINNING,\n ENDING\n }\n\n /**\n * Provide an easy way to mark all operations as underway.\n *\n * @param scenario the test scenario\n * @param state phase of execution of the scenario\n */\n public void mark...
import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); }
public static InParallel inParallel(int count, Unit unit, Every every, Over over) {
4
jenkinsci/ghprb-plugin
src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/downstreambuilds/BuildFlowBuildManagerTest.java
[ "public abstract class GhprbITBaseTestCase {\n\n @Mock\n protected GHCommitPointer commitPointer;\n\n @Mock\n protected GHPullRequest ghPullRequest;\n\n @Mock\n protected GhprbGitHub ghprbGitHub;\n\n @Mock\n protected GHRepository ghRepository;\n\n @Mock\n protected GHUser ghUser;\n\n ...
import com.cloudbees.plugins.flow.BuildFlow; import com.cloudbees.plugins.flow.FlowRun; import com.cloudbees.plugins.flow.JobInvocation; import org.jenkinsci.plugins.ghprb.GhprbITBaseTestCase; import org.jenkinsci.plugins.ghprb.GhprbTestUtil; import org.jenkinsci.plugins.ghprb.manager.GhprbBuildManager; import org.jenkinsci.plugins.ghprb.manager.factory.GhprbBuildManagerFactoryUtil; import org.jenkinsci.plugins.ghprb.rules.JenkinsRuleWithBuildFlow; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.util.Iterator; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.BDDMockito.given;
package org.jenkinsci.plugins.ghprb.manager.impl.downstreambuilds; /** * @author mdelapenya (Manuel de la Peña) */ @RunWith(MockitoJUnitRunner.class) public class BuildFlowBuildManagerTest extends GhprbITBaseTestCase { @Rule
public JenkinsRuleWithBuildFlow jenkinsRule = new JenkinsRuleWithBuildFlow();
4
criticalmaps/criticalmaps-android
app/src/main/java/de/stephanlindauer/criticalmaps/service/ServerSyncService.java
[ "public class App extends Application {\n\n private static AppComponent appComponent;\n\n public static AppComponent components() {\n return appComponent;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n if (BuildConfig.DEBUG) {\n Timber.plant(new T...
import android.app.Service; import android.content.Intent; import android.os.IBinder; import androidx.core.content.ContextCompat; import com.squareup.otto.Subscribe; import java.util.Timer; import java.util.TimerTask; import javax.inject.Inject; import javax.inject.Provider; import de.stephanlindauer.criticalmaps.App; import de.stephanlindauer.criticalmaps.events.NetworkConnectivityChangedEvent; import de.stephanlindauer.criticalmaps.handler.NetworkConnectivityChangeHandler; import de.stephanlindauer.criticalmaps.handler.PullServerHandler; import de.stephanlindauer.criticalmaps.managers.LocationUpdateManager; import de.stephanlindauer.criticalmaps.provider.EventBus; import de.stephanlindauer.criticalmaps.utils.TrackingInfoNotificationBuilder;
package de.stephanlindauer.criticalmaps.service; public class ServerSyncService extends Service { @SuppressWarnings("FieldCanBeLocal") private final int SERVER_SYNC_INTERVAL = 12 * 1000; // 12 sec -> 5 times a minute private Timer timerPullServer; @Inject LocationUpdateManager locationUpdateManager; @Inject NetworkConnectivityChangeHandler networkConnectivityChangeHandler; @Inject Provider<PullServerHandler> pullServerHandler; @Inject
EventBus eventBus;
4
w3c/epubcheck
src/main/java/com/adobe/epubcheck/bitmap/BitmapChecker.java
[ "public final class EPUBLocation implements Comparable<EPUBLocation>\n{\n\n public static EPUBLocation create(String fileName)\n {\n return new EPUBLocation(fileName, -1, -1, null);\n }\n\n public static EPUBLocation create(String fileName, String context)\n {\n return new EPUBLocation(fileName, -1, -1, ...
import javax.imageio.stream.FileImageInputStream; import javax.imageio.stream.ImageInputStream; import com.adobe.epubcheck.api.EPUBLocation; import com.adobe.epubcheck.api.Report; import com.adobe.epubcheck.messages.MessageId; import com.adobe.epubcheck.ocf.OCFPackage; import com.adobe.epubcheck.ocf.OCFZipPackage; import com.adobe.epubcheck.opf.ContentChecker; import com.adobe.epubcheck.util.CheckUtil; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader;
/* * Copyright (c) 2007 Adobe Systems Incorporated * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package com.adobe.epubcheck.bitmap; public class BitmapChecker implements ContentChecker { private final OCFPackage ocf;
private final Report report;
1
sorinMD/MCTS
src/main/java/mcts/tree/selection/PUCT.java
[ "public interface Game {\n\n\t/**\n\t * @return a clone of the game state\n\t */\n\tpublic int[] getState();\n\n\tpublic int getWinner();\n\n\tpublic boolean isTerminal();\n\n\tpublic int getCurrentPlayer();\n\n\t/**\n\t * Updates the state description based on the chosen action\n\t * \n\t * @param a\n\t * ...
import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ThreadLocalRandom; import com.google.common.util.concurrent.AtomicDoubleArray; import mcts.game.Game; import mcts.game.GameFactory; import mcts.tree.Tree; import mcts.tree.node.Key; import mcts.tree.node.StandardNode; import mcts.tree.node.TreeNode; import mcts.utils.Selection; import mcts.utils.Utils;
package mcts.tree.selection; /** * PUCT selection policy for handling a prior probability of certain actions * being optimal (or for using an existing stochastic policy). * * @author sorinMD * */ public class PUCT extends SelectionPolicy { public PUCT() { } /** * Select node based on the best PUCT value. * Ties are broken randomly. * @param node * @param tree * @return */
protected Selection selectChild(StandardNode node, Tree tree, GameFactory factory, Game obsGame){
6
zznate/intravert-ug
src/main/java/io/teknek/intravert/action/ActionFactory.java
[ "public class CreateColumnFamilyAction implements Action {\n\n @Override\n public void doAction(Operation operation, Response response, RequestContext request,\n ApplicationContext application) {\n String keyspace = (String) operation.getArguments().get(\"keyspace\");\n String columnFamily = (Strin...
import java.util.HashMap; import java.util.Map; import io.teknek.intravert.action.impl.CreateColumnFamilyAction; import io.teknek.intravert.action.impl.CreateFilterAction; import io.teknek.intravert.action.impl.CreateKeyspaceAction; import io.teknek.intravert.action.impl.GetKeyspaceAction; import io.teknek.intravert.action.impl.SaveSessionAction; import io.teknek.intravert.action.impl.LoadSessionAction; import io.teknek.intravert.action.impl.SetKeyspaceAction; import io.teknek.intravert.action.impl.SliceAction; import io.teknek.intravert.action.impl.UpsertAction;
package io.teknek.intravert.action; public class ActionFactory { public static final String CREATE_SESSION = "createsession"; public static final String LOAD_SESSION = "loadsession"; public static final String SET_KEYSPACE = "setkeyspace"; public static final String GET_KEYSPACE = "getkeyspace"; public static final String CREATE_FILTER = "createfilter"; public static final String UPSERT = "upsert"; public static final String CREATE_KEYSPACE = "createkeyspace"; public static final String CREATE_COLUMN_FAMILY ="createcolumnfamily"; public static final String SLICE ="slice"; private Map<String,Action> actions; public ActionFactory(){ actions = new HashMap<String,Action>(); actions.put(CREATE_SESSION, new SaveSessionAction());
actions.put(LOAD_SESSION, new LoadSessionAction());
5
badvision/jace
src/main/java/jace/cheat/MetaCheat.java
[ "public class Emulator {\r\n\r\n public static Emulator instance;\r\n public static EmulatorUILogic logic = new EmulatorUILogic();\r\n public static Thread mainThread;\r\n\r\n// public static void main(String... args) {\r\n// mainThread = Thread.currentThread();\r\n// instance = new Emulat...
import jace.Emulator; import jace.JaceApplication; import jace.core.CPU; import jace.core.Computer; import jace.core.RAM; import jace.core.RAMEvent; import jace.core.RAMListener; import jace.state.State; import jace.ui.MetacheatUI; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager;
} public int getEndAddress() { return endAddress; } public void setByteSized(boolean b) { byteSized = b; } public void setSearchType(SearchType searchType) { this.searchType = searchType; } public void setSearchChangeType(SearchChangeType searchChangeType) { this.searchChangeType = searchChangeType; } public Property<Boolean> signedProperty() { return signedProperty; } public Property<String> searchValueProperty() { return searchValueProperty; } public Property<String> searchChangeByProperty() { return changeByProperty; } public ObservableList<DynamicCheat> getCheats() { return cheatList; } public ObservableList<SearchResult> getSearchResults() { return resultList; } public ObservableList<State> getSnapshots() { return snapshotList; } public Property<String> startAddressProperty() { return startAddressProperty; } public Property<String> endAddressProperty() { return endAddressProperty; } public void newSearch() { RAM memory = Emulator.computer.getMemory(); resultList.clear(); int compare = parseInt(searchValueProperty.get()); for (int i = 0; i < 0x10000; i++) { boolean signed = signedProperty.get(); int val = byteSized ? signed ? memory.readRaw(i) : memory.readRaw(i) & 0x0ff : signed ? memory.readWordRaw(i) : memory.readWordRaw(i) & 0x0ffff; if (!searchType.equals(SearchType.VALUE) || val == compare) { SearchResult result = new SearchResult(i, val); resultList.add(result); } } } public void performSearch() { RAM memory = Emulator.computer.getMemory(); boolean signed = signedProperty.get(); resultList.removeIf((SearchResult result) -> { int val = byteSized ? signed ? memory.readRaw(result.address) : memory.readRaw(result.address) & 0x0ff : signed ? memory.readWordRaw(result.address) : memory.readWordRaw(result.address) & 0x0ffff; int last = result.lastObservedValue; result.lastObservedValue = val; switch (searchType) { case VALUE: int compare = parseInt(searchValueProperty.get()); return compare != val; case CHANGE: switch (searchChangeType) { case AMOUNT: int amount = parseInt(searchChangeByProperty().getValue()); return (val - last) != amount; case GREATER: return val <= last; case ANY_CHANGE: return val == last; case LESS: return val >= last; case NO_CHANGE: return val != last; } break; case TEXT: break; } return false; }); } RAMListener memoryViewListener = null; private final Map<Integer, MemoryCell> memoryCells = new ConcurrentHashMap<>(); public MemoryCell getMemoryCell(int address) { return memoryCells.get(address); } public void initMemoryView() { RAM memory = Emulator.computer.getMemory(); for (int addr = getStartAddress(); addr <= getEndAddress(); addr++) { if (getMemoryCell(addr) == null) { MemoryCell cell = new MemoryCell(); cell.address = addr; cell.value.set(memory.readRaw(addr)); memoryCells.put(addr, cell); } } if (memoryViewListener == null) {
memoryViewListener = memory.observe(RAMEvent.TYPE.ANY, startAddress, endAddress, this::processMemoryEvent);
5
wmaop/wm-aop
src/test/java/org/wmaop/aop/stub/StubManagerTest.java
[ "public class Advice {\n\n\tprivate final PointCut pointCut;\n\tprivate final Interceptor interceptor;\n\tprivate final String id;\n\tprivate AdviceState adviceState = AdviceState.NEW;\n\tprivate final Remit remit;\n\n\tpublic Advice(String id, Remit remit, PointCut pointCut, Interceptor interceptor) {\n\t\tthis.po...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; import java.io.IOException; import java.util.Vector; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.wmaop.aop.advice.Advice; import org.wmaop.aop.advice.remit.GlobalRemit; import org.wmaop.aop.interceptor.Interceptor; import org.wmaop.aop.matcher.FlowPositionMatcher; import org.wmaop.aop.pointcut.PointCut; import com.wm.app.b2b.server.BaseService; import com.wm.app.b2b.server.Package; import com.wm.app.b2b.server.PackageManager; import com.wm.app.b2b.server.Resources; import com.wm.app.b2b.server.Server; import com.wm.app.b2b.server.ServerClassLoader; import com.wm.app.b2b.server.ns.Namespace; import com.wm.lang.ns.NSException; import com.wm.lang.ns.NSName; import com.wm.lang.ns.NSNode;
package org.wmaop.aop.stub; @RunWith(PowerMockRunner.class) @PrepareForTest({PackageManager.class,Namespace.class,ServerClassLoader.class,Server.class}) public class StubManagerTest { private StubManager stubManager; private static final String SERVICE_NAME = "foo:bar"; @Rule public TemporaryFolder tempFolder= new TemporaryFolder(); @Before public void setUp() { stubManager = new StubManager(); PowerMockito.mockStatic(PackageManager.class); PowerMockito.mockStatic(ServerClassLoader.class); PowerMockito.mockStatic(Server.class); } @Test public void shouldRegisterStubService() { assertFalse(stubManager.isRegisteredService(SERVICE_NAME)); PowerMockito.when(Server.getResources()).thenReturn(new Resources("",false)); stubManager.registerStubService(SERVICE_NAME); assertTrue(stubManager.hasStub(SERVICE_NAME)); } @Test public void shouldUnregisterStubService() throws NSException { Namespace ns = mockNamespace(); Package pkg = mockPackage(); stubManager.unregisterStubService(SERVICE_NAME); verify(ns, times(1)).deleteNode((NSName) any(), eq(true), eq(pkg)); } @Test public void shouldUnregisterStubFromAdvice() {
Advice advice = createAdviceMock();
0
tomayac/rest-describe-and-compile
src/com/google/code/apis/rest/client/Tree/ResponseItem.java
[ "public class GuiFactory implements WindowResizeListener {\r\n private static DockPanel blockScreen;\r\n public static Strings strings;\r\n public static Notifications notifications; \r\n private DockPanel dockPanel;\r\n public static final String restCompile = \"restCompile\";\r\n public static final String...
import java.util.Vector; import com.google.code.apis.rest.client.GUI.GuiFactory; import com.google.code.apis.rest.client.GUI.SettingsDialog; import com.google.code.apis.rest.client.Util.SyntaxHighlighter; import com.google.code.apis.rest.client.Wadl.MethodNode; import com.google.code.apis.rest.client.Wadl.ResponseNode; import com.google.code.apis.rest.client.Wadl.WadlXml; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.ClickListener; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Hyperlink; import com.google.gwt.user.client.ui.TreeItem; import com.google.gwt.user.client.ui.Widget;
package com.google.code.apis.rest.client.Tree; public class ResponseItem extends Composite { public ResponseItem(final MethodNode method, final TreeItem methodTreeItem) { HorizontalPanel containerPanel = new HorizontalPanel();
HTML response = new HTML(SyntaxHighlighter.highlight("<" + WadlXml.responseNode + ">"));
2
uiuc-ischool-scanr/SAIL
src/core/AnnotationTask.java
[ "public class Prediction {\n\t\n\t\n\tInstances original, labled, unlabled, ep_instances, sns_instances;\n\tString inputFile, outputDir;\n\tMODELTYPE classifierType;\n\tint clsIndex;\n\tString filePrefix;\n\tClassifier cls;\n\t\n\tprivate static int CLASSINDEX = 44;\n\tprivate static String stringAttr = \"3,4,6,8,1...
import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import javafx.collections.ObservableList; import org.apache.commons.io.FilenameUtils; import sentinets.Prediction; import sentinets.Prediction.MODELTYPE; import sentinets.Prediction.outDirIndex; import sentinets.ReadTweetCorpus; import sentinets.ReadTweetCorpus.COL_INDECIES; import sentinets.Utils; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; import com.sun.net.httpserver.HttpServer; import frontend.GUI; import frontend.Tweet;
} if(defaultProperties.getRemoveList() != null){ this.setRemoveList(defaultProperties.getRemoveList()); } Prediction.setModelParams(this.class_index, this.string_list, this.remove_list, this.customModelFile); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private List<String[]> originalData = new ArrayList<>(); public void addTweets(String fileName, ObservableList<Tweet> personData){ CSVReader cr; try { cr = new CSVReader(new FileReader(fileName), '\t'); headerRow = cr.readNext(); HashMap<String, Integer> headers = new HashMap<String, Integer>(); for(int i = 0; i < headerRow.length; i++){ headers.put(headerRow[i], i); System.err.println("["+i+"]="+headerRow[i]); } HashMap<String, Integer> f_list = new HashMap<String, Integer>(); f_list.put("c_emo", headers.get("c_emo")); f_list.put("c_hash", headers.get("c_hash")); f_list.put("c_url", headers.get("c_url")); f_list.put("c_mention", headers.get("c_mention")); f_list.put("length", headers.get("length")); int i = 0; String[] tweetList; while ((tweetList = cr.readNext())!= null){ Tweet t = new Tweet(tweetList[headers.get("tweet_text")], tweetList[headers.get("sentiment")], i, tweetList, Double.parseDouble(tweetList[headers.get("prediction_prob")])); originalData.add(tweetList); for(String key: f_list.keySet()){ t.setFeature(key, Integer.parseInt(tweetList[f_list.get(key)])); } personData.add(t); i++; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void saveChanges(String outFolder, ObservableList<Tweet> personData, boolean predicted) { CSVWriter writer; try { String updateFile = outFolder +"/"+Utils.getOutDir(Utils.OutDirIndex.UPDATES)+"/updates.txt"; System.out.println("Path: " + updateFile); writer = new CSVWriter(new FileWriter(updateFile), '\t', '\"','\\'); writer.writeNext(headerRow); for (Tweet t : personData) { if(t.isChanged() && !predicted){ writer.writeNext(t.getMeta()); } else if (predicted){ writer.writeNext(t.getMeta()); } } writer.close(); } catch (Exception e){ e.printStackTrace(); } } public String updateModel(ArrayList<Double[]> metrics){ String updateFile = this.outputDir+"/"+Utils.getOutDir(Utils.OutDirIndex.UPDATES)+"/updates.txt"; String output = ""; output = obj.updateModel(updateFile, metrics); return output; } public void listFilesForFolder(final File folder) { files.clear(); for (final File fileEntry : folder.listFiles()) { if(FilenameUtils.getExtension(fileEntry.getAbsolutePath()).equals("properties")){ System.out.println("Updating properties file."); setConfigFile(fileEntry.getAbsolutePath()); customProps = true; } else if (fileEntry.isDirectory()) { listFilesForFolder(fileEntry); } else { files.add(fileEntry.getPath()); System.out.println(fileEntry.getName()); } } } public List<String> readHeader() throws Exception{ List<String> combos = new ArrayList<String>(); CSVReader cr = new CSVReader(new FileReader(files.get(0)), '\t'); String[] headers = cr.readNext(); for (String s : headers){ combos.add(s); } String[] carr = combos.toArray(new String[combos.size()]); Arrays.sort(carr); combos = new ArrayList<String>(); combos.addAll(Arrays.asList(carr)); combos.add("<Empty>"); cr.close(); return combos; } /** * * TODO - Move Features folder name to Utils along with all the other list of output folders and use it using the enum index. * @param comboBoxes * @param mt * @param visualize * @param predicted */
public int processAfterLoadFile(ArrayList<String> comboBoxes, MODELTYPE mt, boolean visualize, boolean predicted){
1
Zerokyuuni/Ex-Aliquo
exaliquo/bridges/crossmod/ExtraTic_Mekanism.java
[ "public static Block getBlock(Info info)\n{\n\tBlock block = findBlock(info.mod, info.sname);\n\treturn (block != null) ? block : debugBlockInfo(info);\n}", "public static int getIDs(Info info)\n{\n\tif (info.type == \"block\")\n\t{\n\t\tBlock id = findBlock(info.mod, info.sname);\n\t\treturn (id != null) ? id.bl...
import static exaliquo.data.ModIDs.getBlock; import static exaliquo.data.ModIDs.getIDs; import static exaliquo.data.ModIDs.getItem; import static exaliquo.data.MoltenMetals.*; import static net.minecraftforge.fluids.FluidRegistry.getFluid; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import tconstruct.library.crafting.Smeltery; import exaliquo.Registries; import exaliquo.data.Configurations; import exaliquo.data.ModIDs.Info; import exnihilo.registries.CrucibleRegistry;
package exaliquo.bridges.crossmod; public class ExtraTic_Mekanism { protected static void SmeltMekanism() { for (int i = 0; i < 3; i++) {
Smeltery.addMelting(getBlock(Info.osmiumore), i, 550, new FluidStack(getFluid("molten.osmium"), ingotCostSmeltery));
0
Aurilux/Cybernetica
src/main/java/com/vivalux/cyb/item/implant/ImplantCyberneticArm.java
[ "@Mod(modid = CYBModInfo.MOD_ID,\n name = CYBModInfo.MOD_NAME,\n guiFactory = CYBModInfo.GUI_FACTORY,\n version = CYBModInfo.MOD_VERSION)\npublic class Cybernetica {\n\t@Instance(CYBModInfo.MOD_ID)\n\tpublic static Cybernetica instance;\n\n\t@SidedProxy(clientSide = CYBModInfo.CLIENT_PROXY, serverSide = CY...
import com.vivalux.cyb.Cybernetica; import com.vivalux.cyb.api.Implant; import com.vivalux.cyb.client.model.ModelArmImplant; import com.vivalux.cyb.init.CYBItems; import com.vivalux.cyb.item.module.ModuleArmorPlate; import com.vivalux.cyb.item.module.ModuleBlastResist; import com.vivalux.cyb.item.module.ModuleFireResist; import com.vivalux.cyb.item.module.ModuleProjectileResist; import com.vivalux.cyb.util.MiscUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.World;
package com.vivalux.cyb.item.implant; public class ImplantCyberneticArm extends Implant { // this implant provides modules equipped to the arm public ImplantCyberneticArm(String str, String str2, int renderIndex) { super(renderIndex, ImplantType.TORSO, 1); CYBItems.setItem(this, str, str2); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister reg) { this.itemIcon = reg.registerIcon(MiscUtils.getTexturePath(this.iconString)); } @Override protected void implantTick(World world, EntityPlayer player, ItemStack armor) { } @Override @SideOnly(Side.CLIENT) public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { if ((itemStack != null)) { if (itemStack.getItem() instanceof ImplantCyberneticArm) { ModelArmImplant model = (ModelArmImplant) Cybernetica.proxy.modelArm; model.bipedRightArm.showModel = true; model.isSneak = entityLiving.isSneaking(); model.isRiding = entityLiving.isRiding(); model.isChild = entityLiving.isChild(); model.heldItemRight = ((EntityPlayer) entityLiving).getCurrentArmor(0) != null ? 1 : 0; return model; } } return null; } @Override public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { return "cybernetica:textures/armour/armImplant.png"; } @Override public ArmorProperties getProperties(EntityLivingBase player, ItemStack armor, DamageSource source, double damage, int slot) { //Depending on modules, this could reduce damage from blast, fire, projectiles, etc if(Implant.hasInstalledModule(armor, ModuleFireResist.class) && source.isFireDamage()) { return new ArmorProperties(1, 1, MathHelper.floor_double(damage * .125D)); } else if (Implant.hasInstalledModule(armor, ModuleBlastResist.class) && source.isExplosion()) { return new ArmorProperties(1, 1, MathHelper.floor_double(damage * .125D)); } else if (Implant.hasInstalledModule(armor, ModuleProjectileResist.class) && source.isProjectile()) { return new ArmorProperties(1, 1, MathHelper.floor_double(damage * .125D)); } return new ArmorProperties(0, 0, 0); } @Override public int getArmorDisplay(EntityPlayer player, ItemStack armor, int slot) { //Without the proper modules, this won't provide any armor protection
if (Implant.hasInstalledModule(armor, ModuleArmorPlate.class)) {
4
metamolecular/mx
src/com/metamolecular/mx/test/QueryTest.java
[ "public interface BondMatcher\n{\n public boolean matches(Bond bond);\n}", "public class DefaultAtomMatcher implements AtomMatcher\n{\n\n private String symbol;\n private int maximumNeighbors;\n\n public DefaultAtomMatcher()\n {\n symbol = null;\n maximumNeighbors = -1;\n }\n\n public DefaultAtomMatc...
import com.metamolecular.mx.query.Edge; import com.metamolecular.mx.query.Node; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import com.metamolecular.mx.query.BondMatcher; import com.metamolecular.mx.query.DefaultAtomMatcher; import com.metamolecular.mx.query.DefaultBondMatcher; import com.metamolecular.mx.query.DefaultQuery;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.metamolecular.mx.test; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class QueryTest extends TestCase { private DefaultQuery query; @Override protected void setUp() throws Exception { query = new DefaultQuery(); } public void testItShouldHaveOneNodeAfterAddingOne() { query.addNode(new DefaultAtomMatcher()); assertEquals(1, query.countNodes()); } public void testItShouldReturnANodeHavingNoNeighborsAsFirst() { Node node = query.addNode(new DefaultAtomMatcher()); assertEquals(0, node.countNeighbors()); } public void testItShouldReturnANodeWithCorrectAtomMatcherAfterAdding() { DefaultAtomMatcher matcher = new DefaultAtomMatcher(); Node node = query.addNode(matcher); assertEquals(matcher, node.getAtomMatcher()); } public void testItShouldUpdateNodeNeighborCountAfterConnectingTwoNodes() { Node node1 = query.addNode(new DefaultAtomMatcher()); Node node2 = query.addNode(new DefaultAtomMatcher());
query.connect(node1, node2, new DefaultBondMatcher());
2
netmelody/ci-eye
src/main/java/org/netmelody/cieye/server/response/CiEyeResourceEngine.java
[ "public final class LandscapeObservation {\n\n private final List<TargetDetail> targets = new ArrayList<TargetDetail>();\n private final Set<Sponsor> dohGroup;\n \n public LandscapeObservation() {\n this(new TargetDetailGroup());\n }\n \n public LandscapeObservation(TargetDetailGroup tar...
import com.google.common.base.Function; import org.netmelody.cieye.core.domain.LandscapeObservation; import org.netmelody.cieye.core.domain.Sponsor; import org.netmelody.cieye.server.CiEyeNewVersionChecker; import org.netmelody.cieye.server.CiEyeServerInformationFetcher; import org.netmelody.cieye.server.CiSpyIntermediary; import org.netmelody.cieye.server.LandscapeFetcher; import org.netmelody.cieye.server.PictureFetcher; import org.netmelody.cieye.server.response.resource.CiEyeResource; import org.netmelody.cieye.server.response.responder.CiEyeVersionResponder; import org.netmelody.cieye.server.response.responder.DohHandler; import org.netmelody.cieye.server.response.responder.FileResponder; import org.netmelody.cieye.server.response.responder.LandscapeListResponder; import org.netmelody.cieye.server.response.responder.LandscapeObservationResponder; import org.netmelody.cieye.server.response.responder.NotFoundResponder; import org.netmelody.cieye.server.response.responder.PictureResponder; import org.netmelody.cieye.server.response.responder.RedirectResponder; import org.netmelody.cieye.server.response.responder.SettingsLocationResponder; import org.netmelody.cieye.server.response.responder.SponsorResponder; import org.netmelody.cieye.server.response.responder.TargetNotationHandler; import org.simpleframework.http.Address; import org.simpleframework.http.resource.Resource; import org.simpleframework.http.resource.ResourceEngine;
package org.netmelody.cieye.server.response; public final class CiEyeResourceEngine implements ResourceEngine { private final CiSpyIntermediary spyIntermediary; private final LandscapeFetcher landscapeFetcher; private final PictureFetcher pictureFetcher; private final CiEyeServerInformationFetcher configurationFetcher; private final CiEyeNewVersionChecker updateChecker; private final RequestOriginTracker tracker; private final Prison prison = new Prison(); public CiEyeResourceEngine(LandscapeFetcher landscapeFetcher, PictureFetcher pictureFetcher, CiEyeServerInformationFetcher configurationFetcher, RequestOriginTracker tracker, CiSpyIntermediary spyIntermediary, CiEyeNewVersionChecker updateChecker) { this.landscapeFetcher = landscapeFetcher; this.pictureFetcher = pictureFetcher; this.configurationFetcher = configurationFetcher; this.tracker = tracker; this.spyIntermediary = spyIntermediary; this.updateChecker = updateChecker; } @Override public Resource resolve(Address target) { return new CiEyeResource(route(target)); } private CiEyeResponder route(Address target) { final String[] path = target.getPath().getSegments(); if (path.length == 0) { return new FileResponder("/resources/welcome.html"); } if (path.length == 1) { if ("mugshotconfig.html".equals(path[0])) { return new FileResponder("/resources/mugshotconfig.html"); } if ("landscapelist.json".equals(path[0])) { return new LandscapeListResponder(landscapeFetcher); } if ("settingslocation.json".equals(path[0])) { return new SettingsLocationResponder(configurationFetcher); } if ("version.json".equals(path[0])) { return new CiEyeVersionResponder(configurationFetcher, updateChecker); } if ("sponsor.json".equals(path[0])) { return new SponsorResponder(tracker); } final String name = "/resources/" + path[0]; if (null != getClass().getResource(name)) { return new FileResponder(name); } } if (path.length == 2) { if ("pictures".equals(path[0])) { return new PictureResponder(pictureFetcher, path[1]); } if ("landscapes".equals(path[0])) { if (!target.getPath().getPath().endsWith("/")) { return new RedirectResponder(target.getPath().getPath() + "/"); } return new FileResponder("/resources/cieye.html"); } } if (path.length == 3) { if ("filteredlandscapes".equals(path[0])) { Sponsor sponsor = tracker.sponsorWith(path[2]); if (sponsor == null) { return new NotFoundResponder("Cannot find user " + path[2]); } if (!target.getPath().getPath().endsWith("/")) { return new RedirectResponder(target.getPath().getPath() + "/"); } return new FileResponder("/resources/cieye.html"); } if ("landscapes".equals(path[0]) && "landscapeobservation.json".equals(path[2])) { return new LandscapeObservationResponder(landscapeFetcher.landscapeNamed(path[1]), spyIntermediary, prison); } if ("landscapes".equals(path[0]) && "addNote".equals(path[2])) {
return new TargetNotationHandler(landscapeFetcher.landscapeNamed(path[1]), spyIntermediary, tracker);
4
iostackproject/SDGen
src/com/ibm/test/HelloWorldTest.java
[ "public class DatasetCharacterization implements Serializable, Cloneable{\n\n\tprivate static final long serialVersionUID = 1L;\n\n\t/*List of chunk characterization and deduplication ratio of this dataset*/\n\tprivate List<AbstractChunkCharacterization> chunkCharacterization = new ArrayList<>();\n\tprivate double ...
import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import com.ibm.characterization.DatasetCharacterization; import com.ibm.config.PropertiesStore; import com.ibm.config.PropertyNames; import com.ibm.generation.DataProducer; import com.ibm.scan.CompressionTimeScanner; import com.ibm.scan.DataScanner; import com.ibm.utils.Utils;
package com.ibm.test; public class HelloWorldTest { private static String datasetPath = "path_to_your_dataset"; private static String originalDataset = datasetPath + "LargeCalgaryCorpus.tar"; private static String syntheticDataset = datasetPath + "syntheticDataset"; private static int chunkSize = PropertiesStore.getInt(PropertyNames.GENERATION_CHUNK_SIZE); public static void main(String[] args) throws IOException { //1) Scan a dataset. If the dataset is a collection of files, to run this test is better //to pack them into a .tar fall to do a fair comparison with the synthetic file generated.
DataScanner scanner = new DataScanner();
5
michaelmarconi/oncue
oncue-tests/src/test/java/oncue/tests/base/DistributedActorSystemTest.java
[ "public abstract class AbstractAgent extends UntypedActor {\n\n\t// The scheduled heartbeat\n\tprivate Cancellable heartbeat;\n\n\t// Map jobs in progress to their workers\n\tprotected Map<String, Job> jobsInProgress = new HashMap<>();\n\n\tprotected LoggingAdapter log = Logging.getLogger(getContext().system(), thi...
import oncue.backingstore.RedisBackingStore.RedisConnection; import oncue.common.settings.Settings; import oncue.common.settings.SettingsProvider; import oncue.scheduler.AbstractScheduler; import java.util.Set; import org.junit.After; import org.junit.Before; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import oncue.agent.AbstractAgent; import oncue.backingstore.RedisBackingStore;
/******************************************************************************* * Copyright 2013 Michael Marconi * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package oncue.tests.base; public abstract class DistributedActorSystemTest { protected Config serviceConfig; protected ActorSystem serviceSystem; protected Settings serviceSettings; protected LoggingAdapter serviceLog; protected Config agentConfig; protected ActorSystem agentSystem; protected Settings agentSettings; protected LoggingAdapter agentLog; /** * Create an agent component, with a set of workers and an optional probe * * @param probe can be null */ @SuppressWarnings("serial") public ActorRef createAgent(final Set<String> workers, final ActorRef probe) { return agentSystem.actorOf(new Props(new UntypedActorFactory() { @Override public Actor create() throws Exception { AbstractAgent agent = (AbstractAgent) Class.forName(agentSettings.AGENT_CLASS) .getConstructor(Set.class).newInstance(workers); if (probe != null) agent.injectProbe(probe); return agent; } }), agentSettings.AGENT_NAME); } /** * Create a scheduler component, with an optional probe * * @param probe can be null */ @SuppressWarnings("serial") public ActorRef createScheduler(final ActorRef probe) { return serviceSystem.actorOf(new Props(new UntypedActorFactory() { @Override public Actor create() throws Exception { Class<?> schedulerClass = Class.forName(serviceSettings.SCHEDULER_CLASS); Class<?> backingStoreClass = null; if (serviceSettings.SCHEDULER_BACKING_STORE_CLASS != null) backingStoreClass = Class .forName(serviceSettings.SCHEDULER_BACKING_STORE_CLASS); @SuppressWarnings("rawtypes") AbstractScheduler scheduler = (AbstractScheduler) schedulerClass .getConstructor(Class.class).newInstance(backingStoreClass); if (probe != null) scheduler.injectProbe(probe); return scheduler; } }), serviceSettings.SCHEDULER_NAME); } @Before public void startActorSystems() { /* * Load configuration specific to this test and fall back to the reference configuration */ serviceConfig = ConfigFactory.load(); serviceConfig = ConfigFactory.load(getClass().getSimpleName() + "-Service") .withFallback(serviceConfig); agentConfig = ConfigFactory.load(); agentConfig = ConfigFactory.load(getClass().getSimpleName() + "-Agent") .withFallback(agentConfig); serviceSystem = ActorSystem.create("oncue-service", serviceConfig); serviceSettings = SettingsProvider.SettingsProvider.get(serviceSystem); serviceLog = Logging.getLogger(serviceSystem, this); agentSystem = ActorSystem.create("oncue-agent", agentConfig); agentSettings = SettingsProvider.SettingsProvider.get(agentSystem); agentLog = Logging.getLogger(agentSystem, this); } @After public void stopActorSystems() throws Exception { serviceSystem.shutdown(); agentSystem.shutdown(); while (!serviceSystem.isTerminated() || !agentSystem.isTerminated()) { serviceLog.info("Waiting for systems to shut down..."); Thread.sleep(500); } serviceLog.debug("Systems shut down"); } @Before @After public void cleanRedis() {
try (RedisConnection redis = new RedisBackingStore.RedisConnection()) {
2
noctarius/castmapr
src/main/java/com/noctarius/castmapr/core/IListNodeMapReduceTaskImpl.java
[ "public interface MapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut>\n extends ExecutableMapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut>\n{\n\n /**\n * Defines the mapper for this task. This method is not idempotent and is callable only one time. If called further\n * times an {@link IllegalStateExceptio...
import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.map.MapService; import com.hazelcast.partition.PartitionService; import com.hazelcast.spi.NodeEngine; import com.hazelcast.spi.OperationService; import com.hazelcast.spi.impl.BinaryOperationFactory; import com.hazelcast.util.ExceptionUtil; import com.noctarius.castmapr.MapReduceTask; import com.noctarius.castmapr.core.operation.IListMapReduceOperation; import com.noctarius.castmapr.spi.Collator; import com.noctarius.castmapr.spi.KeyPredicate; import com.noctarius.castmapr.spi.MapReduceCollatorListener; import com.noctarius.castmapr.spi.MapReduceListener; import com.noctarius.castmapr.spi.Reducer;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.noctarius.castmapr.core; public class IListNodeMapReduceTaskImpl<KeyIn, ValueIn, KeyOut, ValueOut> extends AbstractMapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut> { private final NodeEngine nodeEngine; public IListNodeMapReduceTaskImpl( String name, NodeEngine nodeEngine, HazelcastInstance hazelcastInstance ) { super( name, hazelcastInstance ); this.nodeEngine = nodeEngine; } /** * @throws UnsupportedOperationException IList MapReduce tasks do not support keys */ @Override
public MapReduceTask<KeyIn, ValueIn, KeyOut, ValueOut> onKeys( Iterable<KeyIn> keys )
0
loopfz/Lucki
src/shaft/poker/agent/handranges/weightedrange/weighttable/WeightTable.java
[ "public interface IWeightTable {\n \n public double getWeight(Card c1, Card c2);\n \n public void suspendSetWeight(Card c1, Card c2, double weight);\n public void setWeight(Card c1, Card c2, double weight);\n public void setWeight(Rank r1, Rank r2, double weight);\n \n public void initReweig...
import shaft.poker.game.ITable.*; import shaft.poker.game.table.IPlayerData; import java.util.ArrayList; import java.util.List; import shaft.poker.agent.handranges.weightedrange.IWeightTable; import shaft.poker.game.Card; import shaft.poker.game.Card.*; import shaft.poker.game.table.IGameEventListener; import shaft.poker.game.ITable;
/* * The MIT License * * Copyright 2013 Thomas Schaffer <thomas.schaffer@epitech.eu>. * * 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 shaft.poker.agent.handranges.weightedrange.weighttable; /** * * @author Thomas Schaffer <thomas.schaffer@epitech.eu> */ public class WeightTable implements IWeightTable, IGameEventListener { // Dimensions: [Rank1][Suit1][Rank2][Suit2][Weight] private double[][][][] _table1; private double[][][][] _table2; private double[][][][] _tableFrom; private double[][][][] _tableTo; List<WeightChange> _delayedChanges; public WeightTable(ITable table) { _table1 = new double[Rank.values().length][Suit.values().length][Rank.values().length][Suit.values().length]; _table2 = new double[Rank.values().length][Suit.values().length][Rank.values().length][Suit.values().length]; _delayedChanges = new ArrayList<>(100); table.registerEventListener(this); } private void setWeight(Rank r1, Suit s1, Rank r2, Suit s2, double weight) { _tableTo[r1.ordinal()][s1.ordinal()][r2.ordinal()][s2.ordinal()] = weight; } @Override public double getWeight(Card c1, Card c2) { return _tableFrom[c1.rank().ordinal()][c1.suit().ordinal()][c2.rank().ordinal()][c2.suit().ordinal()]; } @Override public void suspendSetWeight(Card c1, Card c2, double weight) { _delayedChanges.add(new WeightChange(c1, c2, weight)); } @Override public void setWeight(Card c1, Card c2, double weight) { setWeight(c1.rank(), c1.suit(), c2.rank(), c2.suit(), weight); } @Override public void setWeight(Rank r1, Rank r2, double weight) { for (Suit s1 : Suit.values()) { for (Suit s2 : Suit.values()) { if (r1 != r2 || s1 != s2) { setWeight(r1, s1, r2, s2, weight); } } } } @Override public void initReweight() { _tableFrom = _table1; _tableTo = _table2; } @Override public void consolidate() { _tableFrom = _table2; for (WeightChange change : _delayedChanges) { setWeight(change.card1(), change.card2(), change.newWeight()); } _delayedChanges.clear(); } @Override public void roundBegin(ITable table, Round r) { if (r == Round.PREFLOP) { for (double[][][] arr1 : _table1) { for (double[][] arr2 : arr1) { for (double[] arr3 : arr2) { for (int i = 0; i < arr3.length; i++) { arr3[i] = 1.0; } } } } } _tableFrom = _table1; _tableTo = _table2; } @Override public void roundEnd(ITable table, ITable.Round r) { double[][][][] tmp = _table1; _table1 = _table2; _table2 = tmp; } @Override public void newHand(ITable table) { } @Override public void newGame(ITable table, int stackSize, int sBlind, int bBlind, List<String> players) { } @Override
public void winHand(ITable table, IPlayerData data, int amount) {
6
scriptkitty/SNC
unikl/disco/calculator/gui/AddVertexDialog.java
[ "public class SNC {\r\n\r\n private final UndoRedoStack undoRedoStack;\r\n private static SNC singletonInstance;\r\n private final List<Network> networks;\r\n private final int currentNetworkPosition;\r\n\r\n private SNC() {\r\n networks = new ArrayList<>();\r\n undoRedoStack = new Undo...
import java.awt.GridLayout; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import unikl.disco.calculator.SNC; import unikl.disco.calculator.commands.AddVertexCommand; import unikl.disco.calculator.commands.Command; import unikl.disco.calculator.symbolic_math.ServiceType; import unikl.disco.misc.NetworkActionException;
/* * (c) 2017 Michael A. Beck, Sebastian Henningsen * disco | Distributed Computer Systems Lab * University of Kaiserslautern, Germany * All Rights Reserved. * * This software is work in progress and is released in the hope that it will * be useful to the scientific community. It is provided "as is" without * express or implied warranty, including but not limited to the correctness * of the code or its suitability for any particular purpose. * * This software is provided under the MIT License, however, we would * appreciate it if you contacted the respective authors prior to commercial use. * * If you find our software useful, we would appreciate if you mentioned it * in any publication arising from the use of this software or acknowledge * our work otherwise. We would also like to hear of any fixes or useful */ package unikl.disco.calculator.gui; /** * A dialog to get input from the user in order to add a vertex to a network. * @author Sebastian Henningsen * @author Michael Beck */ public class AddVertexDialog { private final JPanel panel; private final JLabel alias; private final JLabel service; private final JLabel rate; private final JTextField aliasField; private final JTextField rateField; private final JComboBox<ServiceType> serviceTypes; private final GridLayout layout; /** * Constructs the dialog and initializes all necessary fields. */ public AddVertexDialog() { panel = new JPanel(); alias = new JLabel("Alias of the vertex: "); service = new JLabel("Service Type: "); rate = new JLabel("Rate: "); aliasField = new JTextField(); rateField = new JTextField(10); serviceTypes = new JComboBox<>(ServiceType.values()); panel.add(alias); panel.add(aliasField); panel.add(service); panel.add(serviceTypes); panel.add(rate); panel.add(rateField); layout = new GridLayout(0, 1); panel.setLayout(layout); } /** * Displays the dialog */ public void display() { int result = JOptionPane.showConfirmDialog(null, panel, "Add Vertex", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { SNC snc = SNC.getInstance(); double serviceRate = Double.parseDouble(rateField.getText()); Command cmd = new AddVertexCommand(aliasField.getText(), serviceRate, -1, snc); try { snc.invokeCommand(cmd);
} catch(NetworkActionException e) {
4
xiprox/WaniKani-for-Android
WaniKani/src/tr/xip/wanikani/content/notification/NotificationScheduler.java
[ "public abstract class WaniKaniApi {\n private static final String API_HOST = \"https://www.wanikani.com/api/user/\";\n\n private static WaniKaniService service;\n private static String API_KEY;\n\n static {\n init();\n }\n\n public static void init() {\n API_KEY = PrefManager.getApi...
import android.annotation.SuppressLint; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import java.text.SimpleDateFormat; import retrofit2.Call; import retrofit2.Response; import tr.xip.wanikani.client.WaniKaniApi; import tr.xip.wanikani.client.task.callback.ThroughDbCallback; import tr.xip.wanikani.database.DatabaseManager; import tr.xip.wanikani.models.Request; import tr.xip.wanikani.models.StudyQueue;
package tr.xip.wanikani.content.notification; public class NotificationScheduler { private Context context; private NotificationPreferences prefs; public NotificationScheduler(Context context) { this.context = context; prefs = new NotificationPreferences(context); } public void schedule() {
WaniKaniApi.getStudyQueue().enqueue(new ThroughDbCallback<Request<StudyQueue>, StudyQueue>() {
0
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/resources/S3OperationsFacade.java
[ "public class RequestContext {\n\n private final boolean pathStyle;\n private final String bucket;\n private final String key;\n\n private RequestContext(boolean pathStyle, String bucket, String key) {\n this.pathStyle = pathStyle;\n this.bucket = bucket;\n this.key = key;\n }\n\...
import com.codahale.metrics.annotation.Timed; import de.jeha.s3srv.common.s3.RequestContext; import de.jeha.s3srv.operations.buckets.*; import de.jeha.s3srv.operations.objects.CreateObject; import de.jeha.s3srv.operations.objects.DeleteObject; import de.jeha.s3srv.operations.objects.ExistsObject; import de.jeha.s3srv.operations.objects.GetObject; import de.jeha.s3srv.operations.service.ListBuckets; import de.jeha.s3srv.storage.StorageBackend; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response;
package de.jeha.s3srv.resources; /** * @author jenshadlich@googlemail.com */ @Path("/") public class S3OperationsFacade { private static final Logger LOG = LoggerFactory.getLogger(S3OperationsFacade.class); private final StorageBackend storageBackend; public S3OperationsFacade(StorageBackend storageBackend) { this.storageBackend = storageBackend; } @HEAD @Path("{subResources:.*}") @Timed public Response head(@Context HttpServletRequest request) { LOG.info("head"); final RequestContext context = RequestContext.build(request); LOG.info("{}", context); if (context.getBucket() != null && context.getKey() != null) { return new ExistsObject(storageBackend).doesObjectExist(request, context.getBucket(), context.getKey()); } if (context.getBucket() != null) { return new ExistsBucket(storageBackend).doesBucketExist(request, context.getBucket()); } throw new UnsupportedOperationException("Not yet implemented!"); // TODO } @GET @Path("{subResources:.*}") @Timed public Response get(@Context HttpServletRequest request) { LOG.info("get"); final RequestContext context = RequestContext.build(request); LOG.info("{}", context); if (context.getBucket() != null && context.getKey() != null) { return new GetObject(storageBackend).getObject(request, context.getBucket(), context.getKey()); } if (context.getBucket() != null && "acl".equals(request.getQueryString())) { return new GetBucketACL(storageBackend).getBucketACL(request, context.getBucket()); } if (context.getBucket() != null) { return new ListObjects(storageBackend).listObjects(request, context.getBucket()); } return new ListBuckets(storageBackend).listBuckets(request); } @PUT @Path("{subResources:.*}") @Timed public Response put(@Context HttpServletRequest request) { LOG.info("put"); final RequestContext context = RequestContext.build(request); LOG.info("{}", context); if (context.getBucket() != null && context.getKey() != null) { return new CreateObject(storageBackend).createObject(request, context.getBucket(), context.getKey()); } if (context.getBucket() != null) { return new CreateBucket(storageBackend).createBucket(request, context.getBucket()); } throw new UnsupportedOperationException("Not yet implemented!"); // TODO } @POST @Path("{subResources:.*}") @Timed public Response post(@Context HttpServletRequest request) { LOG.info("post"); final RequestContext context = RequestContext.build(request); LOG.info("{}", context); throw new UnsupportedOperationException("Not yet implemented!"); // TODO } @DELETE @Path("{subResources:.*}") @Timed public Response delete(@Context HttpServletRequest request) { LOG.info("delete"); final RequestContext context = RequestContext.build(request); LOG.info("{}", context); if (context.getBucket() != null && context.getKey() != null) {
return new DeleteObject(storageBackend).deleteObject(request, context.getBucket(), context.getKey());
2
c-rack/cbor-java
src/test/java/co/nstant/in/cbor/decoder/CborDecoderTest.java
[ "public class CborBuilder extends AbstractBuilder<CborBuilder> {\n\n private final LinkedList<DataItem> dataItems = new LinkedList<>();\n\n public CborBuilder() {\n super(null);\n }\n\n public CborBuilder reset() {\n dataItems.clear();\n return this;\n }\n\n public List<DataIt...
import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.junit.Test; import co.nstant.in.cbor.CborBuilder; import co.nstant.in.cbor.CborDecoder; import co.nstant.in.cbor.CborEncoder; import co.nstant.in.cbor.CborException; import co.nstant.in.cbor.encoder.AbstractEncoder; import co.nstant.in.cbor.model.DataItem; import co.nstant.in.cbor.model.MajorType; import co.nstant.in.cbor.model.RationalNumber; import co.nstant.in.cbor.model.Tag; import co.nstant.in.cbor.model.UnsignedInteger;
public int read() throws IOException { return (8 << 5); // invalid major type } }); cborDecoder.decodeNext(); } @Test public void shouldSetAutoDecodeInfinitiveMaps() { InputStream inputStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); CborDecoder cborDecoder = new CborDecoder(inputStream); assertTrue(cborDecoder.isAutoDecodeInfinitiveMaps()); cborDecoder.setAutoDecodeInfinitiveMaps(false); assertFalse(cborDecoder.isAutoDecodeInfinitiveMaps()); } @Test public void shouldSetAutoDecodeRationalNumbers() { InputStream inputStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); CborDecoder cborDecoder = new CborDecoder(inputStream); assertTrue(cborDecoder.isAutoDecodeRationalNumbers()); cborDecoder.setAutoDecodeRationalNumbers(false); assertFalse(cborDecoder.isAutoDecodeRationalNumbers()); } @Test public void shouldSetAutoDecodeLanguageTaggedStrings() { InputStream inputStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); CborDecoder cborDecoder = new CborDecoder(inputStream); assertTrue(cborDecoder.isAutoDecodeLanguageTaggedStrings()); cborDecoder.setAutoDecodeLanguageTaggedStrings(false); assertFalse(cborDecoder.isAutoDecodeLanguageTaggedStrings()); } @Test(expected = CborException.class) public void shouldThrowOnRationalNumberDecode1() throws CborException { List<DataItem> items = new CborBuilder().addTag(30).add(true).build(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); CborEncoder encoder = new CborEncoder(baos); encoder.encode(items); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); CborDecoder decoder = new CborDecoder(bais); decoder.decode(); } @Test(expected = CborException.class) public void shouldThrowOnRationalNumberDecode2() throws CborException { List<DataItem> items = new CborBuilder().addTag(30).addArray().add(true).end().build(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); CborEncoder encoder = new CborEncoder(baos); encoder.encode(items); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); CborDecoder decoder = new CborDecoder(bais); decoder.decode(); } @Test(expected = CborException.class) public void shouldThrowOnRationalNumberDecode3() throws CborException { List<DataItem> items = new CborBuilder().addTag(30).addArray().add(true).add(true).end().build(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); CborEncoder encoder = new CborEncoder(baos); encoder.encode(items); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); CborDecoder decoder = new CborDecoder(bais); decoder.decode(); } @Test(expected = CborException.class) public void shouldThrowOnRationalNumberDecode4() throws CborException { List<DataItem> items = new CborBuilder().addTag(30).addArray().add(1).add(true).end().build(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); CborEncoder encoder = new CborEncoder(baos); encoder.encode(items); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); CborDecoder decoder = new CborDecoder(bais); decoder.decode(); } @Test public void shouldDecodeRationalNumber() throws CborException { List<DataItem> items = new CborBuilder().addTag(30).addArray().add(1).add(2).end().build(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); CborEncoder encoder = new CborEncoder(baos); encoder.encode(items); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); CborDecoder decoder = new CborDecoder(bais); assertEquals(new RationalNumber(new UnsignedInteger(1), new UnsignedInteger(2)), decoder.decodeNext()); } @Test public void shouldDecodeTaggedTags() throws CborException { DataItem decoded = CborDecoder.decode(new byte[] { (byte) 0xC1, (byte) 0xC2, 0x02 }).get(0); Tag outer = new Tag(1); Tag inner = new Tag(2); UnsignedInteger expected = new UnsignedInteger(2); inner.setTag(outer); expected.setTag(inner); assertEquals(expected, decoded); } @Test public void shouldDecodeTaggedRationalNumber() throws CborException { List<DataItem> items = new CborBuilder().addTag(1).addTag(30).addArray().add(1).add(2).end().build(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); CborEncoder encoder = new CborEncoder(baos); encoder.encode(items); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); CborDecoder decoder = new CborDecoder(bais); RationalNumber expected = new RationalNumber(new UnsignedInteger(1), new UnsignedInteger(2)); expected.getTag().setTag(new Tag(1)); assertEquals(expected, decoder.decodeNext()); } @Test public void shouldThrowOnItemWithForgedLength() throws CborException { ByteArrayOutputStream buffer = new ByteArrayOutputStream();
AbstractEncoder<Long> maliciousEncoder = new AbstractEncoder<Long>(null, buffer) {
3
luoyuan800/IPMIUtil4J
src/main/java/request/SensorRequest.java
[ "public class IPMIClient {\n\tprivate String IPMI_META_COMMAND = \"\";\n\tprivate String user;\n\tprivate String password;\n\tprivate String host;\n\tprivate CipherSuite cs;\n\tprivate boolean systemPowerUp;\n\tprivate Platform platform;\n\tpublic String getHost() {\n\t\treturn host;\n\t}\n\tpublic String getPasswo...
import client.IPMIClient; import command.Command; import command.OutputResult; import model.Sensor; import param.SDRType; import respond.SensorRespond; import utils.StringUtils; import java.util.regex.Matcher; import java.util.regex.Pattern;
/* * SensorRequest.java * Date: 7/15/2015 * Time: 10:28 AM * * Copyright 2015 luoyuan. * ALL RIGHTS RESERVED. */ package request; public class SensorRequest extends AbstractRequest { private Command command = new Command(); private static final Pattern sensorIDTypeReadingP = Pattern.compile("^([1234567890abcdef]+) SDR (\\w*) [1234567890abcdef].* snum .{2} (.*) *= .*(?<=[1234567890abcdef]{2}) (\\w+) +(-*\\d+\\.\\d+) (Volts|degrees C|RPM|Amps|Watts|unspecified)$"), sensorIDTypeStatus = Pattern.compile("^([1234567890abcdef]+) SDR (\\w*) [1234567890abcdef].* snum .{2} (.*) *= .* (\\w*)$"), sensorIDType = Pattern.compile("^([1234567890abcdef]+) SDR (\\w*).*"), endP = Pattern.compile("sensor, completed successfully"); @Override public String getCommandString() { return "sensor"; } @Override public SensorRespond sendTo(IPMIClient client) {
OutputResult or = command.exeCmd(buildCommand(client));
2
feldim2425/OC-Minecarts
src/main/java/mods/ocminecart/common/component/ComputerCartController.java
[ "public class Settings {\n\t\n\tpublic static final String OC_ResLoc = \"opencomputers\"; // Resource domain for OpenComputers\n\tpublic static final String OC_Namespace = \"oc:\"; // Namespace for OpenComputers NBT Data\n\t\n\tpublic static float OC_SoundVolume;\n\tpublic static double OC_IC2PWR;\n\tpublic static ...
import li.cil.oc.api.API; import li.cil.oc.api.machine.Arguments; import li.cil.oc.api.machine.Callback; import li.cil.oc.api.machine.Context; import li.cil.oc.api.network.*; import mods.ocminecart.Settings; import mods.ocminecart.common.minecart.ComputerCart; import mods.ocminecart.common.util.InventoryUtil; import mods.ocminecart.common.util.ItemUtil; import mods.ocminecart.common.util.TankUtil; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidHandler; import net.minecraftforge.fluids.IFluidTank; import java.util.ArrayList;
package mods.ocminecart.common.component; public class ComputerCartController implements ManagedEnvironment{ private Node node; private ComputerCart cart; public ComputerCartController(ComputerCart cart){ this.cart = cart; node = API.network.newNode(this, Visibility.Neighbors).withComponent("computercart").create(); } @Override public Node node() { return node; } @Override public void onConnect(Node node) { } @Override public void onDisconnect(Node node) { } @Override public void onMessage(Message message) {} @Override public void load(NBTTagCompound nbt) { if(nbt.hasKey("node")) ((Component)this.node).load(nbt.getCompoundTag("node")); } @Override public void save(NBTTagCompound nbt) { NBTTagCompound node = new NBTTagCompound(); ((Component)this.node).save(node); nbt.setTag("node", node); } @Override public boolean canUpdate() { return false; } @Override public void update() {} /*--------Component-Functions-Cart--------*/ @Callback(doc="function(set:boolean):boolen, string -- Enable/Disable the brake. String for errors") public Object[] setBrake(Context context, Arguments arguments){ boolean state = arguments.checkBoolean(0); if(this.cart.getSpeed() > this.cart.getMaxCartSpeedOnRail() && state){ return new Object[]{this.cart.getBrakeState(), "too fast"}; } this.cart.setBrakeState(state); return new Object[]{state, null}; } @Callback(direct = true,doc="function():boolean -- Get the status of the brake.") public Object[] getBrake(Context context, Arguments arguments){ return new Object[]{this.cart.getBrakeState()}; } @Callback(direct = true,doc="function():number -- Get engine speed") public Object[] getEngineSpeed(Context context, Arguments arguments){ return new Object[]{this.cart.getEngineState()}; } @Callback(doc="function():number -- Get current speed of the cart. -1 if there is no rail") public Object[] getCartSpeed(Context context, Arguments arguments){ double speed = -1; if(this.cart.onRail()){ speed = this.cart.getSpeed(); } return new Object[]{speed}; } @Callback(doc="function(speed:number):number -- Set the engine speed.") public Object[] setEngineSpeed(Context context, Arguments arguments){ double speed = Math.max(Math.min(arguments.checkDouble(0), this.cart.getMaxCartSpeedOnRail()), 0); this.cart.setEngineState(speed); return new Object[]{speed}; } @Callback(doc="function():number -- Get the maximal cart speed") public Object[] getMaxSpeed(Context context, Arguments arguments){ return new Object[]{this.cart.getMaxCartSpeedOnRail()}; } @Callback(doc="function(color:number):number -- Set light color") public Object[] setLightColor(Context context, Arguments arguments){ int color = arguments.checkInteger(0); this.cart.setLightColor(color); return new Object[]{color}; } @Callback(direct = true,doc="function():number -- Get light color") public Object[] getLightColor(Context context, Arguments arguments){ return new Object[]{this.cart.getLightColor()}; } @Callback(doc="function() -- Rotate the cart") public Object[] rotate(Context context, Arguments arguments){ float yaw = this.cart.rotationYaw + 180F; if(yaw>180) yaw-=360F; else if(yaw<-180) yaw+=360F; this.cart.rotationYaw = yaw; //OCMinecart.logger.info("Rotate: "+this.cart.rotationYaw+" + "+cart.facing().toString()); return new Object[]{}; } @Callback(direct = true,doc="function():boolean -- Check if the cart is on a rail") public Object[] onRail(Context context, Arguments arguments){ return new Object[]{this.cart.onRail()}; } @Callback(direct = true,doc="function():boolean -- Check if the cart is connected to a network rail") public Object[] hasNetworkRail(Context context, Arguments arguments){ return new Object[]{this.cart.hasNetRail()}; } @Callback(direct = true,doc="function():boolean -- Check if the cart is locked on a track") public Object[] isLocked(Context context, Arguments arguments){ return new Object[]{this.cart.isLocked()}; } /*--------Component-Functions-Inventory--------*/ @Callback(doc = "function():number -- The size of this device's internal inventory.") public Object[] inventorySize(Context context, Arguments arguments){ return new Object[]{this.cart.getInventorySpace()}; } @Callback(doc = "function([slot:number]):number -- Get the currently selected slot; set the selected slot if specified.") public Object[] select(Context context, Arguments args){ int slot = args.optInteger(0, 0); if(slot > 0 && slot <= this.cart.maininv.getMaxSizeInventory()){ this.cart.setSelectedSlot(slot-1); } else if(args.count() > 0){ throw new IllegalArgumentException("invalid slot"); } return new Object[]{this.cart.selectedSlot()+1}; } @Callback(direct = true, doc = "function([slot:number]):number -- Get the number of items in the specified slot, otherwise in the selected slot.") public Object[] count(Context context, Arguments args){ int slot = args.optInteger(0, -1); int num = 0; slot = (args.count() > 0) ? slot-1 : this.cart.selectedSlot(); if(slot >= 0 && slot < this.cart.getInventorySpace()){ if(this.cart.mainInventory().getStackInSlot(slot)!=null){ num = this.cart.mainInventory().getStackInSlot(slot).stackSize; } } else{ if(args.count() < 1) return new Object[]{ 0 , "no slot selected"}; throw new IllegalArgumentException("invalid slot"); } return new Object[]{num}; } @Callback(direct = true, doc = "function([slot:number]):number -- Get the remaining space in the specified slot, otherwise in the selected slot.") public Object[] space(Context context, Arguments args){ int slot = args.optInteger(0, -1); int num = 0; slot = (args.count() > 0) ? slot-1 : this.cart.selectedSlot(); if(slot > 0 && slot <= this.cart.getInventorySpace()){ ItemStack stack = this.cart.mainInventory().getStackInSlot(slot-1); if(stack!=null){ int maxStack = Math.min(this.cart.mainInventory().getInventoryStackLimit(), stack.getMaxStackSize()); num = maxStack-stack.stackSize; } else{ num = this.cart.mainInventory().getInventoryStackLimit(); } } else{ if(args.count() < 1) return new Object[]{ 0 , "no slot selected"}; throw new IllegalArgumentException("invalid slot"); } return new Object[]{num}; } @Callback(doc = "function(otherSlot:number):boolean -- Compare the contents of the selected slot to the contents of the specified slot.") public Object[] compareTo(Context context, Arguments args){ int slotA = args.checkInteger(0) - 1; int slotB = this.cart.selectedSlot(); boolean result; if(slotB>=0 && slotB<this.cart.mainInventory().getSizeInventory()) return new Object[]{ false , "no slot selected"}; if(slotA>=0 && slotA<this.cart.mainInventory().getSizeInventory()){ ItemStack stackA = this.cart.mainInventory().getStackInSlot(slotA); ItemStack stackB = this.cart.mainInventory().getStackInSlot(slotB); result = (stackA==null && stackB==null) || (stackA!=null && stackB!=null && stackA.isItemEqual(stackB)); return new Object[]{result}; } throw new IllegalArgumentException("invalid slot"); } @Callback(doc = "function(toSlot:number[, amount:number]):boolean -- Move up to the specified amount of items from the selected slot into the specified slot.") public Object[] transferTo(Context context, Arguments args){ int tslot = args.checkInteger(0) - 1; int number = args.optInteger(1, this.cart.mainInventory().getInventoryStackLimit()); if(!(tslot>=0 && tslot<this.cart.mainInventory().getSizeInventory())) throw new IllegalArgumentException("invalid slot"); if(!(this.cart.selectedSlot()>=0 && this.cart.selectedSlot()<this.cart.mainInventory().getSizeInventory())) return new Object[]{ false , "no slot selected"}; ItemStack stackT = this.cart.mainInventory().getStackInSlot(tslot); ItemStack stackS = this.cart.mainInventory().getStackInSlot(this.cart.selectedSlot()); if(!(stackT==null || (stackS!=null && stackT!=null && stackT.isItemEqual(stackS))) || stackS == null) return new Object[]{false}; int items = 0; int maxStack = Math.min(this.cart.mainInventory().getInventoryStackLimit(), stackS.getMaxStackSize()); items = maxStack - ((stackT!=null) ? stackT.stackSize : 0); items = Math.min(items, number); if(items<=0) return new Object[]{false}; ItemStack dif = this.cart.mainInventory().decrStackSize(this.cart.selectedSlot(), items); if(stackT!=null){ stackT.stackSize+=dif.stackSize; } else{ this.cart.mainInventory().setInventorySlotContents(tslot, dif); } return new Object[]{true}; } /*--------Component-Functions-Tank--------*/ @Callback(doc = "function():number -- The number of tanks installed in the device.") public Object[] tankCount(Context context, Arguments args){ return new Object[]{ this.cart.tankcount() }; } @Callback(doc = "function([index:number]):number -- Select a tank and/or get the number of the currently selected tank.") public Object[] selectTank(Context context, Arguments args){ int index = args.optInteger(0, 0); if(index > 0 && index <=this.cart.tankcount()) this.cart.setSelectedTank(index); else if(args.count() > 0) throw new IllegalArgumentException("invalid tank index"); return new Object[]{this.cart.selectedTank()}; } @Callback(direct = true, doc = "function([index:number]):number -- Get the fluid amount in the specified or selected tank.") public Object[] tankLevel(Context context, Arguments args){ int index = args.optInteger(0, 0); index = (args.count()>0) ? index : this.cart.selectedTank(); if(!(index>0 && index<=this.cart.tankcount())){ if(args.count()<1) return new Object[]{ false ,"no tank selected" }; throw new IllegalArgumentException("invalid tank index"); } return new Object[]{ this.cart.getTank(index).getFluidAmount() }; } @Callback(direct = true, doc = "function([index:number]):number -- Get the remaining fluid capacity in the specified or selected tank.") public Object[] tankSpace(Context context, Arguments args){ int index = args.optInteger(0, 0); index = (args.count()>0) ? index : this.cart.selectedTank(); if(!(index>0 && index<=this.cart.tankcount())){ if(args.count()<1) return new Object[]{ false ,"no tank selected" }; throw new IllegalArgumentException("invalid tank index"); } IFluidTank tank = this.cart.getTank(index); return new Object[]{ tank.getCapacity() - tank.getFluidAmount() }; } @Callback(doc = "function(index:number):boolean -- Compares the fluids in the selected and the specified tank. Returns true if equal.") public Object[] compareFluidTo(Context context, Arguments args){ int tankA = args.checkInteger(0); int tankB = this.cart.selectedTank(); if(!(tankA>0 && tankA<=this.cart.tankcount())) throw new IllegalArgumentException("invalid tank index"); if(!(tankB>0 && tankB<=this.cart.tankcount())) return new Object[]{ false ,"no tank selected" }; FluidStack stackA = this.cart.getTank(tankA).getFluid(); FluidStack stackB = this.cart.getTank(tankB).getFluid(); boolean res = (stackA==null && stackB==null); if(!res && stackA!=null && stackB!=null) res = stackA.isFluidEqual(stackB); return new Object[]{ res }; } @Callback(doc = "function(index:number[, count:number=1000]):boolean -- Move the specified amount of fluid from the selected tank into the specified tank.") public Object[] transferFluidTo(Context context, Arguments args){ int tankA = args.checkInteger(0); int tankB = this.cart.selectedTank(); int count = args.optInteger(1, 1000); if(!(tankA>0 && tankA<=this.cart.tankcount())) throw new IllegalArgumentException("invalid tank index"); if(!(tankB>0 && tankB<=this.cart.tankcount())) return new Object[]{ false ,"no tank selected" }; IFluidTank tankT = this.cart.getTank(tankA); IFluidTank tankS = this.cart.getTank(tankB); if(tankS.getFluid()==null || (tankT!=null && tankS.getFluid().isFluidEqual(tankT.getFluid()))) return new Object[]{ false }; FluidStack sim = tankS.drain(count, false); //Simulate the transfer to get the max. moveable amount. int move = tankT.fill(sim, false); if(move<=0) return new Object[]{ false }; FluidStack mv = tankS.drain(move, true); int over = tankT.fill(mv, true); over-=mv.amount; if(over>0){ //Just in case we drained too much. FluidStack ret = mv.copy(); ret.amount = over; tankS.fill(ret, true); } return new Object[]{ true }; } //--------World-Inventory----------// @Callback(doc = "function(side:number[, count:number=64]):boolean -- Drops items from the selected slot towards the specified side.") public Object[] drop(Context context, Arguments args){ int side = args.checkInteger(0); int amount = args.optInteger(1,64); if(side<0 || side > 5) throw new IllegalArgumentException("invalid side"); int sslot = this.cart.selectedSlot(); if(!(sslot>=0 && sslot<this.cart.mainInventory().getSizeInventory())) return new Object[]{ false , "no slot selected"}; if(amount<1) return new Object[]{ false }; ForgeDirection dir = this.cart.toGlobal(ForgeDirection.getOrientation(side)); int x = (int)Math.floor(this.cart.xPosition())+dir.offsetX; int y = (int)Math.floor(this.cart.yPosition())+dir.offsetY; int z = (int)Math.floor(this.cart.zPosition())+dir.offsetZ; ItemStack dstack = this.cart.mainInventory().getStackInSlot(sslot); if(dstack == null) return new Object[]{ false }; if(!(this.cart.world().getTileEntity(x, y, z) instanceof IInventory)){ ArrayList<ItemStack> drop = new ArrayList<ItemStack>(); int mov = Math.min(dstack.stackSize, amount); ItemStack dif = dstack.splitStack(mov); if(dstack.stackSize < 1) this.cart.mainInventory().setInventorySlotContents(sslot, null); drop.add(dif); ItemUtil.dropItemList(drop, this.cart.world(), x+0.5D, y+0.5D, z+0.5D, false); context.pause(Settings.OC_DropDelay); return new Object[]{ true }; } else{
int moved = InventoryUtil.dropItemInventoryWorld(dstack.copy(), this.cart.world(), x, y, z, dir.getOpposite(), amount);
2
Wondersoft/olaper
src/main/java/org/olap/server/processor/functions/IdentifiedMember.java
[ "public class MetadataUtils {\n\n\n @SuppressWarnings(\"serial\")\n\tprivate static class MetadataElementNamedList<T extends MetadataElement> extends ArrayNamedListImpl<T> {\n \t\n \tpublic MetadataElementNamedList(List<T> list){\n \t\tfor(T t : list)\n \t\t\tadd(t);\n \t}\n \t\n public ...
import java.util.Collections; import java.util.List; import org.olap.server.driver.util.MetadataUtils; import org.olap.server.driver.util.ParseUtils; import org.olap.server.processor.LevelMember; import org.olap.server.processor.LevelMemberSet; import org.olap.server.processor.sql.SetSubquery; import org.olap.server.processor.sql.TableMapping; import org.olap.server.processor.sql.TableMapping.LevelMapping; import org.olap4j.OlapException; import org.olap4j.mdx.IdentifierNode; import org.olap4j.metadata.Cube; import org.olap4j.metadata.Member;
package org.olap.server.processor.functions; public class IdentifiedMember extends OlapMethod { private Member cube_member; public IdentifiedMember(IdentifierNode node, Cube cube) throws OlapException { super(node, cube); cube_member = cube.lookupMember(node.getSegmentList()); if(cube_member==null) cube_member = MetadataUtils.lookupMember(cube, node.getSegmentList()); if(cube_member==null) throw new OlapException("Member not found in cube: "+ParseUtils.toString(node)); } @Override public List<LevelMemberSet> memberSet() throws OlapException { return Collections.singletonList(new LevelMemberSet(cube_member, node, this)); } @Override public SetSubquery query(TableMapping mapping, LevelMemberSet layer) throws OlapException {
if(! (cube_member instanceof LevelMember))
2
wseemann/RoMote
app/src/main/java/wseemann/media/romote/service/NotificationService.java
[ "public abstract class RequestCallback {\n public abstract void requestResult(RokuRequestTypes rokuRequestType, RequestTask.Result result);\n public abstract void onErrorResponse(RequestTask.Result result);\n}", "public class RequestTask extends AsyncTask<RokuRequestTypes, Void, RequestTask.Result> {\n\n ...
import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaMetadata; import android.media.session.MediaSession; import android.media.session.PlaybackState; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import com.jaku.core.JakuRequest; import com.jaku.parser.AppsParser; import com.jaku.parser.IconParser; import com.jaku.request.QueryActiveAppRequest; import com.jaku.request.QueryIconRequest; import java.util.List; import java.util.Random; import com.jaku.model.Channel; import wseemann.media.romote.R; import wseemann.media.romote.model.Device; import wseemann.media.romote.tasks.RequestCallback; import wseemann.media.romote.tasks.RequestTask; import wseemann.media.romote.utils.CommandHelper; import wseemann.media.romote.utils.Constants; import wseemann.media.romote.utils.NotificationUtils; import wseemann.media.romote.utils.PreferenceUtils; import wseemann.media.romote.utils.RokuRequestTypes;
package wseemann.media.romote.service; /** * Created by wseemann on 6/19/16. */ public class NotificationService extends Service { public static final String TAG = NotificationService.class.getName(); public static final int NOTIFICATION = 100; private NotificationManager mNM; private Notification notification; private Channel mChannel; private Device mDevice; private SharedPreferences mPreferences; private MediaSession mediaSession; private int mServiceStartId; private boolean mServiceInUse = true; private final Random mGenerator = new Random(); // Binder given to clients private final IBinder mBinder = new LocalBinder(); /** * Class used for the client Binder. Because we know this service always * runs in the same process as its clients, we don't need to deal with IPC. */ public class LocalBinder extends Binder { public NotificationService getService() { // Return this instance of LocalService so clients can call public methods return NotificationService.this; } } @Override public void onCreate() { super.onCreate(); setUpMediaSession(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Constants.UPDATE_DEVICE_BROADCAST); registerReceiver(mUpdateReceiver, intentFilter); mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(getString(R.string.app_name), getString(R.string.app_name), NotificationManager.IMPORTANCE_LOW); channel.setDescription(TAG); channel.enableLights(false); channel.enableVibration(false); mNM.createNotificationChannel(channel); } //startForeground(NotificationService.NOTIFICATION, notification); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); boolean enableNotification = mPreferences.getBoolean("notification_checkbox_preference", false); mPreferences.registerOnSharedPreferenceChangeListener(mPreferencesChangedListener); try { mDevice = PreferenceUtils.getConnectedDevice(this); if (enableNotification && mDevice != null) { notification = NotificationUtils.buildNotification(NotificationService.this, null, null, null, mediaSession.getSessionToken()); mNM.notify(NOTIFICATION, notification); sendStatusCommand(); } } catch (Exception ex) { } } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "Received start id " + startId + ": " + intent); mServiceStartId = startId; return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mUpdateReceiver); // Cancel the persistent notification. mNM.cancel(NOTIFICATION); mPreferences.unregisterOnSharedPreferenceChangeListener(mPreferencesChangedListener); mediaSession.release(); } @Override public IBinder onBind(Intent intent) { mServiceInUse = true; return mBinder; } @Override public void onRebind(Intent intent) { mServiceInUse = true; } @Override public boolean onUnbind(Intent intent) { mServiceInUse = false; return true; } private void sendStatusCommand() { String url = CommandHelper.getDeviceURL(this); QueryActiveAppRequest queryActiveAppRequest = new QueryActiveAppRequest(url); JakuRequest request = new JakuRequest(queryActiveAppRequest, new AppsParser());
new RequestTask(request, new RequestCallback() {
0
rkkr/simple-keyboard
app/src/main/java/rkr/simplekeyboard/inputmethod/latin/RichInputMethodManager.java
[ "public class PreferenceManagerCompat {\n public static Context getDeviceContext(Context context) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n return context.createDeviceProtectedStorageContext();\n }\n\n return context;\n }\n\n public static SharedPreferences...
import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.inputmethodservice.InputMethodService; import android.os.Build; import android.os.IBinder; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.RelativeSizeSpan; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodSubtype; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Executors; import rkr.simplekeyboard.inputmethod.R; import rkr.simplekeyboard.inputmethod.compat.PreferenceManagerCompat; import rkr.simplekeyboard.inputmethod.latin.common.LocaleUtils; import rkr.simplekeyboard.inputmethod.latin.settings.Settings; import rkr.simplekeyboard.inputmethod.latin.utils.SubtypePreferenceUtils; import rkr.simplekeyboard.inputmethod.latin.utils.DialogUtils; import rkr.simplekeyboard.inputmethod.latin.utils.LocaleResourceUtils; import rkr.simplekeyboard.inputmethod.latin.utils.SubtypeLocaleUtils;
* @param token supplies the identifying token given to an input method when it was started, * which allows it to perform this operation on itself. * @param onlyCurrentIme whether to only switch virtual subtypes or also switch to other input * methods. * @return whether the switch was successful. */ public boolean switchToNextInputMethod(final IBinder token, final boolean onlyCurrentIme) { if (onlyCurrentIme) { if (!hasMultipleEnabledSubtypes()) { return false; } return mSubtypeList.switchToNextSubtype(true); } if (mSubtypeList.switchToNextSubtype(false)) { return true; } // switch to a different IME if (mImmService.switchToNextInputMethod(token, false)) { return true; } if (hasMultipleEnabledSubtypes()) { // the virtual subtype should have been reset to the first item to prepare for switching // back to this IME, but we skipped notifying the change because we expected to switch // to a different IME, but since that failed, we just need to notify the listener mSubtypeList.notifySubtypeChanged(); return true; } return false; } /** * Get the subtype that is currently in use. * @return the current subtype. */ public Subtype getCurrentSubtype() { return mSubtypeList.getCurrentSubtype(); } /** * Check if the IME should offer ways to switch to a next input method (eg: a globe key). * @param binder supplies the identifying token given to an input method when it was started, * which allows it to perform this operation on itself. * @return whether the IME should offer ways to switch to a next input method. */ public boolean shouldOfferSwitchingToOtherInputMethods(final IBinder binder) { // Use the default value instead on Jelly Bean MR2 and previous where // {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} isn't yet available // and on KitKat where the API is still just a stub to return true always. if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { return false; } return mImmService.shouldOfferSwitchingToNextInputMethod(binder); } /** * Show a popup to pick the current subtype. * @param context the context for this application. * @param windowToken identifier for the window. * @param inputMethodService the input method service for this IME. * @return the dialog that was created. */ public AlertDialog showSubtypePicker(final Context context, final IBinder windowToken, final InputMethodService inputMethodService) { if (windowToken == null) { return null; } final CharSequence title = context.getString(R.string.change_keyboard); final List<SubtypeInfo> subtypeInfoList = getEnabledSubtypeInfoOfAllImes(context); if (subtypeInfoList.size() < 2) { // if there aren't multiple options, there is no reason to show the picker return null; } final CharSequence[] items = new CharSequence[subtypeInfoList.size()]; final Subtype currentSubtype = getCurrentSubtype(); int currentSubtypeIndex = 0; int i = 0; for (final SubtypeInfo subtypeInfo : subtypeInfoList) { if (subtypeInfo.virtualSubtype != null && subtypeInfo.virtualSubtype.equals(currentSubtype)) { currentSubtypeIndex = i; } final SpannableString itemTitle; final SpannableString itemSubtitle; if (!TextUtils.isEmpty(subtypeInfo.subtypeName)) { itemTitle = new SpannableString(subtypeInfo.subtypeName); itemSubtitle = new SpannableString("\n" + subtypeInfo.imeName); } else { itemTitle = new SpannableString(subtypeInfo.imeName); itemSubtitle = new SpannableString(""); } itemTitle.setSpan(new RelativeSizeSpan(0.9f), 0,itemTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); itemSubtitle.setSpan(new RelativeSizeSpan(0.85f), 0,itemSubtitle.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); items[i++] = new SpannableStringBuilder().append(itemTitle).append(itemSubtitle); } final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int position) { di.dismiss(); int i = 0; for (final SubtypeInfo subtypeInfo : subtypeInfoList) { if (i == position) { if (subtypeInfo.virtualSubtype != null) { setCurrentSubtype(subtypeInfo.virtualSubtype); } else { switchToTargetIme(subtypeInfo.imiId, subtypeInfo.systemSubtype, inputMethodService); } break; } i++; } } }; final AlertDialog.Builder builder = new AlertDialog.Builder(
DialogUtils.getPlatformDialogThemeContext(context));
4
FlyingPumba/SoundBox
src/com/arcusapp/soundbox/adapter/SongsListActivityAdapter.java
[ "public class SoundBoxApplication extends Application {\n private static Context appContext;\n\n public static final String ACTION_MAIN_ACTIVITY = \"com.arcusapp.soundbox.action.MAIN_ACTIVITY\";\n public static final String ACTION_FOLDERS_ACTIVITY = \"com.arcusapp.soundbox.action.FOLDERS_ACTIVITY\";\n p...
import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.provider.MediaStore; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.arcusapp.soundbox.R; import com.arcusapp.soundbox.SoundBoxApplication; import com.arcusapp.soundbox.data.MediaProvider; import com.arcusapp.soundbox.model.BundleExtra; import com.arcusapp.soundbox.model.SongEntry; import com.arcusapp.soundbox.player.MediaPlayerService; import com.arcusapp.soundbox.util.MediaEntryHelper; import java.util.ArrayList; import java.util.List;
/* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SoundBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.adapter; public class SongsListActivityAdapter extends BaseAdapter { private Activity mActivity; private List<SongEntry> songs; private MediaProvider mediaProvider; private MediaEntryHelper<SongEntry> mediaEntryHelper; private String projection = MediaStore.Audio.Media.TITLE; private String focusedID; private boolean hasHeader; public SongsListActivityAdapter(Activity activity, String focusedID, List<String> songsID, boolean hasHeader) { mActivity = activity; mediaProvider = new MediaProvider(); mediaEntryHelper = new MediaEntryHelper<SongEntry>(); this.hasHeader = hasHeader; List<SongEntry> temp_songs = mediaProvider.getValueFromSongs(songsID, projection); songs = new ArrayList<SongEntry>(); // order them by the order given on the songsID for (int i = 0; i < songsID.size(); i++) { for (int j = 0; j < temp_songs.size(); j++) { if (temp_songs.get(j).getID().equals(songsID.get(i))) { songs.add(temp_songs.get(j)); temp_songs.remove(j); break; } } } this.focusedID = focusedID; } public void onSongClick(int position) { //start the playActivity Intent playActivityIntent = new Intent(); playActivityIntent.setAction(SoundBoxApplication.ACTION_MAIN_ACTIVITY); playActivityIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); mActivity.startActivity(playActivityIntent); //call the service to play new songs
Intent serviceIntent = new Intent(MediaPlayerService.PLAY_NEW_SONGS, null, SoundBoxApplication.getContext(), MediaPlayerService.class);
4
superzanti/ServerSync
src/main/java/com/superzanti/serversync/client/Server.java
[ "@Command(name = \"ServerSync\", mixinStandardHelpOptions = true, version = RefStrings.VERSION, description = \"A utility for synchronizing a server<->client style game.\")\npublic class ServerSync implements Callable<Integer> {\n\n /* AWT EVENT DISPATCHER THREAD */\n\n public static final String APPLICATION_...
import com.superzanti.serversync.ServerSync; import com.superzanti.serversync.communication.response.ServerInfo; import com.superzanti.serversync.util.AutoClose; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.enums.EServerMessage; import java.io.*; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException;
package com.superzanti.serversync.client; public class Server { public ObjectOutputStream output; public ObjectInputStream input; public Socket clientSocket; public ServerInfo info; public OutputStream os; public InputStream is; protected final String address; protected final int port; Server(String address, int port) { this.address = address; this.port = port; } public static Server forClient(Client client) { return new Server(client.serverAddress, client.serverPort); } public boolean connect() { InetAddress host; try { host = InetAddress.getByName(address); } catch (UnknownHostException e) { Logger.error(ServerSync.strings.getString("connection_failed_host") + ": " + address); return false; } Logger.debug(ServerSync.strings.getString("connection_attempt_server")); clientSocket = new Socket(); Logger.log("< " + ServerSync.strings.getString("connection_message") + " >"); try { clientSocket.setPerformancePreferences(0, 1, 2); clientSocket.connect(new InetSocketAddress(host.getHostName(), port), 5000); } catch (IOException e) { Logger.error(ServerSync.strings.getString("connection_failed_server") + ": " + address + ":" + port); AutoClose.closeResource(clientSocket); return false; } Logger.debug(ServerSync.strings.getString("debug_IO_streams")); try { os = clientSocket.getOutputStream(); is = clientSocket.getInputStream(); output = new ObjectOutputStream(os); input = new ObjectInputStream(is); } catch (IOException e) { Logger.debug(ServerSync.strings.getString("debug_IO_streams_failed")); AutoClose.closeResource(clientSocket); return false; } try { output.writeUTF(ServerSync.GET_SERVER_INFO); output.flush(); } catch (IOException e) { Logger.outputError(ServerSync.GET_SERVER_INFO); } try { info = (ServerInfo) input.readObject(); } catch (IOException | ClassNotFoundException e) { Logger.error("Failed to read server information"); Logger.debug(e); } return true; } public void close() { try { // Output could be null if the server has never connected, i.e. the client used the wrong details if (output != null) {
output.writeUTF(EServerMessage.EXIT.toString());
4
rapidpro/surveyor
app/src/main/java/io/rapidpro/surveyor/activity/OrgChooseActivity.java
[ "public class Logger {\n\n private static final String TAG = \"Surveyor\";\n\n public static void e(String message, Throwable t) {\n Log.e(TAG, message, t);\n }\n\n public static void w(String message) {\n Log.w(TAG, message);\n }\n\n public static void d(String message) {\n L...
import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import io.rapidpro.surveyor.Logger; import io.rapidpro.surveyor.R; import io.rapidpro.surveyor.SurveyorApplication; import io.rapidpro.surveyor.SurveyorIntent; import io.rapidpro.surveyor.SurveyorPreferences; import io.rapidpro.surveyor.data.Org; import io.rapidpro.surveyor.fragment.OrgListFragment;
package io.rapidpro.surveyor.activity; /** * Let's the user select one of the orgs they have access to */ public class OrgChooseActivity extends BaseActivity implements OrgListFragment.Container { private List<Org> getOrgs() {
Set<String> orgUUIDs = SurveyorApplication.get().getPreferences().getStringSet(SurveyorPreferences.AUTH_ORGS, Collections.<String>emptySet());
1
CvvT/DexTamper
src/org/jf/dexlib2/immutable/ImmutableClassDef.java
[ "public interface Annotation extends BasicAnnotation, Comparable<Annotation> {\n /**\n * Gets the visibility of this annotation.\n *\n * This will be one of the AnnotationVisibility.* constants.\n *\n * @return The visibility of this annotation\n */\n int getVisibility();\n\n /**\n ...
import com.google.common.collect.*; import org.jf.dexlib2.base.reference.BaseTypeReference; import org.jf.dexlib2.iface.Annotation; import org.jf.dexlib2.iface.ClassDef; import org.jf.dexlib2.iface.Field; import org.jf.dexlib2.iface.Method; import org.jf.dexlib2.util.FieldUtil; import org.jf.dexlib2.util.MethodUtil; import org.jf.util.ImmutableConverter; import org.jf.util.ImmutableUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import java.util.List;
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.immutable; public class ImmutableClassDef extends BaseTypeReference implements ClassDef { @Nonnull protected final String type; protected final int accessFlags; @Nullable protected final String superclass; @Nonnull protected final ImmutableList<String> interfaces; @Nullable protected final String sourceFile; @Nonnull protected final ImmutableSet<? extends ImmutableAnnotation> annotations; @Nonnull protected final ImmutableSortedSet<? extends ImmutableField> staticFields; @Nonnull protected final ImmutableSortedSet<? extends ImmutableField> instanceFields; @Nonnull protected final ImmutableSortedSet<? extends ImmutableMethod> directMethods; @Nonnull protected final ImmutableSortedSet<? extends ImmutableMethod> virtualMethods; public ImmutableClassDef(@Nonnull String type, int accessFlags, @Nullable String superclass, @Nullable Collection<String> interfaces, @Nullable String sourceFile, @Nullable Collection<? extends Annotation> annotations, @Nullable Iterable<? extends Field> fields, @Nullable Iterable<? extends Method> methods) { if (fields == null) { fields = ImmutableList.of(); } if (methods == null) { methods = ImmutableList.of(); } this.type = type; this.accessFlags = accessFlags; this.superclass = superclass; this.interfaces = interfaces==null ? ImmutableList.<String>of() : ImmutableList.copyOf(interfaces); this.sourceFile = sourceFile; this.annotations = ImmutableAnnotation.immutableSetOf(annotations); this.staticFields = ImmutableField.immutableSetOf(Iterables.filter(fields, FieldUtil.FIELD_IS_STATIC)); this.instanceFields = ImmutableField.immutableSetOf(Iterables.filter(fields, FieldUtil.FIELD_IS_INSTANCE));
this.directMethods = ImmutableMethod.immutableSetOf(Iterables.filter(methods, MethodUtil.METHOD_IS_DIRECT));
4
be-hase/relumin
src/test/java/com/behase/relumin/e2e/ClusterApiTest.java
[ "@Slf4j\n@Configuration\n@EnableAutoConfiguration\n@EnableScheduling\n@EnableWebSecurity\n@ComponentScan\npublic class Application extends WebMvcConfigurerAdapter {\n private static final String CONFIG_LOCATION = \"config\";\n\n public static void main(String[] args) throws IOException {\n log.info(\"S...
import com.behase.relumin.Application; import com.behase.relumin.TestHelper; import com.behase.relumin.model.Cluster; import com.behase.relumin.model.Notice; import com.behase.relumin.scheduler.NodeScheduler; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.http.HttpHeaders; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
package com.behase.relumin.e2e; /** * Check integration of success behavior */ @Slf4j @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebIntegrationTest public class ClusterApiTest { @Value("${test.redis.host}") private String testRedisHost; @Autowired private TestHelper testHelper; @Autowired private WebApplicationContext wac; @Autowired private ObjectMapper mapper; @Autowired
private NodeScheduler nodeScheduler;
4
pasqualesalza/elephant56
elephant56/src/main/java/it/unisa/elephant56/core/generator/GridReducer.java
[ "public final class Constants {\r\n /**\r\n * The default lock file name.\r\n */\r\n public static final String LOCK_FILE_NAME =\r\n \"lock\";\r\n\r\n public static final long LOCK_TIME_TO_WAIT =\r\n 100L;\r\n\r\n /**\r\n * The meta-data property for Avro files.\r\n ...
import it.unisa.elephant56.core.Constants; import it.unisa.elephant56.core.common.IndividualWrapper; import it.unisa.elephant56.core.common.Properties; import it.unisa.elephant56.core.reporter.individual.IndividualReporter; import it.unisa.elephant56.core.reporter.time.GeneticOperatorsTimeReporter; import it.unisa.elephant56.core.reporter.time.MapReduceTimeReporter; import it.unisa.elephant56.user.common.FitnessValue; import it.unisa.elephant56.user.common.Individual; import it.unisa.elephant56.user.operators.*; import org.apache.avro.mapred.AvroKey; import org.apache.avro.mapreduce.AvroMultipleOutputs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.Reducer; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List;
package it.unisa.elephant56.core.generator; public class GridReducer extends Reducer<AvroKey<IndividualWrapper<Individual, FitnessValue>>, IntWritable, AvroKey<IndividualWrapper<Individual, FitnessValue>>, NullWritable> { // GenerationsExecutor object. private GridDistributedSecondaryGenerationsBlockExecutor generationsBlockExecutor; // Configuration object. private Configuration configuration; // Configuration variables. private boolean isTimeReporterActive; private GeneticOperatorsTimeReporter geneticOperatorsTimeReporter; private MapReduceTimeReporter mapreduceTimeReporter; private Path mapreduceReducerPartialTimeReportFilePath; private boolean isIndividualReporterActive;
private IndividualReporter individualReporter;
3
shaunlebron/flex-fov
src/main/java/mod/render360/coretransform/classtransformers/GuiOptionsTransformer.java
[ "public class ClassName {\n\n private final String deobfuscatedName;\n private final String obfuscatedName;\n\n public ClassName(String deobfuscatedName, String obfuscatedName) {\n this.deobfuscatedName = deobfuscatedName;\n this.obfuscatedName = obfuscatedName;\n }\n\n public String ge...
import static org.objectweb.asm.Opcodes.*; import mod.render360.coretransform.classtransformers.name.ClassName; import mod.render360.coretransform.classtransformers.name.MethodName; import mod.render360.coretransform.classtransformers.name.Names; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; import mod.render360.coretransform.CLTLog; import mod.render360.coretransform.CoreLoader; import mod.render360.coretransform.RenderUtil; import mod.render360.coretransform.gui.Render360Settings; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiCustomizeSkin; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiVideoSettings; import net.minecraft.client.settings.GameSettings;
package mod.render360.coretransform.classtransformers; public class GuiOptionsTransformer extends ClassTransformer { @Override public ClassName getName() { return Names.GuiOptions; } @Override public MethodTransformer[] getMethodTransformers() { MethodTransformer transformInitGui = new MethodTransformer() { @Override public MethodName getName() { return Names.GuiOptions_initGui; } @Override public void transform(ClassNode classNode, MethodNode method, boolean obfuscated) {
CLTLog.info("Found method: " + method.name + " " + method.desc);
3
jskcse4/FreeTamilEBooks
src/com/jskaleel/fte/home/BooksHomeAdapter.java
[ "public class FTEApplication extends Application {\n\t\n\t public static final String TAG = FTEApplication.class.getSimpleName();\n\t\n\tprivate static FTEApplication mInstance;\n\tprivate static Context mAppContext;\n\n\tprivate RequestQueue mRequestQueue;\n\tprivate static ImageLoader mImageLoader;\n\n\t@Override...
import java.util.ArrayList; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.ImageLoader.ImageContainer; import com.android.volley.toolbox.ImageLoader.ImageListener; import com.android.volley.toolbox.NetworkImageView; import com.jskaleel.fte.R; import com.jskaleel.fte.app.FTEApplication; import com.jskaleel.fte.common.FTEDevice; import com.jskaleel.fte.common.PrintLog; import com.jskaleel.fte.listeners.HomeItemListener; import com.jskaleel.fte.listeners.OnListItemTouchListener; import com.nineoldandroids.animation.ObjectAnimator;
package com.jskaleel.fte.home; public class BooksHomeAdapter extends BaseAdapter implements OnScrollListener { private Context context; private ArrayList<BooksHomeListItems> bookListArray; private ArrayList<BooksHomeListItems> searchListArray; private FragmentHome fragmentHome; private Typeface tf; private boolean fastAnim,isAnim; private int SwipeLength;
private HomeItemListener homeItemListener;
3
blinkfox/zealot
src/main/java/com/blinkfox/zealot/core/concrete/ImportHandler.java
[ "public final class BuildSource {\n\n /** xml文件对应的命名空间. */\n private String nameSpace;\n\n /** SQL拼接信息. */\n private SqlInfo sqlInfo;\n\n /** XML节点. */\n private Node node;\n\n /** 参数对象上下文,一般为Bean或者Map. */\n private Object paramObj;\n\n /** 拼接SQL片段的前缀,如:and、or等. */\n private String pre...
import com.blinkfox.zealot.bean.BuildSource; import com.blinkfox.zealot.bean.SqlInfo; import com.blinkfox.zealot.consts.ZealotConst; import com.blinkfox.zealot.core.IConditHandler; import com.blinkfox.zealot.core.Zealot; import com.blinkfox.zealot.helpers.ParseHelper; import com.blinkfox.zealot.helpers.StringHelper; import com.blinkfox.zealot.helpers.XmlNodeHelper; import org.dom4j.Node;
package com.blinkfox.zealot.core.concrete; /** * 引用import标签对应的动态sql生成处理器的实现类. * <p>引用标签的主要内容:`[import match="" namespace="" zealotid="" value="" /]`</p> * @author blinkfox on 2017/8/15. */ public class ImportHandler implements IConditHandler { /** * 构建import标签的sqlInfo信息. * @param source 构建所需的资源对象 * @return 返回SqlInfo对象 */ @Override public SqlInfo buildSqlInfo(BuildSource source) { // 判断是否生成,如果不匹配则不生成SQL片段. String matchText = XmlNodeHelper.getNodeAttrText(source.getNode(), ZealotConst.ATTR_MATCH); if (ParseHelper.isNotMatch(matchText, source.getParamObj())) { return source.getSqlInfo(); } // 获取命名空间的文本值. String nameSpaceText = XmlNodeHelper.getNodeAttrText(source.getNode(), ZealotConst.ATTR_NAME_SPACE);
String nameSpace = StringHelper.isNotBlank(nameSpaceText) ? nameSpaceText : source.getNameSpace();
6
cobaltdev/pipeline
src/main/java/com/cobalt/bamboo/plugin/pipeline/servlet/MainPage.java
[ "public interface CacheManager {\n\t\n\t/**\n\t * Put WallBoardData for all plans into the cache. All of existing data (if any)\n\t * will be replaced.\n\t */\n\tpublic void putAllWallBoardData();\n\t\n\t/**\n\t * Update the WallBoardData in the cache for the given plan. If the plan already\n\t * exists in the cach...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URI; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.atlassian.sal.api.auth.LoginUriProvider; import com.atlassian.sal.api.user.UserManager; import com.atlassian.templaterenderer.TemplateRenderer; import com.cobalt.bamboo.plugin.pipeline.Controllers.CacheManager; import com.cobalt.bamboo.plugin.pipeline.Controllers.MainManager; import com.cobalt.bamboo.plugin.pipeline.cache.WallBoardData; import com.cobalt.bamboo.plugin.pipeline.cdperformance.CDPerformance; import com.cobalt.bamboo.plugin.pipeline.changelist.Change;
package com.cobalt.bamboo.plugin.pipeline.servlet; public class MainPage extends HttpServlet{ private static final Logger log = LoggerFactory.getLogger(MainPage.class); private final UserManager userManager; private final LoginUriProvider loginUriProvider; private final TemplateRenderer renderer; private final CacheManager cacheManager; private final MainManager mainManager; public MainPage(UserManager userManager, LoginUriProvider loginUriProvider, TemplateRenderer renderer, CacheManager cacheManager, MainManager mainManager) { this.userManager = userManager; this.loginUriProvider = loginUriProvider; this.renderer = renderer; this.cacheManager = cacheManager; this.mainManager = mainManager; } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Redirect the user if user is not admin String username = userManager.getRemoteUsername(request); if (username == null) { redirectToLogin(request, response); return; } String query = request.getParameter("data"); if (query == null) { // TODO // Normal case: normal table page response.setContentType("text/html;charset=utf-8"); renderer.render("cdpipeline.vm", response.getWriter()); } else if (query.equalsIgnoreCase("all")) { // Special Case: JSON request ObjectWriter writer = (new ObjectMapper()).writer().withDefaultPrettyPrinter(); List<WallBoardData> resultList = cacheManager.getAllWallBoardData(); String json = writer.writeValueAsString(resultList); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(json); } else if (query.equalsIgnoreCase("changes") && request.getParameter("plankey") != null){
List<Change> changeList = mainManager.getChangeListForPlan(request.getParameter("plankey"));
4
hermannhueck/reactive-mongo-access
src/main/java/shopJava/queries/QueryJ10RxStreamsWithAkkaStreams.java
[ "public class Credentials {\n\n public final String username;\n public final String password;\n\n public Credentials(final String username, final String password) {\n this.username = username;\n this.password = password;\n }\n}", "public class Order {\n\n private static final String I...
import akka.Done; import akka.NotUsed; import akka.actor.ActorSystem; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Source; import com.mongodb.rx.client.MongoClient; import com.mongodb.rx.client.MongoClients; import com.mongodb.rx.client.MongoCollection; import com.mongodb.rx.client.MongoDatabase; import org.bson.Document; import org.reactivestreams.Publisher; import rx.Observable; import rx.Single; import shopJava.model.Credentials; import shopJava.model.Order; import shopJava.model.Result; import shopJava.model.User; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionStage; import java.util.concurrent.CountDownLatch; import static com.mongodb.client.model.Filters.eq; import static java.lang.Thread.sleep; import static rx.RxReactiveStreams.toPublisher; import static shopJava.util.Constants.*; import static shopJava.util.Util.checkUserLoggedIn;
package shopJava.queries; @SuppressWarnings("Convert2MethodRef") public class QueryJ10RxStreamsWithAkkaStreams { public static void main(String[] args) throws Exception { new QueryJ10RxStreamsWithAkkaStreams(); } private final DAO dao = new DAO(); private class DAO { private final MongoCollection<Document> usersCollection; private final MongoCollection<Document> ordersCollection; DAO() { final MongoClient client = MongoClients.create(MONGODB_URI); final MongoDatabase db = client.getDatabase(SHOP_DB_NAME); this.usersCollection = db.getCollection(USERS_COLLECTION_NAME); this.ordersCollection = db.getCollection(ORDERS_COLLECTION_NAME); } private Single<User> _findUserByName(final String name) { return usersCollection .find(eq("_id", name)) .first() .toSingle() .map(doc -> new User(doc)); } private Observable<Order> _findOrdersByUsername(final String username) { return ordersCollection .find(eq("username", username)) .toObservable() .map(doc -> new Order(doc)); } Publisher<User> findUserByName(final String name) { return toPublisher(_findUserByName(name).toObservable()); } Publisher<List<Order>> findOrdersByUsername(final String username) { return toPublisher(_findOrdersByUsername(username).toList()); } } // end DAO private Source<String, NotUsed> logIn(final Credentials credentials) { return Source.fromPublisher(dao.findUserByName(credentials.username))
.map(user -> checkUserLoggedIn(user, credentials))
5
calibre2opds/calibre2opds
OpdsOutput/src/main/java/com/gmail/dpierron/calibre/opds/TagTreeSubCatalog.java
[ "public class Book extends GenericDataObject {\r\n private final static Logger logger = LogManager.getLogger(Book.class);\r\n\r\n private File bookFolder;\r\n private final String id;\r\n private final String uuid;\r\n private String title;\r\n private String titleSort;\r\n private final String path;\r\n ...
import com.gmail.dpierron.calibre.configuration.Icons; import com.gmail.dpierron.calibre.datamodel.Book; import com.gmail.dpierron.calibre.datamodel.Tag; import com.gmail.dpierron.tools.i18n.Localization; import com.gmail.dpierron.calibre.trook.TrookSpecificSearchDatabaseManager; import com.gmail.dpierron.tools.Helper; import com.gmail.dpierron.tools.RootTreeNode; import com.gmail.dpierron.tools.TreeNode; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import java.io.IOException; import java.util.LinkedList; import java.util.List;
package com.gmail.dpierron.calibre.opds; /** * Class for defining a new tree set of levels based on a tag, * with tags possibly split by a defined character. This is * a way f implementing what are known as hierarchical tags * in Calibre. */ public class TagTreeSubCatalog extends TagsSubCatalog { private final static Logger logger = LogManager.getLogger(TagTreeSubCatalog.class); // CONSTRUCTOR(S) public TagTreeSubCatalog(List<Object> stuffToFilterOut, List<Book> books) { super(stuffToFilterOut, books); setCatalogType(Constants.TAGTREE_TYPE); } public TagTreeSubCatalog(List<Book> books) { super(books); setCatalogType(Constants.TAGTREE_TYPE); } // METHODS /** * Generate a tag tree for the current level * * The actual tag associated with a node is stored * as data information * * @param pBreadcrumbs * @return * @throws IOException */ @Override Element getCatalog(Breadcrumbs pBreadcrumbs, boolean inSubDir) throws IOException { Element result; if (logger.isDebugEnabled()) logger.debug("getCatalog: pBreadcrumbs=" + pBreadcrumbs.toString() + ", inSubDir=" + inSubDir); String splitTagsOn = currentProfile.getSplitTagsOn(); assert Helper.isNotNullOrEmpty(splitTagsOn); TreeNode root = new RootTreeNode(); // Work through the tags creating the tree if (logger.isTraceEnabled()) logger.trace("generate initial tree"); for (Tag tag : getTags()) { String[] partsOfTag = tag.getPartsOfTag(splitTagsOn); TreeNode currentPositionInTree = root; for (int i = 0; i < partsOfTag.length; i++) { String partOfTag = partsOfTag[i]; TreeNode nextPositionInTree = currentPositionInTree.getChildWithId(partOfTag); if (nextPositionInTree == null) { nextPositionInTree = new TreeNode(partOfTag); currentPositionInTree.addChild(nextPositionInTree); currentPositionInTree = nextPositionInTree; } else currentPositionInTree = nextPositionInTree; } // Mark the tag this node uses currentPositionInTree.setData(tag); } // browse the tree, removing unneeded levels (single childs up to the leafs) if (logger.isTraceEnabled()) logger.trace("remove unneeded levels"); removeUnNeededLevelsInTree(root, null); // Now get the resulting page set result = getLevelOfTreeNode(pBreadcrumbs, root); if (logger.isDebugEnabled()) logger.debug("getCatalog: exit (pBreadcrumbs=" + pBreadcrumbs.toString() + ")"); return result; } /** * Trim un-needed nodes from the tree. * * We assume that any node that only has a single * child can effectively have the child collapsed * into the parent node. This will stop us generating * a series of pages that only have a single entry. * * NOTE: It is written as a free-standing routine so it cn be called recursively. * * @param node * @param removedParent * @return */ private TreeNode removeUnNeededLevelsInTree(TreeNode node, TreeNode removedParent) { // if (logger.isTraceEnabled()) logger.trace("removeUnNeededLevel: node=" + node + ", removedParent=" + removedParent); if (removedParent != null) { node.setId(removedParent.getId() + currentProfile.getSplitTagsOn() + node.getId()); } if (node.getData() != null) { // this is a leaf return node; } List<TreeNode> newChildren = new LinkedList<TreeNode>(); for (TreeNode childNode : node.getChildren()) { if (childNode.getData() == null && childNode.getChildren().size() <= 1) { if (childNode.getChildren().size() == 0) { // useless node // TODO: ITIMPI: Feel there should be something done here if this condition can really ever occur int dummy = 1; // TODO See if we really ever get here! } else { // useless level so remove it TreeNode newChild = removeUnNeededLevelsInTree(childNode.getChildren().get(0), childNode); if (newChild != null) { newChild.setParent(node); newChildren.add(newChild); } } } else { newChildren.add(removeUnNeededLevelsInTree(childNode, null)); } } node.setChildren(newChildren); return node; } /** * Initial entry point to creating a tree list of tags * * @param pBreadcrumbs * @param level * @return * @throws IOException */ private Element getLevelOfTreeNode(Breadcrumbs pBreadcrumbs, TreeNode level) throws IOException { if (logger.isDebugEnabled()) logger.debug("getLevelOfTreeNode: pBreadcrumbs=" + pBreadcrumbs + ", level=" + level); Element result; if (Helper.isNullOrEmpty(level.getChildren())) { Tag tag = (Tag) level.getData(); if (tag == null) { if (logger.isDebugEnabled()) logger.debug("getLevelOfTreeNode: Exinull (Appears to be an empty level!)"); return null; } // it's a leaf, consisting of a single tag : make a list of books if (logger.isTraceEnabled()) logger.trace("getLevelOfTreeNode: it's a leaf, consisting of a single tag : make a list of books"); String urn = Constants.INITIAL_URN_PREFIX + getCatalogType()+ level.getGuid(); result = getDetailedEntry(pBreadcrumbs, tag, urn, level.getId());
TrookSpecificSearchDatabaseManager.addTag(tag, result);
2
ketayao/fensy
src/main/java/com/ketayao/fensy/mvc/DispatcherFilter.java
[ "public class DBManager {\n\n private final static Logger log = LoggerFactory\n .getLogger(DBManager.class);\n private final static ThreadLocal<Connection> conns = new ThreadLocal<Connection>();\n pri...
import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ketayao.fensy.Constants; import com.ketayao.fensy.db.DBManager; import com.ketayao.fensy.exception.ActionException; import com.ketayao.fensy.exception.NotFoundTemplateException; import com.ketayao.fensy.handler.ExceptionHandler; import com.ketayao.fensy.handler.SimpleExceptionHandler; import com.ketayao.fensy.mvc.interceptor.Interceptor; import com.ketayao.fensy.mvc.view.View; import com.ketayao.fensy.mvc.view.ViewMap; import com.ketayao.fensy.util.ClassUtils; import com.ketayao.fensy.util.Exceptions; import com.ketayao.fensy.util.NumberUtils; import com.ketayao.fensy.util.PropertiesUtils; import com.ketayao.fensy.util.StringUtils;
/** * <pre> * Copyright: Copyright(C) 2011-2012, ketayao.com * Date: 2013年8月13日 * Author: <a href="mailto:ketayao@gmail.com">ketayao</a> * Description: * * </pre> **/ package com.ketayao.fensy.mvc; /** * * @author <a href="mailto:ketayao@gmail.com">ketayao</a> * @since 2013年8月13日 上午11:48:42 */ public class DispatcherFilter implements Filter { private final static Logger log = LoggerFactory .getLogger(DispatcherFilter.class); private ServletContext context; private ExceptionHandler exceptionHandler = new SimpleExceptionHandler(); private Map<String, Interceptor> interceptors = new LinkedHashMap<String, Interceptor>(); private final static String VIEW_INDEX = "/" + Constants.ACTION_DEFAULT_METHOD; private final static Map<String, PathView> templates = new HashMap<String, PathView>(); private final static HashMap<String, Object> actions = new HashMap<String, Object>(); private final static HashMap<String, Method> methods = new HashMap<String, Method>(); // 忽略的URI private List<String> ignoreURIs = new ArrayList<String>(); // 忽略的后缀 private List<String> ignoreExts = new ArrayList<String>(); // 视图类型 private List<View> viewList = new ArrayList<View>(); /** * 视图路径=模板根路径+域名模板路径+视图名称 */ // 其他子域名模板路径 private HashMap<String, String> domainTemplatePathes = new HashMap<String, String>(); // 域名 private String rootDomain = Constants.ACTION_ROOT_DOMAIN; private String rootDomainTemplatePath = Constants.DEFAULT_DOMAIN_TEMPLATE_PATH; // 模板根路径 private String templatePath = Constants.DEFAULT_TEMPLATE_PATH; private String defaultTemplatePath; @Override public void init(FilterConfig cfg) throws ServletException { this.context = cfg.getServletContext(); Map<String, String> config = PropertiesUtils.loadToMap(Constants.FENSY_CONFIG_FILE); // 设置上传文件尺寸 String tmpSzie = config.get(Constants.FENSY_UPLOAD_FILE_MAX_SIZE); if (NumberUtils.isNumber(tmpSzie)) { WebContext.setMaxSize(NumberUtils.toInt(tmpSzie)); } // 模板存放路径 String tmp = config.get(Constants.FENSY_TEMPLATE_PATH); if (StringUtils.isNotBlank(tmp)) { if (tmp.endsWith("/")) { tmp = tmp.substring(0, tmp.length() - 1); } templatePath = tmp; } // 主域名,必须指定 tmp = config.get(Constants.FENSY_ROOT_DOMAIN); if (StringUtils.isNotBlank(tmp)) rootDomain = tmp; tmp = config.get(Constants.FENSY_ROOT_DOMAIN_TEMPLATE_PATH); if (StringUtils.isNotBlank(tmp)) rootDomainTemplatePath = tmp; // 二级域名和对应页面模板路径 tmp = config.get(Constants.FENSY_OTHER_DOMAIN_AND_TEMPLATE_PATH); if (StringUtils.isNotBlank(tmp)) { String[] domainAndPath = tmp.split(","); for (String dp : domainAndPath) { String[] arr = dp.split(":"); domainTemplatePathes.put(arr[0], templatePath + arr[1]); } } defaultTemplatePath = templatePath + rootDomainTemplatePath; // 某些URL前缀不予处理(例如 /img/**) String ignores = config.get(Constants.FENSY_IGNORE_URI); if (StringUtils.isBlank(ignores)) { ignores = Constants.ACTION_IGNORE_URI; } ignoreURIs.addAll(Arrays.asList(StringUtils.split(ignores, ","))); // 某些URL扩展名不予处理(例如 *.jpg) ignores = config.get(Constants.FENSY_IGNORE_EXT); if (StringUtils.isBlank(ignores)) { ignores = Constants.ACTION_IGNORE_EXT; } for (String ig : StringUtils.split(ignores, ',')) { ignoreExts.add('.' + ig.trim()); } // 按顺序创建view String views = config.get(Constants.FENSY_VIEW); if (StringUtils.isNotBlank(views)) { for (String v : StringUtils.split(views, ',')) { View view = ViewMap.getView(v.toLowerCase()); // 从内置的viewMap中查找 if (view != null) { viewList.add(view); continue; } try { viewList.add((View) Class.forName(v).newInstance()); } catch (Exception e) {
log.error("视图对象创建出错:" + view, Exceptions.getStackTraceAsString(e));
4
tmorcinek/android-codegenerator-library
src/test/java/com/morcinek/android/codegenerator/BActivityCodeGeneratorTest.java
[ "public class TemplateCodeGenerator {\n\n private BuildersCollection buildersCollection;\n\n private ResourceProvidersFactory resourceProvidersFactory;\n\n private TemplateManager templateManager;\n\n public TemplateCodeGenerator(String templateName, ResourceProvidersFactory resourceProvidersFactory, Te...
import com.morcinek.android.codegenerator.codegeneration.TemplateCodeGenerator; import com.morcinek.android.codegenerator.codegeneration.providers.factories.BActivityResourceProvidersFactory; import com.morcinek.android.codegenerator.codegeneration.templates.ResourceTemplatesProvider; import com.morcinek.android.codegenerator.codegeneration.templates.TemplatesProvider; import com.morcinek.android.codegenerator.extractor.XMLResourceExtractor; import com.morcinek.android.codegenerator.extractor.string.FileNameExtractor; import com.morcinek.android.codegenerator.util.InputStreamProvider; import org.fest.assertions.Assertions; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import java.io.IOException;
package com.morcinek.android.codegenerator; public class BActivityCodeGeneratorTest { private CodeGenerator codeGenerator; private InputStreamProvider inputStreamProvider = new InputStreamProvider(); private TemplatesProvider templatesProvider = new ResourceTemplatesProvider(); @Before public void setUp() throws Exception {
codeGenerator = new CodeGenerator(XMLResourceExtractor.createResourceExtractor(), new FileNameExtractor(), new TemplateCodeGenerator("BActivity_template", new BActivityResourceProvidersFactory(), new ResourceTemplatesProvider()));
4
damingerdai/web-qq
src/main/java/org/aming/web/qq/contorller/UserController.java
[ "public class User extends AbstractUserDetails implements UserDetails {\n\n private static final long serialVersionUID = -5509256807259591938L;\n\n private String id;\n private String username;\n private String password;\n private String email;\n\n public String getId() {\n return id;\n ...
import org.aming.web.qq.domain.User; import org.aming.web.qq.logger.Logger; import org.aming.web.qq.logger.LoggerManager; import org.aming.web.qq.response.CommonResponse; import org.aming.web.qq.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*;
package org.aming.web.qq.contorller; /** * @author daming * @version 2017/10/2. */ @RestController @RequestMapping("/webqq") public class UserController {
private static final Logger logger = LoggerManager.getLogger(UserController.class);
1
Nanopublication/nanopub-java
src/main/java/org/nanopub/Run.java
[ "public class MakeIndex {\n\n\t@com.beust.jcommander.Parameter(description = \"input-nanopub-files\")\n\tprivate List<File> inputFiles = new ArrayList<File>();\n\n\t@com.beust.jcommander.Parameter(names = \"-fs\", description = \"Add index nanopubs from input files \" +\n\t\t\t\"as sub-indexes (instead of elements)...
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.rdf4j.RDF4JException; import org.nanopub.extra.index.MakeIndex; import org.nanopub.extra.security.MakeKeys; import org.nanopub.extra.security.SignNanopub; import org.nanopub.extra.server.GetNanopub; import org.nanopub.extra.server.GetServerInfo; import org.nanopub.extra.server.NanopubStatus; import org.nanopub.extra.server.PublishNanopub; import org.nanopub.trusty.FixTrustyNanopub; import org.nanopub.trusty.MakeTrustyNanopub;
package org.nanopub; public class Run { private Run() {} // no instances allowed public static void main(String[] args) throws IOException, RDF4JException { NanopubImpl.ensureLoaded(); run(args); } private static List<Class<?>> runnableClasses = new ArrayList<>(); private static Map<String,Class<?>> runnableClassesByName = new HashMap<>(); private static Map<String,Class<?>> runnableClassesByShortcut = new HashMap<>(); private static Map<Class<?>,String> runnableClassNames = new HashMap<>(); private static Map<Class<?>,String> runnableClassShortcuts = new HashMap<>(); private static void addRunnableClass(Class<?> c, String shortcut) { runnableClasses.add(c); runnableClassesByName.put(c.getSimpleName(), c); runnableClassNames.put(c, c.getSimpleName()); if (shortcut != null) { runnableClassesByShortcut.put(shortcut, c); runnableClassShortcuts.put(c, shortcut); } } static { addRunnableClass(CheckNanopub.class, "check"); addRunnableClass(GetNanopub.class, "get"); addRunnableClass(PublishNanopub.class, "publish"); addRunnableClass(SignNanopub.class, "sign"); addRunnableClass(MakeTrustyNanopub.class, "mktrusty");
addRunnableClass(FixTrustyNanopub.class, "fix");
7
engagingspaces/vertx-graphql-service-discovery
graphql-service-consumer/src/main/java/io/engagingspaces/graphql/servicediscovery/consumer/DiscoveryRegistrar.java
[ "public abstract class AbstractRegistrar<T extends Registration> implements Registrar {\n\n protected final Vertx vertx;\n private final Map<String, ManagedServiceDiscovery> serviceDiscoveries;\n private final Map<T, String> registrationMap;\n\n protected AbstractRegistrar(Vertx vertx) {\n this.v...
import io.engagingspaces.graphql.discovery.impl.AbstractRegistrar; import io.engagingspaces.graphql.discovery.impl.AbstractRegistration; import io.engagingspaces.graphql.events.SchemaAnnounceHandler; import io.engagingspaces.graphql.events.SchemaUsageHandler; import io.engagingspaces.graphql.events.impl.SchemaMessageConsumers; import io.vertx.core.Vertx; import io.vertx.servicediscovery.ServiceDiscovery; import io.vertx.servicediscovery.ServiceDiscoveryOptions;
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.engagingspaces.graphql.servicediscovery.consumer; /** * Manages {@link ServiceDiscovery} creation, and registration of discovery events. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ public class DiscoveryRegistrar extends AbstractRegistrar<DiscoveryRegistration> { private final SchemaMessageConsumers eventManager; protected DiscoveryRegistrar(Vertx vertx) { super(vertx); this.eventManager = new SchemaMessageConsumers(vertx); } /** * Creates a new discovery registrar instance for managing service discoveries and their event consumers. * * @param vertx the vert.x instance * @return the discovery registrar */ public static DiscoveryRegistrar create(Vertx vertx) { return new DiscoveryRegistrar(vertx); } /** * Registers the provided event handlers to the `announce` and `usage` events of the service discovery * specified in the service discovery options. * * @param options the service discovery options * @param announceHandler the handler for `announce` events * @param usageHandler the handler for `usage` events * @return the discovery registration */ protected DiscoveryRegistration startListening(
ServiceDiscoveryOptions options, SchemaAnnounceHandler announceHandler, SchemaUsageHandler usageHandler) {
3
startupheroes/startupheroes-checkstyle
startupheroes-checks/src/main/java/es/startuphero/checkstyle/checks/annotation/MissingOverrideCheck.java
[ "public static final String OVERRIDE_ANNOTATION_NAME_BY_PACKAGE = \"java.lang.Override\";", "public static Boolean hasAnnotation(DetailAST ast, String fullAnnotation) {\n return CommonUtils.getSimpleAndFullNames(fullAnnotation).stream()\n .anyMatch(annotation -> AnnotationUtil.containsAnnotati...
import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.lang.reflect.Method; import java.util.Map; import java.util.Optional; import static es.startuphero.checkstyle.util.AnnotationUtils.OVERRIDE_ANNOTATION_NAME_BY_PACKAGE; import static es.startuphero.checkstyle.util.AnnotationUtils.hasAnnotation; import static es.startuphero.checkstyle.util.ClassUtils.getClassName; import static es.startuphero.checkstyle.util.ClassUtils.getClassOf; import static es.startuphero.checkstyle.util.ClassUtils.getImportSimpleFullNameMap; import static es.startuphero.checkstyle.util.CommonUtils.getPackageName; import static es.startuphero.checkstyle.util.MethodUtils.getMethodName; import static es.startuphero.checkstyle.util.MethodUtils.getParameterTypes; import static es.startuphero.checkstyle.util.MethodUtils.isMethodOverriden;
package es.startuphero.checkstyle.checks.annotation; /** * @author ozlem.ulag */ public class MissingOverrideCheck extends AbstractCheck { /** * A key is pointing to the warning message text in "messages.properties" file. */ private static final String MSG_KEY = "missing.override"; private String packageName; private Map<String, String> importSimpleFullNameMap; @Override public int[] getDefaultTokens() { return getAcceptableTokens(); } @Override public int[] getAcceptableTokens() { return new int[] {TokenTypes.METHOD_DEF}; } @Override public int[] getRequiredTokens() { return getAcceptableTokens(); } @Override public void beginTree(DetailAST rootAst) { packageName = getPackageName(rootAst); importSimpleFullNameMap = getImportSimpleFullNameMap(rootAst); } @Override public void visitToken(DetailAST ast) { try { Optional<DetailAST> classNode = getClassOf(ast); if (classNode.isPresent()) { String className = getClassName(classNode.get()); String methodName = getMethodName(ast); Class<?> classOfMethod = Class.forName(packageName + "." + className); Method method = classOfMethod.getDeclaredMethod(methodName, getParameterTypes(ast, importSimpleFullNameMap));
if (isMethodOverriden(method) && !hasAnnotation(ast, OVERRIDE_ANNOTATION_NAME_BY_PACKAGE)) {
0
cerner/beadledom
health/service/src/main/java/com/cerner/beadledom/health/HealthModule.java
[ "@Api(value = \"/health\",\n description = \"Health and dependency checks\")\n@io.swagger.annotations.Api(value = \"/health\",\n description = \"Health and dependency checks\")\n@Path(\"meta/availability\")\npublic interface AvailabilityResource {\n @GET\n @Produces(MediaType.TEXT_HTML)\n StreamingOutput g...
import com.cerner.beadledom.health.api.AvailabilityResource; import com.cerner.beadledom.health.api.DependenciesResource; import com.cerner.beadledom.health.api.DiagnosticResource; import com.cerner.beadledom.health.api.HealthResource; import com.cerner.beadledom.health.api.VersionResource; import com.cerner.beadledom.health.internal.HealthChecker; import com.cerner.beadledom.health.internal.HealthTemplateFactory; import com.cerner.beadledom.health.resource.AvailabilityResourceImpl; import com.cerner.beadledom.health.resource.DependenciesResourceImpl; import com.cerner.beadledom.health.resource.DiagnosticResourceImpl; import com.cerner.beadledom.health.resource.HealthResourceImpl; import com.cerner.beadledom.health.resource.VersionResourceImpl; import com.cerner.beadledom.metadata.ServiceMetadata; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.MustacheFactory; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.multibindings.Multibinder; import com.google.inject.multibindings.MultibindingsScanner; import java.util.Map; import java.util.Set; import javax.inject.Singleton; import javax.ws.rs.core.UriInfo;
package com.cerner.beadledom.health; /** * A Guice module that provides JAX-RS resources to implement the Health Check. * * <p>With the module installed, you can add new 'dependencies' to your service's health check by * adding bindings of {@link com.cerner.beadledom.health.HealthDependency} using the Multibinder. * * <p>Example: * * <p><pre><code> * class MyModule extends AbstractModule { * {@literal @}Override * protected void configure() { * Multibinder&lt;HealthDependency&gt; healthDependencyBinder = Multibinder * .newSetBinder(binder(), HealthDependency.class); * healthDependencyBinder.addBinding().to(FoobarHealthDependency.class); * } * } * * class FoobarHealthDependency extends HealthDependency { * {@literal @}Override * public HealthStatus checkAvailability() { * if (...) { // check health somehow * return HealthStatus.create(200, "foobar is available"); * } else { * return HealthStatus.create(503, "foobar is gone. just gone."); * } * } * * {@literal @}Override * public String getName() { * return "foobar"; * } * } * </code></pre> * * <p>Provides: * <ul> * <li>{@link AvailabilityResource}</li> * <li>{@link HealthResource}</li> * <li>{@link VersionResource}</li> * <li>{@link DiagnosticResource}</li> * <li>{@link DependenciesResource}</li> * <li>The following {@link com.fasterxml.jackson.databind.Module Jackson module} multibindings: * <ul> * <li>{@link com.fasterxml.jackson.datatype.jdk8.Jdk8Module}</li> * <li>{@link com.fasterxml.jackson.datatype.jsr310.JavaTimeModule}</li> * </ul> * </li> * <li>{@link com.cerner.beadledom.health.internal.HealthChecker} (for internal use only)</li> * <li>{@link Map}&lt;{@link String}, {@link com.cerner.beadledom.health.HealthDependency}&gt; * (for internal use only)</li> * <li>{@link com.github.mustachejava.MustacheFactory} with binding annotation * HealthTemplateFactory (for internal use only)</li> * </ul> * * <p>Requires: * <ul> * <li>{@link com.cerner.beadledom.metadata.ServiceMetadata}</li> * <li>{@link javax.ws.rs.core.UriInfo} (request-scoped)</li> * </ul> * * <p>Installs: * <ul> * <li> {@link MultibindingsScanner} </li> * </ul> */ public class HealthModule extends AbstractModule { @Override protected void configure() { requireBinding(ServiceMetadata.class); requireBinding(UriInfo.class); bind(AvailabilityResource.class).to(AvailabilityResourceImpl.class); bind(HealthResource.class).to(HealthResourceImpl.class); bind(DependenciesResource.class).to(DependenciesResourceImpl.class); bind(DiagnosticResource.class).to(DiagnosticResourceImpl.class);
bind(VersionResource.class).to(VersionResourceImpl.class);
4
Expugn/S-argo
src/main/java/io/github/spugn/Sargo/Functions/BannerInfo.java
[ "public class CommandManager\n{\n private final CommandLine COMMAND_LINE;\n private final Message MESSAGE;\n private final String userDiscordID;\n\n public CommandManager(Message message)\n {\n this.MESSAGE = message;\n\n if (message.getAuthor().isPresent())\n {\n user...
import discord4j.core.object.entity.Message; import discord4j.core.object.entity.TextChannel; import io.github.spugn.Sargo.Managers.CommandManager; import io.github.spugn.Sargo.Objects.*; import io.github.spugn.Sargo.Objects.Character; import io.github.spugn.Sargo.Sargo; import io.github.spugn.Sargo.Utilities.GitHubImage; import io.github.spugn.Sargo.XMLParsers.BannerParser; import io.github.spugn.Sargo.XMLParsers.ScoutSettingsParser; import java.text.DecimalFormat; import java.util.*;
package io.github.spugn.Sargo.Functions; /** * BANNER INFO * <p> * Manages the information in the Embed Messages when * listing available banners or information about a * specific banner. * </p> * * @author S'pugn * @version 2.0 * @since v1.0 * @see BannerListMenu * @see BannerInfoMenu */ public class BannerInfo { //private static IChannel CHANNEL; private TextChannel TEXT_CHANNEL; private static List<Banner> BANNERS; private double copper; private double silver; private double gold; private double platinum; private double platinum6; private List<Double> recordCrystal; private List<Double> circulatingRecordCrystal; private int bannerID; private int page; public BannerInfo(Message message, String page) { TEXT_CHANNEL = (TextChannel) message.getChannel().block(); /* READ Banners.xml */ BANNERS = BannerParser.getBanners(); this.page = Integer.parseInt(page); if (this.page < 1) { this.page = 1; } listBanners(); } public BannerInfo(Message message, int bannerID) { TEXT_CHANNEL = (TextChannel) message.getChannel().block(); this.bannerID = bannerID - 1; /* READ Banners.xml */ BANNERS = BannerParser.getBanners(); copper = (int) (ScoutSettingsParser.getCopperRate() * 100); silver = (int) (ScoutSettingsParser.getSilverRate() * 100); gold = (int) (ScoutSettingsParser.getGoldRate() * 100); platinum = (int) (ScoutSettingsParser.getPlatinumRate() * 100); platinum6 = (int) (ScoutSettingsParser.getPlatinum6Rate() * 100); recordCrystal = ScoutSettingsParser.getRecordCrystalRates(); circulatingRecordCrystal = ScoutSettingsParser.getCirculatingRecordCrystalRates(); getBannerInfo(); } private void listBanners() { BannerListMenu menu = new BannerListMenu(); menu.setBannerCount(BANNERS.size()); int pageLength = 10; SortedMap<Integer, String> bannerList = new TreeMap<>(); for (Banner b : BANNERS) { bannerList.put(b.getBannerID(), b.getBannerName()); } String message = ""; if (page > (((bannerList.size() % pageLength) == 0) ? bannerList.size() / pageLength : (bannerList.size() / pageLength) + 1)) page = (((bannerList.size() % pageLength) == 0) ? bannerList.size() / pageLength : (bannerList.size() / pageLength) + 1); menu.setCurrentPage(page); menu.setHighestPage(((bannerList.size() % pageLength) == 0) ? bannerList.size() / pageLength : (bannerList.size() / pageLength) + 1); menu.setBannerCount(bannerList.size()); int i = 0, k = 0; page--; for(final Map.Entry<Integer, String> e : bannerList.entrySet()) { k++; if ((((page * pageLength) + i + 1) == k) && (k != (( page * pageLength) + pageLength + 1))) { i++; message += "**" + e.getKey() + "**) *" + e.getValue() + "*\n"; } } menu.setBannerList(message); Sargo.sendEmbed(TEXT_CHANNEL, menu.get()); } private void getBannerInfo() { if (bannerID < BANNERS.size() && bannerID >= 0) { Banner banner = BANNERS.get(bannerID); BannerInfoMenu menu = new BannerInfoMenu(); Random rng = new Random(); int charIndex = rng.nextInt(banner.getCharacters().size()); menu.setBannerType(banner.bannerTypeToString()); menu.setBannerWepType(banner.getBannerWepType()); menu.setBannerName(banner.getBannerName()); menu.setCharacterAmount(banner.getCharacters().size()); menu.setBannerID(bannerID); menu.setImageURL(new GitHubImage(banner.getCharacters().get(charIndex).getImagePath()).getURL()); /* CREATE CHARACTER LIST */ String charList = ""; for (Character c : banner.getCharacters()) { charList += "\n" + c.toString(); } menu.setCharacterList(charList); /* IF THERE ARE WEAPONS, CREATE WEAPON LIST */ if (banner.getWeapons().size() > 0) { String weapList = ""; for (Weapon w : banner.getWeapons()) { weapList += "\n" + w.toString(); } menu.setWeaponAmount(banner.getWeapons().size()); menu.setWeaponList(weapList); } /* CREATE RATE LIST */ List<Character> goldCharacters = new ArrayList<>(); List<Character> platinumCharacters = new ArrayList<>(); List<Character> platinum6Characters = new ArrayList<>(); /* SORT GOLD/PLATINUM/PLATINUM6 CHARACTERS AND STORE THEM IN THEIR OWN ARRAYS */ for (Character character : banner.getCharacters()) { if (character.getRarity() == 4) { goldCharacters.add(character); } else if (character.getRarity() == 5) { platinumCharacters.add(character); } else if (character.getRarity() == 6) { platinum6Characters.add(character); } } /* NO PLATINUM/PLATINUM6 CHARACTER, ADJUST RATES */ if (platinumCharacters.size() <= 0 && platinum6Characters.size() <= 0) { copper += platinum; platinum = 0; copper += platinum6; platinum6 = 0; } /* PLATINUM CHARACTERS EXIST BUT NOT PLATINUM6, ADJUST RATES */ else if (platinumCharacters.size() > 0 && platinum6Characters.size() <= 0) { copper += platinum6; platinum6 = 0; } /* IF EVENT SCOUT, SET EVERYTHING BUT GOLD TO 0 */ if (banner.getBannerType() == 9) { copper = 0.0; silver = 0.0; if (goldCharacters.size() > 0) { gold = 100.0; } else { gold = 0.0; } if (platinumCharacters.size() > 0) { platinum = 100.0; } else { platinum = 0.0; } if (platinum6Characters.size() > 0) { platinum6 = 100.0; } else { platinum6 = 0.0; } } // IF OLDER THAN RECORD CRYSTAL V4 (EXCEPT EVENT), DECREASE PLATINUM RATES BY 1.5 if (banner.getBannerType() == 10 || banner.getBannerType() == 8 || banner.getBannerType() == 7 || banner.getBannerType() == 6 || banner.getBannerType() == 5 || banner.getBannerType() == 4 || banner.getBannerType() == 3 || banner.getBannerType() == 2 || banner.getBannerType() == 1 || banner.getBannerType() == 0) { copper = copper + (platinum - (platinum / 1.5)); platinum = platinum / 1.5; } String ratesList = ""; if (platinum6 != 0) ratesList += "[6 ★] " + platinum6 + "%\n"; if (platinum != 0) ratesList += "[5 ★] " + platinum + "%\n"; ratesList += "[4 ★] " + gold + "%\n"; ratesList += "[3 ★] " + silver + "%\n"; ratesList += "[2 ★] " + copper + "%"; menu.setRatesList(ratesList); /* BANNER IS STEP UP */ if (banner.getBannerType() == 1) { double tC = copper - ((gold * 1.5) - gold); double tS = silver; double tG = gold * 1.5; double tP = platinum; double tP6 = platinum6; String stepThreeRates = ""; if (tP6 != 0) stepThreeRates += "[6 ★] " + tP6 + "%\n"; if (tP != 0) stepThreeRates += "[5 ★] " + tP + "%\n"; stepThreeRates += "[4 ★] " + tG + "%\n"; stepThreeRates += "[3 ★] " + tS + "%\n"; stepThreeRates += "[2 ★] " + tC + "%\n"; stepThreeRates += "**(4 ★ Scout Rates 1.5x)**"; menu.setStepThreeRatesList(stepThreeRates); tC = copper - ((gold * 2.0) - gold); tS = silver; tG = gold * 2.0; tP = platinum; tP6 = platinum6; String stepFiveRates = ""; if (tP6 != 0) stepFiveRates += "[6 ★] " + tP6 + "%\n"; if (tP != 0) stepFiveRates += "[5 ★] " + tP + "%\n"; stepFiveRates += "[4 ★] " + tG + "%\n"; stepFiveRates += "[3 ★] " + tS + "%\n"; stepFiveRates += "[2 ★] " + tC + "%\n"; stepFiveRates += "**(4 ★ Scout Rates 2.0x)**"; menu.setStepFiveRatesList(stepFiveRates); } /* BANNER IS STEP UP V2 */ else if (banner.getBannerType() == 3 || banner.getBannerType() == 10 || banner.getBannerType() == 12 || banner.getBannerType() == 13 || banner.getBannerType() == 14 || banner.getBannerType() == 16) { double tC = copper - ((platinum * 1.5) - platinum); double tS = silver; double tG = gold; double tP = platinum * 1.5; double tP6 = platinum6; if (banner.getBannerType() == 16) { String stepOneRates = ""; if (tP6 != 0) stepOneRates += "[6 ★] 0.0%\n"; stepOneRates += "[5 ★] 3.0%\n"; stepOneRates += "[4 ★] 97.0%\n"; stepOneRates += "[3 ★] 0.0%\n"; stepOneRates += "[2 ★] 0.0%\n"; stepOneRates += "**(For One Character)**"; menu.setStepOneRatesList(stepOneRates); } String stepThreeRates = ""; if (tP6 != 0) stepThreeRates += "[6 ★] " + tP6 + "%\n"; if (tP != 0) stepThreeRates += "[5 ★] " + tP + "%\n"; stepThreeRates += "[4 ★] " + tG + "%\n"; stepThreeRates += "[3 ★] " + tS + "%\n"; stepThreeRates += "[2 ★] " + tC + "%\n"; stepThreeRates += "**(5 ★ Scout Rates 1.5x)**"; menu.setStepThreeRatesList(stepThreeRates); tC = 0.0; tS = 0.0; tG = 0.0; tP = 100.0; tP6 = 0.0; String stepFiveRates = ""; if (tP6 != 0) stepFiveRates += "[6 ★] " + tP6 + "%\n"; stepFiveRates += "[5 ★] " + tP + "%\n"; stepFiveRates += "[4 ★] " + tG + "%\n"; stepFiveRates += "[3 ★] " + tS + "%\n"; stepFiveRates += "[2 ★] " + tC + "%\n"; stepFiveRates += "**(For One Character)**"; menu.setStepFiveRatesList(stepFiveRates); tC = copper - ((platinum * 2.0) - platinum); tS = silver; tG = gold; tP = platinum * 2.0; tP6 = platinum6; String stepSixRates = ""; if (tP6 != 0) stepSixRates += "[6 ★] " + tP6 + "%\n"; if (tP != 0) stepSixRates += "[5 ★] " + tP + "%\n"; stepSixRates += "[4 ★] " + tG + "%\n"; stepSixRates += "[3 ★] " + tS + "%\n"; stepSixRates += "[2 ★] " + tC + "%\n"; stepSixRates += "**(5 ★ Scout Rates 2.0x)**"; menu.setStepSixRatesList(stepSixRates); } /* BANNER IS STEP UP V7/V8/V9 */ else if (banner.getBannerType() == 17 || banner.getBannerType() == 19 || banner.getBannerType() == 21) { double tC = copper - ((platinum6 * 1.5) - platinum6); double tS = silver; double tG = gold; double tP = platinum; double tP6 = platinum6 * 1.5; String stepThreeRates = ""; if (tP6 != 0) stepThreeRates += "[6 ★] " + tP6 + "%\n"; stepThreeRates += "[5 ★] " + tP + "%\n"; stepThreeRates += "[4 ★] " + tG + "%\n"; stepThreeRates += "[3 ★] " + tS + "%\n"; stepThreeRates += "[2 ★] " + tC + "%\n"; stepThreeRates += "**(6 ★ Scout Rates 1.5x)**"; menu.setStepThreeRatesList(stepThreeRates); tC = 0.0; tS = 0.0; tG = 0.0; tP = 0.0; tP6 = 100.0; String stepFiveRates = ""; stepFiveRates += "[6 ★] " + tP6 + "%\n"; stepFiveRates += "[5 ★] " + tP + "%\n"; stepFiveRates += "[4 ★] " + tG + "%\n"; stepFiveRates += "[3 ★] " + tS + "%\n"; stepFiveRates += "[2 ★] " + tC + "%\n"; if (banner.getBannerType() == 21) { stepFiveRates += "**(" + banner.getCharacters().get(0) + " Guaranteed)**"; } else { stepFiveRates += "**(For One Character)**"; } menu.setStepFiveRatesList(stepFiveRates); tC = copper - ((platinum6 * 2.0) - platinum6); tS = silver; tG = gold; tP = platinum; tP6 = platinum6 * 2.0; String stepSixRates = ""; if (tP6 != 0) stepSixRates += "[6 ★] " + tP6 + "%\n"; stepSixRates += "[5 ★] " + tP + "%\n"; stepSixRates += "[4 ★] " + tG + "%\n"; stepSixRates += "[3 ★] " + tS + "%\n"; stepSixRates += "[2 ★] " + tC + "%\n"; stepSixRates += "**(6 ★ Scout Rates 2.0x)**"; menu.setStepSixRatesList(stepSixRates); } /* BANNER IS BIRTHDAY STEP UP */ else if (banner.getBannerType() == 4) { double tC = copper - (((platinum * 2.0) - platinum) + ((gold * 2.0) - gold)); double tS = silver; double tG = gold * 2.0; double tP = platinum * 2.0; double tP6 = platinum6; String stepThreeRates = ""; if (tP6 != 0) stepThreeRates += "[6 ★] " + tP6 + "%\n"; if (tP != 0) stepThreeRates += "[5 ★] " + tP + "%\n"; stepThreeRates += "[4 ★] " + tG + "%\n"; stepThreeRates += "[3 ★] " + tS + "%\n"; stepThreeRates += "[2 ★] " + tC + "%\n"; stepThreeRates += "**(4+ ★ Scout Rates 2.0x)**"; menu.setStepThreeRatesList(stepThreeRates); } /* BANNER IS RECORD CRYSTAL */ else if (banner.getBannerType() == 2 || banner.getBannerType() == 5 || banner.getBannerType() == 8 || banner.getBannerType() == 11 || banner.getBannerType() == 18 || banner.getBannerType() == 20) { int counter = 0; String recordCrystalRates = ""; DecimalFormat df = new DecimalFormat("0.0"); for (double d : recordCrystal) { if (d != 0) { recordCrystalRates += "[" + ++counter + " RC] " + df.format((d * 100)) + "%\n"; } } menu.setRecordCrystalRatesList(recordCrystalRates); if (banner.getBannerType() == 8 || banner.getBannerType() == 11 || banner.getBannerType() == 20) { int counter2 = 0; String circluatingRecordCrystalRates = ""; if (banner.getBannerType() == 8 || banner.getBannerType() == 11 || banner.getBannerType() == 20) { for (double d : circulatingRecordCrystal) { if (d != 0) { circluatingRecordCrystalRates += "[" + ++counter2 + " RC] " + df.format((d * 100)) + "%\n"; } } } else { for (double d : recordCrystal) { if (d != 0) { circluatingRecordCrystalRates += "[" + ++counter2 + " RC] " + df.format((d * 100)) + "%\n"; } } } menu.setCirculatingRecordCrystalRatesList(circluatingRecordCrystalRates); } } /* BANNER IS STEP UP V3 */ else if (banner.getBannerType() == 7 || banner.getBannerType() == 15) { double tC = copper - ((platinum * 2.0) - platinum); double tS = silver; double tG = gold; double tP = platinum * 2.0; double tP6 = platinum6; String stepThreeRates = ""; if (tP6 != 0) stepThreeRates += "[6 ★] " + tP6 + "%\n"; if (tP != 0) stepThreeRates += "[5 ★] " + tP + "%\n"; stepThreeRates += "[4 ★] " + tG + "%\n"; stepThreeRates += "[3 ★] " + tS + "%\n"; stepThreeRates += "[2 ★] " + tC + "%\n"; stepThreeRates += "**(5 ★ Scout Rates 2.0x)**"; menu.setStepThreeRatesList(stepThreeRates); } /* WEAPON BANNER IS STEP UP */ if (banner.getBannerWepType() == 1) { double tC = (copper + platinum) - ((gold * 2.0) - gold); double tS = silver; double tG = gold * 2.0; String stepThreeRates = ""; stepThreeRates += "[4 ★] " + tG + "%\n"; stepThreeRates += "[3 ★] " + tS + "%\n"; stepThreeRates += "[2 ★] " + tC + "%\n"; stepThreeRates += "**(4 ★ Weapon Rates 2.0x)**"; menu.setStepThreeWeaponRatesList(stepThreeRates); } /* WEAPON BANNER IS GGO STEP UP OR STEP UP V2 OR STEP UP V3 */ else if (banner.getBannerWepType() == 2 || banner.getBannerWepType() == 3 || banner.getBannerWepType() == 4) { double tC = (copper + platinum) - ((gold * 1.5) - gold); double tS = silver; double tG = gold * 1.5; String stepThreeRates = ""; stepThreeRates += "[4 ★] " + tG + "%\n"; stepThreeRates += "[3 ★] " + tS + "%\n"; stepThreeRates += "[2 ★] " + tC + "%\n"; stepThreeRates += "**(4 ★ Weapon Rates 1.5x)**"; menu.setStepThreeWeaponRatesList(stepThreeRates); tC = 0.0; tS = 0.0; tG = 100.0; String stepFiveRates = ""; stepFiveRates += "[4 ★] " + tG + "%\n"; stepFiveRates += "[3 ★] " + tS + "%\n"; stepFiveRates += "[2 ★] " + tC + "%\n"; if (banner.getBannerWepType() == 4) { stepFiveRates += "**(" + banner.getWeapons().get(0) + " Guaranteed)**"; } else { stepFiveRates += "**(For One Weapon)**"; } menu.setStepFiveWeaponRatesList(stepFiveRates); tC = (copper + platinum) - ((gold * 2.0) - gold); tS = silver; tG = gold * 2.0; String stepSixRates = ""; stepSixRates += "[4 ★] " + tG + "%\n"; stepSixRates += "[3 ★] " + tS + "%\n"; stepSixRates += "[2 ★] " + tC + "%\n"; stepSixRates += "**(4 ★ Weapon Rates 2.0x)**"; menu.setStepSixWeaponRatesList(stepSixRates); } Sargo.sendEmbed(TEXT_CHANNEL, menu.get()); } else {
Sargo.replyToMessage_Warning(TEXT_CHANNEL, "UNKNOWN BANNER ID", "Use '" + CommandManager.getCommandPrefix() + "**scout**' for a list of banners.");
0
takeshineshiro/android_convex_128
wireless_scan_B_mode/app/src/main/java/com/medical/lepu/wireless_scan_b_mode/ui/MainActivity.java
[ "public class AppManager {\n\n private static Stack<Activity> activityStack ;\n\n private static AppManager appManager ;\n\n private AppManager () {\n\n\n }\n\n\n public static AppManager getIntance () {\n\n appManager = new AppManager() ;\n\n...
import android.app.FragmentManager; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.medical.lepu.wireless_scan_b_mode.AppManager; import com.medical.lepu.wireless_scan_b_mode.R; import com.medical.lepu.wireless_scan_b_mode.adapter.LeftDrawerAdapter; import com.medical.lepu.wireless_scan_b_mode.base.BaseFragment; import com.medical.lepu.wireless_scan_b_mode.fragment.UtrasoundImageFrag; import com.medical.lepu.wireless_scan_b_mode.fragment.UtrasoundPersonInfo; import com.medical.lepu.wireless_scan_b_mode.fragment.UtrasoundSettingParam; import com.medical.lepu.wireless_scan_b_mode.fragment.UtrasoundVideoFrag;
package com.medical.lepu.wireless_scan_b_mode.ui; public class MainActivity extends AppCompatActivity { private DrawerLayout drawerLayout ; private Toolbar toolbar ; private ListView leftListView ; private ActionBarDrawerToggle actionBarDrawerToggle ; private CharSequence drawerTitle ; private CharSequence title ; private String[] drawer_array ; private BaseFragment contentFragment ; public static final String ITEM_POSITION = "item_position" ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); //set the default fragment for the activity content view created if (savedInstanceState==null) { selectedItem(0); } AppManager.getIntance().addActivity(this); } public void initView() { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout) ; toolbar = (Toolbar) findViewById(R.id.toolbar) ; leftListView = (ListView) findViewById(R.id.left_drawer) ; setSupportActionBar(toolbar); // set a custom shadow that overlays the main content when the drawer opens drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon actionBarDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ drawerLayout, /* DrawerLayout object */ null, /* nav drawer image to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerOpened(View drawerView) { toolbar.setTitle(drawerTitle); // getActionBar().setTitle(drawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerClosed(View view) { toolbar.setTitle(title); // getActionBar().setTitle(title); // getSupportActionBar().setTitle(title); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; drawerLayout.setDrawerListener(actionBarDrawerToggle); // enable ActionBar app icon to behave as action to toggle nav drawer // getActionBar().setHomeButtonEnabled(true); // getActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用 getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_top)); // set up the drawer's list view with items and click listener leftListView.setAdapter(new LeftDrawerAdapter(this)); leftListView.setOnItemClickListener(new DrawerItemClickListener()); } public void initData() { drawer_array = getResources().getStringArray(R.array.drawer_submodules); drawerTitle = title = getTitle(); } //listenser private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectedItem(position); } } private void selectedItem (int position) { switch (position) { case 0: contentFragment = new UtrasoundImageFrag() ; break; case 1:
contentFragment = new UtrasoundVideoFrag() ;
6
b3dgs/warcraft-remake
warcraft-game/src/main/java/com/b3dgs/warcraft/World.java
[ "public final class Constant\r\n{\r\n /** Application name. */\r\n public static final String PROGRAM_NAME = \"Warcraft Remake\";\r\n /** Application version. */\r\n public static final Version PROGRAM_VERSION = Version.create(0, 0, 7);\r\n /** Native resolution. */\r\n public static final Resolut...
import java.io.IOException; import com.b3dgs.lionengine.Align; import com.b3dgs.lionengine.LionEngineException; import com.b3dgs.lionengine.Medias; import com.b3dgs.lionengine.Tick; import com.b3dgs.lionengine.audio.Audio; import com.b3dgs.lionengine.audio.AudioFactory; import com.b3dgs.lionengine.game.Cursor; import com.b3dgs.lionengine.game.feature.Featurable; import com.b3dgs.lionengine.game.feature.LayerableModel; import com.b3dgs.lionengine.game.feature.Services; import com.b3dgs.lionengine.game.feature.Transformable; import com.b3dgs.lionengine.game.feature.collidable.selector.Hud; import com.b3dgs.lionengine.game.feature.collidable.selector.Selector; import com.b3dgs.lionengine.game.feature.producible.Producer; import com.b3dgs.lionengine.game.feature.producible.ProducerListenerVoid; import com.b3dgs.lionengine.game.feature.tile.map.extractable.Extractor; import com.b3dgs.lionengine.game.feature.tile.map.pathfinding.Pathfindable; import com.b3dgs.lionengine.game.feature.tile.map.persister.MapTilePersister; import com.b3dgs.lionengine.geom.Area; import com.b3dgs.lionengine.geom.Geom; import com.b3dgs.lionengine.graphic.Graphic; import com.b3dgs.lionengine.graphic.drawable.Drawable; import com.b3dgs.lionengine.graphic.drawable.Image; import com.b3dgs.lionengine.graphic.drawable.SpriteFont; import com.b3dgs.lionengine.helper.DeviceControllerConfig; import com.b3dgs.lionengine.helper.WorldHelper; import com.b3dgs.lionengine.io.DeviceController; import com.b3dgs.lionengine.io.DevicePointer; import com.b3dgs.lionengine.io.FileReading; import com.b3dgs.warcraft.constant.Constant; import com.b3dgs.warcraft.constant.Folder; import com.b3dgs.warcraft.constant.Gfx; import com.b3dgs.warcraft.object.feature.AutoAttack; import com.b3dgs.warcraft.object.feature.Warehouse; import com.b3dgs.warcraft.world.WorldMinimap; import com.b3dgs.warcraft.world.WorldNavigator; import com.b3dgs.warcraft.world.WorldSelection;
/* * Copyright (C) 2013-2022 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre (contact@b3dgs.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.b3dgs.warcraft; /** * World game representation. */ public class World extends WorldHelper { private static final int VIEW_X = 72; private static final int VIEW_Y = 12; private static final int TEXT_X = 74; private static final int TEXT_Y = 209; private static final int RESOURCES_WOOD_X = 180; private static final int RESOURCES_GOLD_X = 290; private static final int RESOURCES_Y = 2; private static final Area AREA = Geom.createArea(VIEW_X, VIEW_Y, 304, 192); private static final int DELAY_ATTACK = 6000; private final Player player = services.add(new Player(Race.ORC)); private final WorldMinimap minimap = new WorldMinimap(services); private final Cursor cursor = services.create(Cursor.class); private final Image wood = Util.getImage(Gfx.HUD_WOOD, RESOURCES_WOOD_X + 10, RESOURCES_Y - 2); private final Image gold = Util.getImage(Gfx.HUD_GOLD, RESOURCES_GOLD_X + 10, RESOURCES_Y - 1); private final SpriteFont text; private final WorldNavigator navigator; private final WorldSelection selection; private final DeviceController device = services.add(DeviceControllerConfig.create(services, Medias.create("input.xml"))); private final DeviceController deviceCursor = DeviceControllerConfig.create(services, Medias.create("input_cursor.xml")); private final Tick tick = new Tick(); private Audio music; /** * Create the world. * * @param services The services reference. */ public World(Services services) { super(services); services.add(new ProduceProgress()); camera.setView(VIEW_X, VIEW_Y, AREA.getWidth(), AREA.getHeight(), AREA.getHeight()); text = services.add(Drawable.loadSpriteFont(Gfx.GAME_FONT.getSurface(), Medias.create("font.xml"), 6, 6)); text.setLocation(TEXT_X, TEXT_Y); final Hud hud = services.add(factory.create(Medias.create("hud.xml"))); handler.add(hud); final Selector selector = services.get(Selector.class); selector.addFeatureAndGet(new LayerableModel(Constant.LAYER_SELECTION, Constant.LAYER_SELECTION_RENDER)); selector.setClickableArea(AREA); selector.setSelectionColor(Constant.COLOR_SELECTION); selector.setClickSelection(DeviceMapping.ACTION_LEFT.getIndex()); navigator = new WorldNavigator(services); selection = new WorldSelection(services); } @Override protected void loading(FileReading file) throws IOException { map.loadSheets(Medias.create(Folder.MAPS, WorldType.FOREST.getFolder(), "sheets.xml")); map.getFeature(MapTilePersister.class).load(file); minimap.load(); selection.reset(); cursor.addImage(Constant.CURSOR_ID, Medias.create("cursor.png")); cursor.addImage(Constant.CURSOR_ID_ORDER, Medias.create("cursor_order.png")); cursor.addImage(Constant.CURSOR_ID_OVER, Medias.create("cursor_over.png")); cursor.load(); cursor.setGrid(map.getTileWidth(), map.getTileHeight()); cursor.setInputDevice(deviceCursor); cursor.setSync((DevicePointer) getInputDevice(DeviceControllerConfig.imports(services, Medias.create("input_cursor.xml")) .iterator() .next() .getDevice())); cursor.setViewer(camera); createAi(Race.HUMAN, 8, 56); createPlayer(Race.ORC, 46, 14); spawn(Race.ORC, Unit.SPEARMAN, 50, 20); music = AudioFactory.loadAudio(Music.ORC_CAMPAIGN2.get()); music.setVolume(Constant.VOLUME_DEFAULT); music.play(); } /** * Create player base. * * @param race The race reference. * @param tx The horizontal tile base. * @param ty The vertical tile base. */ private void createPlayer(Race race, int tx, int ty) { spawn(Race.NEUTRAL, Unit.GOLDMINE, tx - 6, ty - 8); spawn(race, Unit.WORKER, tx, ty - 2); final Transformable townhall = spawn(race, Unit.TOWNHALL, tx, ty); camera.center(townhall); camera.round(map); player.increaseFood(1); player.consumeFood(); } /** * Create AI base. * * @param race The race reference. * @param tx The horizontal tile base. * @param ty The vertical tile base. */ private void createAi(Race race, int tx, int ty) { final Pathfindable goldmine = spawn(Race.NEUTRAL, Unit.GOLDMINE, tx - 6, ty - 8).getFeature(Pathfindable.class); spawn(race, Unit.TOWNHALL, tx, ty); final Extractor extractorWood = spawn(race, Unit.WORKER, tx, ty - 2).getFeature(Extractor.class); extractorWood.setResource(Constant.RESOURCE_WOOD, tx - 2, ty + 5, 1, 1); extractorWood.startExtraction(); final Extractor extractorGold = spawn(race, Unit.WORKER, tx, ty - 2).getFeature(Extractor.class); extractorGold.setResource(Constant.RESOURCE_GOLD, goldmine); extractorGold.startExtraction(); spawn(race, Unit.FARM, tx - 4, ty - 1); spawn(race, Unit.FARM, tx - 6, ty - 1); spawn(race, Unit.LUMBERMILL, tx + 6, ty - 4); final Producer barracks = spawn(race, Unit.BARRACKS, tx + 6, ty + 1).getFeature(Producer.class); barracks.addListener(new ProducerListenerVoid() { @Override public void notifyProduced(Featurable featurable) { featurable.getFeature(AutoAttack.class).setForce(true);
final Warehouse warehouse = Util.getWarehouse(services, player.getRace());
4
kevalpatel2106/smart-lens
app/src/main/java/com/kevalpatel2106/smartlens/camera/CameraConfig.java
[ "public final class CameraFacing {\n\n /**\n * Rear facing camera id.\n *\n * @see android.hardware.Camera.CameraInfo#CAMERA_FACING_BACK\n */\n public static final int REAR_FACING_CAMERA = 0;\n /**\n * Front facing camera id.\n *\n * @see android.hardware.Camera.CameraInfo#CAMER...
import android.content.Context; import android.support.annotation.NonNull; import com.kevalpatel2106.smartlens.camera.config.CameraFacing; import com.kevalpatel2106.smartlens.camera.config.CameraImageFormat; import com.kevalpatel2106.smartlens.camera.config.CameraResolution; import com.kevalpatel2106.smartlens.camera.config.CameraRotation; import com.kevalpatel2106.smartlens.utils.FileUtils; import java.io.File;
/* * Copyright 2017 Keval Patel. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kevalpatel2106.smartlens.camera; /** * Created by Keval on 12-Nov-16. * This class will manage the camera configuration parameters. User the {@link Builder} class to * set different parameters for the camera. * * @author {@link 'https://github.com/kevalpatel2106'} */ @SuppressWarnings("WeakerAccess") public final class CameraConfig { private Context mContext; @CameraResolution.SupportedResolution private int mResolution = CameraResolution.MEDIUM_RESOLUTION; @CameraFacing.SupportedCameraFacing private int mFacing = CameraFacing.REAR_FACING_CAMERA; @CameraImageFormat.SupportedImageFormat private int mImageFormat = CameraImageFormat.FORMAT_JPEG; @CameraRotation.SupportedRotation private int mImageRotation = CameraRotation.ROTATION_0; private File mImageFile; /** * Public constructor. */ public CameraConfig() { //Do nothing } /** * @param context Instance. * @return {@link Builder} */ public Builder getBuilder(@NonNull Context context) { mContext = context; return new Builder(); } @CameraResolution.SupportedResolution public int getResolution() { return mResolution; } @CameraFacing.SupportedCameraFacing public int getFacing() { return mFacing; } @CameraImageFormat.SupportedImageFormat public int getImageFormat() { return mImageFormat; } public File getImageFile() { return mImageFile; } @CameraRotation.SupportedRotation public int getImageRotation() { return mImageRotation; } /** * This is the builder class for {@link CameraConfig}. */ @SuppressWarnings({"unused", "UnusedReturnValue", "WeakerAccess"}) public class Builder { /** * Set the resolution of the output camera image. If you don't specify any resolution, * default image resolution will set to {@link CameraResolution#MEDIUM_RESOLUTION}. * * @param resolution Any resolution from: * <li>{@link CameraResolution#HIGH_RESOLUTION}</li> * <li>{@link CameraResolution#MEDIUM_RESOLUTION}</li> * <li>{@link CameraResolution#LOW_RESOLUTION}</li> * @return {@link Builder} * @see CameraResolution */ public Builder setCameraResolution(@CameraResolution.SupportedResolution int resolution) { //Validate input if (resolution != CameraResolution.HIGH_RESOLUTION && resolution != CameraResolution.MEDIUM_RESOLUTION && resolution != CameraResolution.LOW_RESOLUTION) { throw new IllegalArgumentException("Invalid camera resolution."); } mResolution = resolution; return this; } /** * Set the camera facing with which you want to capture image. * Either rear facing camera or front facing camera. If you don't provide any camera facing, * default camera facing will be {@link CameraFacing#FRONT_FACING_CAMERA}. * * @param cameraFacing Any camera facing from: * <li>{@link CameraFacing#REAR_FACING_CAMERA}</li> * <li>{@link CameraFacing#FRONT_FACING_CAMERA}</li> * @return {@link Builder} * @see CameraFacing */ public Builder setCameraFacing(@CameraFacing.SupportedCameraFacing int cameraFacing) { //Validate input if (cameraFacing != CameraFacing.REAR_FACING_CAMERA && cameraFacing != CameraFacing.FRONT_FACING_CAMERA) { throw new IllegalArgumentException("Invalid camera facing value."); } //Check if the any camera available? if (!CameraUtils.isCameraAvailable(mContext)) { throw new IllegalStateException("Device camera is not available."); } //Check if the front camera available? if (cameraFacing == CameraFacing.FRONT_FACING_CAMERA && !CameraUtils.isFrontCameraAvailable(mContext)) { throw new IllegalStateException("Front camera is not available."); } mFacing = cameraFacing; return this; } /** * Specify the image format for the output image. If you don't specify any output format, * default output format will be {@link CameraImageFormat#FORMAT_JPEG}. * * @param imageFormat Any supported image format from: * <li>{@link CameraImageFormat#FORMAT_JPEG}</li> * <li>{@link CameraImageFormat#FORMAT_PNG}</li> * @return {@link Builder} * @see CameraImageFormat */ public Builder setImageFormat(@CameraImageFormat.SupportedImageFormat int imageFormat) { //Validate input if (imageFormat != CameraImageFormat.FORMAT_JPEG && imageFormat != CameraImageFormat.FORMAT_PNG) { throw new IllegalArgumentException("Invalid output image format."); } mImageFormat = imageFormat; return this; } /** * Specify the output image rotation. The output image will be rotated by amount of degree specified * before stored to the output file. By default there is no rotation applied. * * @param rotation Any supported rotation from: * <li>{@link CameraRotation#ROTATION_0}</li> * <li>{@link CameraRotation#ROTATION_90}</li> * <li>{@link CameraRotation#ROTATION_180}</li> * <li>{@link CameraRotation#ROTATION_270}</li> * @return {@link Builder} * @see CameraRotation */ public Builder setImageRotation(@CameraRotation.SupportedRotation int rotation) { //Validate input if (rotation != CameraRotation.ROTATION_0 && rotation != CameraRotation.ROTATION_90 && rotation != CameraRotation.ROTATION_180 && rotation != CameraRotation.ROTATION_270) { throw new IllegalArgumentException("Invalid image rotation."); } mImageRotation = rotation; return this; } /** * Set the location of the out put image. If you do not set any file for the output image, by * default image will be stored in the application's cache directory. * * @param imageFile {@link File} where you want to store the image. * @return {@link Builder} */ public Builder setImageFile(File imageFile) { mImageFile = imageFile; return this; } /** * Build the configuration. * * @return {@link CameraConfig} */ public CameraConfig build() { if (mImageFile == null) mImageFile = getDefaultStorageFile(); return CameraConfig.this; } /** * If no file is supplied to save the captured image, image will be saved by default to the * cache directory. * * @return File to save image bitmap. */ @NonNull private File getDefaultStorageFile() {
return new File(FileUtils.getCacheDir(mContext).getAbsolutePath()
4
rholder/fauxflake
fauxflake-core/src/main/java/com/github/rholder/fauxflake/IdGenerators.java
[ "public interface EncodingProvider {\n\n /**\n * Return a raw byte encoding of the given time and sequence number.\n *\n * @param time a time value to encode\n * @param sequence a sequence value to encode\n */\n public byte[] encodeAsBytes(long time, int sequence);\n\n /**\n *...
import com.github.rholder.fauxflake.api.EncodingProvider; import com.github.rholder.fauxflake.api.IdGenerator; import com.github.rholder.fauxflake.api.MachineIdProvider; import com.github.rholder.fauxflake.provider.boundary.FlakeEncodingProvider; import com.github.rholder.fauxflake.provider.MacMachineIdProvider; import com.github.rholder.fauxflake.provider.MacPidMachineIdProvider; import com.github.rholder.fauxflake.provider.SystemTimeProvider; import com.github.rholder.fauxflake.provider.twitter.SnowflakeEncodingProvider;
/* * Copyright 2012-2014 Ray Holder * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.rholder.fauxflake; /** * This class provides a collection of convenience methods for constructing * common {@link IdGenerator} implementations. */ public abstract class IdGenerators { /** * Create a Snowflake-based {@link IdGenerator} using the MAC address and * PID for hashing out a pseudo-unique machine id. * * @return the {@link IdGenerator} */ public static IdGenerator newSnowflakeIdGenerator() { MachineIdProvider machineIdProvider = new MacPidMachineIdProvider(); return newSnowflakeIdGenerator(machineIdProvider); } /** * Create a Snowflake-based {@link IdGenerator} using the given * {@link MachineIdProvider}. * * @return the {@link IdGenerator} */ public static IdGenerator newSnowflakeIdGenerator(MachineIdProvider machineIdProvider) { EncodingProvider encodingProvider = new SnowflakeEncodingProvider(machineIdProvider.getMachineId());
return new DefaultIdGenerator(new SystemTimeProvider(), encodingProvider);
6
taskadapter/redmine-java-api
src/main/java/com/taskadapter/redmineapi/AttachmentManager.java
[ "public class Attachment implements Identifiable, FluentStyle {\n\n private final PropertyStorage storage = new PropertyStorage();\n\n /**\n * database numeric Id\n */\n public final static Property<Integer> DATABASE_ID = new Property<>(Integer.class, \"id\");\n public final static Property<Stri...
import com.taskadapter.redmineapi.bean.Attachment; import com.taskadapter.redmineapi.bean.Issue; import com.taskadapter.redmineapi.internal.CopyBytesHandler; import com.taskadapter.redmineapi.internal.Transport; import com.taskadapter.redmineapi.internal.io.MarkedIOException; import com.taskadapter.redmineapi.internal.io.MarkedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
package com.taskadapter.redmineapi; /** * Works with Attachments (files). * <p>Obtain it via RedmineManager: * <pre> RedmineManager redmineManager = RedmineManagerFactory.createWithUserAuth(redmineURI, login, password); AttachmentManager attachmentManager = redmineManager.getAttachmentManager(); * </pre> * * <p>Sample usage: * <pre> File file = ... attachmentManager.addAttachmentToIssue(issueId, file, ContentType.TEXT_PLAIN.getMimeType()); * </pre> * * @see RedmineManager#getAttachmentManager() */ public class AttachmentManager { private final Transport transport; AttachmentManager(Transport transport) { this.transport = transport; } /** * * @param issueId database ID of the Issue * @param attachmentFile the file to upload * @param contentType MIME type. depending on this parameter, the file will be recognized by the server as * text or image or binary. see http://en.wikipedia.org/wiki/Internet_media_type for possible MIME types. * sample value: ContentType.TEXT_PLAIN.getMimeType() * @return the created attachment object. */
public Attachment addAttachmentToIssue(Integer issueId, File attachmentFile, String contentType) throws RedmineException, IOException {
0
unruly/control
src/test/java/co/unruly/control/pair/PairTest.java
[ "static <K, V> Pair<K, V> entry(K key, V value) {\n return Pair.of(key, value);\n}", "@SafeVarargs\nstatic <K, V> Map<K, V> mapOf(Pair<K, V> ...entries) {\n return Stream.of(entries).collect(toMap());\n}", "static <K, V> Collector<Pair<K, V>, ?, Map<K, V>> toMap() {\n return Collectors.toMap(Pair::left...
import org.hamcrest.CoreMatchers; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import static co.unruly.control.pair.Maps.entry; import static co.unruly.control.pair.Maps.mapOf; import static co.unruly.control.pair.Maps.toMap; import static co.unruly.control.pair.Pairs.*; import static co.unruly.control.pair.Comprehensions.allOf; import static co.unruly.control.pair.Comprehensions.onAll; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat;
package co.unruly.control.pair; public class PairTest { @Test public void canTransformStreamOfPairs() { List<Pair<Integer, String>> transformedPairs = Stream.of(Pair.of(2, "hello"), Pair.of(4, "goodbye")) .map(onLeft(x -> x * 3)) .map(onRight(String::toUpperCase)) .collect(toList()); assertThat(transformedPairs, CoreMatchers.hasItems(Pair.of(6, "HELLO"), Pair.of(12, "GOODBYE"))); } @Test public void canTransformAnIndividualPair() { Pair<Integer, String> transformedPair = Pair.of(2, "hello") .then(onLeft(x -> x * 3)) .then(onRight(String::toUpperCase)); assertThat(transformedPair, is(Pair.of(6, "HELLO"))); } @Test public void canCollectToParallelLists() { Pair<List<Integer>, List<String>> parallelLists = Stream.of(Pair.of(2, "hello"), Pair.of(4, "goodbye")) .collect(toParallelLists()); assertThat(parallelLists, is(Pair.of(asList(2, 4), asList("hello", "goodbye")))); } @Test public void canCollectToParallelArrays() { Pair<Integer[], String[]> parallelArrays = Stream.of(Pair.of(2, "hello"), Pair.of(4, "goodbye")) .collect(toArrays(Integer[]::new, String[]::new)); assertThat(asList(parallelArrays.left), is(asList(2, 4))); assertThat(asList(parallelArrays.right), is(asList("hello", "goodbye"))); } @Test public void canReduceAStreamOfPairs() { Pair<Integer, String> reduced = Stream.of(Pair.of(2, "hello"), Pair.of(4, "goodbye")) .collect(reducing( 0, (x, y) -> x + y, "", String::concat )); assertThat(reduced, is(Pair.of(6, "hellogoodbye"))); } @Test public void canCreateMaps() { Map<String, String> expectedMap = new HashMap<>(); expectedMap.put("hello", "world"); expectedMap.put("six of one", "half a dozen of the other"); Map<String, String> actualMap = mapOf( entry("hello", "world"), entry("six of one", "half a dozen of the other") ); assertThat(actualMap, is(expectedMap)); } @Test public void canCollectPairsIntoMap() { Map<String, String> expectedMap = new HashMap<>(); expectedMap.put("hello", "world"); expectedMap.put("six of one", "half a dozen of the other"); Map<String, String> actualMap = Stream.of( entry("hello", "world"), entry("six of one", "half a dozen of the other") ).collect(toMap()); assertThat(actualMap, is(expectedMap)); } @Test public void canAggregateOptionalPairs() { Optional<String> actual = allOf( Optional.of("hello"), Optional.of("world")
).map(onAll((a, b) -> a + ", " + b));
5
emina/kodkod
test/kodkod/test/sys/ExamplesTestWithRegularSolver.java
[ "public final class Solution {\n\tprivate final Outcome outcome;\n\tprivate final Statistics stats;\n\tprivate final Instance instance;\n\tprivate final Proof proof;\n\n\t\n\t/**\n\t * Constructs a Solution from the given values.\n\t * @requires outcome != null && stats != null\n\t * @requires outcome = SATISFIABLE...
import java.util.ArrayList; import java.util.Collection; import kodkod.ast.Formula; import kodkod.engine.Solution; import kodkod.engine.Solver; import kodkod.engine.satlab.SATFactory; import kodkod.instance.Bounds; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import kodkod.test.util.Solvers;
package kodkod.test.sys; @RunWith(Parameterized.class) public class ExamplesTestWithRegularSolver extends ExamplesTest { private final Solver solver; public ExamplesTestWithRegularSolver(SATFactory solverOpt) { this.solver = new Solver(); this.solver.options().setSolver(solverOpt); } @Parameters public static Collection<Object[]> solversToTestWith() { final Collection<Object[]> ret = new ArrayList<Object[]>();
for(SATFactory factory : Solvers.allAvailableSolvers()) {
4
delving/x3ml
src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
[ "public interface Generator {\r\n\r\n interface UUIDSource {\r\n\r\n String generateUUID();\r\n }\r\n\r\n void setDefaultArgType(SourceType sourceType);\r\n\r\n void setLanguageFromMapping(String language);\r\n\r\n void setNamespace(String prefix, String uri);\r\n\r\n String getLanguageFrom...
import com.damnhandy.uri.template.MalformedUriTemplateException; import com.damnhandy.uri.template.UriTemplate; import com.damnhandy.uri.template.VariableExpansionException; import eu.delving.x3ml.engine.Generator; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import static eu.delving.x3ml.X3MLEngine.exception; import static eu.delving.x3ml.engine.X3ML.*; import static eu.delving.x3ml.engine.X3ML.Helper.generatorStream; import static eu.delving.x3ml.engine.X3ML.Helper.literalValue; import static eu.delving.x3ml.engine.X3ML.Helper.typedLiteralValue; import static eu.delving.x3ml.engine.X3ML.Helper.uriValue; import static eu.delving.x3ml.engine.X3ML.SourceType.constant; import static eu.delving.x3ml.engine.X3ML.SourceType.xpath;
//=========================================================================== // Copyright 2014 Delving B.V. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //=========================================================================== package eu.delving.x3ml; /** * @author Gerald de Jong <gerald@delving.eu> */ public class X3MLGeneratorPolicy implements Generator { private static final Pattern BRACES = Pattern.compile("\\{[?;+#]?([^}]+)\\}"); private Map<String, GeneratorSpec> generatorMap = new TreeMap<String, GeneratorSpec>(); private Map<String, String> namespaceMap = new TreeMap<String, String>(); private UUIDSource uuidSource; private SourceType defaultSourceType; private String languageFromMapping; public interface CustomGenerator { void setArg(String name, String value) throws CustomGeneratorException; String getValue() throws CustomGeneratorException; String getValueType() throws CustomGeneratorException; } public static class CustomGeneratorException extends Exception { public CustomGeneratorException(String message) { super(message); } } public static X3MLGeneratorPolicy load(InputStream inputStream, UUIDSource uuidSource) { return new X3MLGeneratorPolicy(inputStream, uuidSource); } public static UUIDSource createUUIDSource(int uuidSize) { return uuidSize > 0 ? new TestUUIDSource(uuidSize) : new RealUUIDSource(); } private X3MLGeneratorPolicy(InputStream inputStream, UUIDSource uuidSource) { if (inputStream != null) {
GeneratorPolicy policy = (GeneratorPolicy) generatorStream().fromXML(inputStream);
3
senseobservationsystems/sense-android-library
sense-android-library/src/nl/sense_os/service/motion/FallDetector.java
[ "public static class DataPoint implements BaseColumns {\n\n public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE\n + \"/vnd.sense_os.data_point\";\n public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE\n + \"/vnd.sense_os.data_poi...
import nl.sense_os.service.R; import nl.sense_os.service.constants.SenseDataTypes; import nl.sense_os.service.constants.SensorData.DataPoint; import nl.sense_os.service.constants.SensorData.SensorNames; import nl.sense_os.service.provider.SNTP; import nl.sense_os.service.shared.SensorDataPoint; import nl.sense_os.service.shared.SensorDataPoint.DataType; import nl.sense_os.service.subscription.BaseDataProducer; import nl.sense_os.service.subscription.DataConsumer; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.os.SystemClock; import android.util.FloatMath; import android.util.Log;
} } private boolean fallDetected(float accVecSum) { // Log.d("Fall detection:", "time:"+(SystemClock.elapsedRealtime()-time)); time = SystemClock.elapsedRealtime(); if (interrupt.FALL || (demo && interrupt.FREE_FALL)) reset(); freeFall(accVecSum); if (demo) { if (interrupt.FREE_FALL) { reset(); return true; } } else { activity(accVecSum); if (useInactivity) { if (!interrupt.INACTIVITY) inactivity(accVecSum); } else interrupt.FALL = interrupt.ACTIVITY; if (interrupt.FALL) { reset(); return true; } } return false; } private void freeFall(float accVecSum) { if (accVecSum < THRESH_FF) { if (startInterrupt == 0) startInterrupt = SystemClock.elapsedRealtime(); else if ((SystemClock.elapsedRealtime() - startInterrupt > TIME_FF && !demo) || (SystemClock.elapsedRealtime() - startInterrupt > TIME_FF_DEMO && demo)) { // Log.v("Fall detection", "FF time:" + (SystemClock.elapsedRealtime() - // startInterrupt)); interrupt.FREE_FALL = true; } } else if (interrupt.FREE_FALL) { interrupt.stopFreeFall = SystemClock.elapsedRealtime(); interrupt.FREE_FALL = false; startInterrupt = 0; } else startInterrupt = 0; if (interrupt.FREE_FALL) { Log.w(TAG, "FALL!!!"); } } private void inactivity(float accVecSum) { if (interrupt.stopActivity == 0) return; if (accVecSum < THRESH_INACT) { if (SystemClock.elapsedRealtime() - interrupt.stopActivity < TIME_ACT_INACT) if (startInterrupt == 0) startInterrupt = SystemClock.elapsedRealtime(); if (startInterrupt != 0 && SystemClock.elapsedRealtime() - startInterrupt > TIME_INACT) interrupt.INACTIVITY = true; } else if (startInterrupt != 0 && !interrupt.INACTIVITY) reset(); if (SystemClock.elapsedRealtime() - interrupt.stopActivity >= TIME_ACT_INACT && startInterrupt == 0) reset(); interrupt.FALL = interrupt.INACTIVITY; if (interrupt.INACTIVITY) { Log.w(TAG, "Inactivity!!!"); } } @Override public boolean isSampleComplete() { // never unregister return false; } @Override public void onNewData(SensorDataPoint dataPoint) { if(dataPoint.getDataType() != DataType.SENSOREVENT) return; SensorEvent event = dataPoint.getSensorEventValue(); // check if this is useful data point Sensor sensor = event.sensor; if (sensor.getType() != Sensor.TYPE_ACCELEROMETER) { return; } float aX = event.values[1]; float aY = event.values[0]; float aZ = event.values[2]; float accVecSum = FloatMath.sqrt(aX * aX + aY * aY + aZ * aZ); if (fallDetected(accVecSum)) { // send msg sendFallMessage(true); } } private void reset() { interrupt = new Interrupt(); startInterrupt = 0; } public void sendFallMessage(boolean fall) { this.notifySubscribers(); SensorDataPoint dataPoint = new SensorDataPoint(fall);
dataPoint.sensorName = SensorNames.FALL_DETECTOR;
1
1014277960/DailyReader
app/src/main/java/com/wulinpeng/daiylreader/read/ui/BookFactory.java
[ "public class Application extends android.app.Application {\n\n private static Context context;\n\n @Override\n public void onCreate() {\n super.onCreate();\n context = getApplicationContext();\n CrashReport.initCrashReport(getApplicationContext(), \"869beebc76\", false);\n }\n\n ...
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Typeface; import android.util.DisplayMetrics; import android.view.WindowManager; import android.widget.Toast; import com.wulinpeng.daiylreader.Application; import com.wulinpeng.daiylreader.R; import com.wulinpeng.daiylreader.net.ReaderApiManager; import com.wulinpeng.daiylreader.bean.ChapterDetailResponse; import com.wulinpeng.daiylreader.bean.ChaptersResponse; import com.wulinpeng.daiylreader.manager.CacheManager; import com.wulinpeng.daiylreader.read.event.OnChapterLoadEvent; import com.wulinpeng.daiylreader.util.RxUtil; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.wulinpeng.daiylreader.Application.getContext;
package com.wulinpeng.daiylreader.read.ui; /** * @author wulinpeng * @datetime: 17/2/8 下午7:00 * @description: */ public class BookFactory { /** * 翻页的状态,如果是新章节且内存中没有那么可能会有网络请求那就是异步,就不能直接draw了,等待读取完毕再调用接口通知draw */ public static final int STATE_SUCCESS = 0; public static final int STATE_ASYN = 1; public static final int STATE_NULL = 2; private int mHeight; private int mWidth; public int mNormalSize = 45; public int mTitleSize = 64; public Paint mNormalPaint; public Paint mTitlePaint; public int mNormalMargin = 30; private String mTitle; private Bitmap mBackgroundBitmap; // 当前章节数 private int mCurrentChapterIndex; //当前是第几页 public int mCurrentPage; private ChaptersResponse.MixToc mChaptersInfo; // 根据当前格式处理后的章节内容 private Map<Integer, List<List<String>>> mFormatChapters = new HashMap<>(); private ChapterDetailResponse.Chapter mCurrentChapter; public BookFactory(ChaptersResponse.MixToc chaptersInfo){ this.mChaptersInfo = chaptersInfo; getWidthAndHeight(); mNormalPaint = new Paint(); mNormalPaint.setTextSize(mNormalSize); mNormalPaint.setColor(Color.BLACK); mNormalPaint.setTextAlign(Paint.Align.LEFT); mTitlePaint = new Paint(); mTitlePaint.setTextSize(mTitleSize); mTitlePaint.setColor(Color.DKGRAY); mTitlePaint.setTextAlign(Paint.Align.CENTER); mTitlePaint.setTypeface(Typeface.DEFAULT_BOLD); mCurrentPage = 0; mBackgroundBitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.bg_read); } private void getWidthAndHeight() { WindowManager wm = (WindowManager) getContext() .getSystemService(Context.WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(metrics); mWidth = metrics.widthPixels; mHeight = metrics.heightPixels; } /** * 打开小说某一章 * @param chapter * @param start 0首页还是1尾页 * @return */ public int openBook(int chapter, int start) { mCurrentChapterIndex = chapter; mTitle = mChaptersInfo.getChapters().get(chapter).getTitle(); if (mFormatChapters.get(mCurrentChapterIndex) == null) { // 缓存没有到内存拿 if (getChapterFromCache(chapter, start)) { return STATE_SUCCESS; } else { getChapterFromNet(chapter, start); return STATE_ASYN; } } else { // 是0就就是0,否则1不影响 mCurrentPage = (mFormatChapters.get(mCurrentChapterIndex).size() - 1) * start; return STATE_SUCCESS; } } private boolean getChapterFromCache(int chapter, int start) { ChapterDetailResponse.Chapter c = CacheManager.getInstance().getChapter(mChaptersInfo.getBook(), chapter); if (c != null) { formatChapter(c); mCurrentPage = (mFormatChapters.get(mCurrentChapterIndex).size() - 1) * start; return true; } else { return false; } } private void getChapterFromNet(int chapter, int start) { ReaderApiManager.INSTANCE.getChapterDetail(mChaptersInfo.getChapters().get(chapter).getLink())
.compose(RxUtil.rxScheduler())
5
endercrest/VoidSpawn
src/main/java/com/endercrest/voidspawn/commands/DetectorCommand.java
[ "public class ConfigManager {\n private VoidSpawn plugin;\n private static final ConfigManager instance = new ConfigManager();\n private File worldFile;\n private FileConfiguration config;\n private final int CURRENT_VERSION = 2;\n\n /**\n * Get the running instance of the ConfigManager\n ...
import com.endercrest.voidspawn.ConfigManager; import com.endercrest.voidspawn.DetectorManager; import com.endercrest.voidspawn.VoidSpawn; import com.endercrest.voidspawn.detectors.Detector; import com.endercrest.voidspawn.utils.CommandUtil; import com.endercrest.voidspawn.utils.MessageUtil; import com.endercrest.voidspawn.utils.WorldUtil; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors;
package com.endercrest.voidspawn.commands; public class DetectorCommand implements SubCommand { @Override public boolean onCommand(Player p, String[] args){ if(args.length == 1){ p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + "--- &6Available Detectors&f ---")); for(Detector detector : DetectorManager.getInstance().getDetectors().values()){ String detectorSummary = String.format("&6%s &f- %s", detector.getName(), detector.getDescription()); p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + detectorSummary)); } }else if(args.length >= 2) { String world = CommandUtil.constructWorldFromArgs(args, 2, p.getWorld().getName()); if(world == null) { p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + "&cThat is not a valid world!")); return false; } if(DetectorManager.getInstance().getDetectors().containsKey(args[1].toLowerCase())){ Detector detector = DetectorManager.getInstance().getDetector(args[1].toLowerCase()); ConfigManager.getInstance().setDetector(detector.getName().toLowerCase(), world); p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + "Updated detector!")); }else{ p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + "&cThis is not a valid detector!")); } } return false; } @Override public String helpInfo(){ return "/vs detector (detector) [world] - Sets world detector"; } @Override public String permission(){ return "vs.admin.detector"; } @Override public List<String> getTabCompletion(Player player, String[] args) { switch(args.length) { case 1: Set<String> detectors = DetectorManager.getInstance().getDetectors().keySet(); return detectors.stream() .filter(detector -> detector.toLowerCase().startsWith(args[0].toLowerCase())) .collect(Collectors.toList()); case 2:
return WorldUtil.getMatchingWorlds(args[1]);
6
aelstad/keccakj
src/test/java/com/github/aelstad/keccakj/provider/TestKeccakjProvider.java
[ "public interface CipherProviderFactory {\n\tpublic CipherInterface getInstance(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException;\n}", "public final class SHA3_224 extends AbstractKeccakMessageDigest {\n\tprivate final static byte DOMAIN_PADDING = 2;\n\tprivate final static int DOMMA...
import java.security.MessageDigest; import java.security.SecureRandom; import java.security.Security; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.github.aelstad.keccakj.cipher.CipherProviderFactory; import com.github.aelstad.keccakj.fips202.SHA3_224; import com.github.aelstad.keccakj.fips202.SHA3_256; import com.github.aelstad.keccakj.fips202.SHA3_384; import com.github.aelstad.keccakj.fips202.SHA3_512;
/* * Copyright 2014 Amund Elstad. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.aelstad.keccakj.provider; public class TestKeccakjProvider { @BeforeClass public static void beforeClass() { Security.addProvider(new KeccakjProvider()); } @Test public void testSha3_224() throws Exception { Assert.assertTrue(Constants.SHA3_224.equals("SHA3-224")); Assert.assertTrue(MessageDigest.getInstance(Constants.SHA3_224, Constants.PROVIDER) instanceof SHA3_224); } @Test public void testSha3_256() throws Exception { Assert.assertTrue(Constants.SHA3_256.equals("SHA3-256")); Assert.assertTrue(MessageDigest.getInstance(Constants.SHA3_256, Constants.PROVIDER) instanceof SHA3_256); } @Test public void testSha3_384() throws Exception { Assert.assertTrue(Constants.SHA3_384.equals("SHA3-384")); Assert.assertTrue(MessageDigest.getInstance(Constants.SHA3_384, Constants.PROVIDER) instanceof SHA3_384); } @Test public void testSha3_512() throws Exception { Assert.assertTrue(Constants.SHA3_512.equals("SHA3-512")); Assert.assertTrue(MessageDigest.getInstance(Constants.SHA3_512, Constants.PROVIDER) instanceof SHA3_512); } @Test public void testKeccackRnd128() throws Exception { Assert.assertNotNull(SecureRandom.getInstance(Constants.KECCAK_RND128, Constants.PROVIDER)); } @Test public void testKeccackRnd256() throws Exception { Assert.assertNotNull(SecureRandom.getInstance(Constants.KECCAK_RND256, Constants.PROVIDER)); byte[] buf = new byte[1024]; SecureRandom.getInstance(Constants.KECCAK_RND256, Constants.PROVIDER).nextBytes(buf); } @Test public void testShake128StreamCipher() throws Exception {
CipherProviderFactory cpf = (CipherProviderFactory) Security.getProvider(Constants.PROVIDER);
0
flapdoodle-oss/de.flapdoodle.embed.process
src/main/java/de/flapdoodle/embed/process/runtime/Processes.java
[ "@Value.Immutable\npublic interface SupportConfig {\n\n\tString name();\n\n\tString supportUrl();\n\n\tBiFunction<Class<?>, Exception, String> messageOnException();\n\n\tstatic SupportConfig generic() {\n\t\treturn builder()\n\t\t\t\t.name(\"generic\")\n\t\t\t\t.supportUrl(\"https://github.com/flapdoodle-oss/de.fla...
import com.sun.jna.Pointer; import com.sun.jna.platform.win32.Kernel32; import com.sun.jna.platform.win32.WinNT; import de.flapdoodle.embed.process.config.SupportConfig; import de.flapdoodle.embed.process.config.process.ProcessConfig; import de.flapdoodle.embed.process.io.LogWatchStreamProcessor; import de.flapdoodle.embed.process.io.Processors; import de.flapdoodle.embed.process.io.StreamProcessor; import de.flapdoodle.embed.process.io.StreamToLineProcessor; import de.flapdoodle.os.OS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.lang.model.SourceVersion; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashSet; import static java.util.Arrays.asList;
/** * Copyright (C) 2011 * Michael Mosmann <michael@mosmann.de> * Martin Jöhren <m.joehren@googlemail.com> * * with contributions from * konstantin-ba@github, Archimedes Trajano (trajano@github), Kevin D. Keck (kdkeck@github), Ben McCann (benmccann@github) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.flapdoodle.embed.process.runtime; public abstract class Processes { private static final Logger logger = LoggerFactory.getLogger(ProcessControl.class); private static final PidHelper PID_HELPER; static { // Comparing with the string value to avoid a strong dependency on JDK 9 String sourceVersion = SourceVersion.latest().toString(); switch (sourceVersion) { case "RELEASE_9": PID_HELPER = PidHelper.JDK_9; break; case "RELEASE_10": case "RELEASE_11": case "RELEASE_12": case "RELEASE_13": case "RELEASE_14": case "RELEASE_15": case "RELEASE_16": case "RELEASE_17": PID_HELPER = PidHelper.JDK_11; break; default: PID_HELPER = PidHelper.LEGACY; } } private Processes() { // no instance } public static Long processId(Process process) { return PID_HELPER.getPid(process); } private static Long unixLikeProcessId(Process process) { Class<?> clazz = process.getClass(); try { if (clazz.getName().equals("java.lang.UNIXProcess")) { Field pidField = clazz.getDeclaredField("pid"); pidField.setAccessible(true); Object value = pidField.get(process); if (value instanceof Integer) { logger.debug("Detected pid: {}", value); return ((Integer) value).longValue(); } } } catch (SecurityException | IllegalAccessException | IllegalArgumentException | NoSuchFieldException sx) { sx.printStackTrace(); } return null; } /** * @see "http://www.golesny.de/p/code/javagetpid" * * @return windows process id */ private static Long windowsProcessId(Process process) { if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) { /* determine the pid on windows plattforms */ try { Field f = process.getClass().getDeclaredField("handle"); f.setAccessible(true); long handl = f.getLong(process); Kernel32 kernel = Kernel32.INSTANCE; WinNT.HANDLE handle = new WinNT.HANDLE(); handle.setPointer(Pointer.createConstant(handl)); int ret = kernel.GetProcessId(handle); logger.debug("Detected pid: {}", ret); return (long) ret; } catch (Throwable e) { e.printStackTrace(); } } return null; } public static boolean killProcess(SupportConfig support,de.flapdoodle.os.Platform platform, StreamProcessor output, long pid) { return isUnixLike(platform) && ProcessControl.executeCommandLine(support, "[kill process]", ProcessConfig.builder().commandLine(asList("kill", "-2", "" + pid)).output(output).build()); } public static boolean termProcess(SupportConfig support,de.flapdoodle.os.Platform platform, StreamProcessor output, long pid) { return isUnixLike(platform) && ProcessControl.executeCommandLine(support, "[term process]", ProcessConfig.builder().commandLine(asList("kill", "" + pid)).output(output).build()); } public static boolean tryKillProcess(SupportConfig support,de.flapdoodle.os.Platform platform, StreamProcessor output, long pid) { return platform.operatingSystem() == OS.Windows && ProcessControl.executeCommandLine(support, "[taskkill process]", ProcessConfig.builder().commandLine(asList("taskkill", "/F", "/pid", "" + pid)).output(output).build()); } private static boolean isUnixLike(de.flapdoodle.os.Platform platform) { return platform.operatingSystem() != OS.Windows; } public static boolean isProcessRunning(de.flapdoodle.os.Platform platform, long pid) { try { final Process pidof; if (isUnixLike(platform)) { pidof = Runtime.getRuntime().exec( new String[] { "kill", "-0", "" + pid }); return pidof.waitFor() == 0; } else { // windows // process might be in either NOT RESPONDING due to // firewall blocking, or could be RUNNING final String[] cmd = { "tasklist.exe", "/FI", "PID eq " + pid ,"/FO", "CSV" }; logger.trace("Command: {}", asList(cmd)); ProcessBuilder processBuilder = ProcessControl .newProcessBuilder(asList(cmd), true); Process process = processBuilder.start(); // look for the PID in the output, pass it in for 'success' state LogWatchStreamProcessor logWatch = new LogWatchStreamProcessor(""+pid,
new HashSet<>(), StreamToLineProcessor.wrap(Processors.silent()));
5
pdsoftplan/zap-maven-plugin
zap-maven-plugin-core/src/main/java/br/com/softplan/security/zap/maven/SeleniumAnalyzeMojo.java
[ "public class ZapClient {\n\n\tprivate String apiKey;\n\tprivate ClientApi api;\n\t\n\tprivate AuthenticationHandler authenticationHandler;\n\tprivate SessionManager sessionManager;\n\t\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(ZapClient.class);\n\n\t/**\n\t * Constructs the client providing i...
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import br.com.softplan.security.zap.api.ZapClient; import br.com.softplan.security.zap.api.model.AnalysisInfo; import br.com.softplan.security.zap.api.model.AnalysisType; import br.com.softplan.security.zap.api.model.AuthenticationInfo; import br.com.softplan.security.zap.api.report.ZapReport; import br.com.softplan.security.zap.commons.ZapInfo; import br.com.softplan.security.zap.commons.boot.Zap;
package br.com.softplan.security.zap.maven; /** * Run ZAP's Active Scan and generates the reports. <b>No Spider is executed.</b> * This scan assumes that integration tests ran using ZAP as a proxy, so the Active Scan * is able to use the navigation done during the tests for the scan. * <p> * Normally this goal will be executed in the phase <i>post-integration-test</i>, while the * goal {@code startZap} will run in the phase <i>pre-integration-test</i>, to make sure * ZAP is running during the tests. * * @author pdsec */ @Mojo(name="seleniumAnalyze") public class SeleniumAnalyzeMojo extends ZapMojo { @Override public void doExecute() throws MojoExecutionException, MojoFailureException { getLog().info("Starting ZAP analysis at target: " + super.getTargetUrl()); ZapInfo zapInfo = buildZapInfo(); AuthenticationInfo authenticationInfo = buildAuthenticationInfo();
AnalysisInfo analysisInfo = buildAnalysisInfo(AnalysisType.ACTIVE_SCAN_ONLY);
2
Beloumi/PeaFactory
src/peafactory/peas/image_pea/LockFrameImage.java
[ "public class PeaSettings {\n\n\tprivate static JDialog keyboard = null;\n\tprivate static final JDialog pswGenerator = null;\n\t\n\tprivate static final boolean BOUND = true;\n\tprivate static final String EXTERNAL_FILE_PATH = null;\n\tprivate static final boolean EXTERN_FILE = true;\n\tprivate static final String...
import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; import settings.PeaSettings; import cologne.eck.peafactory.crypto.CipherStuff; import cologne.eck.peafactory.peas.PswDialogBase; import cologne.eck.peafactory.peas.gui.LockFrame; import cologne.eck.peafactory.peas.gui.PswDialogView; import cologne.eck.peafactory.tools.Converter; import cologne.eck.peafactory.tools.WriteResources; import cologne.eck.peafactory.tools.Zeroizer; import java.awt.Dimension; import java.awt.Image; import java.awt.event.ActionEvent;
package cologne.eck.peafactory.peas.image_pea; /* * Peafactory - Production of Password Encryption Archives * Copyright (C) 2015 Axel von dem Bruch * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * See: http://www.gnu.org/licenses/gpl-2.0.html * You should have received a copy of the GNU General Public License * along with this library. */ /** * Main view of image pea. */ /* * Frame to display images, decrypted in PswDialogImage * (this is not a daughter class of LockFrame!) * */ @SuppressWarnings("serial") final class LockFrameImage extends LockFrame implements ActionListener { private static byte[] imageBytes; private static boolean isInstantiated = false; private LockFrameImage() { this.setIconImage(PswDialogView.getImage()); this.addWindowListener(this);// for windowClosing JPanel contentPane = new JPanel(); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); this.setContentPane(contentPane); JScrollPane scrollPane = null; // get the image from file name: BufferedImage image = null; try { image = ImageIO.read(new ByteArrayInputStream(imageBytes)); //Arrays.fill(imageBytes, (byte) 0); } catch (IOException e) { System.err.println("LockFrameImage: " + e); e.printStackTrace(); } if (image == null) { // invalid file JOptionPane.showMessageDialog(this, "Invalid or unsuitable image file: \n" + PswDialogImage.getEncryptedFileName(), "Error", JOptionPane.ERROR_MESSAGE); System.exit(1); } // get settings: int picWidth = PswDialogImage.imageWidth; int picHeight = PswDialogImage.imageHeight; int w = picWidth,h = picHeight; JLabel picLabel = null; // keep ratio of image width and height if resize == true: if (PswDialogImage.resize == true) { double op = 0; if (image.getWidth() < picWidth) { op = (double)picWidth / image.getWidth(); if (image.getHeight() * op > picHeight) op = (double)picHeight / image.getHeight(); w = (int) (image.getWidth() * op); h = (int) (image.getHeight() * op); } else { op = image.getWidth() / (double)picWidth; if ( (image.getHeight() / op) > picHeight) op = image.getHeight() / (double)picHeight; w = (int) (image.getWidth() / op); h = (int) (image.getHeight() / op); } Image scaledImage = image.getScaledInstance(w, h, Image.SCALE_FAST); picLabel = new JLabel(new ImageIcon(scaledImage)); scrollPane = new JScrollPane(picLabel); } else { picLabel = new JLabel(new ImageIcon(image)); scrollPane = new JScrollPane(picLabel); scrollPane.setPreferredSize(new Dimension(PswDialogImage.imageWidth, PswDialogImage.imageHeight)); } contentPane.add(scrollPane); if (PeaSettings.getExternFile() == true) { JPanel buttonPanel = new JPanel(); JButton unencryptedButton = new JButton ("close unencrypted"); unencryptedButton.setActionCommand("unencrypted"); unencryptedButton.addActionListener(this); buttonPanel.add(unencryptedButton); JButton encryptedButton = new JButton ("close encrypted"); encryptedButton.setActionCommand("encrypted"); encryptedButton.addActionListener(this); buttonPanel.add(encryptedButton); JButton passwordButton = new JButton ("change password"); passwordButton.setActionCommand("changePassword"); passwordButton.addActionListener(this); buttonPanel.add(passwordButton); contentPane.add(buttonPanel); } this.setLocation(100, 100); pack(); } protected final static LockFrameImage getInstance() { LockFrameImage frame = null; if (isInstantiated == false) { frame = new LockFrameImage(); } else { //return null } return frame; } protected final static void setImageBytes( byte[] input ) { //imageBytes = input; imageBytes = new byte[input.length]; System.arraycopy(input, 0, imageBytes, 0, input.length); } @Override public void actionPerformed(ActionEvent ape) { String command = ape.getActionCommand(); if (command.equals("unencrypted")) { WriteResources.write(imageBytes, PeaSettings.getExternalFilePath(), null ); Zeroizer.zero(imageBytes); System.exit(0); } else if (command.equals("encrypted")){ // file was not modified, just loaded unencrypted in RAM Zeroizer.zero(imageBytes); System.exit(0); } else if (command.equals("changePassword")){ String[] fileNames = {PswDialogBase.getEncryptedFileName()}; changePassword(imageBytes, fileNames); } } @Override protected void windowClosingCommands() { // append settings for this image and then encrypt and store if (PswDialogView.isInitializing() == true) { // get setting values int resizeValue = 0; if (PswDialogImage.resize == true) resizeValue = 1; int[] settings = new int[3]; settings[0] = PswDialogImage.imageWidth; settings[1] = PswDialogImage.imageHeight; settings[2] = resizeValue; byte[] settingBytes = Converter.ints2bytesBE(settings);; // append setting values to plaintext byte[] plainBytes = new byte[imageBytes.length + settingBytes.length]; System.arraycopy(imageBytes, 0, plainBytes, 0, imageBytes.length); System.arraycopy(settingBytes, 0, plainBytes, imageBytes.length, settingBytes.length); // encrypt
byte[] cipherBytes = CipherStuff.getInstance().encrypt(plainBytes, null, true);
1
gillius/jalleg
jalleg-framework/src/main/java/org/gillius/jalleg/framework/io/AllegroLoader.java
[ "@SuppressWarnings({\"unused\", \"WeakerAccess\", \"PointlessBitwiseExpression\"})\npublic class AllegroLibrary implements Library {\n\tpublic static final String JNA_LIBRARY_NAME;\n\tpublic static final NativeLibrary JNA_NATIVE_LIB;\n\t/**\n\t * Keep a strong reference to all loaded libraries, so that GC won't clo...
import org.gillius.jalleg.binding.AllegroLibrary; import org.gillius.jalleg.binding.AllegroLibrary.ALLEGRO_BITMAP; import org.gillius.jalleg.binding.AllegroLibrary.ALLEGRO_CONFIG; import org.gillius.jalleg.framework.AllegroException; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import static org.gillius.jalleg.binding.AllegroLibrary.al_load_bitmap_flags_f; import static org.gillius.jalleg.binding.AllegroLibrary.al_load_config_file_f;
package org.gillius.jalleg.framework.io; /** * Utility methods to load Allegro resources such as images from Java byte arrays, {@link InputStream}s, or classpath * resources. */ public class AllegroLoader { /** * Pulls an Allegro "ident" file extension such as ".png" by looking at the end of the given path. */ public static String getIdentFromPath(String path) { int idx = path.lastIndexOf('.'); if (idx >= 0) { return path.substring(idx); } else { return null; } } /** * Uses {@link AllegroLibrary#al_load_bitmap_f} to load bitmap data. File type will be autodetected from the path's * extension if possible (via {@link #getIdentFromPath(String)}), or from {@link AllegroLibrary#al_identify_bitmap_f}. * * @param path classpath available from the root (boot) classpath * * @throws AllegroException if al_load_bitmap_flags_f fails */ public static ALLEGRO_BITMAP loadBitmapFromClasspath(String path) throws IOException { return loadBitmapFromClasspath(path, null, 0); } /** * Uses {@link AllegroLibrary#al_load_bitmap_f} to load bitmap data. * * @param path classpath available from the root (boot) classpath * @param ident type of file such as ".png" or null to use {@link #getIdentFromPath(String)}. If the path does not * end with a file extension, then auto-detect with {@link AllegroLibrary#al_identify_bitmap_f} * @param flags flags to pass such as {@link AllegroLibrary#ALLEGRO_NO_PREMULTIPLIED_ALPHA} * * @throws AllegroException if al_load_bitmap_flags_f fails */ public static ALLEGRO_BITMAP loadBitmapFromClasspath(String path, String ident, int flags) throws IOException { if (ident == null) ident = getIdentFromPath(path); return loadBitmap(getInputStream(path), ident, flags); } /** * Uses {@link AllegroLibrary#al_load_bitmap_f} to load bitmap data. * * @param is image data; stream is closed by this function * @param ident type of file such as ".png" or null to auto-detect with {@link AllegroLibrary#al_identify_bitmap_f} * * @throws AllegroException if al_load_bitmap_flags_f fails */ public static ALLEGRO_BITMAP loadBitmap(InputStream is, String ident) throws IOException { return loadBitmap(is, ident, 0); } /** * Uses {@link AllegroLibrary#al_load_bitmap_f} to load bitmap data. * * @param is image data; stream is closed by this function * @param ident type of file such as ".png" or null to auto-detect with {@link AllegroLibrary#al_identify_bitmap_f} * @param flags flags to pass such as {@link AllegroLibrary#ALLEGRO_NO_PREMULTIPLIED_ALPHA} * * @throws AllegroException if al_load_bitmap_flags_f fails */ public static ALLEGRO_BITMAP loadBitmap(InputStream is, String ident, int flags) throws IOException { try (Memfile file = Memfile.from(is)) { ALLEGRO_BITMAP ret = al_load_bitmap_flags_f(file.getFile(), ident, flags); if (ret == null) throw new AllegroException("Failed to load bitmap with type " + ident); return ret; } }
public static ALLEGRO_CONFIG loadConfigFromClasspath(String path) throws IOException {
2
yammer/tenacity
tenacity-core/src/test/java/com/yammer/tenacity/tests/TenacityCircuitBreakerHealthCheckTest.java
[ "@JsonDeserialize(using = CircuitBreaker.Deserializer.class)\npublic class CircuitBreaker {\n public enum State {\n OPEN, CLOSED, FORCED_OPEN, FORCED_CLOSED,\n FORCED_RESET //Used to \"unset\" any FORCED state\n }\n\n public static class Deserializer extends StdDeserializer<CircuitBreaker> {\...
import com.codahale.metrics.health.HealthCheck; import com.google.common.collect.ImmutableList; import com.yammer.tenacity.core.core.CircuitBreaker; import com.yammer.tenacity.core.core.CircuitBreakers; import com.yammer.tenacity.core.healthcheck.TenacityCircuitBreakerHealthCheck; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import com.yammer.tenacity.core.properties.TenacityPropertyRegister; import com.yammer.tenacity.testing.TenacityTestRule; import io.dropwizard.util.Duration; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
package com.yammer.tenacity.tests; public class TenacityCircuitBreakerHealthCheckTest { @Rule public final TenacityTestRule tenacityTestRule = new TenacityTestRule(); @Before public void setup() { TenacityPropertyRegister.setDefaultMetricsHealthSnapshotInterval(Duration.milliseconds(10)); } @Test public void healthyWhenNoCircuitBreakers() { assertThat(new TenacityCircuitBreakerHealthCheck().execute().isHealthy()).isTrue(); } @Test public void healthyWhenThereIsNoOpenCircuitBreakers() { final HealthCheck healthCheck = new TenacityCircuitBreakerHealthCheck(DependencyKey.EXISTENT_HEALTHCHECK); assertThat(CircuitBreakers.all(DependencyKey.EXISTENT_HEALTHCHECK)).isEmpty(); new TenacitySuccessCommand(DependencyKey.EXISTENT_HEALTHCHECK).execute(); assertThat(CircuitBreakers.all(DependencyKey.EXISTENT_HEALTHCHECK)) .contains(CircuitBreaker.closed(DependencyKey.EXISTENT_HEALTHCHECK)); assertThat(healthCheck.execute().isHealthy()).isTrue(); } @Test public void unhealthyWhenThereIsAnOpenCircuitBreaker() { final HealthCheck healthCheck = new TenacityCircuitBreakerHealthCheck(DependencyKey.EXISTENT_HEALTHCHECK); assertThat(CircuitBreakers.all(DependencyKey.EXISTENT_HEALTHCHECK)).isEmpty(); tryToOpenCircuitBreaker(DependencyKey.EXISTENT_HEALTHCHECK); assertThat(CircuitBreakers.all(DependencyKey.EXISTENT_HEALTHCHECK)) .contains(CircuitBreaker.open(DependencyKey.EXISTENT_HEALTHCHECK)); assertThat(healthCheck.execute()) .isEqualToComparingOnlyGivenFields(HealthCheck.Result.unhealthy(""), "healthy"); } @Test public void multipleUnhealthyWhenThereIsAnOpenCircuitBreaker() {
final ImmutableList<TenacityPropertyKey> keys = ImmutableList.<TenacityPropertyKey>of(
3
Cazsius/Spice-of-Life-Carrot-Edition
src/main/java/com/cazsius/solcarrot/client/TooltipHandler.java
[ "@Mod(SOLCarrot.MOD_ID)\n@Mod.EventBusSubscriber(modid = SOLCarrot.MOD_ID, bus = MOD)\npublic final class SOLCarrot {\n\tpublic static final String MOD_ID = \"solcarrot\";\n\t\n\tpublic static final Logger LOGGER = LogManager.getLogger(MOD_ID);\n\t\n\tprivate static final String PROTOCOL_VERSION = \"1.0\";\n\tpubli...
import com.cazsius.solcarrot.SOLCarrot; import com.cazsius.solcarrot.SOLCarrotConfig; import com.cazsius.solcarrot.tracking.FoodList; import com.cazsius.solcarrot.tracking.ProgressInfo; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.text.*; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import java.util.List; import static com.cazsius.solcarrot.lib.Localization.localizedComponent;
package com.cazsius.solcarrot.client; @OnlyIn(Dist.CLIENT) @Mod.EventBusSubscriber(value = Dist.CLIENT, modid = SOLCarrot.MOD_ID) public final class TooltipHandler { @SubscribeEvent public static void onItemTooltip(ItemTooltipEvent event) { if (!SOLCarrotConfig.isFoodTooltipEnabled()) return; if (event.getEntityPlayer() == null) return; PlayerEntity player = event.getEntityPlayer(); Item food = event.getItemStack().getItem(); if (!food.isFood()) return;
FoodList foodList = FoodList.get(player);
2
sherlok/sherlok
src/main/java/org/sherlok/mappings/PipelineDef.java
[ "public static void validateArgument(boolean expression, String errorMessage)\n throws SherlokException {\n if (!expression) {\n throw new SherlokException(errorMessage);\n }\n}", "public static void validateDomain(String domain) throws SherlokException {\n if (domain == null) {\n th...
import static com.fasterxml.jackson.annotation.JsonInclude.Include.ALWAYS; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_DEFAULT; import static org.sherlok.utils.CheckThat.validateArgument; import static org.sherlok.utils.CheckThat.validateDomain; import static org.sherlok.utils.CheckThat.validateTypeIdentifier; import static org.sherlok.utils.Create.list; import static org.sherlok.utils.Create.map; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import org.sherlok.Controller; import org.sherlok.mappings.BundleDef.EngineDef; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/** * Copyright (C) 2014-2015 Renaud Richardet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sherlok.mappings; /** * A pipeline describes the steps to perform a text mining analysis. This * analysis consists of a script that defines a list of steps to be performed on * text (e.g. split words, remove determinants, annotate locations, ...). * * @author renaud@apache.org */ // ensure property output order @JsonPropertyOrder(value = { "name", "version", "description", "language", "domain", "loadOnStartup", "scriptLines", "config", "output", "tests" }, alphabetic = true) @JsonInclude(NON_DEFAULT) public class PipelineDef extends Def { /** Which language this pipeline works for (ISO code). Defaults to 'en' */ private String language = "en"; /** The list of engine definitions */ @JsonProperty("script") @JsonSerialize(using = ListSerializer.class) private List<String> scriptLines = list(); /** Controls the output of this pipeline */ private PipelineOutput output = new PipelineOutput(); /** Embedded (integration) tests */ @JsonInclude(ALWAYS) private List<PipelineTest> tests = list(); /** Defines what kind of annotation this pipeline outputs */ @JsonInclude(JsonInclude.Include.NON_DEFAULT) public static class PipelineOutput { @JsonProperty("filter_annotations") private List<String> annotationFilters = list(); @JsonProperty("include_annotations") private List<String> annotationIncludes = list(); public List<String> getAnnotationFilters() { return annotationFilters; } public PipelineOutput setAnnotationFilters( List<String> annotationFilters) { this.annotationFilters = annotationFilters; return this; } public List<String> getAnnotationIncludes() { return annotationIncludes; } public PipelineOutput setAnnotationIncludes( List<String> annotationIncludes) { this.annotationIncludes = annotationIncludes; return this; } } /** * Tests one single input string against a list of expected * {@link JsonAnnotation}s */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(NON_DEFAULT) @JsonPropertyOrder(value = { "comment", "input", "expected", "comparison" }, alphabetic = true) public static class PipelineTest { public enum Comparison { /** all expected {@link JsonAnnotation}s are present in system */ atLeast, /** expected and system {@link JsonAnnotation}s are exactly equals */ exact; } private String comment; private String input;
private Map<String, List<JsonAnnotation>> expected = map();
4
nkarasch/ChessGDX
core/src/nkarasch/chessgdx/view/renderers/OverlayRenderer.java
[ "public class GameCore implements ApplicationListener {\n\n\tpublic static final String TITLE = \"ChessGDX\";\n\n\tprivate Camera mCameraController;\n\tprivate ChessLogicController mLogicController;\n\tprivate BoardController mBoardController;\n\tprivate PerspectiveRenderer mPerspectiveRenderer;\n\tprivate OverlayR...
import nkarasch.chessgdx.GameCore; import nkarasch.chessgdx.gui.MenuSkin; import nkarasch.chessgdx.gui.other.CheckMateTable; import nkarasch.chessgdx.gui.other.EngineThinkingImage; import nkarasch.chessgdx.gui.other.ExitConfirmTable; import nkarasch.chessgdx.gui.other.PromotionTable; import nkarasch.chessgdx.gui.settings.SettingsMenuGroup; import nkarasch.chessgdx.gui.slider.MoveHistoryTable; import nkarasch.chessgdx.gui.slider.SlidingMenuGroup; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Skin;
package nkarasch.chessgdx.view.renderers; public class OverlayRenderer extends Stage { private final Skin mSkin; private final PromotionTable mPromotionDialog; private final CheckMateTable mCheckmateDialog;
private final EngineThinkingImage mEngineThinking;
3
sfPlayer1/Matcher
src/matcher/mapping/MappedElementComparators.java
[ "public enum NameType {\n\tPLAIN(true, false, false, 0),\n\tMAPPED(false, true, false, 0),\n\tAUX(false, false, false, 1),\n\tAUX2(false, false, false, 2),\n\n\tMAPPED_PLAIN(true, true, false, 0),\n\tMAPPED_AUX_PLAIN(true, true, false, 1),\n\tMAPPED_AUX2_PLAIN(true, true, false, 2),\n\tMAPPED_TMP_PLAIN(true, true, ...
import java.util.Comparator; import java.util.Objects; import matcher.NameType; import matcher.type.ClassInstance; import matcher.type.Matchable; import matcher.type.MemberInstance; import matcher.type.MethodVarInstance;
package matcher.mapping; public final class MappedElementComparators { public static <T extends MemberInstance<T>> Comparator<T> byName(NameType ns) { return new Comparator<T>() { @Override public int compare(T a, T b) { return compareNullLast(a.getName(ns), b.getName(ns)); } }; } public static <T extends Matchable<T>> Comparator<T> byNameShortFirst(NameType ns) { return new Comparator<T>() { @Override public int compare(T a, T b) { String nameA = a.getName(ns); String nameB = b.getName(ns); if (nameA == null || nameB == null) { return compareNullLast(nameA, nameB); } else { return compareNameShortFirst(nameA, 0, nameA.length(), nameB, 0, nameB.length()); } } }; } public static Comparator<ClassInstance> byNameShortFirstNestaware(NameType ns) { return new Comparator<ClassInstance>() { @Override public int compare(ClassInstance a, ClassInstance b) { String nameA = a.getName(ns); String nameB = b.getName(ns); if (nameA == null || nameB == null) { return compareNullLast(nameA, nameB); } int pos = 0; do { int endA = nameA.indexOf('$', pos); int endB = nameB.indexOf('$', pos); int ret = compareNameShortFirst(nameA, pos, endA >= 0 ? endA : nameA.length(), nameB, pos, endB >= 0 ? endB : nameB.length()); if (ret != 0) { return ret; } else if ((endA < 0) != (endB < 0)) { return endA < 0 ? -1 : 1; } pos = endA + 1; } while (pos > 0); return 0; } }; } private static int compareNameShortFirst(String nameA, int startA, int endA, String nameB, int startB, int endB) { int lenA = endA - startA; int ret = Integer.compare(lenA, endB - startB); if (ret != 0) return ret; for (int i = 0; i < lenA; i++) { char a = nameA.charAt(startA + i); char b = nameB.charAt(startB + i); if (a != b) { return a - b; } } return 0; } public static <T extends MemberInstance<?>> Comparator<T> byNameDescConcat(NameType ns) { return new Comparator<T>() { @Override public int compare(T a, T b) { String valA = Objects.toString(a.getName(ns)).concat(Objects.toString(a.getDesc(ns))); String valB = Objects.toString(b.getName(ns)).concat(Objects.toString(b.getDesc(ns))); return valA.compareTo(valB); } }; }
public static Comparator<MethodVarInstance> byLvIndex() {
4
kdgregory/pathfinder
lib-servlet/src/main/java/com/kdgregory/pathfinder/servlet/ServletInspector.java
[ "public enum HttpMethod\n{\n ALL(\"\"),\n GET(\"GET\"),\n POST(\"POST\"),\n PUT(\"PUT\"),\n DELETE(\"DELETE\");\n\n private String stringValue;\n\n HttpMethod(String stringValue)\n {\n this.stringValue = stringValue;\n }\n\n @Override\n public String toString()\n {\n ...
import org.apache.log4j.Logger; import com.kdgregory.pathfinder.core.HttpMethod; import com.kdgregory.pathfinder.core.Inspector; import com.kdgregory.pathfinder.core.PathRepo; import com.kdgregory.pathfinder.core.WarMachine; import com.kdgregory.pathfinder.core.WarMachine.ServletMapping;
// Copyright (c) Keith D Gregory // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.kdgregory.pathfinder.servlet; public class ServletInspector implements Inspector { private Logger logger = Logger.getLogger(getClass()); //---------------------------------------------------------------------------- // Inspector //---------------------------------------------------------------------------- @Override
public void inspect(WarMachine war, PathRepo paths)
3
WojciechZankowski/iextrading4j-hist
iextrading4j-hist-test/src/test/java/pl/zankowski/iextrading4j/hist/test/message/IEXSecurityDirectoryMessageTest.java
[ "public enum IEXMessageType implements IEXByteEnum {\n\n QUOTE_UPDATE((byte) 0x51),\n TRADE_REPORT((byte) 0x54),\n TRADE_BREAK((byte) 0x42),\n SYSTEM_EVENT((byte) 0x53),\n SECURITY_DIRECTORY((byte) 0x44),\n TRADING_STATUS((byte) 0x48),\n OPERATIONAL_HALT_STATUS((byte) 0x4f),\n SHORT_SALE_PRI...
import org.junit.jupiter.api.Test; import pl.zankowski.iextrading4j.hist.api.IEXMessageType; import pl.zankowski.iextrading4j.hist.api.field.IEXPrice; import pl.zankowski.iextrading4j.hist.api.message.administrative.IEXSecurityDirectoryMessage; import pl.zankowski.iextrading4j.hist.api.message.administrative.field.IEXLULDTier; import pl.zankowski.iextrading4j.hist.test.ExtendedUnitTestBase; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; import static pl.zankowski.iextrading4j.hist.api.message.administrative.IEXSecurityDirectoryMessage.createIEXMessage;
package pl.zankowski.iextrading4j.hist.test.message; class IEXSecurityDirectoryMessageTest extends ExtendedUnitTestBase { @Test void testIEXSecurityDirectoryMessage() throws IOException { final byte[] packet = loadPacket("IEXSecurityDirectoryMessage.dump"); final IEXSecurityDirectoryMessage message = createIEXMessage(packet); assertThat(message.getMessageType()).isEqualTo(IEXMessageType.SECURITY_DIRECTORY); assertThat(message.getTimestamp()).isEqualTo(1509795046090464161L); assertThat(message.getSymbol()).isEqualTo("ZEXIT"); assertThat(message.getRoundLotSize()).isEqualTo(100);
assertThat(message.getAdjustedPOCPrice()).isEqualTo(new IEXPrice(100000));
1
presidentio/teamcity-plugin-jmh
teamcity-plugin-jmh-common/src/main/java/com/presidentio/teamcity/jmh/runner/common/param/RunnerParamProvider.java
[ "public class TimeUnitConst {\n\n public static final String DEFAULT = \"default\";\n public static final String MINUTES = \"m\";\n public static final String SECONDS = \"s\";\n public static final String MILLISECONDS = \"ms\";\n public static final String MICROSECONDS = \"us\";\n public static fi...
import com.presidentio.teamcity.jmh.runner.common.cons.TimeUnitConst; import com.presidentio.teamcity.jmh.runner.common.cons.VerboseModeConst; import com.presidentio.teamcity.jmh.runner.common.cons.WarmupModeConst; import java.util.Collection; import java.util.HashMap; import static com.presidentio.teamcity.jmh.runner.common.cons.ModeConst.MODES_WITH_DESCRIPTION; import static com.presidentio.teamcity.jmh.runner.common.cons.SettingsConst.*;
/** * Copyright 2015 presidentio * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.presidentio.teamcity.jmh.runner.common.param; /** * Created by presidentio on 12.05.15. */ public class RunnerParamProvider { private static final HashMap<String, RunnerParam> ALL = new HashMap<>(); static { ALL.put(PROP_BENCHMARKS, new BaseRunnerParam(PROP_BENCHMARKS, "", false, "Benchmarks", "Benchmarks to run (regexp+).")); ALL.put(PROP_MODE, new SelectRunnerParameter(MODES_WITH_DESCRIPTION, PROP_MODE, "-bm", false, "Benchmark mode", "Benchmark mode.")); ALL.put(PROP_BATCH_SIZE, new IntRunnerParam(PROP_BATCH_SIZE, "-bs", false, "Batch size", "Number of benchmark method calls per operation. (some benchmark modes can ignore this setting)", 0)); ALL.put(PROP_EXCLUDE, new BaseRunnerParam(PROP_EXCLUDE, "-e", false, "Exclude", "Benchmarks to exclude from the run.")); ALL.put(PROP_FORKS, new IntRunnerParam(PROP_FORKS, "-f", false, "Forks", "How many times to forks a single benchmark. Use 0 to disable forking altogether (WARNING: disabling " + "forking may have detrimental impact on benchmark and infrastructure reliability, you might want " + "to use different warmup mode instead).", 0)); ALL.put(PROP_FAIL_ON_ERROR, new BoolRunnerParam(PROP_FAIL_ON_ERROR, "-foe", false, "Fail on error", "Should JMH fail immediately if any benchmark had experienced the unrecoverable error?")); ALL.put(PROP_GC, new BoolRunnerParam(PROP_GC, "-gc", false, "Force GC", "Should JMH force GC between iterations?")); ALL.put(PROP_MEASUREMENT_ITERATIONS, new IntRunnerParam(PROP_MEASUREMENT_ITERATIONS, "-i", false, "Iterations", "Number of measurement iterations to do.", 0)); ALL.put(PROP_JVM, new BaseRunnerParam(PROP_JVM, "-jvm", false, "Custom JVM", "Custom JVM to use when forking (path to JVM executable).")); ALL.put(PROP_JVM_ARGS, new BaseRunnerParam(PROP_JVM_ARGS, "-jvmArgs", false, "Custom JVM args", "Custom JVM args to use when forking.")); ALL.put(PROP_JVM_ARGS_APPEND, new BaseRunnerParam(PROP_JVM_ARGS_APPEND, "-jvmArgsAppend", false, "Custom JVM args append", "Custom JVM args to use when forking (append these)")); ALL.put(PROP_JVM_ARGS_PREPEND, new BaseRunnerParam(PROP_JVM_ARGS_PREPEND, "-jvmArgsPrepend", false, "Custom JVM args prepend", "Custom JVM args to use when forking (prepend these)")); ALL.put(PROP_OPERATIONS_PER_INVOCATION, new IntRunnerParam(PROP_OPERATIONS_PER_INVOCATION, "-opi", false, "Operations", "Operations per invocation.", 0)); ALL.put(PROP_BENCHMARK_PARAMETERS, new BaseRunnerParam(PROP_BENCHMARK_PARAMETERS, "-p", false, "Benchmark parameters", "This option is expected to be used once per parameter. Parameter name and " + "parameter values should be separated with equals sign. Parameter values should be separated with commas.")); ALL.put(PROP_PROFILERS, new BaseRunnerParam(PROP_PROFILERS, "-prof", false, "Profilers", "Use profilers to collect additional data.")); ALL.put(PROP_TIME_PER_MEASUREMENT, new BaseRunnerParam(PROP_TIME_PER_MEASUREMENT, "-r", false, "Measurement time", "Time to spend at each measurement iteration. Arguments accept time suffixes, like \"100ms\".")); ALL.put(PROP_SYNCHRONIZE, new BoolRunnerParam(PROP_SYNCHRONIZE, "-si", false, "Synchronized", "Synchronize iterations?")); ALL.put(PROP_THREADS, new IntRunnerParam(PROP_THREADS, "-t", false, "Threads", "Number of worker threads to run with.", 0)); ALL.put(PROP_THREAD_DISTRIBUTION, new BaseRunnerParam(PROP_THREAD_DISTRIBUTION, "-tg", false, "Thread group distribution", "Override thread group distribution for asymmetric benchmarks.")); ALL.put(PROP_TIMEOUT, new BaseRunnerParam(PROP_TIMEOUT, "-to", false, "Timeout", "Timeout for benchmark iteration. Arguments accept time suffixes, like \"100ms\".")); ALL.put(PROP_TIME_UNIT, new SelectRunnerParameter(TimeUnitConst.TIME_UNITS_WITH_DESCRIPTION, PROP_TIME_UNIT, "-tu", false, "Time unit", "Output time unit. Available time units are: [m, s, ms, us, ns].")); ALL.put(PROP_VERBOSITY, new SelectRunnerParameter(VerboseModeConst.ALL_WITH_DESCRIPTION, PROP_VERBOSITY, "-v", false, "Verbosity", "Verbosity mode. Available modes are: [SILENT, NORMAL, EXTRA]")); ALL.put(PROP_TIME_PER_WARMUP, new BaseRunnerParam(PROP_TIME_PER_WARMUP, "-w", false, "Warmup time", "Time to spend at each warmup iteration. Arguments accept time suffixes, like \"100ms\".")); ALL.put(PROP_WARMUP_BATCH_SIZE, new IntRunnerParam(PROP_WARMUP_BATCH_SIZE, "-wbs", false, "Warmup batch size", "Warmup batch size: number of benchmark method calls per operation. " + "(some benchmark modes can ignore this setting)", 0)); ALL.put(PROP_WARMUP_FORKS, new IntRunnerParam(PROP_WARMUP_FORKS, "-wf", false, "Warmup forks", "How many warmup forks to make for a single benchmark. 0 to disable warmup forks.", 0)); ALL.put(PROP_WARMUP_ITERATIONS, new IntRunnerParam(PROP_WARMUP_ITERATIONS, "-wi", false, "Warmup iterations", "Number of warmup iterations to do.", 0));
ALL.put(PROP_WARMUP_MODE, new SelectRunnerParameter(WarmupModeConst.ALL_WITH_DESCRIPTION, PROP_WARMUP_MODE,
2
vert-x3/vertx-jdbc-client
src/main/java/examples/JDBCTypeExamples.java
[ "@VertxGen\npublic interface JDBCClient extends SQLClient {\n\n /**\n * The default data source provider is C3P0\n */\n String DEFAULT_PROVIDER_CLASS = \"io.vertx.ext.jdbc.spi.impl.C3P0DataSourceProvider\";\n\n /**\n * The name of the default data source\n */\n String DEFAULT_DS_NAME = \"DEFAULT_DS\";\...
import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.docgen.Source; import io.vertx.ext.jdbc.JDBCClient; import io.vertx.ext.jdbc.spi.DataSourceProvider; import io.vertx.ext.jdbc.spi.JDBCDecoder; import io.vertx.ext.jdbc.spi.JDBCEncoder; import io.vertx.ext.jdbc.spi.impl.JDBCEncoderImpl; import io.vertx.jdbcclient.JDBCConnectOptions; import io.vertx.jdbcclient.JDBCPool; import io.vertx.jdbcclient.impl.AgroalCPDataSourceProvider; import io.vertx.jdbcclient.impl.actions.JDBCColumnDescriptor; import io.vertx.sqlclient.PoolOptions; import java.sql.Date; import java.sql.JDBCType; import java.time.LocalDate;
package examples; @Source public class JDBCTypeExamples { public static class DerbyEncoder extends JDBCEncoderImpl { @Override protected Object encodeDateTime(JDBCColumnDescriptor descriptor, Object value) { Object v = super.encodeDateTime(descriptor, value); if (descriptor.jdbcType() == JDBCType.DATE) { return Date.valueOf((LocalDate) v); } return v; } } public JDBCClient createJDBCClient(Vertx vertx, Class<JDBCEncoder> encoderClass, Class<JDBCDecoder> decoderClass) { JsonObject options = new JsonObject().put("url", "your_jdbc_url") .put("user", "your_database_user") .put("password", "your_database_password") .put("encoderCls", encoderClass.getName()) .put("decoderCls", decoderClass.getName()); return JDBCClient.createShared(vertx, options); } public JDBCPool createJDBCPool(Vertx vertx, Class<JDBCEncoder> encoderClass, Class<JDBCDecoder> decoderClass) { JsonObject extraOptions = new JsonObject() .put("encoderCls", encoderClass.getName()) .put("decoderCls", decoderClass.getName()); JDBCConnectOptions options = new JDBCConnectOptions().setJdbcUrl("your_jdbc_url") .setUser("your_database_user") .setPassword("your_database_password"); PoolOptions poolOptions = new PoolOptions().setMaxSize(1);
DataSourceProvider provider = new AgroalCPDataSourceProvider(options, poolOptions).init(extraOptions);
7
yuqirong/NewsPublish
src/com/cjlu/newspublish/services/impl/AdminServiceImpl.java
[ "@Repository(\"adminDao\")\npublic class AdminDaoImpl extends BaseDaoImpl<Admin> {\n\n\tpublic Admin isAdmin(String username, String password) {\n\t\tString hql = \"FROM Admin WHERE username = ? AND password= ?\";\n\t\tAdmin admin = (Admin) getSession().createQuery(hql).setString(0, username)\n\t\t\t\t.setString(1,...
import java.util.Date; import java.util.HashSet; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjlu.newspublish.daos.impl.AdminDaoImpl; import com.cjlu.newspublish.models.security.Admin; import com.cjlu.newspublish.models.security.Role; import com.cjlu.newspublish.services.AdminService; import com.cjlu.newspublish.services.RoleService; import com.cjlu.newspublish.utils.ValidateUtils;
package com.cjlu.newspublish.services.impl; @Service("adminService") public class AdminServiceImpl extends BaseServiceImpl<Admin> implements AdminService { @Autowired
private AdminDaoImpl adminDao;
0
mattbrejza/rtty_modem
rtty_dev/src/rttywin.java
[ "public class Gps_coordinate implements java.io.Serializable {\r\n\r\n\tprivate static final long serialVersionUID = 0x5901fa8c0e38abb4L;\r\n\t\r\n\tpublic double latitude = 0;\r\n\tpublic double longitude = 0;\r\n\tpublic boolean latlong_valid = false;\r\n\t\r\n\tpublic double altitude = 0;\r\n\tpublic boolean alt...
import java.awt.EventQueue; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.Mixer; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import org.math.plot.*; import edu.emory.mathcs.jtransforms.fft.*; import graphics.Waterfall; import ukhas.Gps_coordinate; import ukhas.Habitat_interface; import ukhas.Listener; import rtty.StringRxEvent; import rtty.fsk_receiver; import ukhas.Telemetry_string; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JTextField; import javax.swing.SwingConstants;
// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. //import rtty.Mappoint_interface; public class rttywin extends JFrame implements StringRxEvent { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; AudioFormat audioFormat; TargetDataLine targetDataLine; private String _habitat_url = "habitat.habhub.org"; private String _habitat_db = "habitat"; boolean stopCapture = false; ByteArrayOutputStream byteArrayOutputStream; Waterfall wf; AudioInputStream audioInputStream; SourceDataLine sourceDataLine; //rtty_decode decoder = new rtty_decode(1200,1800,7); fsk_receiver rcv = new fsk_receiver(); DoubleFFT_1D ft = new DoubleFFT_1D(512); //private graph_line grtty = new graph_line(); Plot2DPanel plot = new Plot2DPanel(); int plotint; JLabel lb_freqs; JTextArea txtDecode; JLabel lbfreq; JScrollPane scrollPane; JCheckBox ckFreeze; @SuppressWarnings("rawtypes") JComboBox cbSoundCard; JCheckBox ck300b; JLabel lbStatus; JLabel lbimage; JCheckBox chkOnline; private JCheckBox ckPause; Habitat_interface hi;// = new Habitat_interface("MATT"); private JTextField txtcall = new JTextField(); private JTextField txtLat; private JTextField txtLong;; // graph_line grtty = new graph_line(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { rttywin frame = new rttywin(); frame.setVisible(true); Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); //Output Available Mixers System.out.println("Available mixers:"); for(int cnt = 0; cnt < mixerInfo.length; cnt++){ System.out.println(cnt + ": " + mixerInfo[cnt].getName()); } } catch (Exception e) { e.printStackTrace(); } } }); } public void StringRx(Telemetry_string str, boolean checksum) { } /** * Create the frame. */ public rttywin() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 546, 628); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); rcv.addStringRecievedListener(this); try { Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); //Output Available Mixers System.out.println("Available mixers:"); String[] devices = new String[mixerInfo.length]; for(int cnt = 0; cnt < mixerInfo.length; cnt++){ devices[cnt] = mixerInfo[cnt].getName(); } cbSoundCard = new JComboBox<Object>(devices); cbSoundCard.setBounds(269, 27, 208, 20); contentPane.add(cbSoundCard); BufferedImage grad; grad = ImageIO.read(new File("C:/grad.png")); wf = new Waterfall(grad,200); } catch (Exception e) { e.printStackTrace(); } JButton btnStart = new JButton("New button"); btnStart.setEnabled(false); btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); btnStart.setBounds(50, 103, 89, 23); contentPane.add(btnStart); JButton btnStop = new JButton("New button"); btnStop.setEnabled(false); btnStop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { targetDataLine.stop(); targetDataLine.close(); } }); btnStop.setBounds(149, 103, 89, 23); contentPane.add(btnStop); JButton btnStartst = new JButton("GO!"); btnStartst.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
hi = new Habitat_interface(_habitat_url, _habitat_db, new Listener(txtcall.getText(), new Gps_coordinate(txtLat.getText(), txtLong.getText(),"0"),false));
0
Vrael/eManga
app/src/main/java/com/emanga/emanga/app/adapters/MangaItemListAdapter.java
[ "public class ImageCacheManager {\n\n /**\n * Volley recommends in-memory L1 cache but both a disk and memory cache are provided.\n * Volley includes a L2 disk cache out of the box but you can technically use a disk cache as an L1 cache provided\n * you can live with potential i/o blocking.\n *\n...
import android.content.Context; import android.os.AsyncTask; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AlphabetIndexer; import android.widget.BaseAdapter; import android.widget.SectionIndexer; import android.widget.TextView; import com.android.volley.toolbox.ImageLoader; import com.emanga.emanga.app.R; import com.emanga.emanga.app.cache.ImageCacheManager; import com.emanga.emanga.app.database.DatabaseHelper; import com.emanga.emanga.app.listeners.CoverListener; import com.emanga.emanga.app.models.Genre; import com.emanga.emanga.app.models.Manga; import com.emanga.emanga.app.utils.CustomNetworkImageView; import com.j256.ormlite.android.AndroidDatabaseResults; import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.dao.CloseableIterator; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; import org.apache.commons.lang.WordUtils; import java.sql.SQLException; import java.util.List;
package com.emanga.emanga.app.adapters; /** * Created by Ciro on 25/05/2014. */ public class MangaItemListAdapter extends BaseAdapter implements SectionIndexer{ private static String sections = " -0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private AlphabetIndexer mAlphabetIndexer; private Context mContext; private ImageLoader mImageLoader; private DatabaseHelper databaseHelper; private CloseableIterator<Manga> itMangas; private AndroidDatabaseResults mMangas; private PreparedQuery<Manga> mangaQuery = null; public MangaItemListAdapter(Context context){ super(); mContext = context; mImageLoader = ImageCacheManager.getInstance().getImageLoader(); databaseHelper = OpenHelperManager.getHelper(mContext, DatabaseHelper.class); try{ mangaQuery = makeMangasQuery(); reload(); } catch (SQLException e){ e.printStackTrace(); } } private PreparedQuery<Manga> makeMangasQuery() throws SQLException { QueryBuilder<Manga,String> mangaQb = databaseHelper.getMangaRunDao().queryBuilder(); mangaQb.orderBy(Manga.TITLE_COLUMN_NAME, true); return mangaQb.prepare(); } public void reload(){ if(itMangas != null){ itMangas.closeQuietly(); } try{ itMangas = databaseHelper.getMangaRunDao().iterator(mangaQuery); mMangas = (AndroidDatabaseResults) itMangas.getRawResults(); mAlphabetIndexer = new AlphabetIndexer(mMangas.getRawCursor(), mMangas.findColumn(Manga.TITLE_COLUMN_NAME), sections); } catch (SQLException e){ e.printStackTrace(); } } public void destroy(){ if(databaseHelper != null) { OpenHelperManager.releaseHelper(); databaseHelper = null; } if(itMangas != null){ itMangas.closeQuietly(); itMangas = null; mMangas = null; } } @Override public int getPositionForSection(int section) { return mAlphabetIndexer.getPositionForSection(section); } @Override public int getSectionForPosition(int position) { return mAlphabetIndexer.getSectionForPosition(position); } @Override public Object[] getSections() { String[] sectionsArr = new String[sections.length()]; for (int i=0; i < sections.length(); i++) sectionsArr[i] = "" + sections.charAt(i); return sectionsArr; } @Override public int getCount() { return mMangas.getCount(); } @Override public Manga getItem(int position) { mMangas.moveAbsolute(position); try { return itMangas.current(); } catch (SQLException e) { e.printStackTrace(); } return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; Manga manga = getItem(position); // if it's not recycled, initialize some attributes if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.manga_item_list, parent, false); holder = new ViewHolder(); holder.title = (TextView) convertView.findViewById(R.id.manga_list_title); holder.cover = (CustomNetworkImageView) convertView.findViewById(R.id.manga_list_cover); holder.categories = (TextView) convertView.findViewById(R.id.manga_list_categories); holder.cover.setErrorImageResId(R.drawable.empty_cover); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.title.setText(manga.title.toUpperCase()); new AsyncTask<Manga, Void, Manga>(){ @Override protected Manga doInBackground(Manga... manga) { try { manga[0].genres = databaseHelper.genresForManga(manga[0]); } catch (SQLException e) { e.printStackTrace(); } return manga[0]; } @Override protected void onPostExecute(Manga manga){ holder.categories.setText(manga.genres != null? MangaItemListAdapter.toString(manga.genres) : ""); } }.execute(manga);
holder.cover.setImageUrl(manga.cover, mImageLoader, new CoverListener(manga.cover, holder.cover));
2
cdancy/artifactory-rest
src/test/java/com/cdancy/artifactory/rest/features/ArtifactApiLiveTest.java
[ "public static void assertFalse(boolean value) {\n assertThat(value).isFalse();\n}", "public static void assertNotNull(Object value) {\n assertThat(value).isNotNull();\n}", "public static void assertTrue(boolean value) {\n assertThat(value).isTrue();\n}", "@Test(groups = \"live\")\npublic class BaseA...
import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.cdancy.artifactory.rest.TestUtilities.assertFalse; import static com.cdancy.artifactory.rest.TestUtilities.assertNotNull; import static com.cdancy.artifactory.rest.TestUtilities.assertTrue; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import com.cdancy.artifactory.rest.BaseArtifactoryApiLiveTest; import com.cdancy.artifactory.rest.domain.artifact.Artifact; import com.cdancy.artifactory.rest.domain.error.RequestStatus; import com.google.common.collect.Lists; import org.jclouds.io.Payloads;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cdancy.artifactory.rest.features; @Test(groups = "live", testName = "ArtifactApiLiveTest") public class ArtifactApiLiveTest extends BaseArtifactoryApiLiveTest { private File tempArtifact; private String repoKey = "libs-snapshot-local"; private String repoReleaseKey = "ext-snapshot-local"; private String itemPath; private String itemPathWithProperties; private Map<String, List<String>> itemProperties = new HashMap<>(); @BeforeClass public void testInitialize() { tempArtifact = randomFile(); itemPath = randomPath(); itemPathWithProperties = randomPath(); itemProperties.put("key1", Lists.newArrayList("value1")); itemProperties.put("key2", Lists.newArrayList("value2")); itemProperties.put("key3", Lists.newArrayList("value3")); } @Test public void testDeployArtifact() { Artifact artifact = api().deployArtifact(repoKey, itemPath + "/" + tempArtifact.getName(), Payloads.newPayload(tempArtifact), null); assertNotNull(artifact);
assertTrue(artifact.repo().equals(repoKey));
2
tobyweston/tempus-fugit
src/test/java/com/google/code/tempusfugit/concurrency/AbstractConcurrentTestRunnerTest.java
[ "public interface Condition {\n boolean isSatisfied();\n}", "protected final static int CONCURRENT_COUNT = 3;", "public static Duration seconds(long seconds) {\n validate(seconds, TimeUnit.SECONDS);\n return new Duration(seconds, TimeUnit.SECONDS);\n}", "public static Timeout timeout(Duration duratio...
import static java.util.Collections.synchronizedSet; import static junit.framework.Assert.fail; import com.google.code.tempusfugit.concurrency.annotations.Concurrent; import com.google.code.tempusfugit.temporal.Condition; import junit.framework.AssertionFailedError; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeoutException; import static com.google.code.tempusfugit.concurrency.AbstractConcurrentTestRunnerTest.CONCURRENT_COUNT; import static com.google.code.tempusfugit.temporal.Duration.seconds; import static com.google.code.tempusfugit.temporal.Timeout.timeout; import static com.google.code.tempusfugit.temporal.WaitFor.waitOrTimeout;
/* * Copyright (c) 2009-2018, toby weston & tempus-fugit committers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.code.tempusfugit.concurrency; @RunWith(ConcurrentTestRunner.class) @Concurrent(count = CONCURRENT_COUNT) public abstract class AbstractConcurrentTestRunnerTest { protected final static int CONCURRENT_COUNT = 3; protected static final Set<String> THREADS = synchronizedSet(new HashSet<>()); @Test public void shouldRunInParallel1() throws TimeoutException, InterruptedException { logCurrentThread(); } @Test public void shouldRunInParallel2() throws TimeoutException, InterruptedException { logCurrentThread(); } @Test public void shouldRunInParallel3() throws TimeoutException, InterruptedException { logCurrentThread(); } @Test public void shouldRunInParallel4() throws TimeoutException, InterruptedException { logCurrentThread(); } @Test public void shouldRunInParallel5() throws TimeoutException, InterruptedException { logCurrentThread(); } private void logCurrentThread() throws TimeoutException, InterruptedException { THREADS.add(Thread.currentThread().getName()); waitToForceCachedThreadPoolToCreateNewThread(); } private void waitToForceCachedThreadPoolToCreateNewThread() throws InterruptedException, TimeoutException {
waitOrTimeout(() -> THREADS.size() == getConcurrentCount(), timeout(seconds(1)));
2
52North/SensorPlanningService
52n-sps-api/src/test/java/org/n52/sps/util/nodb/InMemorySensorConfigurationRepositoryTest.java
[ "public abstract class SensorPlugin implements ResultAccessAvailabilityDescriptor, ResultAccessServiceReference {\r\n\r\n protected SensorConfiguration configuration;\r\n\r\n protected SensorTaskService sensorTaskService;\r\n \r\n protected SensorPlugin() {\r\n // allow default constructor for de...
import org.junit.Test; import org.n52.sps.sensor.SensorPlugin; import org.n52.sps.sensor.SimpleSensorPluginTestInstance; import org.n52.sps.sensor.model.SensorConfiguration; import org.n52.sps.service.InternalServiceException; import org.n52.sps.store.SensorConfigurationRepository; import org.n52.sps.util.nodb.InMemorySensorConfigurationRepository; import static org.junit.Assert.*; import org.junit.Before;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package org.n52.sps.util.nodb; public class InMemorySensorConfigurationRepositoryTest { private SensorConfigurationRepository repository; @Before public void setUp() { repository = new InMemorySensorConfigurationRepository(); } @Test public void testCreateNewInstance() throws InternalServiceException { SensorPlugin testInstance = SimpleSensorPluginTestInstance.createInstance();
SensorConfiguration sensorConfiguration = testInstance.getSensorConfiguration();
2
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/PrismojiPopup.java
[ "public final class Emoji implements Serializable {\n private static final long serialVersionUID = 3L;\n\n @NonNull\n private final String unicode;\n @DrawableRes\n private final int resource;\n @NonNull\n private List<Emoji> variants;\n @SuppressWarnings(\"PMD.ImmutableField\")\n @Nullab...
import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.View; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.PopupWindow; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.listeners.OnEmojiBackspaceClickListener; import com.apradanas.prismoji.listeners.OnEmojiClickedListener; import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener; import com.apradanas.prismoji.listeners.OnEmojiPopupDismissListener; import com.apradanas.prismoji.listeners.OnEmojiPopupShownListener; import com.apradanas.prismoji.listeners.OnSoftKeyboardCloseListener; import com.apradanas.prismoji.listeners.OnSoftKeyboardOpenListener; import static com.apradanas.prismoji.Utils.checkNotNull;
package com.apradanas.prismoji; public final class PrismojiPopup { private static final int MIN_KEYBOARD_HEIGHT = 100; final View rootView; final Context context; @NonNull final RecentEmoji recentEmoji; @NonNull final PrismojiVariantPopup variantPopup; final PopupWindow popupWindow; private final PrismojiEditText prismojiEditText; private final PrismojiAutocompleteTextView prismojiAutocompleteTextView; int keyBoardHeight; boolean isPendingOpen; boolean isKeyboardOpen; @Nullable OnEmojiPopupShownListener onEmojiPopupShownListener; @Nullable OnSoftKeyboardCloseListener onSoftKeyboardCloseListener; @Nullable
OnSoftKeyboardOpenListener onSoftKeyboardOpenListener;
7
TalkingData/Myna
Android/lib-Myna/src/main/java/com/talkingdata/myna/MynaTrainTest.java
[ "public class Feature {\n private int batchSize;\n private SensorFeature feature;\n\n public Feature() {\n feature = new SensorFeature();\n batchSize = 0;\n }\n\n /**\n * Get selected feature\n * @return selected feature\n */\n public SensorFeature getSelectedFeatures(){\...
import android.content.Context; import android.os.Environment; import android.util.Log; import android.util.SparseArray; import android.util.SparseIntArray; import com.talkingdata.myna.sensor.Feature; import com.talkingdata.myna.sensor.SensorData; import com.talkingdata.myna.sensor.SensorFeature; import com.talkingdata.myna.tools.Utils; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Arrays; import java.util.Locale; import dice.data.Instances; import dice.data.io.ArffReader; import dice.tree.builder.TreeBuilder; import dice.tree.structure.Node;
package com.talkingdata.myna; class MynaTrainTest { private MynaTrainTestCallback ttcallback; private Context context; private int attrSize = 30; private int labelNum = 6; private int maxS = 10; private int treeNum = 3; private int maxTreeDepth = 15; private Node[] trees = new Node[treeNum]; private SparseArray<Feature> rfFeatures = new SparseArray<>(); private SparseIntArray rfLabels = new SparseIntArray();
private SensorData[] periodVal;
1
Spedge/hangar
hangar-api/src/main/java/com/spedge/hangar/index/memory/InMemoryIndex.java
[ "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \"index\")\n@JsonSubTypes(\n { \n @JsonSubTypes.Type(value = InMemoryIndex.class, name = \"in-memory\"),\n @JsonSubTypes.Type(value = ZooKeeperIndex.class, name = \"zookeeper\"), \n })\npublic interface IIndex\n{\n\n /**\n * Confirms t...
import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.spedge.hangar.index.IIndex; import com.spedge.hangar.index.IndexArtifact; import com.spedge.hangar.index.IndexConfictException; import com.spedge.hangar.index.IndexException; import com.spedge.hangar.index.IndexKey; import com.spedge.hangar.index.ReservedArtifact; import com.spedge.hangar.repo.RepositoryType; import com.spedge.hangar.storage.IStorage; import com.spedge.hangar.storage.StorageException;
package com.spedge.hangar.index.memory; public class InMemoryIndex implements IIndex { private Map<String, IndexArtifact> index; protected final Logger logger = LoggerFactory.getLogger(InMemoryIndex.class); public InMemoryIndex() { this.index = new HashMap<String, IndexArtifact>(); } public boolean isArtifact(IndexKey key) { return index.containsKey(key.toString()); } /** * Registers an Artifact with the Index. */ public void addArtifact(IndexKey key, IndexArtifact artifact) throws IndexConfictException { if (index.containsKey(key.toString())) {
if (!(index.get(key.toString()) instanceof ReservedArtifact))
5
xuxueli/xxl-api
xxl-api-admin/src/main/java/com/xxl/api/admin/controller/XxlApiDocumentController.java
[ "public class RequestConfig {\n\n /**\n * Request Method\n */\n public enum RequestMethodEnum {\n POST,GET,PUT,DELETE,HEAD,OPTIONS,PATCH;\n }\n\n /**\n * Request Headers\n */\n public static List<String> requestHeadersEnum = new LinkedList<String>();\n static {\n req...
import com.xxl.api.admin.core.consistant.RequestConfig; import com.xxl.api.admin.core.model.*; import com.xxl.api.admin.core.util.tool.ArrayTool; import com.xxl.api.admin.core.util.JacksonUtil; import com.xxl.api.admin.core.util.tool.StringTool; import com.xxl.api.admin.dao.*; import com.xxl.api.admin.service.IXxlApiDataTypeService; import com.xxl.api.admin.service.impl.LoginService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.List;
package com.xxl.api.admin.controller; /** * @author xuxueli 2017-03-31 18:10:37 */ @Controller @RequestMapping("/document") public class XxlApiDocumentController { @Resource private IXxlApiDocumentDao xxlApiDocumentDao; @Resource private IXxlApiProjectDao xxlApiProjectDao; @Resource private IXxlApiGroupDao xxlApiGroupDao; @Resource private IXxlApiMockDao xxlApiMockDao; @Resource private IXxlApiTestHistoryDao xxlApiTestHistoryDao; @Resource private IXxlApiDataTypeService xxlApiDataTypeService; private boolean hasBizPermission(HttpServletRequest request, int bizId){ XxlApiUser loginUser = (XxlApiUser) request.getAttribute(LoginService.LOGIN_IDENTITY); if ( loginUser.getType()==1 || ArrayTool.contains(StringTool.split(loginUser.getPermissionBiz(), ","), String.valueOf(bizId)) ) { return true; } else { return false; } } @RequestMapping("/markStar") @ResponseBody public ReturnT<String> markStar(HttpServletRequest request, int id, int starLevel) { XxlApiDocument document = xxlApiDocumentDao.load(id); if (document == null) { return new ReturnT<String>(ReturnT.FAIL_CODE, "操作失败,接口ID非法"); } // 权限 XxlApiProject apiProject = xxlApiProjectDao.load(document.getProjectId()); if (!hasBizPermission(request, apiProject.getBizId())) { return new ReturnT<String>(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通"); } document.setStarLevel(starLevel); int ret = xxlApiDocumentDao.update(document); return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL; } @RequestMapping("/delete") @ResponseBody public ReturnT<String> delete(HttpServletRequest request, int id) { XxlApiDocument document = xxlApiDocumentDao.load(id); if (document == null) { return new ReturnT<String>(ReturnT.FAIL_CODE, "操作失败,接口ID非法"); } // 权限 XxlApiProject apiProject = xxlApiProjectDao.load(document.getProjectId()); if (!hasBizPermission(request, apiProject.getBizId())) { return new ReturnT<String>(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通"); } // 存在Test记录,拒绝删除 List<XxlApiTestHistory> historyList = xxlApiTestHistoryDao.loadByDocumentId(id); if (historyList!=null && historyList.size()>0) { return new ReturnT<String>(ReturnT.FAIL_CODE, "拒绝删除,该接口下存在Test记录,不允许删除"); } // 存在Mock记录,拒绝删除 List<XxlApiMock> mockList = xxlApiMockDao.loadAll(id); if (mockList!=null && mockList.size()>0) { return new ReturnT<String>(ReturnT.FAIL_CODE, "拒绝删除,该接口下存在Mock记录,不允许删除"); } int ret = xxlApiDocumentDao.delete(id); return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL; } /** * 新增,API * * @param projectId * @return */ @RequestMapping("/addPage") public String addPage(HttpServletRequest request, Model model, int projectId, @RequestParam(required = false, defaultValue = "0") int groupId) { // project XxlApiProject project = xxlApiProjectDao.load(projectId); if (project == null) { throw new RuntimeException("操作失败,项目ID非法"); } model.addAttribute("projectId", projectId); model.addAttribute("groupId", groupId); // 权限 if (!hasBizPermission(request, project.getBizId())) { throw new RuntimeException("您没有相关业务线的权限,请联系管理员开通"); } // groupList List<XxlApiGroup> groupList = xxlApiGroupDao.loadAll(projectId); model.addAttribute("groupList", groupList); // enum model.addAttribute("RequestMethodEnum", RequestConfig.RequestMethodEnum.values()); model.addAttribute("requestHeadersEnum", RequestConfig.requestHeadersEnum); model.addAttribute("QueryParamTypeEnum", RequestConfig.QueryParamTypeEnum.values()); model.addAttribute("ResponseContentType", RequestConfig.ResponseContentType.values()); return "document/document.add"; } @RequestMapping("/add") @ResponseBody public ReturnT<Integer> add(HttpServletRequest request, XxlApiDocument xxlApiDocument) { XxlApiProject project = xxlApiProjectDao.load(xxlApiDocument.getProjectId()); if (project == null) { return new ReturnT<Integer>(ReturnT.FAIL_CODE, "操作失败,项目ID非法"); } // 权限 if (!hasBizPermission(request, project.getBizId())) { return new ReturnT<Integer>(ReturnT.FAIL_CODE, "您没有相关业务线的权限,请联系管理员开通"); } int ret = xxlApiDocumentDao.add(xxlApiDocument); return (ret>0)?new ReturnT<Integer>(xxlApiDocument.getId()):new ReturnT<Integer>(ReturnT.FAIL_CODE, null); } /** * 更新,API * @return */ @RequestMapping("/updatePage") public String updatePage(HttpServletRequest request, Model model, int id) { // document XxlApiDocument xxlApiDocument = xxlApiDocumentDao.load(id); if (xxlApiDocument == null) { throw new RuntimeException("操作失败,接口ID非法"); } model.addAttribute("document", xxlApiDocument);
model.addAttribute("requestHeadersList", (StringTool.isNotBlank(xxlApiDocument.getRequestHeaders()))?JacksonUtil.readValue(xxlApiDocument.getRequestHeaders(), List.class):null );
2
AfterLifeLochie/fontbox
src/main/java/net/afterlifelochie/fontbox/document/Paragraph.java
[ "public interface ITracer {\r\n\r\n\t/**\r\n\t * <p>\r\n\t * Called by Fontbox to trace a particular event to the tracer.\r\n\t * </p>\r\n\t * <p>\r\n\t * Events triggered usually take the following parameter forms:\r\n\t * <ol>\r\n\t * <li>The method name being invoked (the source)</li>\r\n\t * <li>The return argu...
import java.io.IOException; import net.afterlifelochie.fontbox.api.ITracer; import net.afterlifelochie.fontbox.data.FormattedString; import net.afterlifelochie.fontbox.document.property.AlignmentMode; import net.afterlifelochie.fontbox.layout.LayoutException; import net.afterlifelochie.fontbox.layout.PageWriter; import net.afterlifelochie.fontbox.layout.components.Page; import net.afterlifelochie.fontbox.render.BookGUI;
package net.afterlifelochie.fontbox.document; public class Paragraph extends Element { public FormattedString text; public AlignmentMode align; /** * Create a new paragraph with a specified text and the default alignment * (justified). * * @param text * The text */ public Paragraph(FormattedString text) { this(text, AlignmentMode.JUSTIFY); } /** * Create a new paragraph with the specified properties. * * @param text * The text * @param align * The alignment mode */ public Paragraph(FormattedString text, AlignmentMode align) { this.text = text; this.align = align; } @Override
public void layout(ITracer trace, PageWriter writer) throws IOException, LayoutException {
4
erlymon/erlymon-monitor-android
erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/StorageService.java
[ "public class DbOpenHelper extends SQLiteOpenHelper {\n\n public DbOpenHelper(@NonNull Context context) {\n super(context, \"erlymondb\", null, 1);\n }\n\n @Override\n public void onCreate(@NonNull SQLiteDatabase db) {\n db.execSQL(ServersTable.getCreateTableQuery());\n db.execSQL(U...
import android.content.Context; import android.database.Cursor; import com.fernandocejas.frodo.annotation.RxLogObservable; import com.pushtorefresh.storio.sqlite.StorIOSQLite; import com.pushtorefresh.storio.sqlite.impl.DefaultStorIOSQLite; import com.pushtorefresh.storio.sqlite.operations.put.PutResults; import com.pushtorefresh.storio.sqlite.queries.DeleteQuery; import com.pushtorefresh.storio.sqlite.queries.Query; import org.erlymon.monitor.mvp.model.DbOpenHelper; import org.erlymon.monitor.mvp.model.Device; import org.erlymon.monitor.mvp.model.DevicesTable; import org.erlymon.monitor.mvp.model.Position; import org.erlymon.monitor.mvp.model.PositionsTable; import org.erlymon.monitor.mvp.model.Server; import org.erlymon.monitor.mvp.model.ServerSQLiteTypeMapping; import org.erlymon.monitor.mvp.model.ServersTable; import org.erlymon.monitor.mvp.model.User; import org.erlymon.monitor.mvp.model.UserSQLiteTypeMapping; import org.erlymon.monitor.mvp.model.UsersTable; import java.util.Arrays; import java.util.List; import rx.Observable; import rx.functions.Func1; import rx.functions.Func3;
/* * Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com> * * This file is part of Erlymon Monitor. * * Erlymon Monitor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Erlymon Monitor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>. */ package org.erlymon.monitor.mvp; /** * Created by sergey on 21.03.17. */ public class StorageService { private StorIOSQLite storIOSQLite; public StorageService(Context context) { storIOSQLite = DefaultStorIOSQLite.builder() .sqliteOpenHelper(new DbOpenHelper(context)) .addTypeMapping(Server.class, new ServerSQLiteTypeMapping()) .addTypeMapping(User.class, new UserSQLiteTypeMapping())
.addTypeMapping(Device.class, new DevicesTable.DeviceSQLiteTypeMapping())
1
idega/se.idega.idegaweb.commune.accounting
src/java/se/idega/idegaweb/commune/accounting/posting/business/PostingBusinessBean.java
[ "public interface ExportDataMapping extends IDOEntity {\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getPrimaryKeyClass\n\t */\n\tpublic Class getPrimaryKeyClass();\n\n\t/**\n\t * @see se.idega.idegaweb.commune.accounting.export.data.ExportDataMappingBMPBean#getOpera...
import java.rmi.RemoteException; import java.sql.Date; import java.util.Collection; import java.util.Iterator; import javax.ejb.CreateException; import javax.ejb.FinderException; import se.idega.idegaweb.commune.accounting.export.data.ExportDataMapping; import se.idega.idegaweb.commune.accounting.posting.data.PostingField; import se.idega.idegaweb.commune.accounting.posting.data.PostingFieldHome; import se.idega.idegaweb.commune.accounting.posting.data.PostingParameters; import se.idega.idegaweb.commune.accounting.posting.data.PostingParametersHome; import se.idega.idegaweb.commune.accounting.posting.data.PostingString; import se.idega.idegaweb.commune.accounting.posting.data.PostingStringHome; import se.idega.idegaweb.commune.accounting.regulations.data.ActivityType; import se.idega.idegaweb.commune.accounting.regulations.data.ActivityTypeHome; import se.idega.idegaweb.commune.accounting.regulations.data.CommuneBelongingType; import se.idega.idegaweb.commune.accounting.regulations.data.CommuneBelongingTypeHome; import se.idega.idegaweb.commune.accounting.school.data.Provider; import com.idega.block.school.data.SchoolCategory; import com.idega.block.school.data.SchoolType; import com.idega.core.location.data.Commune; import com.idega.data.IDOLookup; import com.idega.util.IWTimestamp;
} /** * Validates that all the required fields have been set. If they are not * set, a MissingMandatoryFieldException will be thrown. * * @param postingString * @param date * @throws MissingMandatoryFieldException * @throws PostingException * * @author Joakim */ public void validateString(String postingString, Date date) throws PostingException { int fieldLength, readPointer = 0; try { PostingStringHome ksHome = getPostingStringHome(); PostingFieldHome kfHome = getPostingFieldHome(); PostingString posting = ksHome.findPostingStringByDate(date); Collection list = kfHome.findAllFieldsByPostingString(Integer.parseInt(posting.getPrimaryKey().toString())); Iterator iter = list.iterator(); // Go through all fields while (iter.hasNext()) { PostingField field = (PostingField) iter.next(); fieldLength = field.getLen(); if (field.getIsMandatory()) { // Check if mandatory field is empty if (trim(postingString.substring(readPointer, readPointer + fieldLength), field).length() == 0) { throw new MissingMandatoryFieldException(field.getFieldTitle()); } } readPointer += fieldLength; } } catch (Exception e) { System.out.println("Error: The postingt definition and the posting strings did not match."); System.out.println("First posting string: '" + postingString + "'"); System.out.println("Date for posting rule: " + date.toString()); e.printStackTrace(); throw new PostingException("posting.exception", "malformated posting field encountered"); } } /** * extractField Retrieves portion of a PostingString * * @param ps * posting string * @param readPointer * index in string * @param postingField * The field itself * @return an extracted part of the ps string */ public String extractField(String ps, int readPointer, int fieldLength, PostingField field) { if (ps == null) { return ""; } try { return trim(ps.substring(readPointer, readPointer + fieldLength), field); } catch (StringIndexOutOfBoundsException e) { return ""; } } /** * Hämta konteringsinformation Retrieves accounting default information. * Matching on the main rules like Verksamhet, Regspectyp, Bolagstyp, * kommuntill.hörighet is done via primary keys * * @param date * Date when the transaction took place * * @param act_id * Verksamhet. Related to: * @see com.idega.block.school.data.SchoolType# * * @param reg_id * Reg.Spec type. Related to: * @see se.idega.idegaweb.commune.accounting.regulations.data.RegulationSpecType# * * @param com_id * Company type * @see se.idega.idegaweb.commune.accounting.regulations.data.CompanyType# * This bean will be moved later to the Idega * school:com.idega.block.school.data * * @param com_bel_id * Commmune belonging type * @see se.idega.idegaweb.commune.accounting.regulations.data.CommuneBelongingType# * This will probably be moved into the accounting.data * * make parameter 0 for macthing of all * * @return PostingParameters * @see se.idega.idegaweb.commune.accounting.posting.data.PostingParameters# * @throws PostingParametersException * * @author Kjell */ public PostingParameters getPostingParameter(Date date, int act_id, int reg_id, String com_id, int com_bel_id) throws PostingParametersException { return getPostingParameter(date, act_id, reg_id, com_id, com_bel_id, 0, 0); } public PostingParameters getPostingParameter(Date date, int act_id, int reg_id, String com_id, int com_bel_id, int schoolYear1_id, int schoolYear2_id) throws PostingParametersException { logDebug("date: " + date); logDebug("act_id: " + act_id); logDebug("reg_id: " + reg_id); logDebug("com_id: " + com_id); logDebug("com_bel_id: " + com_bel_id); logDebug("schoolYear1_id: " + schoolYear1_id); logDebug("schoolYear2_id: " + schoolYear2_id); PostingParameters pp = null; try {
PostingParametersHome home = getPostingParametersHome();
2
excelsior-oss/excelsior-jet-api
src/main/java/com/excelsiorjet/api/tasks/PackagerArgsGenerator.java
[ "public class ExcelsiorJet {\n\n private final JetHome jetHome;\n private final Log logger;\n\n private JetEdition edition;\n private OS targetOS;\n private CpuArch targetCpu;\n\n public ExcelsiorJet(JetHome jetHome, Log logger) throws JetHomeException {\n this.jetHome = jetHome;\n t...
import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static com.excelsiorjet.api.util.Txt.s; import com.excelsiorjet.api.ExcelsiorJet; import com.excelsiorjet.api.platform.Host; import com.excelsiorjet.api.tasks.config.ApplicationType; import com.excelsiorjet.api.tasks.config.excelsiorinstaller.*; import com.excelsiorjet.api.tasks.config.packagefile.PackageFile; import com.excelsiorjet.api.tasks.config.runtime.RuntimeConfig; import com.excelsiorjet.api.tasks.config.windowsservice.WindowsServiceConfig; import com.excelsiorjet.api.util.Utils;
argsToString(config.afterInstallRunnable.arguments))); } if (config.compressionLevel != null) { xpackOptions.add(new XPackOption("-compression-level", config.compressionLevel)); } if (config.installationDirectory.isDefined()) { if (!Utils.isEmpty(config.installationDirectory.path)) { xpackOptions.add(new XPackOption("-installation-directory", config.installationDirectory.path)); } if (config.installationDirectory.type != null) { xpackOptions.add(new XPackOption("-installation-directory-type", config.installationDirectory.type)); } if (config.installationDirectory.fixed) { xpackOptions.add(new XPackOption("-installation-directory-fixed")); } } if (excelsiorJet.getTargetOS().isWindows()) { //handle windows only parameters xpackOptions.addAll(getWindowsOnlyExcelsiorInstallerOptions(config)); } if (config.installCallback != null) { xpackOptions.add(new XPackOption("-install-callback", config.installCallback.getAbsolutePath())); } if (config.uninstallCallback.isDefined()) { if (config.uninstallCallback.path != null) { xpackOptions.add(new XPackOption("-add-file", config.uninstallCallback.path.getAbsolutePath(), config.uninstallCallback.packagePath)); } xpackOptions.add(new XPackOption("-uninstall-callback", config.uninstallCallback.getLocationInPackage())); } if ((project.appType() == ApplicationType.TOMCAT) && project.tomcatConfiguration().allowUserToChangeTomcatPort) { xpackOptions.add(new XPackOption("-allow-user-to-change-tomcat-port")); } xpackOptions.add(new XPackOption("-backend", "excelsior-installer")); xpackOptions.add(new XPackOption("-company", project.vendor())); xpackOptions.add(new XPackOption("-product", project.product())); xpackOptions.add(new XPackOption("-version", project.version())); xpackOptions.add(new XPackOption("-target", target.getAbsolutePath())); return xpackOptions; } private ArrayList<XPackOption> getWindowsOnlyExcelsiorInstallerOptions(ExcelsiorInstallerConfig config) { ArrayList<XPackOption> xpackOptions = new ArrayList<>(); if (config.registryKey != null) { xpackOptions.add(new XPackOption("-registry-key", config.registryKey)); } for (Shortcut shortcut: config.shortcuts) { if (shortcut.icon.path != null) { xpackOptions.add(new XPackOption("-add-file", shortcut.icon.path.getAbsolutePath(), shortcut.icon.packagePath)); } xpackOptions.add(new XPackOption("-shortcut", argsValidForRsp(shortcut.arguments), shortcut.location, shortcut.target, shortcut.name, shortcut.icon.getLocationInPackage(), shortcut.workingDirectory, argsToString(shortcut.arguments))); } if (config.noDefaultPostInstallActions) { xpackOptions.add(new XPackOption("-no-default-post-install-actions")); } for (PostInstallCheckbox postInstallCheckbox: config.postInstallCheckboxes) { switch (postInstallCheckbox.type()) { case RUN: xpackOptions.add(new XPackOption("-post-install-checkbox-run", argsValidForRsp(postInstallCheckbox.arguments), postInstallCheckbox.target, postInstallCheckbox.workingDirectory, argsToString(postInstallCheckbox.arguments), postInstallCheckbox.checkedArg())); break; case OPEN: xpackOptions.add(new XPackOption("-post-install-checkbox-open", postInstallCheckbox.target, postInstallCheckbox.checkedArg())); break; case RESTART: xpackOptions.add(new XPackOption("-post-install-checkbox-restart", postInstallCheckbox.checkedArg())); break; default: throw new AssertionError("Unknown PostInstallCheckBox type: " + postInstallCheckbox.type); } } for (FileAssociation fileAssociation: config.fileAssociations) { if (fileAssociation.icon.path != null) { xpackOptions.add(new XPackOption("-add-file", fileAssociation.icon.path.getAbsolutePath(), fileAssociation.icon.packagePath)); } xpackOptions.add(new XPackOption("-file-association", argsValidForRsp(fileAssociation.arguments), fileAssociation.extension, fileAssociation.target, fileAssociation.description, fileAssociation.targetDescription,fileAssociation.icon.getLocationInPackage(), argsToString(fileAssociation.arguments), fileAssociation.checked? "checked" : "unchecked")); } if (config.welcomeImage != null) { xpackOptions.add(new XPackOption("-welcome-image", config.welcomeImage.getAbsolutePath())); } if (config.installerImage != null) { xpackOptions.add(new XPackOption("-installer-image", config.installerImage.getAbsolutePath())); } if (config.uninstallerImage != null) { xpackOptions.add(new XPackOption("-uninstaller-image", config.uninstallerImage.getAbsolutePath())); } return xpackOptions; } //Surprisingly Windows just removes empty argument from list of arguments if we do not pass "" instead. private static String escapeEmptyArgForWindows(String arg) { return arg.isEmpty() ? "\"\"" : arg; } private ArrayList<XPackOption> getWindowsServiceArgs() { ArrayList<XPackOption> xpackOptions = new ArrayList<>(); String exeRelPath = project.exeRelativePath(excelsiorJet);
WindowsServiceConfig serviceConfig = project.windowsServiceConfiguration();
5
CodeAndMagic/android-deferred-object
core/src/test/java/org/codeandmagic/promise/tests/PipePromisesTests.java
[ "public class DeferredObject<Success> extends AbstractPromise<Success> {\n\n public static <S> DeferredObject<S> successful(S value) {\n final DeferredObject<S> deferredObject = new DeferredObject<S>();\n deferredObject.success(value);\n return deferredObject;\n }\n\n public static <S>...
import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; import org.codeandmagic.promise.*; import org.codeandmagic.promise.impl.DeferredObject; import org.codeandmagic.promise.Pipe; import org.codeandmagic.promise.Promise; import org.codeandmagic.promise.Pipe3; import org.codeandmagic.promise.impl.DeferredObject3; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static java.lang.System.currentTimeMillis;
/* * Copyright (c) 2014 Cristian Vrabie, Evelina Vrabie. * * This file is part of android-promise. * android-deferred-object is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License,or (at your option) * any later version. * * android-promise is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with android-promise * If not, see <http://www.gnu.org/licenses/>. */ package org.codeandmagic.promise.tests; /** * Created by cristian on 11/02/2014. */ @RunWith(JUnit4.class) public class PipePromisesTests { public Promise<Integer> deferredInt(final int number) { final DeferredObject<Integer> deferredObject = new DeferredObject<Integer>(); new Thread() { @Override public void run() { try { Thread.sleep(1000); deferredObject.success(number); } catch (InterruptedException e) { deferredObject.failure(e); } } }.start(); return deferredObject; } public Promise<Integer> deferredException() { final DeferredObject<Integer> deferredObject = new DeferredObject<Integer>(); new Thread() { @Override public void run() { try { Thread.sleep(1000); deferredObject.failure(new Exception("Failed!")); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); return deferredObject; } @Test public void testPipe() { Callback<String> onSuccess = mock(Callback.class); Callback<Throwable> onFailure = mock(Callback.class);
DeferredObject3.<Integer, Throwable, Void>successful(3).pipe(new Pipe3<Integer, String, Throwable>() {
4
turn/camino
src/main/java/com/turn/camino/render/functions/TimeFunctions.java
[ "public interface Context {\n\n\t/**\n\t * Get system environment\n\t *\n\t * @return system environment\n\t */\n\tEnv getEnv();\n\n\t/**\n\t * Creates child context\n\t *\n\t * @return new context\n\t */\n\tContext createChild();\n\n\t/**\n\t * Gets parent context\n\t *\n\t * Returns a parent context, or null if c...
import com.turn.camino.Context; import com.turn.camino.render.Function; import com.turn.camino.render.FunctionCallException; import com.turn.camino.render.FunctionCallExceptionFactory; import com.turn.camino.render.TimeValue; import com.turn.camino.util.Validation; import static com.turn.camino.util.Message.*; import com.google.common.collect.ImmutableMap; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*;
/* * Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and */ package com.turn.camino.render.functions; /** * Time functions * * @author llo */ public class TimeFunctions { private final static Validation<FunctionCallException> VALIDATION = new Validation<>(new FunctionCallExceptionFactory()); private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000L; /** * Supported time units */ public enum Unit { YEAR("y", Calendar.YEAR), MONTH("M", Calendar.MONTH), DAY("D", Calendar.DATE), HOUR("h", Calendar.HOUR), MINUTE("m", Calendar.MINUTE), SECOND("s", Calendar.SECOND), MILLISECOND("S", Calendar.MILLISECOND); private final String symbol; private final int unit; Unit(String symbol, int unit) { this.symbol = symbol; this.unit = unit; } public String getSymbol() { return symbol; } public int getUnit() { return unit; } } /** * Time units */ private final static Map<String, Unit> TIME_UNITS = ImmutableMap.<String, Unit>builder() .put(Unit.YEAR.getSymbol(), Unit.YEAR) .put(Unit.MONTH.getSymbol(), Unit.MONTH) .put(Unit.DAY.getSymbol(), Unit.DAY) .put(Unit.HOUR.getSymbol(), Unit.HOUR) .put(Unit.MINUTE.getSymbol(), Unit.MINUTE) .put(Unit.SECOND.getSymbol(), Unit.SECOND) .put(Unit.MILLISECOND.getSymbol(), Unit.MILLISECOND) .build(); /** * Function to returns current time * * Function returns current time in either system default time zone if no argument is * given, or in specified time zone. * * @author llo */ public static class Now implements Function { @Override
public Object invoke(List<?> params, Context context) throws FunctionCallException {
0
chudooder/FEMultiplayer
src/net/fe/network/FEServer.java
[ "public class Player implements Serializable {\n\tprivate static final long serialVersionUID = -7461827659473965623L;\n\tprivate Party party;\n\tprivate byte clientID;\n\tprivate String nickname;\n\tprivate int team;\n\tpublic boolean ready;\n\t\n//\tpublic static final int TEAM_UNASSIGNED = 0;\n\tpublic static fin...
import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JSpinner; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SpinnerNumberModel; import net.fe.Player; import net.fe.Session; import net.fe.lobbystage.LobbyStage; import net.fe.modifier.DivineIntervention; import net.fe.modifier.MadeInChina; import net.fe.modifier.Modifier; import net.fe.modifier.SuddenDeath; import net.fe.modifier.Treasury; import net.fe.modifier.Vegas; import net.fe.modifier.Veterans; import net.fe.overworldStage.objective.Objective; import net.fe.overworldStage.objective.Rout; import net.fe.overworldStage.objective.Seize; import net.fe.pick.AllPick; import net.fe.pick.Draft; import net.fe.pick.PickMode; import net.fe.unit.Unit; import net.fe.unit.UnitIdentifier; import chu.engine.Game; import chu.engine.Stage;
package net.fe.network; /** * A game that does not render anything. Manages logic only * @author Shawn * */ public class FEServer extends Game { private static Server server; private static Stage currentStage; public static LobbyStage lobby; private static Map<String, Objective[]> maps; public static void main(String[] args) { final JFrame frame = new JFrame("FEServer"); Rout rout = new Rout();
Seize seize = new Seize();
5
roybailey/research-graphql
research-graphql-server/src/main/java/me/roybailey/springboot/graphql/domain/schema/OrderItemResolver.java
[ "@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonPropertyOrder({\n \"id\",\n \"userId\",\n \"items\",\n \"status\"\n})\n@lombok.Builder\n@lombok.NoArgsConstructor\n@lombok.AllArgsConstructor\npublic class OrderDto {\n\n @JsonProperty(\"id\")\n private String id;\n /**\n * \n * (Require...
import com.coxautodev.graphql.tools.GraphQLResolver; import me.roybailey.data.schema.OrderDto; import me.roybailey.data.schema.OrderItemDto; import me.roybailey.data.schema.ProductDto; import me.roybailey.data.schema.UserDto; import me.roybailey.springboot.service.ProductAdaptor; import me.roybailey.springboot.service.UserAdaptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package me.roybailey.springboot.graphql.domain.schema; /** * This class contains resolver methods for the "Data Class" type */ @Service public class OrderItemResolver implements GraphQLResolver<OrderItemDto> { @Autowired
ProductAdaptor productAdaptor;
4
Rezar/Ubiqlog
app/src/main/java/com/ubiqlog/sensors/HardwareSensor_OLD.java
[ "public class DataAcquisitor {\n\n\tprivate static final String LOG_TAG = DataAcquisitor.class.getSimpleName();\n\tprivate String folderName;\n\tprivate String fileName;\n\t//private Context context;\n\tprivate ArrayList<String> dataBuffer;\n\n\n\t@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n\tpublic static ...
import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; import com.ubiqlog.core.DataAcquisitor; import com.ubiqlog.utils.IOManager; import com.ubiqlog.vis.utils.JsonEncodeDecode; import com.ubiqlog.vis.utils.SensorState; import com.ubiqlog.vis.utils.SensorState.Movement; import android.app.Service; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.IBinder; import android.util.Log;
package com.ubiqlog.sensors; public class HardwareSensor_OLD extends Service implements SensorConnector, SensorEventListener { private SensorManager sensorManager; private Sensor sensorAccelerometer;
private DataAcquisitor dataAcq = new DataAcquisitor();
0
lukaspili/Volley-Ball
samples/src/main/java/com/siu/android/volleyball/samples/activity/CompleteRequestActivity.java
[ "public class BallResponse<T> {\n\n public static enum ResponseSource {\n LOCAL, CACHE, NETWORK\n }\n\n protected Response<T> mResponse;\n protected ResponseSource mResponseSource;\n protected boolean mIdentical = false;\n\n /**\n * Returns whether this response is considered successful...
import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.widget.ListView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.siu.android.volleyball.BallResponse; import com.siu.android.volleyball.response.ResponseListener; import com.siu.android.volleyball.samples.Application; import com.siu.android.volleyball.samples.R; import com.siu.android.volleyball.samples.adapter.EntriesAdapter; import com.siu.android.volleyball.samples.model.Entry; import com.siu.android.volleyball.samples.util.SimpleLogger; import com.siu.android.volleyball.samples.volley.request.CompleteEntryRequest; import com.siu.android.volleyball.samples.volley.request.SampleRequest; import java.util.ArrayList; import java.util.List;
package com.siu.android.volleyball.samples.activity; public class CompleteRequestActivity extends Activity { private ListView mListView;
private EntriesAdapter mEntriesAdapter;
3
criticalmaps/criticalmaps-android
app/src/main/java/de/stephanlindauer/criticalmaps/handler/ShowGpxHandler.java
[ "public class App extends Application {\n\n private static AppComponent appComponent;\n\n public static AppComponent components() {\n return appComponent;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n if (BuildConfig.DEBUG) {\n Timber.plant(new T...
import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.widget.Toast; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.Marker; import org.osmdroid.views.overlay.Polyline; import org.xml.sax.SAXException; import java.io.IOException; import java.io.InputStream; import javax.inject.Inject; import javax.xml.parsers.ParserConfigurationException; import de.stephanlindauer.criticalmaps.App; import de.stephanlindauer.criticalmaps.R; import de.stephanlindauer.criticalmaps.model.gpx.GpxModel; import de.stephanlindauer.criticalmaps.model.gpx.GpxPoi; import de.stephanlindauer.criticalmaps.model.gpx.GpxTrack; import de.stephanlindauer.criticalmaps.prefs.SharedPrefsKeys; import de.stephanlindauer.criticalmaps.utils.GpxReader; import info.metadude.android.typedpreferences.BooleanPreference; import info.metadude.android.typedpreferences.StringPreference;
package de.stephanlindauer.criticalmaps.handler; public class ShowGpxHandler { private final SharedPreferences sharedPreferences; private final GpxModel gpxModel; private final App app; private final GpxReader gpxReader; @Inject public ShowGpxHandler(SharedPreferences sharedPreferences, GpxModel gpxModel, App app, GpxReader gpxReader) { this.sharedPreferences = sharedPreferences; this.gpxModel = gpxModel; this.app = app; this.gpxReader = gpxReader; } public void showGpx(MapView mapView) { boolean showTrack = new BooleanPreference(sharedPreferences, SharedPrefsKeys.SHOW_GPX).get(); if (!showTrack) { return; } String gpxUri = new StringPreference(sharedPreferences, SharedPrefsKeys.GPX_FILE).get(); if (gpxModel.getUri() == null || !gpxModel.getUri().equals(gpxUri)) { readFile(gpxUri); } showModelOnMap(mapView); } private void readFile(String gpxUri) { try { InputStream gpxInputStream = app.getContentResolver().openInputStream(Uri.parse(gpxUri)); gpxReader.readDataFromStream(gpxInputStream, gpxUri); } catch (SecurityException | IOException | SAXException | ParserConfigurationException e) { Toast.makeText(app, R.string.gpx_reading_error, Toast.LENGTH_SHORT).show(); } } private void showModelOnMap(MapView mapView) {
for (GpxTrack track : gpxModel.getTracks()) {
2
sarnowski/eve-api
cdi/src/main/java/org/onsteroids/eve/api/provider/eve/DefaultAllianceList.java
[ "public final class DateUtility {\n private static final Logger LOG = LoggerFactory.getLogger(DateUtility.class);\n\n // CCPs date scheme\n private static final DateFormat dateParser = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n\n public static Date parse(String date) {\n\t try {\n\t\t retu...
import com.eveonline.api.ApiListResult; import com.eveonline.api.eve.AllianceList; import com.eveonline.api.exceptions.ApiException; import org.onsteroids.eve.api.DateUtility; import org.onsteroids.eve.api.XmlUtility; import org.onsteroids.eve.api.connector.XmlApiResult; import org.onsteroids.eve.api.provider.SerializableApiListResult; import org.onsteroids.eve.api.provider.SerializableApiResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Node; import java.util.Date; import java.util.concurrent.TimeUnit;
/** * Copyright 2010 Tobias Sarnowski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onsteroids.eve.api.provider.eve; /** * @author Tobias Sarnowski */ public final class DefaultAllianceList extends SerializableApiListResult<DefaultAllianceList.DefaultAlliance> implements AllianceList<DefaultAllianceList.DefaultAlliance> { private static final Logger LOG = LoggerFactory.getLogger(DefaultAllianceList.class); @Override public Class<? extends DefaultAlliance> getRowDefinition() { return DefaultAlliance.class; } public static final class DefaultAlliance extends SerializableApiResult implements AllianceList.Alliance { private long id; private String name; private String shortName; private long executorCorporationId; private int memberCount; private Date startDate; private SerializableApiListResult<DefaultAllianceList.CorporationImpl> corporations; @Override
public void processResult(XmlApiResult xmlApiResult, Node xmlResult) throws ApiException {
2
nullpointerexceptionapps/TeamCityDownloader
java/com/raidzero/teamcitydownloader/activities/settings/SettingsServerActivity.java
[ "public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {\n\n private static final String tag = \"MainActivity\";\n\n public static AppHelper helper;\n\n private long lastBackPressTime = 0;\n\n private NavigationDrawerFragment mNavigationDrawerF...
import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.MenuItem; import com.raidzero.teamcitydownloader.R; import com.raidzero.teamcitydownloader.activities.MainActivity; import com.raidzero.teamcitydownloader.data.WebResponse; import com.raidzero.teamcitydownloader.fragments.settings.SettingsFragmentServer; import com.raidzero.teamcitydownloader.global.DialogUtility; import com.raidzero.teamcitydownloader.global.QueryUtility; import com.raidzero.teamcitydownloader.global.ThemeUtility;
package com.raidzero.teamcitydownloader.activities.settings; /** * Created by raidzero on 1/11/15. */ public class SettingsServerActivity extends ActionBarActivity implements QueryUtility.QueryCallbacks { private QueryUtility queryUtility; private boolean cameFromError; private ProgressDialog progDialog; public static boolean querying = false; @Override public void onCreate(Bundle savedInstanceState) { ThemeUtility.setAppTheme(this); super.onCreate(savedInstanceState); setContentView(R.layout.settings); cameFromError = getIntent().getBooleanExtra("cameFromError", false); getFragmentManager().beginTransaction().replace(R.id.frameLayout_settings, new SettingsFragmentServer()).commit(); progDialog = new ProgressDialog(this, ThemeUtility.getHoloDialogTheme(this)); progDialog.setIndeterminate(true); progDialog.setMessage(getString(R.string.querying_please_wait)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (cameFromError) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
0