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
goerlitz/rdffederator
src/de/uni_koblenz/west/splendid/optimizer/AbstractFederationOptimizer.java
[ "public abstract class AbstractCostEstimator extends QueryModelVisitorBase<RuntimeException> implements ModelEvaluator {\n\t\n\tprotected double cost;\n\t\n\tprotected AbstractCardinalityEstimator cardEst;\n\t\n\tpublic AbstractCardinalityEstimator getCardinalityEstimator() {\n\t\treturn cardEst;\n\t}\n\n\tpublic v...
import org.slf4j.LoggerFactory; import de.uni_koblenz.west.splendid.estimation.AbstractCostEstimator; import de.uni_koblenz.west.splendid.estimation.ModelEvaluator; import de.uni_koblenz.west.splendid.helpers.AnnotatingTreePrinter; import de.uni_koblenz.west.splendid.helpers.FilterConditionCollector; import de.uni_koblenz.west.splendid.model.BasicGraphPatternExtractor; import de.uni_koblenz.west.splendid.model.MappedStatementPattern; import de.uni_koblenz.west.splendid.model.SubQueryBuilder; import de.uni_koblenz.west.splendid.sources.SourceSelector; import java.util.List; import org.openrdf.query.BindingSet; import org.openrdf.query.Dataset; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.evaluation.QueryOptimizer; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.slf4j.Logger;
/* * This file is part of RDF Federator. * Copyright 2011 Olaf Goerlitz * * RDF Federator 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. * * RDF Federator 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 RDF Federator. If not, see <http://www.gnu.org/licenses/>. * * RDF Federator uses libraries from the OpenRDF Sesame Project licensed * under the Aduna BSD-style license. */ package de.uni_koblenz.west.splendid.optimizer; /** * Base functionality for federated query optimizers * * @author Olaf Goerlitz */ public abstract class AbstractFederationOptimizer implements QueryOptimizer { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFederationOptimizer.class); protected SourceSelector sourceSelector; protected SubQueryBuilder queryBuilder; protected AbstractCostEstimator costEstimator;
protected ModelEvaluator modelEvaluator;
1
campaignmonitor/createsend-java
src/com/createsend/General.java
[ "public class ExternalSessionOptions {\n\tpublic String Email;\n\tpublic String Chrome;\n\tpublic String Url;\n\tpublic String IntegratorID;\n\tpublic String ClientID;\n}", "public class ExternalSessionResult {\n\tpublic String SessionUrl;\n}", "public class OAuthTokenDetails {\n\tpublic String access_token;\n\...
import com.createsend.models.OAuthTokenDetails; import com.createsend.models.SystemDate; import com.createsend.models.administrators.Administrator; import com.createsend.models.administrators.AdministratorResult; import com.createsend.models.clients.ClientBasics; import com.createsend.util.AuthenticationDetails; import com.createsend.util.Configuration; import com.createsend.util.JerseyClient; import com.createsend.util.JerseyClientImpl; import com.createsend.util.exceptions.CreateSendException; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import com.createsend.models.ExternalSessionOptions; import com.createsend.models.ExternalSessionResult;
/** * Copyright (c) 2011 Toby Brain * * 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.createsend; /** * Provides methods for accessing all * <a href="http://www.campaignmonitor.com/api/account/" target="_blank">Account</a> * methods in the Campaign Monitor API * */ public class General extends CreateSendBase { /** * Constructor. * @param auth The authentication details to use when making API calls. * May be either an OAuthAuthenticationDetails or * ApiKeyAuthenticationDetails instance. */ public General(AuthenticationDetails auth) { this.jerseyClient = new JerseyClientImpl(auth); } /** * Get the authorization URL for your application, given the application's * Client ID, Redirect URI, Scope, and optional State data. * @param clientID The Client ID value for your application. * @param redirectUri The Redirect URI value for your application. * @param scope The permission scope your application is requesting. * @param state Optional state data to include in the authorization URL. * @return The authorization URL to which your application should redirect * your users. */ public static String getAuthorizeUrl( int clientID, String redirectUri, String scope, String state) { String qs = "client_id=" + String.valueOf(clientID); try { qs += "&redirect_uri=" + URLEncoder.encode(redirectUri, URL_ENCODING_SCHEME); qs += "&scope=" + URLEncoder.encode(scope, URL_ENCODING_SCHEME); if (state != null) qs += "&state=" + URLEncoder.encode(state, URL_ENCODING_SCHEME); } catch (UnsupportedEncodingException e) { qs = null; } return Configuration.Current.getOAuthBaseUri() + "?" + qs; } /** * Exchange a provided OAuth code for an OAuth access token, 'expires in' * value, and refresh token. * @param clientID The Client ID value for your application. * @param clientSecret The Client Secret value for your application. * @param redirectUri The Redirect URI value for your application. * @param code A unique code provided to your user which can be exchanged * for an access token. * @return An OAuthTokenDetails object containing the access token, * 'expires in' value, and refresh token. */
public static OAuthTokenDetails exchangeToken(
2
Drusy/Wisper
wisper-libgdx/core/src/java/fr/wisper/screens/gamescreen/WisperChooseMenu.java
[ "public class WisperGame extends Game {\n // Fps\n private FPSLogger fps;\n\n // Preferences\n public static Preferences preferences;\n\n // Loader\n private LoadingScreen loader;\n\n // Camera\n static public OrthographicCameraWithVirtualViewport Camera;\n static public MultipleVirtualVi...
import aurelienribon.tweenengine.BaseTween; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenCallback; import aurelienribon.tweenengine.TweenManager; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.List; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.Scaling; import com.badlogic.gdx.utils.viewport.ScalingViewport; import fr.wisper.Game.WisperGame; import fr.wisper.assets.WisperChooseAssets; import fr.wisper.entities.AnimatedWisper; import fr.wisper.animations.tween.TableAccessor; import fr.wisper.entities.Wisper; import fr.wisper.screens.loading.LoadingScreen; import fr.wisper.utils.Config; import fr.wisper.utils.Debug; import fr.wisper.utils.ExtendedStage;
package fr.wisper.screens.gamescreen; public class WisperChooseMenu implements FadingScreen { // Stage private ExtendedStage<WisperChooseMenu> stage; private Table table; private Skin skin; List<String> list; // Wisper private final String CHOSEN_WISPER = "chosen-wisper"; private SpriteBatch batch;
private AnimatedWisper wisper;
2
exoplatform/task
services/src/test/java/org/exoplatform/task/rest/TestProjectRestService.java
[ "public class TestUtils {\n\n private static Connection conn;\n private static Liquibase liquibase;\n\n public static long EXISTING_TASK_ID = 1;\n public static long UNEXISTING_TASK_ID = 2;\n\n public static long EXISTING_PROJECT_ID = 1;\n public static long UNEXISTING_PROJECT_ID = 2;\n\n public static long ...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.*; import java.util.*; import javax.ws.rs.core.Response; import javax.ws.rs.ext.RuntimeDelegate; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; import org.exoplatform.social.core.manager.IdentityManager; import org.exoplatform.social.core.space.SpaceUtils; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.task.dao.OrderBy; import org.exoplatform.task.rest.model.PaginatedTaskList; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.exoplatform.services.rest.impl.RuntimeDelegateImpl; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.Identity; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.task.TestUtils; import org.exoplatform.task.dto.ProjectDto; import org.exoplatform.task.dto.StatusDto; import org.exoplatform.task.dto.TaskDto; import org.exoplatform.task.service.UserService; import org.exoplatform.task.model.User; import org.exoplatform.task.service.*; import org.exoplatform.task.storage.ProjectStorage; import org.exoplatform.task.storage.StatusStorage;
package org.exoplatform.task.rest; @RunWith(MockitoJUnitRunner.class) public class TestProjectRestService { @Mock TaskService taskService; @Mock ProjectService projectService; @Mock ProjectStorage projectStorage; @Mock StatusService statusService; @Mock StatusStorage statusStorage; @Mock UserService userService; @Mock SpaceService spaceService; @Mock CommentService commentService; @Mock LabelService labelService; @Mock IdentityManager identityManager; @Before public void setup() { RuntimeDelegate.setInstance(new RuntimeDelegateImpl()); } @Test public void testGetTasks() throws Exception { // Given TaskRestService taskRestService = new TaskRestService(taskService, commentService, projectService, statusService, userService, spaceService, labelService); Identity root = new Identity("root"); ConversationState.setCurrent(new ConversationState(root)); TaskDto task1 = new TaskDto(); TaskDto task2 = new TaskDto(); TaskDto task3 = new TaskDto(); TaskDto task4 = new TaskDto(); List<TaskDto> uncompletedTasks = new ArrayList<TaskDto>(); task1.setCompleted(true); uncompletedTasks.add(task2); uncompletedTasks.add(task3); uncompletedTasks.add(task4); List<TaskDto> overdueTasks = new ArrayList<TaskDto>(); overdueTasks.add(task1); overdueTasks.add(task2); List<TaskDto> incomingTasks = new ArrayList<TaskDto>(); incomingTasks.add(task1); incomingTasks.add(task2); when(taskService.getUncompletedTasks("root", 20)).thenReturn(uncompletedTasks); when(taskService.countUncompletedTasks("root")).thenReturn(Long.valueOf(uncompletedTasks.size())); when(taskService.getOverdueTasks("root", 20)).thenReturn(overdueTasks); when(taskService.countOverdueTasks("root")).thenReturn(Long.valueOf(overdueTasks.size())); when(taskService.getIncomingTasks("root", 0, 20)).thenReturn(incomingTasks); when(taskService.countIncomingTasks("root")).thenReturn(incomingTasks.size()); when(taskService.findTasks(eq("root"), eq("searchTerm"), anyInt())).thenReturn(Collections.singletonList(task4)); when(taskService.countTasks(eq("root"), eq("searchTerm"))).thenReturn(1L); // When Response response = taskRestService.getTasks("overdue", null, 0, 20, false, false); Response response1 = taskRestService.getTasks("incoming", null, 0, 20, false, false); Response response2 = taskRestService.getTasks("", null, 0, 20, false, false); Response response3 = taskRestService.getTasks("whatever", "searchTerm", 0, 20, true, false); // Then assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); PaginatedTaskList tasks = (PaginatedTaskList) response.getEntity(); assertNotNull(tasks); assertEquals(2, tasks.getTasksNumber()); assertEquals(Response.Status.OK.getStatusCode(), response1.getStatus()); PaginatedTaskList tasks1 = (PaginatedTaskList) response1.getEntity(); assertNotNull(tasks1); assertEquals(2, tasks1.getTasksNumber()); assertEquals(Response.Status.OK.getStatusCode(), response2.getStatus()); PaginatedTaskList tasks2 = (PaginatedTaskList) response2.getEntity(); assertNotNull(tasks2); assertEquals(3, tasks2.getTasksNumber()); assertEquals(Response.Status.OK.getStatusCode(), response3.getStatus()); // JSONObject tasks3JsonObject = (JSONObject) response3.getEntity(); // assertNotNull(tasks3JsonObject); // assertTrue(tasks3JsonObject.has("size")); // assertTrue(tasks3JsonObject.has("tasks")); // JSONArray tasks3 = (JSONArray) tasks3JsonObject.get("tasks"); // assertNotNull(tasks3); // assertEquals(1, tasks3.length()); // Long tasks3Size = (Long) tasks3JsonObject.get("size"); // assertEquals(1L, tasks3Size.longValue()); } @Test public void testGetProjects() throws Exception { // Given ProjectRestService projectRestService = new ProjectRestService(taskService, commentService, projectService, statusService, userService, spaceService, labelService, identityManager); Identity root = new Identity("root"); ConversationState.setCurrent(new ConversationState(root));
ProjectDto project1 = new ProjectDto();
1
mast-group/codemining-core
src/main/java/codemining/java/codeutils/binding/AbstractJavaNameBindingsExtractor.java
[ "public class JavaASTExtractor {\n\n\tprivate static final class TopMethodRetriever extends ASTVisitor {\n\t\tpublic MethodDeclaration topDcl;\n\n\t\t@Override\n\t\tpublic boolean visit(final MethodDeclaration node) {\n\t\t\ttopDcl = node;\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Remembers if the given Extra...
import java.io.File; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.SortedMap; import java.util.function.Predicate; import org.apache.commons.io.FileUtils; import org.eclipse.jdt.core.dom.ASTNode; import codemining.java.codeutils.JavaASTExtractor; import codemining.languagetools.ITokenizer; import codemining.languagetools.ITokenizer.FullToken; import codemining.languagetools.bindings.AbstractNameBindingsExtractor; import codemining.languagetools.bindings.ResolvedSourceCode; import codemining.languagetools.bindings.TokenNameBinding; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets;
/** * */ package codemining.java.codeutils.binding; /** * A name bindings extractor interface for Java. * * @author Miltos Allamanis <m.allamanis@ed.ac.uk> * */ public abstract class AbstractJavaNameBindingsExtractor extends AbstractNameBindingsExtractor { /** * Return the token index for the given position. * * @param sourceCode * @return */ protected static SortedMap<Integer, Integer> getTokenIndexForPostion( final SortedMap<Integer, String> tokenPositions) { final SortedMap<Integer, Integer> positionToIndex = Maps.newTreeMap(); int i = 0; for (final int position : tokenPositions.keySet()) { positionToIndex.put(position, i); i++; } return positionToIndex; } final ITokenizer tokenizer; public AbstractJavaNameBindingsExtractor(final ITokenizer tokenizer) { this.tokenizer = tokenizer; } protected JavaASTExtractor createExtractor() { return new JavaASTExtractor(false); } protected abstract Set<String> getFeatures(final Set<ASTNode> boundNodes); /** * Return a set of sets of SimpleName ASTNode objects that are bound * together * * @param node * @return */ public abstract Set<Set<ASTNode>> getNameBindings(final ASTNode node);
public final List<TokenNameBinding> getNameBindings(final ASTNode node,
5
CreativeMD/IGCM
src/main/java/com/creativemd/igcm/IGCMGuiManager.java
[ "public class ConfigTab extends ConfigGroupElement {\n\t\n\tpublic static final ConfigTab root = new ConfigTab(\"root\", ItemStack.EMPTY);\n\t\n\tpublic static ConfigSegment getSegmentByPath(String path) {\n\t\tif (path.equals(\"root\"))\n\t\t\treturn root;\n\t\tif (path.startsWith(\"root.\"))\n\t\t\treturn root.ge...
import com.creativemd.creativecore.common.gui.container.SubContainer; import com.creativemd.creativecore.common.gui.container.SubGui; import com.creativemd.creativecore.common.gui.opener.CustomGuiHandler; import com.creativemd.creativecore.common.gui.opener.GuiHandler; import com.creativemd.igcm.api.ConfigTab; import com.creativemd.igcm.block.SubContainerAdvancedWorkbench; import com.creativemd.igcm.block.SubGuiAdvancedWorkbench; import com.creativemd.igcm.client.gui.SubGuiConfigSegement; import com.creativemd.igcm.client.gui.SubGuiProfile; import com.creativemd.igcm.container.SubContainerConfigSegment; import com.creativemd.igcm.container.SubContainerProfile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package com.creativemd.igcm; public class IGCMGuiManager extends CustomGuiHandler { public static void openConfigGui(EntityPlayer player) { openConfigGui(player, "root"); } public static void openConfigGui(EntityPlayer player, String path) { NBTTagCompound nbt = new NBTTagCompound(); nbt.setInteger("gui", 0); nbt.setString("path", path); GuiHandler.openGui(IGCM.guiID, nbt, player); } public static void openProfileGui(EntityPlayer player) { NBTTagCompound nbt = new NBTTagCompound(); nbt.setInteger("gui", 1); nbt.setInteger("index", 0); GuiHandler.openGui(IGCM.guiID, nbt, player); } @Override public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) { int gui = nbt.getInteger("gui"); String name = nbt.getString("path"); switch (gui) { case 0: return new SubContainerConfigSegment(player, ConfigTab.getSegmentByPath(name)); case 1: return new SubContainerProfile(player); case 2: return new SubContainerAdvancedWorkbench(player); } return null; } @Override @SideOnly(Side.CLIENT) public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) { int gui = nbt.getInteger("gui"); String name = nbt.getString("path"); switch (gui) { case 0:
return new SubGuiConfigSegement(ConfigTab.getSegmentByPath(name));
3
susom/database
src/test/java/com/github/susom/database/example/VertxServer.java
[ "public interface Config extends Function<String, String>, Supplier<Config> {\n /**\n * Convenience method for fluent syntax.\n *\n * @return a builder for specifying from where configuration should be loaded\n */\n static @Nonnull ConfigFrom from() {\n return new ConfigFromImpl();\n }\n\n // TODO ad...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.susom.database.Config; import com.github.susom.database.ConfigFrom; import com.github.susom.database.DatabaseProviderVertx; import com.github.susom.database.DatabaseProviderVertx.Builder; import com.github.susom.database.Metric; import com.github.susom.database.Schema; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject;
package com.github.susom.database.example; /** * Demo of using some com.github.susom.database classes with Vertx and HyperSQL. */ public class VertxServer { private static final Logger log = LoggerFactory.getLogger(VertxServer.class); private final Object lock = new Object(); public void run() throws Exception { // A JSON config you might get from Vertx. In a real scenario you would // also set database.user, database.password and database.pool.size. JsonObject jsonConfig = new JsonObject() .put("database.url", "jdbc:hsqldb:file:target/hsqldb;shutdown=true"); // Set up Vertx and database access Vertx vertx = Vertx.vertx();
Config config = ConfigFrom.firstOf().custom(jsonConfig::getString).get();
0
WSDOT/social-analytics
src/main/java/gov/wa/wsdot/apps/analytics/client/activities/twitter/view/ranking/RankingView.java
[ "public interface ClientFactory {\n EventBus getEventBus();\n PlaceController getPlaceController();\n AnalyticsView getAnalyticsView();\n}", "public class DateSubmitEvent extends GenericEvent {\n\n\n private final String dateRange;\n private final String account;\n private final Date startDate;\...
import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.jsonp.client.JsonpRequestBuilder; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import com.google.web.bindery.event.shared.binder.EventBinder; import com.google.web.bindery.event.shared.binder.EventHandler; import gov.wa.wsdot.apps.analytics.client.ClientFactory; import gov.wa.wsdot.apps.analytics.client.activities.events.DateSubmitEvent; import gov.wa.wsdot.apps.analytics.client.resources.Resources; import gov.wa.wsdot.apps.analytics.shared.Mention; import gov.wa.wsdot.apps.analytics.util.Consts; import gwt.material.design.client.constants.IconType; import gwt.material.design.client.ui.*; import java.util.Date;
/* * Copyright (c) 2016 Washington State Department of Transportation * * 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 <http://www.gnu.org/licenses/> * */ package gov.wa.wsdot.apps.analytics.client.activities.twitter.view.ranking; /** * Custom widget for displaying top 5 tweets for most/least likes and most/least retweets. * * Listens for DateSubmitEvents */ public class RankingView extends Composite{ interface MyEventBinder extends EventBinder<RankingView> {} private final MyEventBinder eventBinder = GWT.create(MyEventBinder.class); private static TweetsViewUiBinder uiBinder = GWT .create(TweetsViewUiBinder.class); interface TweetsViewUiBinder extends UiBinder<Widget, RankingView> { } @UiField static MaterialPreLoader loader; @UiField static MaterialCollection mostRetweet; @UiField static MaterialCollection mostLiked; @UiField static MaterialCollection leastRetweet; @UiField static MaterialCollection leastLiked; @UiField static MaterialLink retweetTab; @UiField static MaterialLink likeTab; final Resources res;
public RankingView(ClientFactory clientFactory) {
0
Petschko/Java-RPG-Maker-MV-Decrypter
src/main/java/org/petschko/rpgmakermv/decrypt/gui/Update.java
[ "public class Const {\n\tpublic static final String CREATOR = \"Petschko\";\n\tpublic static final String CREATOR_URL = \"https://petschko.org/\";\n\tpublic static final String CREATOR_DONATION_URL = \"https://www.paypal.me/petschko\";\n\n\t// System Constance's\n\tpublic static final String DS = System.getProperty...
import org.petschko.lib.Const; import org.petschko.lib.gui.JOptionPane; import org.petschko.lib.gui.notification.ErrorWindow; import org.petschko.lib.gui.notification.InfoWindow; import org.petschko.lib.update.UpdateException; import org.petschko.rpgmakermv.decrypt.App; import org.petschko.rpgmakermv.decrypt.Config; import org.petschko.rpgmakermv.decrypt.Preferences; import java.awt.*; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException;
package org.petschko.rpgmakermv.decrypt.gui; /** * @author Peter Dragicevic */ class Update { private GUI gui; private org.petschko.lib.update.Update update = null; private String[] options; private boolean autoOptionExists = false; private boolean ranAutomatically = false; /** * Update constructor * * @param gui - Main GUI-Object */ Update(GUI gui) { this.gui = gui; this.options = new String[] {"Update", "Show whats new", "Cancel"}; this.init(); } /** * Update constructor * * @param gui - Main GUI-Object * @param auto - This ran automatically */ Update(GUI gui, boolean auto) { this.gui = gui; this.options = new String[] {"Update", "Show whats new", "Disable update check", "Cancel"}; this.autoOptionExists = true; this.ranAutomatically = auto; this.init(); } /** * Inits the Object */ private void init() { try { if(this.ranAutomatically) update = new org.petschko.lib.update.Update(Config.UPDATE_URL, Config.VERSION_NUMBER, Config.UPDATE_CHECK_EVERY_SECS); else update = new org.petschko.lib.update.Update(Config.UPDATE_URL, Config.VERSION_NUMBER, true); } catch (IOException e) { if(! this.ranAutomatically) {
ErrorWindow ew = new ErrorWindow("Can't check for Updates...", ErrorWindow.ERROR_LEVEL_WARNING, false);
2
meridor/stecker
stecker-plugin-loader/src/main/java/org/meridor/stecker/impl/DefaultDependencyChecker.java
[ "public class PluginException extends Exception {\n\n private Optional<DependencyProblem> dependencyProblem = Optional.empty();\n\n private Optional<PluginMetadata> pluginMetadata = Optional.empty();\n\n public PluginException(Exception e) {\n super(e);\n }\n\n public PluginException(String me...
import org.meridor.stecker.PluginException; import org.meridor.stecker.PluginMetadata; import org.meridor.stecker.VersionRelation; import org.meridor.stecker.interfaces.Dependency; import org.meridor.stecker.interfaces.DependencyChecker; import org.meridor.stecker.interfaces.PluginsAware; import org.meridor.stecker.interfaces.VersionComparator; import java.util.ArrayList; import java.util.List; import java.util.Optional;
package org.meridor.stecker.impl; public class DefaultDependencyChecker implements DependencyChecker { @Override
public void check(PluginsAware pluginRegistry, PluginMetadata pluginMetadata) throws PluginException {
1
swookiee/com.swookiee.runtime
com.swookiee.runtime.ewok/src/main/java/com/swookiee/runtime/ewok/servlet/BundleServlet.java
[ "public class BundleRepresentation {\n\n private long id;\n private long lastModified;\n private String location;\n private int state;\n private String symbolicName;\n private String version;\n\n public BundleRepresentation() {\n }\n\n public BundleRepresentation(final long id, final long...
import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.startlevel.BundleStartLevel; import org.osgi.framework.wiring.FrameworkWiring; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.swookiee.runtime.ewok.representation.BundleRepresentation; import com.swookiee.runtime.ewok.representation.BundleStartlevelRepresentation; import com.swookiee.runtime.ewok.representation.BundleStatusRepresentation; import com.swookiee.runtime.ewok.util.HttpErrorException; import com.swookiee.runtime.ewok.util.ServletUtil;
/******************************************************************************* * Copyright (c) 2014 Lars Pfannenschmidt and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Lars Pfannenschmidt - initial API and implementation, ongoing development and documentation *******************************************************************************/ package com.swookiee.runtime.ewok.servlet; /** * This {@link HttpServlet} implements the Bundle Resource (5.1.3), Bundle State Resource (5.1.4), Bundle Header * Resource (5.1.5) &amp; Bundle Startlevel Resource (5.1.6) of the OSGi RFC-182 draft version 8. @see <a href= * https://github.com/osgi/design/tree/master/rfcs/rfc0182> https://github.com/osgi/design/tree/master/rfcs/rfc0182</a> * */ public class BundleServlet extends HttpServlet { public static final String ALIAS = "/framework/bundle"; private static final long serialVersionUID = -8784847583201231060L; private static final Logger logger = LoggerFactory.getLogger(BundleServlet.class); private final BundleContext bundleContext; private final ObjectMapper mapper; public BundleServlet(final BundleContext bundleContext) { this.bundleContext = bundleContext; this.mapper = new ObjectMapper(); } @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException { try { final long bundleId = ServletUtil.getId(request); final Bundle bundle = ServletUtil.checkAndGetBundle(bundleContext, bundleId); String json; if (isStartLevelRequest(request)) { json = getBundleStartlevel(bundle); } else if (isHeaderRequest(request)) { final Map<String, String> header = ServletUtil.transformToMapAndCleanUp(bundle.getHeaders()); json = mapper.writeValueAsString(header); } else if (isStateRequest(request)) {
final BundleStatusRepresentation bundleStatusRepresentation = new BundleStatusRepresentation(
2
dkzwm/SmoothRefreshLayout
app/src/main/java/me/dkzwm/widget/srl/sample/DemoApplication.java
[ "public interface IRefreshViewCreator {\n IRefreshView<IIndicator> createHeader(SmoothRefreshLayout layout);\n\n IRefreshView<IIndicator> createFooter(SmoothRefreshLayout layout);\n}", "public class SmoothRefreshLayout extends ViewGroup\n implements NestedScrollingParent3, NestedScrollingChild3 {\n ...
import android.app.Application; import me.dkzwm.widget.srl.IRefreshViewCreator; import me.dkzwm.widget.srl.SmoothRefreshLayout; import me.dkzwm.widget.srl.extra.IRefreshView; import me.dkzwm.widget.srl.extra.footer.ClassicFooter; import me.dkzwm.widget.srl.extra.header.ClassicHeader; import me.dkzwm.widget.srl.indicator.IIndicator;
package me.dkzwm.widget.srl.sample; /** * Created by dkzwm on 2017/6/28. * * @author dkzwm */ public class DemoApplication extends Application { @Override public void onCreate() { super.onCreate(); SmoothRefreshLayout.setDefaultCreator( new IRefreshViewCreator() { @Override
public IRefreshView<IIndicator> createHeader(SmoothRefreshLayout layout) {
5
ajonkisz/TraVis
src/travis/view/project/graph/GraphTooltip.java
[ "public class UIHelper {\n\n private static final UIHelper INSTANCE = new UIHelper();\n\n public enum MessageType {\n INFORMATION, WARNING, ERROR\n }\n\n public enum Mode {\n ATTACH, PLAYBACK\n }\n\n private Mode mode;\n\n private final JFileChooser fc;\n private volatile File ...
import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.util.Collection; import java.util.concurrent.LinkedBlockingDeque; import javax.swing.JPanel; import travis.controller.UIHelper; import travis.model.attach.Playback.Mode; import travis.view.Util; import travis.view.project.graph.connection.ConnectionPainter; import travis.view.project.graph.connection.ExecutionPoint; import travis.view.project.graph.connection.GraphBspline; import travis.view.settings.Settings;
String text = null; switch (mode) { case METHOD: text = ep.getComponentData().getComp().getTooltipFriendlyName() + " THREAD: " + ep.getTrace().getThreadId(); break; case CLASS: text = ep.getComponentData().getComp().getParent() .getTooltipFriendlyName() + " THREAD: " + ep.getTrace().getThreadId(); break; case PACKAGE: text = ep.getComponentData().getComp().getParent().getParent() .getTooltipFriendlyName() + " THREAD: " + ep.getTrace().getThreadId(); break; default: break; } return text; } private String getTextForSpline(SplineData sd) { Mode mode = getMode(); String text = null; switch (mode) { case METHOD: text = "FROM " + sd.getSrc().getComp().getTooltipFriendlyName() + " TO " + sd.getDest().getComp().getTooltipFriendlyName() + " THREAD: " + sd.getDestTrace().getThreadId(); break; case CLASS: text = "FROM " + sd.getSrc().getComp().getParent() .getTooltipFriendlyName() + " TO " + sd.getDest().getComp().getParent() .getTooltipFriendlyName() + " THREAD: " + sd.getDestTrace().getThreadId(); break; case PACKAGE: text = "FROM " + sd.getSrc().getComp().getParent().getParent() .getTooltipFriendlyName() + " TO " + sd.getDest().getComp().getParent().getParent() .getTooltipFriendlyName() + " THREAD: " + sd.getDestTrace().getThreadId(); break; default: break; } return text; } private Mode getMode() { Mode mode = Mode.PACKAGE; if (Settings.getInstance().isDrawingStruct(Settings.STRUCT_METHOD)) { mode = Mode.METHOD; } else if (Settings.getInstance().isDrawingStruct( Settings.STRUCT_CLASS)) { mode = Mode.CLASS; } return mode; } private void drawTooltip(FontMetrics fm, String text, Point tooltipCoord, Graphics2D g2, int height, Color background) { int width = fm.stringWidth(text); int rectWidth = width + MARGIN * 2; Point coord = new Point(tooltipCoord); if (coord.x + rectWidth >= getWidth()) coord.x -= coord.x + rectWidth - getWidth(); g2.setColor(background); g2.fillRoundRect(coord.x, coord.y - height + fm.getDescent(), rectWidth, height, height / 2, height / 2); g2.setColor(Color.BLACK); g2.drawString(text, coord.x + MARGIN, coord.y); } public void displayExecutionPointTooltip(ExecutionPoint ep) { UIHelper helper = UIHelper.getInstance(); if (helper.getMode() == UIHelper.Mode.PLAYBACK && Settings.getInstance().getCurvesPerSec() <= MAX_CURVES_PER_SEC_FOR_PLAYBACK_TOOLTIP) { playbackExecutionPoint = ep; } else { playbackExecutionPoint = null; } if (ep == null || ep.getComponentData() == null || ep.getCenter() == null) { playbackExecutionPoint = null; } } private class MouseListener extends MouseAdapter { @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { text = null; splines.clear(); repaint(); } @Override public void mouseMoved(MouseEvent e) { text = null; splines.clear(); GraphPanel graph = UIHelper.getInstance().getGraph(); TreeRepresentation treeRep = graph.getTreeRepRepresentation();
ConnectionPainter connPainter = graph.getConnectionPainter();
3
hufeiya/CoolSignIn
AndroidClient/app/src/main/java/com/hufeiya/SignIn/fragment/SignInFragment.java
[ "public class CategorySelectionActivity extends AppCompatActivity {\n\n private static final String EXTRA_PLAYER = \"player\";\n private User user;\n\n public static void start(Activity activity, User user, ActivityOptionsCompat options) {\n Intent starter = getStartIntent(activity, user);\n ...
import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.app.Fragment; import android.support.v4.util.Pair; import android.support.v4.view.ViewCompat; import android.support.v4.view.animation.FastOutSlowInInterpolator; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.ProgressBar; import android.widget.Toast; import com.hufeiya.SignIn.R; import com.hufeiya.SignIn.activity.CategorySelectionActivity; import com.hufeiya.SignIn.adapter.AvatarAdapter; import com.hufeiya.SignIn.helper.PreferencesHelper; import com.hufeiya.SignIn.helper.TransitionHelper; import com.hufeiya.SignIn.model.Avatar; import com.hufeiya.SignIn.model.User; import com.hufeiya.SignIn.net.AsyncHttpHelper;
/* * Copyright 2015 Google Inc. * * 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.hufeiya.SignIn.fragment; /** * Enable selection of an {@link Avatar} and user name. */ public class SignInFragment extends Fragment { private static final String ARG_EDIT = "EDIT"; private static final String KEY_SELECTED_AVATAR_INDEX = "selectedAvatarIndex"; private User mUser; private EditText phone; private EditText pass; private Avatar mSelectedAvatar = Avatar.ONE; private View mSelectedAvatarView; private GridView mAvatarGrid; private FloatingActionButton mDoneFab; private boolean edit; public ProgressBar progressBar; public static SignInFragment newInstance(boolean edit) { Bundle args = new Bundle(); args.putBoolean(ARG_EDIT, edit); SignInFragment fragment = new SignInFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { if (savedInstanceState != null) { int savedAvatarIndex = savedInstanceState.getInt(KEY_SELECTED_AVATAR_INDEX); mSelectedAvatar = Avatar.values()[savedAvatarIndex]; } super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View contentView = inflater.inflate(R.layout.fragment_sign_in, container, false); contentView.addOnLayoutChangeListener(new View. OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { v.removeOnLayoutChangeListener(this); setUpGridView(getView()); } }); return contentView; } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(KEY_SELECTED_AVATAR_INDEX, mSelectedAvatar.ordinal()); super.onSaveInstanceState(outState); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { assurePlayerInit(); checkIsInEditMode(); if (null == mUser || edit) { view.findViewById(R.id.empty).setVisibility(View.GONE); view.findViewById(R.id.content).setVisibility(View.VISIBLE); initContentViews(view); initContents(); } else { final Activity activity = getActivity(); CategorySelectionActivity.start(activity, mUser); activity.finish(); } super.onViewCreated(view, savedInstanceState); } private void checkIsInEditMode() { final Bundle arguments = getArguments(); //noinspection SimplifiableIfStatement if (null == arguments) { edit = false; } else { edit = arguments.getBoolean(ARG_EDIT, false); } } private void initContentViews(View view) { TextWatcher textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* no-op */ } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // showing the floating action button if text is entered if (s.length() == 0) { mDoneFab.hide(); } else { mDoneFab.show(); } } @Override public void afterTextChanged(Editable s) { /* no-op */ } }; progressBar = (ProgressBar)view.findViewById(R.id.empty); phone = (EditText) view.findViewById(R.id.phone); phone.addTextChangedListener(textWatcher); pass = (EditText) view.findViewById(R.id.pass); pass.addTextChangedListener(textWatcher); mDoneFab = (FloatingActionButton) view.findViewById(R.id.done); mDoneFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.done: progressBar.setVisibility(View.VISIBLE);
AsyncHttpHelper.login(phone.getText().toString(),pass.getText().toString(),SignInFragment.this);
6
lauriholmas/batmapper
src/main/java/com/glaurung/batMap/controller/MapperEngine.java
[ "public class CorpsePanel extends JPanel implements ActionListener, ComponentListener, KeyListener, DocumentListener {\n\n private CorpseModel model = new CorpseModel();\n private String BASEDIR;\n private MapperPlugin plugin;\n private final Color TEXT_COLOR = Color.LIGHT_GRAY;\n private final Color...
import java.awt.Color; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.io.IOException; import java.util.*; import com.glaurung.batMap.gui.*; import com.glaurung.batMap.gui.corpses.CorpsePanel; import com.glaurung.batMap.io.AreaDataPersister; import com.glaurung.batMap.io.GuiDataPersister; import com.glaurung.batMap.vo.Area; import com.glaurung.batMap.vo.AreaSaveObject; import com.glaurung.batMap.vo.Exit; import com.glaurung.batMap.vo.Room; import com.mythicscape.batclient.interfaces.BatWindow; import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath; import edu.uci.ics.jung.graph.SparseMultigraph; import edu.uci.ics.jung.graph.util.EdgeType; import edu.uci.ics.jung.graph.util.Pair; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.RenderContext; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.PluggableGraphMouse; import edu.uci.ics.jung.visualization.control.ScalingGraphMousePlugin; import edu.uci.ics.jung.visualization.control.TranslatingGraphMousePlugin; import edu.uci.ics.jung.visualization.decorators.EdgeShape; import edu.uci.ics.jung.visualization.decorators.ToStringLabeller; import edu.uci.ics.jung.visualization.picking.PickedState; import edu.uci.ics.jung.visualization.transform.MutableTransformer;
package com.glaurung.batMap.controller; public class MapperEngine implements ItemListener, ComponentListener { SparseMultigraph<Room, Exit> graph; VisualizationViewer<Room, Exit> vv; MapperLayout mapperLayout; Room currentRoom = null; Area area = null; MapperPanel panel; PickedState<Room> pickedState; String baseDir; BatWindow batWindow; ScalingGraphMousePlugin scaler; MapperPickingGraphMousePlugin mapperPickingGraphMousePlugin; boolean snapMode = true;
CorpsePanel corpsePanel;
0
thlcly/Mini-JVM
src/main/java/com/aaront/exercise/jvm/commands/GetStaticFieldCommand.java
[ "@Data\npublic class ClassFile {\n private String magicNumber;\n private int majorVersion;\n private int minorVersion;\n private ClassIndex classIndex;\n private InterfaceIndex interfaceIndex;\n private ConstantPool constantPool;\n private List<ClassAccessFlag> accessFlags;\n private List<Fi...
import com.aaront.exercise.jvm.ClassFile; import com.aaront.exercise.jvm.constant.ClassConstant; import com.aaront.exercise.jvm.constant.ConstantPool; import com.aaront.exercise.jvm.constant.FieldRefConstant; import com.aaront.exercise.jvm.engine.ExecutionResult; import com.aaront.exercise.jvm.engine.Heap; import com.aaront.exercise.jvm.engine.JavaObject; import com.aaront.exercise.jvm.engine.StackFrame;
package com.aaront.exercise.jvm.commands; /** * @author tonyhui * @since 17/6/17 */ public class GetStaticFieldCommand extends TwoOperandCommand { public GetStaticFieldCommand(ClassFile clzFile, String opCode, int operand1, int operand2) { super(clzFile, opCode, operand1, operand2); } @Override public String toString(ConstantPool pool) { return super.getOperandAsField(pool); } /** * 获取对象的静态字段值 */ @Override public void execute(StackFrame frame, ExecutionResult result) { FieldRefConstant fieldRefConstant = (FieldRefConstant) this.getConstantInfo(this.getIndex()); ClassConstant classConstant = fieldRefConstant.getClassConstant(); String className = classConstant.getClassName();
JavaObject jo = Heap.getInstance().newObject(className);
5
jGleitz/JUnit-KIT
src/final2/subtests/PraktomatPublicTest.java
[ "public class Input {\n\tprivate static HashMap<String, String[]> filesMap = new HashMap<>();\n\tprivate static HashMap<String[], String> reverseFileMap = new HashMap<>();\n\n\t/**\n\t * This class is not meant to be instantiated.\n\t */\n\tprivate Input() {\n\t}\n\n\t/**\n\t * Returns a path to a file containing t...
import static org.hamcrest.CoreMatchers.is; import org.junit.Test; import test.Input; import test.SystemExitStatus; import test.runs.LineRun; import test.runs.NoOutputRun; import test.runs.Run;
package final2.subtests; /** * Simulates the Praktomat's public test. * * @author Martin Löper */ public class PraktomatPublicTest extends LangtonSubtest { public PraktomatPublicTest() { setAllowedSystemExitStatus(SystemExitStatus.WITH_0); } /** * "Fundamental tests with ordinary ant" Asserts that tested program fulfils the first public Praktomat test. */ @Test public void fundamentalTestsWithOrdinaryAnt() { String[] expectedOutput = pitchToLowercase(PUBLIC_PRAKTOMAT_TEST_FILE_1); runs = new Run[] { checkPitch(expectedOutput), new LineRun("position A", is("2,1")), new LineRun("position a", is("2,1")), new LineRun("field 2,1", is("a")), new LineRun("direction a", is("N")), new LineRun("ant", is("a")), new NoOutputRun("create e,0,0"), new LineRun("ant", is("a,e")), new LineRun("direction e", is("S")), new NoOutputRun("move 1"), new LineRun("direction e", is("O")), new NoOutputRun("quit") };
sessionTest(runs, Input.getFile(PUBLIC_PRAKTOMAT_TEST_FILE_1));
0
codebulb/LambdaOmega
src/test/java/ch/codebulb/lambdaomega/LBaseTest.java
[ "public static <T> L<T> L(Stream<T> stream) {\n return new L(stream.collect(Collectors.toList()));\n}", "public static <T> L<T> l() {\n return new L<>(new ArrayList<>());\n}", "public static <T> List<T> list(T... ts) {\n return l(ts).l;\n}", "public static final List<Integer> EXPECTED_LIST = new Arra...
import static ch.codebulb.lambdaomega.L.L; import static ch.codebulb.lambdaomega.L.l; import static ch.codebulb.lambdaomega.L.list; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST; import static ch.codebulb.lambdaomega.TestUtil.assertEquals; import ch.codebulb.lambdaomega.abstractions.I; import java.util.ArrayList; import java.util.List; import org.junit.AfterClass; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.BeforeClass; import org.junit.Test;
package ch.codebulb.lambdaomega; /** * Basic test cases for {@link L}. */ public class LBaseTest { @BeforeClass public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
0
TreyRuffy/CommandBlocker
Command Blocker Bungee/src/main/java/me/treyruffy/commandblocker/bungeecord/BungeeMain.java
[ "public class Universal {\n\n\tprivate static Universal instance = null;\n\tprivate MethodInterface mi;\n\t\n\tpublic static Universal get() {\n\t\treturn instance == null ? instance = new Universal() : instance;\n\t}\n\t\n\tpublic void setup(MethodInterface mi) {\n\t\tthis.mi = mi;\n\t\t\n\t\tmi.setupMetrics();\n\...
import me.treyruffy.commandblocker.Universal; import me.treyruffy.commandblocker.bungeecord.commands.CommandBlockerCommand; import me.treyruffy.commandblocker.bungeecord.config.BungeeConfigManager; import me.treyruffy.commandblocker.bungeecord.config.BungeeUpdateConfig; import me.treyruffy.commandblocker.bungeecord.listeners.BungeeBlock; import me.treyruffy.commandblocker.bungeecord.listeners.BungeeCommandValueListener; import me.treyruffy.commandblocker.bungeecord.listeners.TabCompletion; import me.treyruffy.commandblocker.bungeecord.listeners.Update; import net.kyori.adventure.platform.bungeecord.BungeeAudiences; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.config.Configuration; import org.jetbrains.annotations.NotNull; import java.io.IOException;
package me.treyruffy.commandblocker.bungeecord; public class BungeeMain extends Plugin { private static BungeeMain instance; private static BungeeAudiences adventure; public static @NotNull BungeeAudiences adventure() { if (adventure == null) { throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!"); } return adventure; } public static BungeeMain get() { return instance; } @Override public void onEnable() { if (!getDataFolder().exists()) { getDataFolder().mkdir(); } adventure = BungeeAudiences.create(this); instance = this; Universal.get().setup(new BungeeMethods()); getProxy().getPluginManager().registerListener(this, new Update()); getProxy().getPluginManager().registerListener(this, new BungeeBlock());
getProxy().getPluginManager().registerListener(this, new TabCompletion());
6
artur-tamazian/avro-schema-generator
src/test/java/com/at/avro/integration/HsqlIntegrationTest.java
[ "public class AvroSchema {\n private final String name;\n private final String namespace;\n private final String doc;\n\n private List<AvroField> fields;\n\n private Map<String, String> customProperties = new LinkedHashMap<>();\n\n public AvroSchema(Table table, AvroConfig avroConfig) {\n t...
import com.at.avro.AvroSchema; import com.at.avro.DbSchemaExtractor; import com.at.avro.SchemaGenerator; import com.at.avro.config.AvroConfig; import com.at.avro.config.FormatterConfig; import com.at.avro.formatters.SchemaFormatter; import com.at.avro.mappers.RemovePlural; import com.at.avro.mappers.ToCamelCase; import org.flywaydb.core.Flyway; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.List; import java.util.function.Function; import static helper.Utils.classPathResourceContent; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.at.avro.integration; /** * @author artur@callfire.com */ public class HsqlIntegrationTest { private static final String CONNECTION_URL = "jdbc:hsqldb:mem:testcase;shutdown=true"; private static Connection CONNECTION; private AvroConfig avroConfig = new AvroConfig("test.namespace"); private DbSchemaExtractor extractor; @BeforeClass public static void setupClass() throws SQLException { CONNECTION = DriverManager.getConnection(CONNECTION_URL, "sa", ""); Flyway.configure() .dataSource(CONNECTION_URL, "sa", "") .locations("classpath:hsql/db/migration") .load().migrate(); } @AfterClass public static void teardownClass() throws Exception { CONNECTION.close(); } @Before public void setup() throws SQLException { extractor = new DbSchemaExtractor(CONNECTION_URL, "sa", ""); } @Test public void testGenerationWithDefaultSettings() { AvroSchema avroSchema = extractor.getForTable(avroConfig, "public", "test_records"); assertThat(SchemaGenerator.generate(avroSchema), is(classPathResourceContent("/hsql/avro/default.avsc"))); } @Test public void testGenerationWithAllNullableFields() { avroConfig.setNullableTrueByDefault(true); AvroSchema avroSchema = extractor.getForTable(avroConfig, "public", "test_records"); assertThat(SchemaGenerator.generate(avroSchema), is(classPathResourceContent("/hsql/avro/all_nullable.avsc"))); } @Test public void testGenerationAllFieldsDefaultNull() { avroConfig.setAllFieldsDefaultNull(true); AvroSchema avroSchema = extractor.getForTable(avroConfig, "public", "test_records"); assertThat(SchemaGenerator.generate(avroSchema), is(classPathResourceContent("/hsql/avro/all_fields_default_null.avsc"))); } @Test public void testSpecificFormatterConfig() { FormatterConfig formatterConfig = FormatterConfig.builder() .setIndent(" ") .setPrettyPrintFields(true) .build(); AvroSchema avroSchema = extractor.getForTable(avroConfig, "public", "test_records"); assertThat(SchemaGenerator.generate(avroSchema, formatterConfig), is(classPathResourceContent("/hsql/avro/pretty_print_bigger_indent.avsc"))); } @Test public void testNonPrettyPrint() { FormatterConfig formatterConfig = FormatterConfig.builder() .setPrettyPrintSchema(false) .build(); AvroSchema avroSchema = extractor.getForTable(avroConfig, "public", "test_records"); assertThat(SchemaGenerator.generate(avroSchema, formatterConfig), is(classPathResourceContent("/hsql/avro/non_pretty_print.avsc"))); } @Test public void testNameMappers() {
Function<String, String> nameMapper = new ToCamelCase().andThen(new RemovePlural());
7
azinik/ADRMine
release/v1/java_src/ADRMine/src/main/java/edu/asu/diego/loader/DocumentAnalyzer.java
[ "@Entity\n@Table( name = \"Artifact\" )\npublic class Artifact {\n\tString content;\n\tString generalized_content;\n\tList<Artifact> childsArtifact;\n\tArtifact parentArtifact;\n\tArtifact nextArtifact;\n\tArtifact previousArtifact;\n\tType artifactType;\n\tprivate boolean forTrain;\n\tprivate boolean forDemo=false...
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.prefs.PreferenceChangeEvent; import rainbownlp.core.Artifact; import rainbownlp.core.Setting; import rainbownlp.util.FileUtil; import rainbownlp.util.HibernateUtil; import rainbownlp.util.StringUtil; import rainbownlp.analyzer.IDocumentAnalyzer; import rainbownlp.analyzer.Tokenizer; import edu.stanford.nlp.ling.HasWord; import edu.stanford.nlp.ling.Word; import edu.stanford.nlp.process.PTBTokenizer; import preprocessutils.Preprocess; import preprocessutils.TwitterPreprocessing;
package edu.asu.diego.loader; public class DocumentAnalyzer implements IDocumentAnalyzer{ public boolean isForDemo =false;
List<Artifact> loadedSentences = new ArrayList<>();
0
cattaka/AdapterToolbox
example/src/main/java/net/cattaka/android/adaptertoolbox/example/FizzBuzzExampleActivity.java
[ "public class ScrambleAdapter<T> extends AbsScrambleAdapter<\n ScrambleAdapter<T>,\n ScrambleAdapter<?>,\n RecyclerView.ViewHolder,\n ForwardingListener<ScrambleAdapter<?>, RecyclerView.ViewHolder>,\n T\n > {\n private Context mContext;\n private List<T> mItems;\n\n ...
import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import net.cattaka.android.adaptertoolbox.adapter.ScrambleAdapter; import net.cattaka.android.adaptertoolbox.adapter.listener.ListenerRelay; import net.cattaka.android.adaptertoolbox.example.adapter.factory.BuzzViewHolderFactory; import net.cattaka.android.adaptertoolbox.example.adapter.factory.FizzBuzzViewHolderFactory; import net.cattaka.android.adaptertoolbox.example.adapter.factory.FizzViewHolderFactory; import net.cattaka.android.adaptertoolbox.example.adapter.factory.IntegerViewHolderFactory; import net.cattaka.android.adaptertoolbox.example.logic.SnackbarLogic; import java.util.ArrayList; import java.util.List;
package net.cattaka.android.adaptertoolbox.example; /** * Created by cattaka on 16/05/02. */ public class FizzBuzzExampleActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener { ListenerRelay<ScrambleAdapter<?>, RecyclerView.ViewHolder> mListenerRelay = new ListenerRelay<ScrambleAdapter<?>, RecyclerView.ViewHolder>() { @Override public void onClick(@NonNull RecyclerView recyclerView, @NonNull ScrambleAdapter adapter, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull View view) { if (recyclerView.getId() == R.id.recycler) { if (viewHolder instanceof FizzViewHolderFactory.ViewHolder) { Integer item = (Integer) adapter.getItemAt(viewHolder.getAdapterPosition()); mSnackbarLogic.make(viewHolder.itemView, "Fizz " + item + " is clicked.", Snackbar.LENGTH_SHORT).show();
} else if (viewHolder instanceof BuzzViewHolderFactory.ViewHolder) {
2
DorsetProject/dorset-framework
agents/web-api/src/test/java/edu/jhuapl/dorset/agents/StockAgentTest.java
[ "public interface Agent {\n\n /**\n * Get the name of the agent\n *\n * @return name\n */\n public String getName();\n\n /**\n * Override the default name of the agent\n *\n * @param name New name for the agent\n */\n public void setName(String name);\n\n /**\n * ...
import edu.jhuapl.dorset.agents.Agent; import edu.jhuapl.dorset.agents.AgentRequest; import edu.jhuapl.dorset.agents.AgentResponse; import edu.jhuapl.dorset.http.HttpClient; import edu.jhuapl.dorset.http.HttpRequest; import edu.jhuapl.dorset.http.HttpResponse; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.io.FileNotFoundException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; import org.junit.Test;
/** * Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC * 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 * limitations under the License. */ package edu.jhuapl.dorset.agents; public class StockAgentTest { private String apikey = "default_apikey"; protected String getJsonData(String filename) { ClassLoader classLoader = StockAgent.class.getClassLoader(); URL url = classLoader.getResource(filename); try { Path path = Paths.get(url.toURI()); try (Scanner scanner = new Scanner(new File(path.toString()))) { return scanner.useDelimiter("\\Z").next(); } } catch (URISyntaxException | FileNotFoundException e) { throw new RuntimeException(e); } } @Test public void testStockAgentExactMatch() { String keyword = "facebook, Inc."; String jsonData = getJsonData("stockagent/MockJson_Facebook.json");
HttpClient client = new FakeHttpClient(new FakeHttpResponse(jsonData));
3
bladecoder/blade-ink
src/test/java/com/bladecoder/ink/runtime/test/RuntimeSpecTest.java
[ "public class Profiler {\n\tprivate Stopwatch continueWatch = new Stopwatch();\n\tprivate Stopwatch stepWatch = new Stopwatch();\n\tprivate Stopwatch snapWatch = new Stopwatch();\n\n\tprivate double continueTotal;\n\tprivate double snapTotal;\n\tprivate double stepTotal;\n\n\tprivate String[] currStepStack;\n\tpriv...
import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.bladecoder.ink.runtime.Profiler; import com.bladecoder.ink.runtime.Story; import com.bladecoder.ink.runtime.Story.ExternalFunction; import com.bladecoder.ink.runtime.Story.ExternalFunction0; import com.bladecoder.ink.runtime.Story.ExternalFunction1; import com.bladecoder.ink.runtime.Story.ExternalFunction2; import com.bladecoder.ink.runtime.Story.ExternalFunction3; import com.bladecoder.ink.runtime.Story.VariableObserver; import com.bladecoder.ink.runtime.StoryException;
package com.bladecoder.ink.runtime.test; public class RuntimeSpecTest { /** * Test external function call. */ @Test public void externalFunction() throws Exception { List<String> text = new ArrayList<>(); String json = TestUtils.getJsonString("inkfiles/runtime/external-function-2-arg.ink.json"); final Story story = new Story(json); story.bindExternalFunction("externalFunction", new ExternalFunction<Integer>() { @Override public Integer call(Object[] args) throws Exception { int x = story.tryCoerce(args[0], Integer.class); int y = story.tryCoerce(args[1], Integer.class); return x - y; } }); TestUtils.nextAll(story, text); Assert.assertEquals(1, text.size()); Assert.assertEquals("The value is -1.", text.get(0)); } /** * Test external function zero arguments call. */ @Test public void externalFunctionZeroArguments() throws Exception { List<String> text = new ArrayList<>(); String json = TestUtils.getJsonString("inkfiles/runtime/external-function-0-arg.ink.json"); final Story story = new Story(json); story.bindExternalFunction("externalFunction", new ExternalFunction0<String>() { @Override protected String call() { return "Hello world"; } }); TestUtils.nextAll(story, text); Assert.assertEquals(1, text.size()); Assert.assertEquals("The value is Hello world.", text.get(0)); } /** * Test external function one argument call. */ @Test public void externalFunctionOneArgument() throws Exception { List<String> text = new ArrayList<>(); String json = TestUtils.getJsonString("inkfiles/runtime/external-function-1-arg.ink.json"); final Story story = new Story(json); story.bindExternalFunction("externalFunction", new ExternalFunction1<Integer, Boolean>() { @Override protected Boolean call(Integer arg) { return arg != 1; } }); TestUtils.nextAll(story, text); Assert.assertEquals(1, text.size()); Assert.assertEquals("The value is false.", text.get(0)); } /** * Test external function one argument call. Overrides coerce method. */ @Test public void externalFunctionOneArgumentCoerceOverride() throws Exception { List<String> text = new ArrayList<>(); String json = TestUtils.getJsonString("inkfiles/runtime/external-function-1-arg.ink.json"); final Story story = new Story(json); story.bindExternalFunction("externalFunction", new ExternalFunction1<Boolean, Boolean>() { @Override protected Boolean coerceArg(Object arg) throws Exception { return story.tryCoerce(arg, Boolean.class); } @Override protected Boolean call(Boolean arg) { return !arg; } }); TestUtils.nextAll(story, text); Assert.assertEquals(1, text.size()); Assert.assertEquals("The value is false.", text.get(0)); } /** * Test external function two arguments call. */ @Test public void externalFunctionTwoArguments() throws Exception { List<String> text = new ArrayList<>(); String json = TestUtils.getJsonString("inkfiles/runtime/external-function-2-arg.ink.json"); final Story story = new Story(json);
story.bindExternalFunction("externalFunction", new ExternalFunction2<Integer, Float, Integer>() {
5
neoremind/navi-pbrpc
src/main/java/com/baidu/beidou/navi/pbrpc/client/BlockingIOPbrpcClient.java
[ "public class CallFuture<T> implements Future<T>, Callback<T> {\r\n\r\n /**\r\n * 内部回调用的栅栏\r\n */\r\n private final CountDownLatch latch = new CountDownLatch(1);\r\n\r\n /**\r\n * 调用返回结果\r\n */\r\n private T result = null;\r\n\r\n /**\r\n * 调用错误信息\r\n */\r\n private Throwab...
import io.netty.channel.ChannelFuture; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.baidu.beidou.navi.pbrpc.client.callback.CallFuture; import com.baidu.beidou.navi.pbrpc.codec.Codec; import com.baidu.beidou.navi.pbrpc.codec.impl.ProtobufCodec; import com.baidu.beidou.navi.pbrpc.exception.client.OperationNotSupportException; import com.baidu.beidou.navi.pbrpc.exception.client.PbrpcConnectionException; import com.baidu.beidou.navi.pbrpc.exception.client.PbrpcException; import com.baidu.beidou.navi.pbrpc.protocol.Header; import com.baidu.beidou.navi.pbrpc.transport.PbrpcMsg; import com.google.protobuf.GeneratedMessage;
package com.baidu.beidou.navi.pbrpc.client; /** * ClassName: BlockingIOPbrpcClient <br/> * Function: 简单的远程访问客户端,使用短连接Blocking IO方式调用服务端,不使用nio * * @author Zhang Xu */ public class BlockingIOPbrpcClient implements PbrpcClient { private static final Logger LOG = LoggerFactory.getLogger(BlockingIOPbrpcClient.class); /** * 远程服务ip地址 */ private String ip; /** * 远程服务端口 */ private int port; /** * 客户端连接超时,单位毫秒 */ private int connTimeout; /** * 客户端调用超时,单位毫秒 */ private int readTimeout; /** * 是否为短连接调用 */ private boolean isShortAliveConn = true; /** * 长连接调用会使用的 */ private Socket socket; /** * 客户端配置 */ private PbrpcClientConfiguration pbrpcClientConfiguration = new PbrpcClientConfiguration(); /** * 可配置,默认使用protobuf来做body的序列化 */ private Codec codec = new ProtobufCodec(); /** * header+body通讯协议方式的头解析构造器 */ private HeaderResolver headerResolver = new NsHeaderResolver(); public BlockingIOPbrpcClient() { } /** * Creates a new instance of BlockingIOPbrpcClient. * * @param pbrpcClientConfiguration * @param isShortAliveConnection * @param ip * @param port * @param connTimeout * @param readTimeout */ BlockingIOPbrpcClient(PbrpcClientConfiguration pbrpcClientConfiguration, boolean isShortAliveConnection, String ip, int port, int connTimeout, int readTimeout) { if (pbrpcClientConfiguration != null) { this.pbrpcClientConfiguration = pbrpcClientConfiguration; } this.isShortAliveConn = isShortAliveConnection; this.ip = ip; this.port = port; this.connTimeout = connTimeout; this.readTimeout = readTimeout; } /** * Creates a new instance of BlockingIOPbrpcClient. * * @param ip * @param port * @param connTimeout * @param readTimeout */ public BlockingIOPbrpcClient(String ip, int port, int connTimeout, int readTimeout) { this(null, true, ip, port, connTimeout, readTimeout); } /** * @see com.baidu.beidou.navi.pbrpc.client.PbrpcClient#connect() */ public ChannelFuture connect() {
throw new OperationNotSupportException();
3
buni-rock/Pixie
04_Software/03_Development/02_SourceCode/java/src/gui/editobject/BoxEdit.java
[ "public class Constants {\n\n /**\n * Number of objects which can be segmented in the application\n */\n public static final int NUMBER_OF_OBJECTS = 2;\n\n /**\n * The path to the user preferences containing the configuration specific to\n * the user.\n */\n public static final Strin...
import gui.support.CustomTreeNode; import gui.support.Objects; import java.awt.Color; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.List; import java.util.Observable; import library.BoxLRTB; import observers.ObservedActions; import paintpanels.DrawConstants; import common.Constants; import common.ConstantsLabeling; import common.UserPreferences; import common.Utils;
// refresh the displayed image displayImage(); // change the title of the frame setFrameTitle(); // refresh also the image on the GUI observable.notifyObservers(ObservedActions.Action.SELECTED_OBJECT_MOVED); } @Override protected void changeObjColor() { // set the color of the object objectColor = getNewObjColor(objectColor); // set the color on the drawing panel dPPreviewImg.setObjColor(objectColor); // refresh the image on the panel showImage(); // refresh the color of the object id label setObjIdColor(); } @Override protected void displayObjId() { // add the object id // set the text of the object jLObjId.setText("Object id: " + currentObject.getObjectId()); // set the color of the object id label setObjIdColor(); } @Override protected void setFrameTitle() { String title = ""; // add the size of the object (original) title += "Preview " + currentObject.getOuterBBox().width + "x" + currentObject.getOuterBBox().height; // if the work image has different size, show it in brackets (for zooming) if (!dPPreviewImg.getWorkImgSize().equals(dPPreviewImg.getOrigImgSize())) { // compute the size of the box with the zooming factor Rectangle resizedOuterBox = dPPreviewImg.getResize().resizeBox(currentObject.getOuterBBox()); // display the zoomed size title += " (" + resizedOuterBox.width + "x" + resizedOuterBox.height + ")"; } setTitle(title); } @Override protected void updateBorderValue(int value) { // get the value of the border only if it is valid // the border has to be greater than a min value value = Math.max(value, Constants.MIN_BORDER); // the border cannot be more than the distance from the box to the image border value = Math.min(value, getMaxPossibleBorder()); // set the border size borderPX = value; // save the user preference currentObject.getUserPreference().setBorderSize(borderPX); // update text field jTFBorder.setText(Integer.toString(borderPX)); // refresh the displayed image displayImage(); } /** * Compute the distances from the box to the borders and sort it. * * @return the value of the max displayable border */ protected int getMaxPossibleBorder() { // for simplicity, use a shorter name Rectangle objBox = currentObject.getOuterBBox(); // save the borders inside an array int[] maxBorder = new int[4]; // save the max border values (the distance from box to the image border) maxBorder[0] = objBox.x; maxBorder[1] = objBox.y; maxBorder[2] = frameImg.getWidth() - (objBox.x + objBox.width); maxBorder[3] = frameImg.getHeight() - (objBox.y + objBox.height); // sort the array into ascending order, according to the natural ordering of its elements Arrays.sort(maxBorder); // return the greatest value of the array return maxBorder[3]; } @Override protected final void displayImage() { displayBox = getBorderedSize(currentObject.getOuterBBox(), borderPX); displayImage(displayBox); } /** * Display the image with the segmented box. */ @Override protected void showImage() { // get the graphics of the image Graphics2D g2d = workImg.createGraphics(); // draw the outer box of the object drawObjContour(g2d); g2d.dispose();
updatePreview(workImg, DrawConstants.DrawType.DO_NOT_DRAW, currentObject.getUserPreference().getZoomingIndex());
8
corehunter/corehunter3
corehunter-services/corehunter-services-simple/src/main/java/org/corehunter/services/simple/SimpleCoreHunterRunServices.java
[ "public class CoreHunter {\n\n // defaults\n private static final int DEFAULT_MAX_TIME_WITHOUT_IMPROVEMENT = 10000;\n private static final int FAST_MAX_TIME_WITHOUT_IMPROVEMENT = 2000;\n \n // parallel tempering settings\n private static final int PT_NUM_REPLICAS = 10;\n private static fina...
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.ObjectUtils; import org.corehunter.CoreHunter; import org.corehunter.CoreHunterArguments; import org.corehunter.listener.SimpleCoreHunterListener; import org.corehunter.services.CoreHunterRun; import org.corehunter.services.CoreHunterRunArguments; import org.corehunter.services.CoreHunterRunResult; import org.corehunter.services.CoreHunterRunServices; import org.corehunter.services.CoreHunterRunStatus; import org.corehunter.services.DatasetServices; import org.jamesframework.core.subset.SubsetSolution; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.XStreamException; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.StaxDriver; import uno.informatics.data.pojo.SimpleEntityPojo;
/*--------------------------------------------------------------*/ /* 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 org.corehunter.services.simple; /** * A simple CoreHunterRunServices implementation. Sub-classes, can use the * {@link #SimpleCoreHunterRunServices(DatasetServices) constructor} provided * path is defined in the overloaded constructor using the * {@link #setPath(Path)} method * * @author daveneti * */ public class SimpleCoreHunterRunServices implements CoreHunterRunServices { Logger logger = LoggerFactory.getLogger(SimpleCoreHunterRunServices.class); private static final String RESULTS_PATH = "RESULTS_PATH"; private DatasetServices datasetServices; private ExecutorService executor; private List<CoreHunterRun> corehunterRuns; private Map<String, CoreHunterRunResult> corehunterResultsMap; public String charsetName = "utf-8"; private boolean shuttingDown; private boolean shutDown; private Path path; /** * Constructor that can be used by sub-classes provided the path is defined * in the overloaded constructor using the {@link #setPath(Path)} method * * @param datasetServices * the dataset services in to be used by these services * @throws IOException * if the path can not be set or is invalid */ protected SimpleCoreHunterRunServices(DatasetServices datasetServices) throws IOException { this.datasetServices = datasetServices; executor = createExecutorService(); corehunterResultsMap = new HashMap<>(); } /** * Constructor that is a path to defined the location of the datasets * * @param path * the location of the datasets * @param datasetServices * the dataset services in to be used by these services * @throws IOException * if the path can not be set or is invalid */ public SimpleCoreHunterRunServices(Path path, DatasetServices datasetServices) throws IOException { this(datasetServices); setPath(path); } public final Path getPath() { return path; } public synchronized final void setPath(Path path) throws IOException { if (path == null) { throw new IOException("Path must be defined!"); } this.path = path; initialise(); } @Override
public CoreHunterRun executeCoreHunter(CoreHunterRunArguments arguments) {
4
eckig/graph-editor
api/src/main/java/de/tesis/dynaware/grapheditor/GraphEditor.java
[ "public interface GConnection extends EObject {\n\t/**\n\t * Returns the value of the '<em><b>Id</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <p>\n\t * If the meaning of the '<em>Id</em>' attribute isn't clear,\n\t * there really should be more of a description here...\n\t * </p>\n\t * <!-- end-user-doc...
import java.util.Collection; import java.util.function.BiFunction; import java.util.function.Function; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.ecore.EObject; import de.tesis.dynaware.grapheditor.model.GConnection; import de.tesis.dynaware.grapheditor.model.GModel; import de.tesis.dynaware.grapheditor.model.GNode; import de.tesis.dynaware.grapheditor.utils.GraphEditorProperties; import de.tesis.dynaware.grapheditor.utils.RemoveContext; import javafx.beans.property.ObjectProperty; import javafx.scene.layout.Region;
/* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor; /** * Provides functionality for displaying and editing graph-like diagrams in * JavaFX. * * <p> * Example: * * <pre> * <code>GModel model = GraphFactory.eINSTANCE.createGModel(); * * GraphEditor graphEditor = new DefaultGraphEditor(); * graphEditor.setModel(model); * * Region view = graphEditor.getView();</code> * </pre> * * The view is a {@link Region} and can be added to the JavaFX scene graph in * the usual way. For large graphs, the editor can be put inside a pannable * container (see module core) instead. * </p> * * <p> * The editor updates its underlying model via EMF commands. This means any user * action should be undoable. Helper methods for common operations are provided * in the {@link Commands} class, such as: * * <ul> * <li>Add Node</li> * <li>Clear All</li> * <li>Undo</li> * <li>Redo</li> * </ul> * * </p> * * <p> * Look and feel can be customised by setting custom skin classes. The default * skins can also be customised to some extent via CSS. See <b>defaults.css</b> * in the core module for more information. * </p> */ public interface GraphEditor extends GraphEditorSkins { /** * Sets a custom connector validator. * * <p> * This will be used to decide which connections are allowed / forbidden during drag and drop events in the editor. * </p> * * @param validator a custom validator implements {@link GConnectorValidator}, or null to use the default validator */ void setConnectorValidator(final GConnectorValidator validator); /** * Sets the graph model to be edited. * * @param model the {@link GModel} to be edited */ void setModel(final GModel model); /** * Gets the graph model that is currently being edited. * * @return the {@link GModel} being edited, or {@code null} if no model was ever set */ GModel getModel(); /** * Reloads the graph model currently being edited. * * <p> * <b>Note: </b><br> * If the model is updated via EMF commands, as is recommended, it should rarely be necessary to call this method. * The model will be reloaded automatically via a command-stack listener. * </p> */ void reload(); /** * The property containing the graph model being edited. * * @return a property containing the {@link GModel} being edited */ ObjectProperty<GModel> modelProperty(); /** * Gets the view where the graph is displayed and edited. * * <p> * The view is a JavaFX {@link Region}. It should be added to the scene * graph in the usual way. * </p> * * @return the {@link Region} where the graph is displayed and edited */ Region getView(); /** * Gets the properties of the editor. * * <p> * This provides access to global properties such as: * * <ul> * <li>Show/hide alignment grid.</li> * <li>Toggle snap-to-grid on/off.</li> * <li>Toggle editor bounds on/off.</li> * </ul> * * </p> * * @return an {@link GraphEditorProperties} instance containing the properties of the editor */ GraphEditorProperties getProperties(); /** * Gets the skin lookup. * * <p> * The skin lookup is used to get any skin instance associated to a model element instance. * </p> * * @return a {@link SkinLookup} used to lookup skins */ SkinLookup getSkinLookup(); /** * Gets the selection manager. * * <p> * The selection manager keeps track of the selected nodes, connections, * etc. * </p> * * @return the {@link SelectionManager} */ SelectionManager getSelectionManager(); /** * Sets a method to be called when a connection is created in the editor. * * <p> * This can be used to append additional commands to the one that created the connection. * </p> * * @param consumer a consumer to append additional commands */
void setOnConnectionCreated(Function<GConnection, Command> consumer);
0
cert-se/megatron-java
src/se/sitic/megatron/db/ImportSystemData.java
[ "public class AppProperties {\n // -- Keys in properties file --\n\n // Implicit\n public static final String JOB_TYPE_NAME_KEY = \"implicit.jobTypeName\";\n\n // General\n public static final String LOG4J_FILE_KEY = \"general.log4jConfigFile\";\n public static final String LOG_DIR_KEY = \"general...
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import se.sitic.megatron.core.AppProperties; import se.sitic.megatron.core.MegatronException; import se.sitic.megatron.core.TypedProperties; import se.sitic.megatron.entity.Organization; import se.sitic.megatron.util.Constants; import se.sitic.megatron.util.IpAddressUtil;
package se.sitic.megatron.db; public class ImportSystemData { private static final Logger log = Logger.getLogger(ImportSystemData.class);
private TypedProperties props;
1
loehndorf/scengen
src/main/java/scengen/paper/QuantizationGridBench.java
[ "public class Generator {\n\t\n\tstatic long _seed = 191;\n\t\n\t/**\n\t * <p>Generate a reduced set of scenarios from a normal, log-normal, or uniform, probability distribution with given parameters.</br>\n\t * Use the following arguments to run the program:</p>\n\t * <ul><li>dist=(Normal, Lognormal, Student, Unif...
import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Map; import java.util.Random; import scengen.application.Generator; import scengen.distribution.MultivariateDistribution; import scengen.distribution.MultivariateNormal; import scengen.measures.WassersteinDistance; import scengen.methods.METHOD; import scengen.methods.MonteCarlo; import scengen.tools.Statistics; import scengen.tools.Xorshift;
package scengen.paper; public class QuantizationGridBench { static int _sampleSize = 100000; static int _numRepititions = 10; static long _seed = 191; static Random _rand = new Xorshift(_seed); static String filename = "comparison_"+System.nanoTime()+".txt"; static int[][] dimScens = new int[][]{{2,4},{2,40},{10,20},{10,200}}; public static void main (String... args) throws IOException { FileOutputStream stream = new FileOutputStream(filename); BufferedWriter br = new BufferedWriter(new OutputStreamWriter(stream)); String s = "Dimensions\tScenarios\tMethod\tWasserstein\tSE\n"; br.write(s);br.flush(); System.out.print(s); for (int[] dimScen : dimScens) { int dim = dimScen[0]; int numScen = dimScen[1]; double[] means = new double[dim]; double[][] cov = new double[dim][dim]; for (int i=0; i<dim; i++) cov[i][i] = 1; MultivariateDistribution mvDist = new MultivariateNormal(means,cov,_rand); for (METHOD method : new METHOD[]{METHOD.QuantizationGrids,METHOD.QuantizationLearning}) {
Statistics wasserStat = new Statistics();
6
FabioZumbi12/PixelVip
PixelVip-Spigot/src/main/java/br/net/fabiozumbi12/pixelvip/bukkit/PixelVip.java
[ "public class PackageManager {\n\n private YamlConfiguration packages;\n private PixelVip plugin;\n private File fPack;\n\n public PackageManager(PixelVip plugin) {\n this.plugin = plugin;\n\n packages = new YamlConfiguration();\n fPack = new File(plugin.getDataFolder(), \"packages....
import br.net.fabiozumbi12.pixelvip.bukkit.Packages.PackageManager; import br.net.fabiozumbi12.pixelvip.bukkit.PaymentsAPI.MercadoPagoHook; import br.net.fabiozumbi12.pixelvip.bukkit.PaymentsAPI.PagSeguroHook; import br.net.fabiozumbi12.pixelvip.bukkit.PaymentsAPI.PayPalHook; import br.net.fabiozumbi12.pixelvip.bukkit.PaymentsAPI.PaymentModel; import br.net.fabiozumbi12.pixelvip.bukkit.bungee.PixelVipBungee; import br.net.fabiozumbi12.pixelvip.bukkit.cmds.PVCommands; import br.net.fabiozumbi12.pixelvip.bukkit.config.PVConfig; import br.net.fabiozumbi12.pixelvip.bukkit.metrics.Metrics; import com.earth2me.essentials.Essentials; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*;
package br.net.fabiozumbi12.pixelvip.bukkit; public class PixelVip extends JavaPlugin implements Listener { public PixelVip plugin; public Server serv; public PluginDescriptionFile pdf; public Essentials ess; public HashMap<String, String> processTrans; private PVLogger logger; private int task = 0; private List<PaymentModel> payments; private PVUtil util; private Permission perms; private PVConfig config; private PermsAPI permApi; private PixelVipBungee pvBungee;
private PackageManager packageManager;
0
sviperll/static-mustache
static-mustache/src/main/java/com/github/sviperll/staticmustache/token/MustacheTokenizer.java
[ "public abstract class MustacheToken {\n public static MustacheToken beginSection(final String name) {\n return new MustacheToken() {\n @Override\n public <R, E extends Exception> R accept(Visitor<R, E> visitor) throws E {\n return visitor.beginSection(name);\n ...
import com.github.sviperll.staticmustache.Position; import com.github.sviperll.staticmustache.PositionedToken; import com.github.sviperll.staticmustache.ProcessingException; import com.github.sviperll.staticmustache.TokenProcessor; import com.github.sviperll.staticmustache.token.util.BracesTokenizer; import com.github.sviperll.staticmustache.token.util.PositionHodingTokenProcessor; import javax.annotation.Nonnull; import com.github.sviperll.staticmustache.MustacheToken;
/* * Copyright (c) 2014, Victor Nazarov <asviraspossible@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.github.sviperll.staticmustache.token; /** * * @author Victor Nazarov <asviraspossible@gmail.com> */ public class MustacheTokenizer implements TokenProcessor<PositionedToken<BracesToken>> { /** * Creates TokenProcessor to be feed one-by-one with each character of mustache template. * Last fed character must be TokenProcessor#EOF wich denotes end of file. * * @param fileName fileName used in error messages. It can be custom string like "&lt;stdin&gt;" * @param downstream TokenProcessor is invoked on each found MustacheToken * @return . */ public static TokenProcessor<Character> createInstance(String fileName, TokenProcessor<PositionedToken<MustacheToken>> downstream) { TokenProcessor<PositionedToken<BracesToken>> mustacheTokenizer = new MustacheTokenizer(new PositionHodingTokenProcessor<MustacheToken>(downstream)); return BracesTokenizer.createInstance(fileName, mustacheTokenizer); } private final PositionHodingTokenProcessor<MustacheToken> downstream; private MustacheTokenizerState state = new OutsideMustacheTokenizerState(this); private Position position; MustacheTokenizer(PositionHodingTokenProcessor<MustacheToken> downstream) { this.downstream = downstream; } @Override
public void processToken(@Nonnull PositionedToken<BracesToken> positionedToken) throws ProcessingException {
3
epfl-labos/eagle
src/main/java/ch/epfl/eagle/api/EagleFrontendClient.java
[ "public class Network {\n \n public static THostPort socketAddressToThrift(InetSocketAddress address) {\n return new THostPort(address.getAddress().getHostAddress(), address.getPort());\n }\n\n /** Return the hostname of this machine, based on configured value, or system\n * Interrogation. */\n public sta...
import ch.epfl.eagle.daemon.util.Network; import ch.epfl.eagle.daemon.util.TClients; import ch.epfl.eagle.daemon.util.TServers; import ch.epfl.eagle.thrift.FrontendService; import ch.epfl.eagle.thrift.IncompleteRequestException; import ch.epfl.eagle.thrift.SchedulerService; import ch.epfl.eagle.thrift.SchedulerService.Client; import ch.epfl.eagle.thrift.TSchedulingRequest; import ch.epfl.eagle.thrift.TUserGroupInfo; import java.util.Random; import java.io.IOException; import java.net.InetSocketAddress; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.log4j.Logger; import org.apache.thrift.TException;
/* * EAGLE * * Copyright 2016 Operating Systems Laboratory EPFL * * Modified from Sparrow - University of California, Berkeley * * 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 ch.epfl.eagle.api; //[[FLORIN /** * Java client to Eagle scheduling service. Once a client is initialize()'d it * can be used safely from multiple threads. */ public class EagleFrontendClient { public static boolean launchedServerAlready = false; private final static Logger LOG = Logger.getLogger(EagleFrontendClient.class); private final static int NUM_CLIENTS = 8; // Number of concurrent requests we support //[[FLORIN private final static int DEFAULT_LISTEN_PORT = new Random().nextInt(30000)+20000; BlockingQueue<SchedulerService.Client> clients = new LinkedBlockingQueue<SchedulerService.Client>(); /** * Initialize a connection to an eagle scheduler. * @param eagleSchedulerAddr. The socket address of the Eagle scheduler. * @param app. The application id. Note that this must be consistent across frontends * and backends. * @param frontendServer. A class which implements the frontend server interface (for * communication from Eagle). * @throws IOException */ public void initialize(InetSocketAddress eagleSchedulerAddr, String app, FrontendService.Iface frontendServer) throws TException, IOException { LOG.info("EagleFrontendClient using port: "+DEFAULT_LISTEN_PORT); initialize(eagleSchedulerAddr, app, frontendServer, DEFAULT_LISTEN_PORT); } /** * Initialize a connection to an eagle scheduler. * @param eagleSchedulerAddr. The socket address of the Eagle scheduler. * @param app. The application id. Note that this must be consistent across frontends * and backends. * @param frontendServer. A class which implements the frontend server interface (for * communication from Eagle). * @param listenPort. The port on which to listen for request from the scheduler. * @throws IOException */ public void initialize(InetSocketAddress eagleSchedulerAddr, String app, FrontendService.Iface frontendServer, int listenPort) throws TException, IOException { FrontendService.Processor<FrontendService.Iface> processor = new FrontendService.Processor<FrontendService.Iface>(frontendServer); if (!launchedServerAlready) { try { TServers.launchThreadedThriftServer(listenPort, 8, processor); } catch (IOException e) { LOG.fatal("Couldn't launch server side of frontend", e); } launchedServerAlready = true; } for (int i = 0; i < NUM_CLIENTS; i++) { Client client = TClients.createBlockingSchedulerClient( eagleSchedulerAddr.getAddress().getHostAddress(), eagleSchedulerAddr.getPort(), 60000); clients.add(client); }
clients.peek().registerFrontend(app, Network.getIPAddress(new PropertiesConfiguration())
0
cjstehno/ersatz
ersatz/src/test/java/io/github/cjstehno/ersatz/impl/RequestMatcherTest.java
[ "public enum HttpMethod {\r\n\r\n /**\r\n * Wildcard matching any HTTP method.\r\n */\r\n ANY(\"*\"),\r\n\r\n /**\r\n * HTTP GET method matcher.\r\n */\r\n GET(\"GET\"),\r\n\r\n /**\r\n * HTTP HEAD method matcher.\r\n */\r\n HEAD(\"HEAD\"),\r\n\r\n /**\r\n * HTTP POS...
import io.github.cjstehno.ersatz.cfg.HttpMethod; import io.github.cjstehno.ersatz.encdec.DecoderChain; import io.github.cjstehno.ersatz.encdec.Decoders; import io.github.cjstehno.ersatz.encdec.RequestDecoders; import io.github.cjstehno.ersatz.match.CookieMatcher; import io.github.cjstehno.ersatz.server.MockClientRequest; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN; import static io.github.cjstehno.ersatz.cfg.HttpMethod.GET; import static io.github.cjstehno.ersatz.cfg.HttpMethod.HEAD; import static io.github.cjstehno.ersatz.match.ErsatzMatchers.stringIterableMatcher; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.IsIterableContaining.hasItem; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.params.provider.Arguments.arguments;
/** * Copyright (C) 2022 Christopher J. Stehno * * 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.github.cjstehno.ersatz.impl; class RequestMatcherTest { @ParameterizedTest @DisplayName("method") @MethodSource("methodProvider") void method(final HttpMethod method, final boolean result) { assertEquals(result, RequestMatcher.method(equalTo(HEAD)).matches(new MockClientRequest(method))); } private static Stream<Arguments> methodProvider() { return Stream.of( arguments(HEAD, true), arguments(GET, false) ); } @ParameterizedTest @DisplayName("path") @CsvSource({ "/something,true", "/some,false" }) void path(final String path, final boolean result) { assertEquals(result, RequestMatcher.path(equalTo("/something")).matches(new MockClientRequest(GET, path))); } @ParameterizedTest @DisplayName("content-type") @MethodSource("contentTypeProvider") void contentType(final MockClientRequest request, final boolean result) { assertEquals(result, RequestMatcher.contentType(startsWith("application/")).matches(request)); } private static Stream<Arguments> contentTypeProvider() { final var factory = new Function<String, MockClientRequest>() { @Override public MockClientRequest apply(String ctype) { final var mcr = new MockClientRequest(); mcr.setContentType(ctype); return mcr; } }; return Stream.of( arguments(factory.apply("application/json"), true), arguments(factory.apply("application/"), true), arguments(new MockClientRequest(), false) ); } @ParameterizedTest @DisplayName("header") @MethodSource("headerProvider") void header(final MockClientRequest request, final boolean result) { assertEquals(result, RequestMatcher.header("foo", hasItem("bar")).matches(request)); } private static Stream<Arguments> headerProvider() { return Stream.of( arguments(new MockClientRequest().header("foo", "bar"), true), arguments(new MockClientRequest().header("one", "two"), false), arguments(new MockClientRequest().header("Foo", "bar"), true), arguments(new MockClientRequest().header("Foo", "Bar"), false), arguments(new MockClientRequest(), false) ); } @ParameterizedTest @DisplayName("query") @MethodSource("queryProvider") void query(final MockClientRequest request, final boolean result) { assertEquals( result, RequestMatcher.query( "name",
stringIterableMatcher(List.of(equalTo("alpha"), equalTo("blah")))
7
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ApiClientIntegrationTest.java
[ "public abstract class ApiCallback {\n\n /**\n * Called when the API request succeeded.\n * This method executes on the main UI thread.\n * @param result The result from the API call.\n */\n\tpublic abstract void onSuccess(JSONObject result);\n\n /**\n * Called when an unrecoverable error ...
import android.content.Context; import com.sharethis.loopy.sdk.ApiCallback; import com.sharethis.loopy.sdk.ApiClient; import com.sharethis.loopy.sdk.Event; import com.sharethis.loopy.sdk.Item; import com.sharethis.loopy.sdk.Loopy; import com.sharethis.loopy.sdk.LoopyAccess; import com.sharethis.loopy.sdk.LoopyException; import com.sharethis.loopy.test.util.Holder; import com.sharethis.loopy.test.util.JsonAssert; import org.json.JSONObject; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
package com.sharethis.loopy.test; /** * tests against the mock API * * @author Jason Polites */ public class ApiClientIntegrationTest extends LoopyAndroidTestCase { ApiClient apiClient; String apiKey = "foobar_api_key"; String apiSecret = "foobar_api_secret"; String stdid = "foobar_stdid"; @Override public void setUp() throws Exception { super.setUp(); Context context = getLocalContext(); Loopy.onCreate(context, apiKey, apiSecret); Loopy.onStart(context); apiClient = LoopyAccess.getApiClient(); // Create a dummy STID apiClient.getState().setStdid("foobar_stdid"); } @Override public void tearDown() throws Exception { Context context = getLocalContext(); Loopy.onStop(context); Loopy.onDestroy(context); super.tearDown(); } public void testInstall() throws Exception { new ApiTestRunner() { @Override
void doApiCall(ApiClient client, ApiCallback callback) {
0
KodeMunkie/imagetozxspec
src/main/java/uk/co/silentsoftware/core/colourstrategy/GigaScreenPaletteStrategy.java
[ "public class OptionsObject {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(OptionsObject.class);\n\t\n\t/**\n\t * The version of preferences\n\t */\n\t@PreferencesField\n\tprivate int prefsVersion = 1;\n\t\n\t/**\n\t * The number of starts this app has had\n\t */\n\t@PreferencesField\n\tprivate in...
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import uk.co.silentsoftware.config.OptionsObject; import uk.co.silentsoftware.config.SpectrumDefaults; import uk.co.silentsoftware.core.attributestrategy.GigaScreenAttributeStrategy; import uk.co.silentsoftware.core.converters.image.processors.GigaScreenAttribute; import uk.co.silentsoftware.core.helpers.ColourHelper; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.concurrent.TimeUnit; import static uk.co.silentsoftware.config.LanguageSupport.getCaption; import static uk.co.silentsoftware.config.SpectrumDefaults.ATTRIBUTE_BLOCK_SIZE;
/* Image to ZX Spec * Copyright (C) 2020 Silent Software (Benjamin Brown) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.silentsoftware.core.colourstrategy; /** * GigaScreen palette strategy */ public class GigaScreenPaletteStrategy implements ColourChoiceStrategy { private static final int CACHE_TIME_SECONDS = 10; private static final Cache<String, GigaScreenAttribute[][]> CACHE = Caffeine.newBuilder().expireAfterAccess(CACHE_TIME_SECONDS, TimeUnit.SECONDS).build(); public String toString() { return getCaption("colour_mode_gigascreen"); } /** * Processing of the colours cannot be applied to both Spectrum screens used in Gigascreen at the same time. * If this method is called then the wrong processor implementation is being used. */ @Override public int chooseBestPaletteMatch(int originalRgb, int[] mostPopularRgbColours) { throw new UnsupportedOperationException("GigaScreen palette colouring cannot be applied to dither image processors - this is a placeholder class to allow identification during getClosestColour conversions for the GigaScreenConverter."); } @Override public int chooseBestPaletteMatch(int rgb) { return ColourHelper.getClosestColour(rgb, SpectrumDefaults.GIGASCREEN_COLOURS_ALL); } @Override public int[] getPalette() { return SpectrumDefaults.GIGASCREEN_COLOURS_ALL; } @Override public BufferedImage colourAttributes(BufferedImage output) { // Algorithm replaces each pixel with the colour from the closest matching // 4 colour GigaScreen attribute block. GigaScreenAttribute[] palette = OptionsObject.getInstance().getGigaScreenAttributeStrategy().getPalette(); GigaScreenAttribute[][] quad = getGigaScreenAttributes(output, palette); GigaScreenAttribute currentGigaScreenAttribute = null; for (int y = 0; y < output.getHeight(); ++y) { for (int x = 0; x < output.getWidth(); ++x) {
if (x % ATTRIBUTE_BLOCK_SIZE == 0) {
6
CyclopsMC/ColossalChests
src/main/java/org/cyclops/colossalchests/item/ItemUpgradeTool.java
[ "public class Advancements {\n\n public static final ChestFormedTrigger CHEST_FORMED = AdvancementHelpers\n .registerCriteriaTrigger(new ChestFormedTrigger());\n\n public static void load() {}\n\n}", "public class ChestMaterial extends ForgeRegistryEntry<ChestMaterial> {\n\n public static fina...
import com.google.common.collect.Lists; import lombok.Data; import lombok.EqualsAndHashCode; import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUseContext; import net.minecraft.util.ActionResultType; import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.math.vector.Vector3i; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import org.apache.commons.lang3.tuple.Pair; import org.cyclops.colossalchests.Advancements; import org.cyclops.colossalchests.block.ChestMaterial; import org.cyclops.colossalchests.block.ChestWall; import org.cyclops.colossalchests.block.ColossalChest; import org.cyclops.colossalchests.block.IBlockChestMaterial; import org.cyclops.colossalchests.block.Interface; import org.cyclops.colossalchests.tileentity.TileColossalChest; import org.cyclops.colossalchests.tileentity.TileInterface; import org.cyclops.cyclopscore.block.multi.DetectionResult; import org.cyclops.cyclopscore.datastructure.Wrapper; import org.cyclops.cyclopscore.helper.BlockHelpers; import org.cyclops.cyclopscore.helper.InventoryHelpers; import org.cyclops.cyclopscore.helper.MinecraftHelpers; import org.cyclops.cyclopscore.helper.TileHelpers; import org.cyclops.cyclopscore.inventory.PlayerInventoryIterator; import org.cyclops.cyclopscore.inventory.SimpleInventory; import java.util.List;
package org.cyclops.colossalchests.item; /** * An item to upgrade chests to the next tier. * @author rubensworks */ @EqualsAndHashCode(callSuper = false) @Data public class ItemUpgradeTool extends Item { private final boolean upgrade; public ItemUpgradeTool(Properties properties, boolean upgrade) { super(properties); this.upgrade = upgrade; } @Override public ActionResultType onItemUseFirst(ItemStack itemStack, ItemUseContext context) { BlockState blockState = context.getWorld().getBlockState(context.getPos());
if (blockState.getBlock() instanceof IBlockChestMaterial
4
ArtificialPB/DevelopmentKit
src/com/artificial/cachereader/fs/RT4CacheSystem.java
[ "public enum GameType {\n RT6(\"runescape\"),\n RT4(\"oldschool\");\n\n private final String folderName;\n\n GameType(final String folderName) {\n this.folderName = folderName;\n }\n\n public String getFolderName() {\n return folderName;\n }\n}", "public class ItemDefinitionLoad...
import com.artificial.cachereader.GameType; import com.artificial.cachereader.wrappers.rt4.loaders.ItemDefinitionLoader; import com.artificial.cachereader.wrappers.rt4.loaders.NpcDefinitionLoader; import com.artificial.cachereader.wrappers.rt4.loaders.ObjectDefinitionLoader; import com.artificial.cachereader.wrappers.rt4.loaders.ScriptLoader; import com.artificial.cachereader.wrappers.rt4.loaders.WidgetLoader;
package com.artificial.cachereader.fs; public class RT4CacheSystem extends CacheSystem<RT4CacheSystem> { public final ItemDefinitionLoader itemLoader; public final ObjectDefinitionLoader objectLoader; public final NpcDefinitionLoader npcLoader;
public final ScriptLoader scriptLoader;
4
olivierlemasle/java-certificate-authority
ca-api/src/main/java/io/github/olivierlemasle/caweb/cli/CreateCertificate.java
[ "public static CsrBuilder createCsr() {\n return new CsrBuilderImpl();\n}", "public static DnBuilder dn() {\n return new DnBuilderImpl();\n}", "public static RootCertificate loadRootCertificate(final String keystorePath,\n final char[] password, final String alias) {\n return RootCertificateLoader.loadRoo...
import static io.github.olivierlemasle.ca.CA.createCsr; import static io.github.olivierlemasle.ca.CA.dn; import static io.github.olivierlemasle.ca.CA.loadRootCertificate; import io.dropwizard.cli.Command; import io.dropwizard.setup.Bootstrap; import io.github.olivierlemasle.ca.Certificate; import io.github.olivierlemasle.ca.CertificateWithPrivateKey; import io.github.olivierlemasle.ca.CsrWithPrivateKey; import io.github.olivierlemasle.ca.DistinguishedName; import io.github.olivierlemasle.ca.RootCertificate; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser;
package io.github.olivierlemasle.caweb.cli; public class CreateCertificate extends Command { public CreateCertificate() { super("createcert", "Creates a signed certificate."); } @Override public void configure(final Subparser parser) { parser.addArgument("-s", "--subject") .dest("subject") .type(String.class) .required(true) .help("The subject CN"); parser.addArgument("-r", "--signer") .dest("signer") .type(String.class) .required(true) .help("The CN of the root certificate."); parser.addArgument("-i", "--in") .dest("in") .type(String.class) .required(true) .help("The name of the root certificate keystore"); parser.addArgument("-p", "--password") .dest("password") .type(String.class) .required(true) .help("The password of the keystore"); parser.addArgument("-c", "--cert") .dest("cert") .type(String.class) .required(true) .help("The certificate file to be created"); parser.addArgument("-k", "--key") .dest("key") .type(String.class) .required(true) .help("The key file to be created"); } @Override public void run(final Bootstrap<?> bootstrap, final Namespace namespace) throws Exception { final String subject = namespace.getString("subject"); final String signer = namespace.getString("signer"); final String in = namespace.getString("in"); final String password = namespace.getString("password"); final String cert = namespace.getString("cert"); final String key = namespace.getString("key"); final RootCertificate root = loadRootCertificate(in, password.toCharArray(), signer);
final DistinguishedName dn = dn().setCn(subject).build();
1
ivannov/predcomposer
src/test/java/com/nosoftskills/predcomposer/browser/fixtures/TestDataInserter.java
[ "@Stateless\npublic class CompetitionsService implements Serializable {\n\n public static final String DEFAULT_COMPETITION_NAME = \"Champions League 2016-2017\";\n\n private static final long serialVersionUID = 7432416155835050214L;\n\n @PersistenceContext\n EntityManager entityManager;\n\n private s...
import static com.nosoftskills.predcomposer.user.PasswordHashUtil.hashPassword; import com.nosoftskills.predcomposer.competition.CompetitionsService; import com.nosoftskills.predcomposer.model.Competition; import com.nosoftskills.predcomposer.model.Game; import com.nosoftskills.predcomposer.model.User; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Arrays;
/* * Copyright 2016 Microprofile.io * * 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.nosoftskills.predcomposer.browser.fixtures; @Singleton @Startup public class TestDataInserter { @PersistenceContext private EntityManager entityManager; @PostConstruct public void insertTestData() { User user1 = new User("ivan", hashPassword("ivan"), "ivan@example.com", "Ivan", "Ivanov", true); User user2 = new User("koko", hashPassword("koko"), "koko@example.com", "Koko", "Stefanov", false); LocalDate tomorrow = LocalDate.now().plusDays(1); LocalDateTime gameTime = LocalDateTime.of(tomorrow, LocalTime.of(21, 45));
Competition competition = new Competition(CompetitionsService.DEFAULT_COMPETITION_NAME);
1
KlubJagiellonski/pola-android
app/src/test/java/pl/pola_app/ui/activity/MainPresenterTest.java
[ "public class TestApplication extends Application {\n}", "public class EventLogger {\n\n private Context c;\n\n public EventLogger(Context context) {\n c = context;\n }\n\n public void logSearch(String result, String deviceId, String source) {\n if (!BuildConfig.USE_FIREBASE) {\n ...
import android.os.Bundle; import android.util.Log; import com.squareup.otto.Bus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import pl.pola_app.TestApplication; import pl.pola_app.helpers.EventLogger; import pl.pola_app.helpers.SessionId; import pl.pola_app.helpers.SettingsPreference; import pl.pola_app.model.SearchResult; import pl.pola_app.network.Api; import pl.pola_app.testutil.SearchUtil; import pl.pola_app.ui.adapter.ProductList; import retrofit2.Call; import retrofit2.Response; import static org.junit.Assert.fail; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when;
package pl.pola_app.ui.activity; @Config(application = TestApplication.class) @RunWith(RobolectricTestRunner.class) public class MainPresenterTest { @Mock private MainViewBinder viewBinder; @Mock private ProductList productList; @Mock private Api api; @Mock private Bus eventBus; @Mock private EventLogger logger; @Mock
private SessionId sessionId;
2
johndavidbustard/RoughWorld
src/utils/shapes/skinned/Animate.java
[ "public class GeneralMatrixDouble implements Serializable\r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic static final double EPSILON=5.9e-8f;\r\n\tpublic int width; //columns\r\n\tpublic int height; //rows\r\n\tpublic double[] value; //array of values\r\n\r\n\tpublic static void main(St...
import utils.GeneralMatrixDouble; import utils.GeneralMatrixFloat; import utils.GeneralMatrixInt; import utils.GeneralMatrixObject; import utils.GeneralMatrixString; import utils.Quaternion; import utils.shapes.human.HumanBones;
pbmat.width = 9; pbmat.height = 1; pbmat.setFromSubset(bmats, pbi); pbmat.width = 3; pbmat.height = 3; } //Calc inverse GeneralMatrixDouble.transpose(pbmat, pbmati); //calc the local matrix //calc the local bmat bmatl.width = 3; bmatl.height = 3; GeneralMatrixDouble.mult(bmat, pbmati, bmatl); //Now need to calc the inverse of the localbindmat //and compose to get the relative localmat bmat.width = 9; bmat.height = 1; bmat.setFromSubset(localbindbmats, bi); bmat.width = 3; bmat.height = 3; GeneralMatrixDouble.transpose(bmat, pbmati); GeneralMatrixDouble.mult(bmatl, pbmati, bmat); GeneralMatrixDouble.getEulerYXZ(bmat, euler); //now lets get the props from the params params.setRow(bi+1,euler); for(int li=0;li<3;li++) { int lind = bi*3+3+li; if(params.value[lind]<localboneangleLimits.value[6*bi+li*2]) { float dl = Math.abs(params.value[lind]-localboneangleLimits.value[6*bi+li*2+0]); totalerror += dl; params.value[lind] = localboneangleLimits.value[6*bi+li*2]; } if(params.value[lind]>localboneangleLimits.value[6*bi+li*2+1]) { float dl = Math.abs(params.value[lind]-localboneangleLimits.value[6*bi+li*2+1]); totalerror += dl; params.value[lind] = localboneangleLimits.value[6*bi+li*2+1]; } } } return totalerror; } public static String calcLocalRotationParams( GeneralMatrixInt bones, GeneralMatrixInt boneParents, GeneralMatrixInt boneUpdateOrder, GeneralMatrixFloat bmats, GeneralMatrixFloat localbindbmats, GeneralMatrixFloat localboneangleLimits, GeneralMatrixFloat params, GeneralMatrixString plog ) { float totalerror = 0.0f; params.setDimensions(3, bones.height+1); //Go through the bones and calculate their starting local mats (deformations are relative to this) for(int ubi=0;ubi<bones.height;ubi++) { int bi = ubi; if(boneUpdateOrder!=null) bi = boneUpdateOrder.value[ubi]; int pbi = boneParents.value[bi]; bmat.width = 9; bmat.height = 1; bmat.setFromSubset(bmats, bi); bmat.width = 3; bmat.height = 3; if(pbi==-1) { pbmat.width = 3; pbmat.height = 3; pbmat.setIdentity(); } else { pbmat.width = 9; pbmat.height = 1; pbmat.setFromSubset(bmats, pbi); pbmat.width = 3; pbmat.height = 3; } //Calc inverse GeneralMatrixDouble.transpose(pbmat, pbmati); //calc the local matrix //calc the local bmat bmatl.width = 3; bmatl.height = 3; GeneralMatrixDouble.mult(bmat, pbmati, bmatl); //Now need to calc the inverse of the localbindmat //and compose to get the relative localmat bmat.width = 9; bmat.height = 1; bmat.setFromSubset(localbindbmats, bi); bmat.width = 3; bmat.height = 3; GeneralMatrixDouble.transpose(bmat, pbmati); GeneralMatrixDouble.mult(bmatl, pbmati, bmat); GeneralMatrixDouble.getEulerYXZ(bmat, euler); //now lets get the props from the params params.setRow(bi+1,euler); for(int li=0;li<3;li++) { int lind = bi*3+3+li; if(params.value[lind]<localboneangleLimits.value[6*bi+li*2]) { float dl = Math.abs(params.value[lind]-localboneangleLimits.value[6*bi+li*2+0]); if(dl>0.01f)
plog.value[0] += ""+HumanBones.snames[bi]+":"+li+":"+dl+":"+params.value[lind]/HumanBones.DEG2RAD+"\n";
6
zqingyang521/qingyang
QingYangDemo/src/com/example/qingyangdemo/SettingActivity.java
[ "public class AppManager {\n\n\t// activity的堆栈\n\tprivate static Stack<Activity> activityStack;\n\n\tprivate static AppManager instance;\n\n\t/**\n\t * 单例\n\t */\n\tpublic static AppManager getAppManager() {\n\n\t\tif (instance == null) {\n\t\t\tinstance = new AppManager();\n\t\t}\n\t\treturn instance;\n\n\t}\n\n\t...
import java.io.File; import com.example.qingyangdemo.base.AppManager; import com.example.qingyangdemo.base.BaseApplication; import com.example.qingyangdemo.common.FileUtil; import com.example.qingyangdemo.common.UIHelper; import com.example.qingyangdemo.common.UpdateManager; import com.example.qingyangdemo.net.Constant; import com.example.qingyangdemo.ui.IpSetDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.view.View; import android.view.ViewGroup; import android.widget.ListView;
package com.example.qingyangdemo; /** * 系统设置类 * * @author 赵庆洋 * */ public class SettingActivity extends PreferenceActivity { private SharedPreferences mPreferences; private BaseApplication myApplication; // 设置Ip private Preference ipset; // 账户 private Preference account; // 清除缓存 private Preference cache; // 清除已下载数据 private Preference down; // 是否启动应用检查更新 private CheckBoxPreference checkup; // 是否开启提示声音 private CheckBoxPreference voice; // 检查更新 private Preference update; // 意见反馈 private Preference feedback; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 添加Activity到堆栈 AppManager.getAppManager().addActivity(this); myApplication = (BaseApplication) getApplication(); // 设置显示Preferences addPreferencesFromResource(R.xml.preferences); // 获得SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this); ListView localListView = getListView(); localListView.setBackgroundColor(0); localListView.setCacheColorHint(0); ((ViewGroup) localListView.getParent()).removeView(localListView); ViewGroup localViewGroup = (ViewGroup) getLayoutInflater().inflate( R.layout.setting_activity, null); ((ViewGroup) localViewGroup.findViewById(R.id.setting_content)) .addView(localListView, -1, -1); setContentView(localViewGroup); initView(); } private void initView() { // 登陆/注销 account = findPreference("account"); if (myApplication.isLogin()) { account.setTitle(R.string.main_menu_logout); } else { account.setTitle(R.string.main_menu_login); } account.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) {
UIHelper.loginOrLogout(SettingActivity.this);
3
jhy/jsoup
src/test/java/org/jsoup/parser/HtmlParserTest.java
[ "public class Jsoup {\n private Jsoup() {}\n\n /**\n Parse HTML into a Document. The parser will make a sensible, balanced document tree out of any HTML.\n\n @param html HTML to parse\n @param baseUri The URL where the HTML was retrieved from. Used to resolve relative URLs to absolute URLs, tha...
import org.jsoup.Jsoup; import org.jsoup.TextUtil; import org.jsoup.integration.ParseTest; import org.jsoup.internal.StringUtil; import org.jsoup.nodes.*; import org.jsoup.safety.Safelist; import org.jsoup.select.Elements; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.List; import static org.jsoup.parser.ParseSettings.preserveCase; import static org.junit.jupiter.api.Assertions.*;
@Test public void handlesJavadocFont() { String h = "<TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A>&nbsp;</TD>"; Document doc = Jsoup.parse(h); Element a = doc.select("a").first(); assertEquals("Deprecated", a.text()); assertEquals("font", a.child(0).tagName()); assertEquals("b", a.child(0).child(0).tagName()); } @Test public void handlesBaseWithoutHref() { String h = "<head><base target='_blank'></head><body><a href=/foo>Test</a></body>"; Document doc = Jsoup.parse(h, "http://example.com/"); Element a = doc.select("a").first(); assertEquals("/foo", a.attr("href")); assertEquals("http://example.com/foo", a.attr("abs:href")); } @Test public void normalisesDocument() { String h = "<!doctype html>One<html>Two<head>Three<link></head>Four<body>Five </body>Six </html>Seven "; Document doc = Jsoup.parse(h); assertEquals("<!doctype html><html><head></head><body>OneTwoThree<link>FourFive Six Seven </body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesEmptyDocument() { Document doc = Jsoup.parse(""); assertEquals("<html><head></head><body></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisesHeadlessBody() { Document doc = Jsoup.parse("<html><body><span class=\"foo\">bar</span>"); assertEquals("<html><head></head><body><span class=\"foo\">bar</span></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void normalisedBodyAfterContent() { Document doc = Jsoup.parse("<font face=Arial><body class=name><div>One</div></body></font>"); assertEquals("<html><head></head><body class=\"name\"><font face=\"Arial\"><div>One</div></font></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void findsCharsetInMalformedMeta() { String h = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"; // example cited for reason of html5's <meta charset> element Document doc = Jsoup.parse(h); assertEquals("gb2312", doc.select("meta").attr("charset")); } @Test public void testHgroup() { // jsoup used to not allow hgroup in h{n}, but that's not in spec, and browsers are OK Document doc = Jsoup.parse("<h1>Hello <h2>There <hgroup><h1>Another<h2>headline</hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup>"); assertEquals("<h1>Hello </h1><h2>There <hgroup><h1>Another</h1><h2>headline</h2></hgroup> <hgroup><h1>More</h1><p>stuff</p></hgroup></h2>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testRelaxedTags() { Document doc = Jsoup.parse("<abc_def id=1>Hello</abc_def> <abc-def>There</abc-def>"); assertEquals("<abc_def id=\"1\">Hello</abc_def> <abc-def>There</abc-def>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testHeaderContents() { // h* tags (h1 .. h9) in browsers can handle any internal content other than other h*. which is not per any // spec, which defines them as containing phrasing content only. so, reality over theory. Document doc = Jsoup.parse("<h1>Hello <div>There</div> now</h1> <h2>More <h3>Content</h3></h2>"); assertEquals("<h1>Hello <div>There</div> now</h1> <h2>More </h2><h3>Content</h3>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testSpanContents() { // like h1 tags, the spec says SPAN is phrasing only, but browsers and publisher treat span as a block tag Document doc = Jsoup.parse("<span>Hello <div>there</div> <span>now</span></span>"); assertEquals("<span>Hello <div>there</div> <span>now</span></span>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testNoImagesInNoScriptInHead() { // jsoup used to allow, but against spec if parsing with noscript Document doc = Jsoup.parse("<html><head><noscript><img src='foo'></noscript></head><body><p>Hello</p></body></html>"); assertEquals("<html><head><noscript>&lt;img src=\"foo\"&gt;</noscript></head><body><p>Hello</p></body></html>", TextUtil.stripNewlines(doc.html())); } @Test public void testUnclosedNoscriptInHead() { // Was getting "EOF" in html output, because the #anythingElse handler was calling an undefined toString, so used object.toString. String[] strings = {"<noscript>", "<noscript>One"}; for (String html : strings) { Document doc = Jsoup.parse(html); assertEquals(html + "</noscript>", TextUtil.stripNewlines(doc.head().html())); } } @Test public void testAFlowContents() { // html5 has <a> as either phrasing or block Document doc = Jsoup.parse("<a>Hello <div>there</div> <span>now</span></a>"); assertEquals("<a>Hello <div>there</div> <span>now</span></a>", TextUtil.stripNewlines(doc.body().html())); } @Test public void testFontFlowContents() { // html5 has no definition of <font>; often used as flow Document doc = Jsoup.parse("<font>Hello <div>there</div> <span>now</span></font>"); assertEquals("<font>Hello <div>there</div> <span>now</span></font>", TextUtil.stripNewlines(doc.body().html())); } @Test public void handlesMisnestedTagsBI() { // whatwg: <b><i></b></i> String h = "<p>1<b>2<i>3</b>4</i>5</p>"; Document doc = Jsoup.parse(h); assertEquals("<p>1<b>2<i>3</i></b><i>4</i>5</p>", doc.body().html()); // adoption agency on </b>, reconstruction of formatters on 4. } @Test public void handlesMisnestedTagsBP() { // whatwg: <b><p></b></p> String h = "<b>1<p>2</b>3</p>"; Document doc = Jsoup.parse(h); assertEquals("<b>1</b>\n<p><b>2</b>3</p>", doc.body().html()); } @Test public void handlesMisnestedAInDivs() { String h = "<a href='#1'><div><div><a href='#2'>child</a></div</div></a>"; String w = "<a href=\"#1\"></a> <div> <a href=\"#1\"></a> <div> <a href=\"#1\"></a><a href=\"#2\">child</a> </div> </div>"; Document doc = Jsoup.parse(h); assertEquals(
StringUtil.normaliseWhitespace(w),
3
gamblore/AndroidPunk
sample/AndroidPunkTest/src/com/gamblore/androidpunk/entities/Ogmo.java
[ "public class Entity extends Tweener {\n\n\tprivate static final String TAG = \"Entity\";\n\t\n /**\n * If the Entity should render.\n */\n public boolean visible = true;\n\n /**\n * If the Entity should respond to collision checks.\n */\n public boolean collidable = true;\n\n /**\n ...
import java.util.Vector; import net.androidpunk.Entity; import net.androidpunk.FP; import net.androidpunk.graphics.atlas.SpriteMap; import net.androidpunk.graphics.atlas.TileMap; import net.androidpunk.graphics.opengl.SubTexture; import net.androidpunk.utils.Input; import android.graphics.Point; import android.graphics.PointF; import android.view.KeyEvent; import com.gamblore.androidpunk.Main; import com.gamblore.androidpunk.OgmoEditorWorld;
package com.gamblore.androidpunk.entities; public class Ogmo extends Entity { private static final String TAG = "Ogmo"; public static final String TYPE_PLAYER = "player"; private static final int X_SPEED = 200; private static final int MAX_FALL_SPEED = 200; private static final int JUMP_SPEED = -500; private boolean mMoveLeft = false; private boolean mMoveRight = false; private boolean mMoveJump = false; //private static final String ANIM_STANDING = "standing"; public static final String ANIM_WALKING = "walking"; private PointF mVelocity = new PointF(); private SpriteMap mMap; private boolean mDead = false; private boolean mCanJump = false; private static final Vector<String> CollidableTypes = new Vector<String>(); public Ogmo(int x, int y) { super(x, y); SubTexture ogmo = Main.mAtlas.getSubTexture("ogmo"); mMap = new SpriteMap(ogmo, (int) ogmo.getWidth()/6, (int) ogmo.getHeight()); //mMap.add(ANIM_STANDING, new int[] {0}, 0); mMap.add(ANIM_WALKING, FP.frames(0, 5), 20); mMap.setFrame(0); //mMap.play(ANIM_STANDING); setGraphic(mMap); //setGraphic(new Image(FP.getBitmap(R.drawable.ogmo), new Rect(45,0,90,45))); setHitbox((int) ogmo.getWidth()/6, (int) ogmo.getHeight()); setType(TYPE_PLAYER); CollidableTypes.clear(); CollidableTypes.add("level"); } private void updateMoveBooleans() { mMoveJump = mMoveLeft = mMoveRight = false; if (Input.mouseDown) { Point points[] = Input.getTouches(); if (points[0].y < FP.height/4) { mMoveJump = true; return; } if (Input.getTouchesCount() > 1 || Input.checkKey(KeyEvent.KEYCODE_SPACE)) { mMoveJump = true; } if (points[0].x > FP.screen.getWidth()/2) { mMoveRight = true; } else { mMoveLeft = true; } } } @Override public void update() { updateMoveBooleans(); float deltax = 0, deltay = 0; mVelocity.y = mVelocity.y > MAX_FALL_SPEED ? MAX_FALL_SPEED : mVelocity.y + (1000 * FP.elapsed); if (mMoveJump && mCanJump) { Main.mJump.play(); y -= 1; // break locks to moving platforms. mVelocity.y = JUMP_SPEED; mCanJump = false; } if (mMoveLeft) { mVelocity.x = -X_SPEED; } if (mMoveRight) { mVelocity.x = X_SPEED; } mCanJump = false; deltax = (int)(mVelocity.x * FP.elapsed); deltay = (int)(mVelocity.y * FP.elapsed); float previousXVelocity = mVelocity.x; // Check for moving platforms Entity e; Entity platformVertical = collide(Platform.TYPE, x, (int) (y + deltay)); if ((e = collide(Platform.TYPE, (int) (x + deltax), y)) != null && platformVertical == null) { if (previousXVelocity < 0) { x = e.x + e.width + 1; } else { x = e.x - width - 1; } if (!Main.mBonk.getPlaying()) Main.mBonk.loop(1); } else if ((e = collideTypes(CollidableTypes, (int) (x + deltax), y)) != null) { if (mVelocity.y > 0) { mVelocity.y *= 0.90; }
int width = ((TileMap)e.getGraphic()).getTileWidth();
3
crukci-bioinformatics/MGA
src/main/java/org/cruk/mga/report/SummaryPlotter.java
[ "public static final int DEFAULT_PLOT_WIDTH = 800;", "public class AlignmentSummary implements Serializable\n{\n private static final long serialVersionUID = 1121576146340427575L;\n\n private String referenceGenomeId;\n private int alignedCount = 0;\n private int totalAlignedSequenceLength = 0;\n p...
import static org.cruk.mga.MGAConfig.DEFAULT_PLOT_WIDTH; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.imageio.ImageIO; import org.cruk.mga.AlignmentSummary; import org.cruk.mga.MGAConfig; import org.cruk.mga.MultiGenomeAlignmentSummary; import org.cruk.mga.ReferenceGenomeSpeciesMapping; import org.cruk.util.OrderedProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.cruk.mga.report; public class SummaryPlotter { private static final int[] INTERVALS = new int[] {5, 10, 25}; private static final int OPTIMUM_NO_INTERVALS = 6; private static final float ROW_HEIGHT_SCALING_FACTOR = 1.5f; private static final float ROW_GAP_SCALING_FACTOR = 2.0f; private static final int DEFAULT_FONT_SIZE = 12; private static final int DEFAULT_AXIS_FONT_SIZE = 10; private static final int DEFAULT_GAP_SIZE = 10; private static final Color ADAPTER_COLOR = new Color(255, 102, 255); private static final float MAX_ALPHA = 1.0f; private static final float MIN_ALPHA = 0.1f; private static final float MIN_ERROR = 0.0025f; private static final float MAX_ERROR = 0.01f; private static final String[] SPECIES_PROPERTY_NAMES = new String[] { "Species", "species" }; private static final String[] CONTROL_PROPERTY_NAMES = new String[] { "Control", "control" }; protected Logger log = LoggerFactory.getLogger(SummaryPlotter.class); public SummaryPlotter() { } /** * Creates a summary plot for the given set of multi-genome alignment summaries. * * @param multiGenomeAlignmentSummaries * @param the name of the image file * @throws IOException */
public void createSummaryPlot(MGAConfig mgaConfig,
2
ericleong/forceengine
Force Engine/src/forceengine/demo/objects/Gel.java
[ "public interface Colored {\n\tpublic Color getColor();\n}", "public class CircleMath {\n\t/**\n\t * checks whether or not 2 circles have collided with each other\n\t * \n\t * @param circle1\n\t * the first circle\n\t * @param circle2\n\t * the second circle\n\t * @return whether or not they...
import java.awt.Color; import forceengine.graphics.Colored; import forceengine.math.CircleMath; import forceengine.objects.Circle; import forceengine.objects.ForceCircle; import forceengine.objects.Point; import forceengine.objects.PointVector; import forceengine.objects.RectVector; import forceengine.objects.Vector;
package forceengine.demo.objects; public class Gel extends ForceCircle implements Colored { public static final Color color = new Color(26, 141, 240, 100); public Gel(double x, double y, double vx, double vy, double radius, double mass, double restitution) { super(x, y, vx, vy, radius, mass, restitution); } @Override public boolean isCollide(Object o) { if (o instanceof ForceCircle) return false; return true; } public boolean isResponsive(Object o) { return true; }
public Vector responsiveAcceleration(PointVector pv, double t, Point b) {
5
TU-Berlin-SNET/JCPABE
src/main/java/cpabe/bsw07/policy/Bsw07PolicyParentNode.java
[ "public class AbeDecryptionException extends GeneralSecurityException {\n\n private static final long serialVersionUID = 2848983353356933397L;\n\n public AbeDecryptionException(String msg) {\n super(msg);\n }\n\n public AbeDecryptionException(String msg, Throwable t) {\n super(msg, t);\n ...
import cpabe.AbeDecryptionException; import cpabe.AbeOutputStream; import cpabe.AbePrivateKey; import cpabe.AbePublicKey; import cpabe.bsw07.Bsw07Polynomial; import it.unisa.dia.gas.jpbc.Element; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
package cpabe.bsw07.policy; public class Bsw07PolicyParentNode extends Bsw07PolicyAbstractNode { private int threshold; private ArrayList<Bsw07PolicyAbstractNode> children; private ArrayList<Integer> satl; private Bsw07Polynomial poly; private Integer satisfiableChildrenCount = null; public Bsw07PolicyParentNode(int threshold, int numberOfChildren) { this.threshold = threshold; children = new ArrayList<>(numberOfChildren); } private static Element evalPoly(Bsw07Polynomial q, Element x) { Element r = x.duplicate().setToZero(); Element t = x.duplicate().setToOne(); for (Element coeff : q.coef) { r.add(coeff.duplicate().mul(t)); t.mul(x); } return r; } private static void lagrangeCoef(Element r, ArrayList<Integer> s, int i) { Element t = r.duplicate(); r.setToOne(); for (Integer j : s) { if (j == i) continue; t.set(-j); r.mul(t); /* num_muls++; */ t.set(i - j).invert(); r.mul(t); /* num_muls++; */ } } public boolean addChild(Bsw07PolicyAbstractNode child) { return children.add(child); } public boolean addAllChildren(List<Bsw07PolicyAbstractNode> newChildren) { return children.addAll(newChildren); } public int getThreshold() { return threshold; } public List<Bsw07PolicyAbstractNode> getChildren() { return children; } @Override public void writeToStream(AbeOutputStream stream) throws IOException { stream.writeInt(getThreshold()); stream.writeInt(children.size()); for (Bsw07PolicyAbstractNode child : children) { child.writeToStream(stream); } } @Override
public void fillPolicy(AbePublicKey pub, Element e) {
3
armouroflight/gstreamer1.x-java
src/org/gstreamer/lowlevel/SubtypeMapper.java
[ "public class DurationMessage extends Message {\n private static interface API extends GstMessageAPI {\n Pointer ptr_gst_message_new_duration(GstObject src, Format format, long duration);\n }\n private static final API gst = GstNative.load(API.class);\n \n /**\n * Creates a new Buffering m...
import java.util.HashMap; import java.util.Map; import org.gstreamer.Event; import org.gstreamer.EventType; import org.gstreamer.Message; import org.gstreamer.MessageType; import org.gstreamer.Query; import org.gstreamer.QueryType; import org.gstreamer.event.BufferSizeEvent; import org.gstreamer.event.EOSEvent; import org.gstreamer.event.FlushStartEvent; import org.gstreamer.event.FlushStopEvent; import org.gstreamer.event.LatencyEvent; import org.gstreamer.event.NavigationEvent; import org.gstreamer.event.NewSegmentEvent; import org.gstreamer.event.QOSEvent; import org.gstreamer.event.SeekEvent; import org.gstreamer.event.TagEvent; import org.gstreamer.message.BufferingMessage; import org.gstreamer.message.DurationMessage; import org.gstreamer.message.EOSMessage; import org.gstreamer.message.ErrorMessage; import org.gstreamer.message.InfoMessage; import org.gstreamer.message.LatencyMessage; import org.gstreamer.message.SegmentDoneMessage; import org.gstreamer.message.StateChangedMessage; import org.gstreamer.message.TagMessage; import org.gstreamer.message.WarningMessage; import org.gstreamer.query.ConvertQuery; import org.gstreamer.query.DurationQuery; import org.gstreamer.query.FormatsQuery; import org.gstreamer.query.LatencyQuery; import org.gstreamer.query.PositionQuery; import org.gstreamer.query.SeekingQuery; import org.gstreamer.query.SegmentQuery; import com.sun.jna.Pointer;
/* * Copyright (c) 2008 Wayne Meissner * * This file is part of gstreamer-java. * * This code is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3 only, as * published by the Free Software Foundation. * * This code 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 * version 3 for more details. * * You should have received a copy of the GNU Lesser General Public License * version 3 along with this work. If not, see <http://www.gnu.org/licenses/>. */ package org.gstreamer.lowlevel; /** * Mapper for classes which have subtypes (e.g. Event, Message, Query). * <p> * This class will return the subtype of the super class that best matches the * raw pointer passed in. */ @SuppressWarnings("serial") class SubtypeMapper { static <T extends NativeObject> Class<?> subtypeFor(final Class<T> defaultClass, final Pointer ptr) { Mapper mapper = MapHolder.mappers.get(defaultClass); Class<?> cls = mapper != null ? mapper.subtypeFor(ptr) : null; return cls != null ? cls : defaultClass; } private static final class MapHolder { public static final Map<Class<?>, Mapper> mappers = new HashMap<Class<?>, Mapper>() {{ put(Event.class, new EventMapper()); put(Message.class, new MessageMapper()); put(Query.class, new QueryMapper()); }}; } private static interface Mapper { public Class<? extends NativeObject> subtypeFor(Pointer ptr); } private static class EventMapper implements Mapper { static class MapHolder { private static final Map<EventType, Class<? extends Event>> typeMap = new HashMap<EventType, Class<? extends Event>>() {{ put(EventType.BUFFERSIZE, BufferSizeEvent.class); put(EventType.EOS, EOSEvent.class); put(EventType.LATENCY, LatencyEvent.class); put(EventType.FLUSH_START, FlushStartEvent.class); put(EventType.FLUSH_STOP, FlushStopEvent.class); put(EventType.NAVIGATION, NavigationEvent.class); put(EventType.NEWSEGMENT, NewSegmentEvent.class); put(EventType.SEEK, SeekEvent.class); put(EventType.TAG, TagEvent.class); put(EventType.QOS, QOSEvent.class); }}; public static Class<? extends NativeObject> subtypeFor(Pointer ptr) { GstEventAPI.EventStruct struct = new GstEventAPI.EventStruct(ptr); EventType type = EventType.valueOf((Integer) struct.readField("type")); Class<? extends Event> eventClass = MapHolder.typeMap.get(type); return eventClass != null ? eventClass : Event.class; } } public Class<? extends NativeObject> subtypeFor(Pointer ptr) { return MapHolder.subtypeFor(ptr); } } private static class MessageMapper implements Mapper { static class MapHolder { private static final Map<MessageType, Class<? extends Message>> typeMap = new HashMap<MessageType, Class<? extends Message>>() {{ put(MessageType.EOS, EOSMessage.class); put(MessageType.ERROR, ErrorMessage.class); put(MessageType.BUFFERING, BufferingMessage.class); put(MessageType.DURATION, DurationMessage.class); put(MessageType.INFO, InfoMessage.class); put(MessageType.LATENCY, LatencyMessage.class); put(MessageType.SEGMENT_DONE, SegmentDoneMessage.class); put(MessageType.STATE_CHANGED, StateChangedMessage.class); put(MessageType.TAG, TagMessage.class); put(MessageType.WARNING, WarningMessage.class); }}; public static Class<? extends NativeObject> subtypeFor(Pointer ptr) { GstMessageAPI.MessageStruct struct = new GstMessageAPI.MessageStruct(ptr); MessageType type = (MessageType) struct.readField("type"); Class<? extends Message> messageClass = MapHolder.typeMap.get(type); return messageClass != null ? messageClass : Message.class; } } public Class<? extends NativeObject> subtypeFor(Pointer ptr) { return MapHolder.subtypeFor(ptr); } } private static class QueryMapper implements Mapper { static class MapHolder { private static final Map<QueryType, Class<? extends Query>> typeMap = new HashMap<QueryType, Class<? extends Query>>() {{ put(QueryType.CONVERT, ConvertQuery.class); put(QueryType.DURATION, DurationQuery.class); put(QueryType.FORMATS, FormatsQuery.class); put(QueryType.LATENCY, LatencyQuery.class);
put(QueryType.POSITION, PositionQuery.class);
4
sTorro/triviazo
src/com/torrosoft/triviazo/screens/GameScreen.java
[ "public class TriviazoGame extends Game {\n public static final String VERSION = \" - v0.7 ALPHA - \";\n public static final boolean DEBUG_MODE = false;\n public static final boolean FULL_DEBUG_MODE = false;\n\n /* SERVICES */\n private MusicManager musicManager;\n private SoundManager soundManage...
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.torrosoft.triviazo.TriviazoGame; import com.torrosoft.triviazo.core.data.wrappers.Question; import com.torrosoft.triviazo.core.enums.Difficulty; import com.torrosoft.triviazo.core.enums.Discipline; import com.torrosoft.triviazo.core.enums.GameMode; import com.torrosoft.triviazo.core.enums.Language; import com.torrosoft.triviazo.services.music.TriviazoMusic; import com.torrosoft.triviazo.services.music.TriviazoSound; import com.torrosoft.triviazo.util.DefaultButtonListener;
/* * This file is part of Triviazo project. * * 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 triviazo-project. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2013 Sergio Torró. */ package com.torrosoft.triviazo.screens; /** * Abstract class witch defines the default behavior of the game screen. * * @author Sergio Torró * @since 04/06/2013 * @version 0.3 */ public abstract class GameScreen extends AbstractScreen { private static final int BUTTON_SIZE_MOD = 60; protected static final int QUESTION_VALUE = 50; /** * The main skin used by all the UI components. */ protected final Skin mainSkin; /** * The questions of the current game. */ protected final List<Question> questions = new ArrayList<Question>(); /** * The current index of the list. */ protected int index = 0; protected int correct = 0; protected int incorrect = 0; /** * The main table of the super class. */ private Table mainTable; private Label lblQuestion; private TextButton btnAns1; private TextButton btnAns2; private TextButton btnAns3; private TextButton btnAns4; protected Label lblCorrect; protected Label lblIncorrect; protected Label lblTimer; protected int maxQuestions; public GameScreen(final TriviazoGame game) { super(game); game.getMusicManager().play(TriviazoMusic.IN_GAME); mainSkin = super.getSkin(); } /** * The method for show the UI. It handles the main {@link Table}. */ @Override public final void show() { super.show(); mainTable = super.getTable(); final Texture texture = new Texture( Gdx.files.internal("images/default.png")); final Drawable drawable = new TextureRegionDrawable(new TextureRegion( texture)); mainTable.setBackground(drawable); createUI(); createScoreboard(); createTimerTable(); loadQuestions(); nextQuestion(); // Start game } private void createScoreboard() { final Table tableScore = new Table(mainSkin); tableScore.setFillParent(true); lblCorrect = new Label("", mainSkin); lblIncorrect = new Label("", mainSkin); setScore(null); tableScore.add(lblCorrect); tableScore.row(); tableScore.add(lblIncorrect); tableScore.bottom().left().pad(0, 10, 10, 0); stage.addActor(tableScore); } private void createTimerTable() { final Table timerTable = new Table(mainSkin); timerTable.setFillParent(true); lblTimer = new Label("", mainSkin); timerTable.add(lblTimer); timerTable.row(); timerTable.top().right().pad(0, 0, 10, 10); stage.addActor(timerTable); if (gameConfig.getGameMode() == GameMode.INTELLECTUS_MACHINA) lblTimer.setVisible(false); } private void createUI() { final Table tableUI = new Table(mainSkin); tableUI.setFillParent(true); lblQuestion = new Label("", getSkin()); btnAns1 = new TextButton("", getSkin()); btnAns1.setName("0"); btnAns2 = new TextButton("", getSkin()); btnAns2.setName("1"); btnAns3 = new TextButton("", getSkin()); btnAns3.setName("2"); btnAns4 = new TextButton("", getSkin()); btnAns4.setName("3"); btnAns1.addListener(btnListener); btnAns2.addListener(btnListener); btnAns3.addListener(btnListener); btnAns4.addListener(btnListener); tableUI.add(lblQuestion).center().colspan(2); tableUI.row(); tableUI.add("\n\n").colspan(2); tableUI.row(); tableUI.add(btnAns1).size(BUTTON_WIDTH + BUTTON_SIZE_MOD, BUTTON_HEIGHT + BUTTON_SIZE_MOD); tableUI.add(btnAns2).size(BUTTON_WIDTH + BUTTON_SIZE_MOD, BUTTON_HEIGHT + BUTTON_SIZE_MOD); tableUI.row(); tableUI.add(btnAns3).size(BUTTON_WIDTH + BUTTON_SIZE_MOD, BUTTON_HEIGHT + BUTTON_SIZE_MOD); tableUI.add(btnAns4).size(BUTTON_WIDTH + BUTTON_SIZE_MOD, BUTTON_HEIGHT + BUTTON_SIZE_MOD); tableUI.row(); tableUI.add("\n\n").colspan(2); tableUI.row(); tableUI.center(); stage.addActor(tableUI); } /** * It loads all the questions and keeps a certain number of them in * "questions" List (mixed). Never keeps repeated questions. */ private void loadQuestions() {
final List<Discipline> selectedDis = new ArrayList<Discipline>();
3
urbanairship/datacube
src/main/java/com/urbanairship/datacube/idservices/HBaseIdService.java
[ "public interface IdService {\n byte[] getOrCreateId(int dimensionNum, byte[] input, int numIdBytes) throws IOException, InterruptedException;\n\n Optional<byte[]> getId(int dimensionNum, byte[] input, int numIdBytes) throws IOException, InterruptedException;\n\n /**\n * Utilities to make implementatio...
import com.codahale.metrics.Gauge; import com.codahale.metrics.Meter; import com.codahale.metrics.Timer; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.math.LongMath; import com.urbanairship.datacube.IdService; import com.urbanairship.datacube.Util; import com.urbanairship.datacube.dbharnesses.WithHTable; import com.urbanairship.datacube.dbharnesses.WithHTable.ScanRunnable; import com.urbanairship.datacube.metrics.Metrics; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang.ArrayUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTablePool; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; import java.util.Map.Entry; import java.util.Optional; import java.util.Set;
/* Copyright 2012 Urban Airship and Contributors */ package com.urbanairship.datacube.idservices; public class HBaseIdService implements IdService { private static final Logger log = LoggerFactory.getLogger(HBaseIdService.class); public static final byte[] QUALIFIER = ArrayUtils.EMPTY_BYTE_ARRAY; public static final int MAX_COMPAT_TRIES = 20; public static final int COMPAT_RETRY_SLEEP = 2000; private enum Status {@Deprecated ALLOCATING, ALLOCATED} // don't change ordinals private static final byte[] ALLOCATED_BYTES = new byte[]{(byte) Status.ALLOCATED.ordinal()}; private static final byte[] NULL_BYTE_ARRAY = null; private final HTablePool pool; private final byte[] counterTable; private final byte[] lookupTable; private final byte[] uniqueCubeName; private final byte[] cf; private final Meter allocatingSleeps; private final Meter wastedIdNumbers; private final Timer idCreationTime; private final Timer idGetTime; private final Set<Integer> dimensionsApproachingExhaustion; public HBaseIdService(Configuration configuration, byte[] lookupTable, byte[] counterTable, byte[] cf, byte[] uniqueCubeName) { this(new HTablePool(configuration, Integer.MAX_VALUE), lookupTable, counterTable, cf, uniqueCubeName); } public HBaseIdService(HTablePool pool, byte[] lookupTable, byte[] counterTable, byte[] cf, byte[] uniqueCubeName) { this.pool = pool; this.lookupTable = lookupTable; this.counterTable = counterTable; this.uniqueCubeName = uniqueCubeName; this.cf = cf; this.dimensionsApproachingExhaustion = Sets.newConcurrentHashSet(); this.allocatingSleeps = Metrics.meter(HBaseIdService.class, "ALLOCATING_sleeps", Bytes.toString(uniqueCubeName)); this.wastedIdNumbers = Metrics.meter(HBaseIdService.class, "wasted_id_numbers", Bytes.toString(uniqueCubeName)); this.idCreationTime = Metrics.timer(HBaseIdService.class, "id_create", Bytes.toString(uniqueCubeName)); this.idGetTime = Metrics.timer(HBaseIdService.class, "id_get", Bytes.toString(uniqueCubeName)); Metrics.gauge(HBaseIdService.class, "ids_approaching_exhaustion", Bytes.toString(uniqueCubeName), new Gauge<String>() { @Override public String getValue() { return dimensionsApproachingExhaustion.toString(); } }); } @Override public byte[] getOrCreateId(int dimensionNum, byte[] input, int numIdBytes) throws IOException, InterruptedException { Validate.validateDimensionNum(dimensionNum); Validate.validateNumIdBytes(numIdBytes); // First check if the ID exists already final byte[] lookupKey = makeLookupKey(dimensionNum, input); final Optional<byte[]> existingId = getId(lookupKey, numIdBytes); if (existingId.isPresent()) { return existingId.get(); } final Timer.Context timer = idCreationTime.time(); // If not, we need to create it. First get a new id # from the counter table... byte[] counterKey = makeCounterKey(dimensionNum);
final long id = WithHTable.increment(pool, counterTable, counterKey, cf, QUALIFIER, 1L);
2
moxious/neoprofiler
src/main/java/org/mitre/neoprofiler/markdown/MarkdownMaker.java
[ "public class DBProfile extends NeoProfile {\n\tprotected List<NeoProfile> profiles = new ArrayList<NeoProfile>();\n\t\t\n\tpublic DBProfile(String storageLoc) {\t\t\n\t\tDateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\n\t\tDate date = new Date();\n\t\t\n\t\tname = \"Profile of \" + storageLo...
import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import org.mitre.neoprofiler.profile.DBProfile; import org.mitre.neoprofiler.profile.NeoConstraint; import org.mitre.neoprofiler.profile.NeoProfile; import org.mitre.neoprofiler.profile.ParameterizedNeoProfile; import org.mitre.neoprofiler.profile.SchemaProfile;
package org.mitre.neoprofiler.markdown; /** * A class to write profiles as Markdown. * @author moxious */ public class MarkdownMaker { public MarkdownMaker() { } public String link(String text, String url) { return "[" + text + "](" + url + ")"; } public String h1(String content) { return "\n# " + content + "\n"; } public String h2(String content) { return "\n## " + content + "\n"; } public String h3(String content) { return "\n### " + content + "\n"; } public String h4(String content) { return "\n#### " + content + "\n"; } protected String observations(Map<String,Object>observations) { if(observations.isEmpty()) return ""; StringBuffer b = new StringBuffer(""); b.append(h3("Observations")); ArrayList<String>keys = new ArrayList<String>(observations.keySet()); Collections.sort(keys); for(String key : keys) { b.append("* " + key + ": " + observation(observations.get(key))); if(b.charAt(b.length() - 1) != '\n') b.append("\n"); } return b.toString(); } protected String observation(Object ob) { if(ob == null) return "N/A"; if(ob instanceof String || ob instanceof Number) return ""+ob; if(ob instanceof Collection) { StringBuffer b = new StringBuffer("\n"); for(Object o : ((Collection)ob)) { b.append(" * " + o + "\n"); } return b.toString(); } return ""+ob; } // End observation public String constraints(String title, List<NeoConstraint> constraints) { StringBuffer b = new StringBuffer(""); b.append(h3(title)); if(constraints.isEmpty()) b.append("**None found**"); else { for(NeoConstraint con : constraints) { b.append("* " + (con.isIndex() ? "Index" : "Constraint") + " " + con.getDescription() + "\n"); } } return b.toString(); } public String parameters(Map<String,Object>parameters) { if(parameters.isEmpty()) return ""; StringBuffer b = new StringBuffer(""); b.append(h3("Parameters")); ArrayList<String>keys = new ArrayList<String>(parameters.keySet()); Collections.sort(keys); for(String key : keys) { b.append("* " + key + ": " + observation(parameters.get(key)) + "\n"); } b.append("\n"); return b.toString(); } public void markdownComponentProfile(NeoProfile profile, Writer writer) throws IOException { writer.write(h2(profile.getName()) + "*" + profile.getDescription() + "*\n"); //if(profile instanceof ParameterizedNeoProfile) { // writer.write(parameters(((ParameterizedNeoProfile)profile).getParameters())); //}
if(profile instanceof SchemaProfile) {
4
StumbleUponArchive/hbase
src/test/java/org/apache/hadoop/hbase/MiniHBaseCluster.java
[ "@SuppressWarnings(\"serial\")\npublic class HConnectionManager {\n // An LRU Map of HConnectionKey -> HConnection (TableServer). All\n // access must be synchronized. This map is not private because tests\n // need to be able to tinker with it.\n static final Map<HConnectionKey, HConnectionImplementation> HB...
import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.JVMClusterUtil; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.io.MapWritable; import java.io.IOException; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.hbase.client.HConnectionManager; import org.apache.hadoop.hbase.master.HMaster;
/** * Copyright 2008 The Apache Software Foundation * * 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 org.apache.hadoop.hbase; /** * This class creates a single process HBase cluster. * each server. The master uses the 'default' FileSystem. The RegionServers, * if we are running on DistributedFilesystem, create a FileSystem instance * each and will close down their instance on the way out. */ public class MiniHBaseCluster { static final Log LOG = LogFactory.getLog(MiniHBaseCluster.class.getName()); private Configuration conf; public LocalHBaseCluster hbaseCluster; private static int index; /** * Start a MiniHBaseCluster. * @param conf Configuration to be used for cluster * @param numRegionServers initial number of region servers to start. * @throws IOException */ public MiniHBaseCluster(Configuration conf, int numRegionServers) throws IOException, InterruptedException { this(conf, 1, numRegionServers); } /** * Start a MiniHBaseCluster. * @param conf Configuration to be used for cluster * @param numMasters initial number of masters to start. * @param numRegionServers initial number of region servers to start. * @throws IOException */ public MiniHBaseCluster(Configuration conf, int numMasters, int numRegionServers) throws IOException, InterruptedException { this.conf = conf; conf.set(HConstants.MASTER_PORT, "0"); init(numMasters, numRegionServers); } public Configuration getConfiguration() { return this.conf; } /** * Subclass so can get at protected methods (none at moment). Also, creates * a FileSystem instance per instantiation. Adds a shutdown own FileSystem * on the way out. Shuts down own Filesystem only, not All filesystems as * the FileSystem system exit hook does. */
public static class MiniHBaseClusterRegionServer extends HRegionServer {
3
lingochamp/FileDownloader
library/src/main/java/com/liulishuo/filedownloader/FileDownloadServiceSharedTransmit.java
[ "public class DownloadServiceConnectChangedEvent extends IDownloadEvent {\n public static final String ID = \"event.service.connect.changed\";\n\n public DownloadServiceConnectChangedEvent(final ConnectStatus status,\n final Class<?> serviceClass) {\n super(...
import java.util.ArrayList; import java.util.List; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.os.Build; import com.liulishuo.filedownloader.event.DownloadServiceConnectChangedEvent; import com.liulishuo.filedownloader.model.FileDownloadHeader; import com.liulishuo.filedownloader.services.FDServiceSharedHandler; import com.liulishuo.filedownloader.services.FDServiceSharedHandler.FileDownloadServiceSharedConnection; import com.liulishuo.filedownloader.services.FileDownloadService.SharedMainProcessService; import com.liulishuo.filedownloader.util.DownloadServiceNotConnectedHelper; import com.liulishuo.filedownloader.util.ExtraKeys; import com.liulishuo.filedownloader.util.FileDownloadLog; import com.liulishuo.filedownloader.util.FileDownloadUtils;
/* * Copyright (c) 2015 LingoChamp Inc. * * 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.liulishuo.filedownloader; /** * This transmit layer is used for the FileDownloader-Process is shared the main process. * <p/> * If you want use this transmit and want the FileDownloadService share the main process, not in the * separate process, just add a command `process.non-separate=true` in `/filedownloader.properties`. * * @see FileDownloadServiceUIGuard */ class FileDownloadServiceSharedTransmit implements IFileDownloadServiceProxy, FileDownloadServiceSharedConnection { private static final Class<?> SERVICE_CLASS = SharedMainProcessService.class; private boolean runServiceForeground = false; @Override public boolean start(String url, String path, boolean pathAsDirectory, int callbackProgressTimes, int callbackProgressMinIntervalMillis, int autoRetryTimes, boolean forceReDownload, FileDownloadHeader header, boolean isWifiRequired) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.start(url, path, pathAsDirectory); } handler.start(url, path, pathAsDirectory, callbackProgressTimes, callbackProgressMinIntervalMillis, autoRetryTimes, forceReDownload, header, isWifiRequired); return true; } @Override public boolean pause(int id) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.pause(id); } return handler.pause(id); } @Override public boolean isDownloading(String url, String path) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.isDownloading(url, path); } return handler.checkDownloading(url, path); } @Override public long getSofar(int id) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.getSofar(id); } return handler.getSofar(id); } @Override public long getTotal(int id) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.getTotal(id); } return handler.getTotal(id); } @Override public byte getStatus(int id) { if (!isConnected()) { return DownloadServiceNotConnectedHelper.getStatus(id); } return handler.getStatus(id); } @Override public void pauseAllTasks() { if (!isConnected()) { DownloadServiceNotConnectedHelper.pauseAllTasks(); return; } handler.pauseAllTasks(); } @Override public boolean isIdle() { if (!isConnected()) { return DownloadServiceNotConnectedHelper.isIdle(); } return handler.isIdle(); } @Override public boolean isConnected() { return handler != null; } @Override public void bindStartByContext(Context context) { bindStartByContext(context, null); } private final ArrayList<Runnable> connectedRunnableList = new ArrayList<>(); @Override public void bindStartByContext(Context context, Runnable connectedRunnable) { if (connectedRunnable != null) { if (!connectedRunnableList.contains(connectedRunnable)) { connectedRunnableList.add(connectedRunnable); } } Intent i = new Intent(context, SERVICE_CLASS); runServiceForeground = FileDownloadUtils.needMakeServiceForeground(context); i.putExtra(ExtraKeys.IS_FOREGROUND, runServiceForeground); if (runServiceForeground) {
if (FileDownloadLog.NEED_LOG) FileDownloadLog.d(this, "start foreground service");
7
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/data/source/RemoteGirlsDataSource.java
[ "public class DataType {\n\n /*返回数据为String*/\n public static final int STRING = 1;\n /*返回数据为xml类型*/\n public static final int XML = 2;\n /*返回数据为json对象*/\n public static final int JSON_OBJECT = 3;\n /*返回数据为json数组*/\n public static final int JSON_ARRAY = 4;\n\n /**\n * 自定义一个播放器状态注解\n ...
import com.guiying.module.common.http.DataType; import com.guiying.module.common.http.HttpClient; import com.guiying.module.common.http.OnResultListener; import com.guiying.module.girls.Constants; import com.guiying.module.girls.data.GirlsDataSource; import com.guiying.module.girls.data.bean.GirlsParser;
package com.guiying.module.girls.data.source; public class RemoteGirlsDataSource implements GirlsDataSource { @Override public void getGirls(int size, int page, final LoadGirlsCallback callback) { HttpClient client = new HttpClient.Builder() .baseUrl(Constants.GAN_HUO_API) .url("福利/" + size + "/" + page)
.bodyType(DataType.JSON_OBJECT, GirlsParser.class)
5
iychoi/libra
src/libra/merge/Merge.java
[ "public class CommandArgumentsParser<T extends CommandArgumentsBase> {\n public boolean parse(String[] args, T cmdargs) {\n CmdLineParser parser = new CmdLineParser(cmdargs);\n CmdLineException parseException = null;\n try {\n parser.parseArgument(args);\n } catch (CmdLineE...
import libra.common.cmdargs.CommandArgumentsParser; import libra.merge.common.MergeConfig; import libra.merge.merge.MergeMap; import libra.preprocess.common.filetable.FileTable; import libra.preprocess.common.helpers.FileTableHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner;
/* * Copyright 2016 iychoi. * * 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 libra.merge; /** * * @author iychoi */ public class Merge extends Configured implements Tool { private static final Log LOG = LogFactory.getLog(Merge.class); public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new Merge(), args); System.exit(res); } @Override public int run(String[] args) throws Exception { Configuration common_conf = this.getConf();
CommandArgumentsParser<MergeCmdArgs> parser = new CommandArgumentsParser<MergeCmdArgs>();
0
PuffOpenSource/Puff-Android
app/src/main/java/sun/bob/leela/App.java
[ "public class AccountHelper {\n private static AccountHelper ourInstance;\n private Context context;\n private DaoMaster daoMaster;\n private DaoSession daoSession;\n private AccountDao accountDao;\n\n public static AccountHelper getInstance(Context context) {\n if (ourInstance == null) {\n...
import android.app.Application; import sun.bob.leela.db.AccountHelper; import sun.bob.leela.db.CategoryHelper; import sun.bob.leela.db.TypeHelper; import sun.bob.leela.utils.CategoryUtil; import sun.bob.leela.utils.EnvUtil; import sun.bob.leela.utils.ResUtil; import sun.bob.leela.utils.UserDefault;
package sun.bob.leela; /** * Created by bob.sun on 16/3/19. */ public class App extends Application { @Override public void onCreate(){ super.onCreate(); AccountHelper.getInstance(getApplicationContext()); CategoryHelper categoryHelper = CategoryHelper.getInstance(getApplicationContext());
TypeHelper typeHelper = TypeHelper.getInstance(getApplicationContext());
2
IYCI/MyClass
app/src/main/java/com/YC2010/MyClass/ui/fragments/SearchScheduleFragment.java
[ "public class CourseInfo {\n private String courseName;\n private String courseNum;\n private String courseSec;\n private String courseTime;\n private String courseLoc;\n private String courseProf;\n private String tutName;\n private String tutNum;\n private String tutTime;\n private S...
import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.DialogInterface; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.widget.AppCompatButton; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.YC2010.MyClass.model.CourseInfo; import com.YC2010.MyClass.model.LectureSectionObject; import com.YC2010.MyClass.R; import com.YC2010.MyClass.data.CoursesDBHandler; import com.YC2010.MyClass.ui.adapters.SectionListAdapter; import com.YC2010.MyClass.ui.adapters.TstListAdapter; import com.YC2010.MyClass.ui.adapters.TutListAdapter; import com.YC2010.MyClass.utils.Constants; import java.util.ArrayList;
package com.YC2010.MyClass.ui.fragments; /** * Created by Danny on 2015/12/26. */ public class SearchScheduleFragment extends Fragment { private Activity mActivity; private View mView; private Bundle mFetchedResult; private boolean mCourseTaken; private String mTakenCourseNumber; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.mActivity = getActivity(); this.mFetchedResult = this.getArguments(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_search_schedule, container, false); TextView courseName = (TextView) mView.findViewById(R.id.course_name); courseName.setText(mFetchedResult.getString("courseName")); setupLists(); setupAddButton(); return mView; } private void setupLists() { // get default divider int[] attrs = {android.R.attr.listDivider}; TypedArray ta = mActivity.obtainStyledAttributes(attrs); Drawable divider = ta.getDrawable(0); ta.recycle(); LinearLayout mLecLinearLayout = (LinearLayout) mView.findViewById(R.id.lec_list); SectionListAdapter LecAdapter = new SectionListAdapter(mActivity, R.layout.section_item, mFetchedResult); for (int i = 0; i < LecAdapter.getCount(); i++) { View view = LecAdapter.getView(i, null, mLecLinearLayout); mLecLinearLayout.addView(view); mLecLinearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE | LinearLayout.SHOW_DIVIDER_BEGINNING); mLecLinearLayout.setDividerDrawable(divider); } TextView lec = (TextView) mView.findViewById(R.id.lec); if (lec != null) { lec.setVisibility(View.VISIBLE); } if (mFetchedResult.getBoolean("has_tst", false)) { TextView tst = (TextView) mView.findViewById(R.id.tst); if (tst != null) { tst.setVisibility(View.VISIBLE); } LinearLayout mTstLinearLayout = (LinearLayout) mView.findViewById(R.id.tst_list);
TstListAdapter TstAdapter = new TstListAdapter(mActivity, R.layout.section_item, mFetchedResult);
4
kakao/hbase-tools
hbase0.98/hbase-manager-0.98/src/main/java/com/kakao/hbase/manager/command/MC.java
[ "public abstract class Args {\n public static final String OPTION_REGION = \"region\";\n public static final String OPTION_OUTPUT = \"output\";\n public static final String OPTION_SKIP_EXPORT = \"skip-export\";\n public static final String OPTION_VERBOSE = \"verbose\";\n public static final String OP...
import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.annotations.VisibleForTesting; import com.kakao.hbase.common.Args; import com.kakao.hbase.common.Constant; import com.kakao.hbase.common.util.Util; import com.kakao.hbase.specific.CommandAdapter; import com.kakao.hbase.specific.RegionLoadAdapter; import com.kakao.hbase.specific.RegionLoadDelegator; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.NotServingRegionException; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.util.StringUtils;
/* * Copyright 2015 Kakao Corporation * * 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.kakao.hbase.manager.command; public class MC implements Command { private final HBaseAdmin admin; private final Args args; private final AtomicInteger mcCounter = new AtomicInteger(); private final Map<byte[], String> regionTableMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); private final Map<byte[], Integer> regionSizeMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); private final Map<byte[], Float> regionLocalityMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); private final Map<byte[], String> regionRSMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); private Map<String, NavigableMap<HRegionInfo, ServerName>> regionLocations = new HashMap<>(); // regions or tables private Set<byte[]> targets = null; private boolean tableLevel = false; public MC(HBaseAdmin admin, Args args) { if (args.getOptionSet().nonOptionArguments().size() != 2) { throw new IllegalArgumentException(Args.INVALID_ARGUMENTS); } this.admin = admin; this.args = args; } @SuppressWarnings("unused") public static String usage() { return "Run major compaction on tables.\n" + "usage: " + MC.class.getSimpleName().toLowerCase() + " <zookeeper quorum> <table regex> [options]\n" + " options:\n" + " --" + Args.OPTION_WAIT_UNTIL_FINISH + ": Wait until all of MCs are finished.\n" + " --" + Args.OPTION_INTERACTIVE + ": Ask whether to proceed MC for each region or table.\n" + " --" + Args.OPTION_REGION_SERVER + "=<RS regex>: Compact the regions on these RSs.\n" + " --" + Args.OPTION_CF + "=<CF>: Compact the regions of this CF.\n" + " --" + Args.OPTION_LOCALITY_THRESHOLD + "=<threshold%>: Compact only if the data locality of the region is lower than this threshold.\n" + Args.commonUsage(); } @VisibleForTesting int getMcCounter() { return mcCounter.get(); } @VisibleForTesting Set<byte[]> getTargets() { return targets; } @VisibleForTesting boolean isTableLevel() { return tableLevel; } @Override public void run() throws Exception { targets = Collections.newSetFromMap(new TreeMap<byte[], Boolean>(Bytes.BYTES_COMPARATOR)); tableLevel = false; // or region level Set<String> tables = Args.tables(args, admin); assert tables != null; for (String table : tables) { if (args.has(Args.OPTION_REGION_SERVER) || args.has(Args.OPTION_LOCALITY_THRESHOLD)) { // MC at region level tableLevel = false; if (args.has(Args.OPTION_REGION_SERVER)) { filterWithRsAndLocality(targets, table); } else { if (args.has(Args.OPTION_LOCALITY_THRESHOLD)) { filterWithLocalityOnly(targets, table); } } } else { // MC at table level tableLevel = true; targets.add(table.getBytes()); } } // todo check compaction queue before running if (tableLevel) { System.out.println(targets.size() + " tables will be compacted."); } else { System.out.println(targets.size() + " regions will be compacted."); } if (targets.size() == 0) return;
if (!args.isForceProceed() && !Util.askProceed()) return;
2
Martin20150405/Pano360
vrlib/src/main/java/com/martin/ads/vrlib/filters/base/OrthoFilter.java
[ "public enum PanoMode\n{\n MOTION,TOUCH,SINGLE_SCREEN,DUAL_SCREEN\n}", "public class Plane {\n private FloatBuffer mVerticesBuffer;\n private FloatBuffer mTexCoordinateBuffer;\n private final float TRIANGLES_DATA_CW[] = {\n -1.0f, -1.0f, 0f, //LD\n -1.0f, 1.0f, 0f, //LU\n ...
import android.opengl.GLES20; import android.opengl.Matrix; import com.martin.ads.vrlib.constant.PanoMode; import com.martin.ads.vrlib.object.Plane; import com.martin.ads.vrlib.programs.GLPassThroughProgram; import com.martin.ads.vrlib.utils.MatrixUtils; import com.martin.ads.vrlib.utils.StatusHelper; import com.martin.ads.vrlib.utils.TextureUtils;
package com.martin.ads.vrlib.filters.base; /** * Created by Ads on 2016/11/19. * let the image pass through * and simply fit the image to the screen */ public class OrthoFilter extends AbsFilter { private int adjustingMode; private GLPassThroughProgram glPassThroughProgram; private Plane plane; private float[] projectionMatrix = new float[16]; private int videoWidth,videoHeight;
private StatusHelper statusHelper;
4
KMax/cqels
src/main/java/org/deri/cqels/engine/IndexedOnWindowBuff.java
[ "public class EnQuad {\n\tlong gID,sID,pID,oID;\n\tlong time;\n\tpublic EnQuad(long gID,long sID, long pID, long oID){\n\t\tthis.gID=gID;\n\t\tthis.sID=sID;\n\t\tthis.pID=pID;\n\t\tthis.oID=oID;\n\t\ttime=System.nanoTime();\n\t}\n\t\n\tpublic long getGID(){\n\t\treturn gID;\n\t}\n\t\n\tpublic long getSID(){\n\t\tre...
import java.util.ArrayList; import java.util.concurrent.TimeUnit; import org.deri.cqels.data.EnQuad; import org.deri.cqels.data.Mapping; import org.deri.cqels.engine.iterator.MappingIterCursorAll; import org.deri.cqels.engine.iterator.MappingIterCursorByKey; import org.deri.cqels.engine.iterator.MappingIterCursorByRangeKey; import org.deri.cqels.engine.iterator.MappingIterator; import org.deri.cqels.engine.iterator.NullMappingIter; import org.deri.cqels.util.Utils; import com.hp.hpl.jena.sparql.algebra.Op; import com.hp.hpl.jena.sparql.core.Quad; import com.hp.hpl.jena.sparql.core.Var; import com.sleepycat.bind.tuple.LongBinding; import com.sleepycat.bind.tuple.TupleInput; import com.sleepycat.bind.tuple.TupleOutput; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.SecondaryConfig; import com.sleepycat.je.SecondaryDatabase; import com.sleepycat.je.SecondaryKeyCreator;
package org.deri.cqels.engine; /** * @author Danh Le Phuoc * @organization DERI Galway, NUIG, Ireland www.deri.ie * @email danh.lephuoc@deri.org */ public class IndexedOnWindowBuff { ExecContext context; Quad quad; Database buff; Op op; OpRouter router; ArrayList<Var> vars; ArrayList<ArrayList<Integer>> indexes; SecondaryDatabase[] idxDbs; Window w; public IndexedOnWindowBuff(ExecContext context,Quad quad, OpRouter router, Window w){ this.context = context; this.quad = quad; this.router = router; this.op = router.getOp(); init(); this.w = w; //if(w==null) System.out.println("null "+quad); w.setBuff(buff); } public void init() { DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setAllowCreate(true); dbConfig.setTemporary(true); //dbConfig.setTransactional(true); buff = context.env().openDatabase(null, "pri_synopsis_" + router.getId(), dbConfig); //System.out.println("ttrans "+dbConfig.getTransactional()); initIndexes(); } public void initIndexes() {
vars = Utils.quad2Vars(quad);
7
yunnet/kafkaEagle
src/main/java/org/smartloli/kafka/eagle/web/service/impl/AlarmServiceImpl.java
[ "public class AlarmDomain {\n\n\tprivate String group = \"\";\n\tprivate String topics = \"\";\n\tprivate long lag = 0L;\n\tprivate String owners = \"\";\n\tprivate String modifyDate = \"\";\n\n\tpublic String getGroup() {\n\t\treturn group;\n\t}\n\n\tpublic void setGroup(String group) {\n\t\tthis.group = group;\n\...
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.smartloli.kafka.eagle.common.domain.AlarmDomain; import org.smartloli.kafka.eagle.core.factory.KafkaFactory; import org.smartloli.kafka.eagle.core.factory.KafkaService; import org.smartloli.kafka.eagle.core.factory.ZkFactory; import org.smartloli.kafka.eagle.core.factory.ZkService; import org.smartloli.kafka.eagle.web.service.AlarmService; import org.springframework.stereotype.Service;
/** * 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 org.smartloli.kafka.eagle.web.service.impl; /** * Alarm implements service to get configure info. * * @Author smartloli. * * Created by Sep 6, 2016. * * Update by hexiang 20170216 */ @Service public class AlarmServiceImpl implements AlarmService { /** Kafka service interface. */
private KafkaService kafkaService = new KafkaFactory().create();
2
cjdaly/fold
net.locosoft.fold.channel.fold/src/net/locosoft/fold/channel/fold/internal/FoldChannel.java
[ "public abstract class AbstractChannel implements IChannel, IChannelInternal {\n\n\t//\n\t// IChannel\n\t//\n\n\tprivate String _id;\n\n\tpublic String getChannelId() {\n\t\treturn _id;\n\t}\n\n\tprivate String _description;\n\n\tpublic String getChannelData(String key, String... params) {\n\t\tswitch (key) {\n\t\t...
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.locosoft.fold.channel.AbstractChannel; import net.locosoft.fold.channel.ChannelUtil; import net.locosoft.fold.channel.IChannel; import net.locosoft.fold.channel.fold.IFoldChannel; import net.locosoft.fold.sketch.pad.html.ChannelHeaderFooterHtml; import net.locosoft.fold.sketch.pad.neo4j.CounterPropertyNode; import net.locosoft.fold.sketch.pad.neo4j.HierarchyNode; import net.locosoft.fold.util.HtmlComposer; import org.eclipse.core.runtime.Path; import com.eclipsesource.json.JsonObject;
/***************************************************************************** * Copyright (c) 2015 Chris J Daly (github user cjdaly) * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * cjdaly - initial API and implementation ****************************************************************************/ package net.locosoft.fold.channel.fold.internal; public class FoldChannel extends AbstractChannel implements IFoldChannel { private FoldFinder _foldFinder = new FoldFinder(this); private long _startCount = -1; public long getStartCount() { return _startCount; } public Class<? extends IChannel> getChannelInterface() { return IFoldChannel.class; } public void init() { CounterPropertyNode foldStartCount = new CounterPropertyNode( getChannelNodeId()); _startCount = foldStartCount.incrementCounter("fold_startCount"); _foldFinder.start(); } public void fini() { _foldFinder.stop(); } public void channelHttpGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); if ((pathInfo == null) || ("".equals(pathInfo)) || ("/".equals(pathInfo))) { // empty channel segment (/fold) new ChannelHttpGetDashboard() .composeHtmlResponse(request, response); } else { Path path = new Path(pathInfo); String channelSegment = path.segment(0); if ("fold".equals(channelSegment)) { // fold channel segment (/fold/fold) new ChannelHttpGetFold().composeHtmlResponse(request, response); } else { // everything else new ChannelHttpGetUndefined().composeHtmlResponse(request, response); } } } private class ChannelHttpGetDashboard extends ChannelHeaderFooterHtml { ChannelHttpGetDashboard() { super(FoldChannel.this); } protected void composeHtmlResponseBody(HttpServletRequest request, HttpServletResponse response, HtmlComposer html) throws ServletException, IOException { html.h(2, "fold"); html.p(); html.text("Thing: "); String thingName = getChannelService().getChannelData("thing", "name"); html.b(thingName); html.br(); html.text("start count: "); html.b(Long.toString(getStartCount())); html.p(false); html.h(3, "channels"); html.table(); IChannel[] channels = ChannelUtil.getChannelService() .getAllChannels(); for (IChannel channel : channels) { String channelLink = html.A("/fold/" + channel.getChannelId(), channel.getChannelId()); html.tr(channelLink, channel.getChannelData("channel.description")); } html.table(false); } } private class ChannelHttpGetFold extends ChannelHeaderFooterHtml { public ChannelHttpGetFold() { super(FoldChannel.this); } protected void composeHtmlResponseBody(HttpServletRequest request, HttpServletResponse response, HtmlComposer html) throws ServletException, IOException { html.h(2, "fold finder");
HierarchyNode foldChannelNode = new HierarchyNode(
6
khasang/SmartForecast
Forecast/app/src/main/java/com/khasang/forecast/stations/OpenWeatherMap.java
[ "public class MyApplication extends Application {\n\n private static Context context;\n\n public static Context getAppContext() {\n return MyApplication.context;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n /** Проверяет, если Debug mode, то не отправляет ...
import android.content.SharedPreferences; import android.support.annotation.Nullable; import android.support.v7.preference.PreferenceManager; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.CustomEvent; import com.facebook.stetho.okhttp.StethoInterceptor; import com.khasang.forecast.MyApplication; import com.khasang.forecast.R; import com.khasang.forecast.models.DailyResponse; import com.khasang.forecast.models.OpenWeatherMapResponse; import com.khasang.forecast.position.Coordinate; import com.khasang.forecast.position.PositionManager; import com.khasang.forecast.utils.AppUtils; import com.squareup.okhttp.Cache; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.logging.HttpLoggingInterceptor; import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Locale; import io.fabric.sdk.android.Fabric; import retrofit.Call; import retrofit.Callback; import retrofit.GsonConverterFactory; import retrofit.Response; import retrofit.Retrofit;
package com.khasang.forecast.stations; /** * Этот класс скачивает и парсит данные с API в фоновом потоке, после чего отправляет их * на UI поток через методы onResponse или onFailure. */ public class OpenWeatherMap extends WeatherStation { private final static String API = "OpenWeaterMap API"; /** * Тэг для дебаггинга. */ private static final String TAG = OpenWeatherMap.class.getSimpleName(); /** * API URL. */ private static final String API_BASE_URL = "http://api.openweathermap.org"; /** * API ключ. */ private static final String APP_ID = MyApplication.getAppContext().getString(R.string.open_weather_map_key); /** * Количество 3-х часовых интервалов для запроса к API. */ private static final int TIME_PERIOD = 8; /** * Количество дней для запроса к API. */ private static final int DAYS_PERIOD = 7; /** * Получаем директорию кэша приложения. */ final @Nullable File baseDir = MyApplication.getAppContext().getCacheDir(); /** * Нам необходимо вручную создать экземпляр объекта HttpLoggingInterceptor и OkHttpClient, * потому что Retrofit версии 2.0.0-beta2 использует их старые версии, в которых еще нет * некоторых нужных нам возможностей. Например, получения полного тела запроса. */ private HttpLoggingInterceptor logging; private OkHttpClient client; /** * Создаем сервис из интерфейса {@link OpenWeatherMapService} с заданными конечными точками * для запроса. */ private OpenWeatherMapService service; /** * Конструктор. */ public OpenWeatherMap() { logging = new HttpLoggingInterceptor(); client = new OkHttpClient(); if (baseDir != null) { final File cacheDir = new File(baseDir, "HttpResponseCache"); client.setCache(new Cache(cacheDir, 10 * 1024 * 1024)); } addInterceptors(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); service = retrofit.create(OpenWeatherMapService.class); } /** * Метод, который добавляет постоянно-используемые параметры к нашему запросу, а так же * устанавливает уровень логирования. */ private void addInterceptors() { logging.setLevel(Level.BODY); client.interceptors().add(new Interceptor() { @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MyApplication .getAppContext()); String key = MyApplication.getAppContext().getString(R.string.pref_language_key); String languageCode = sharedPreferences.getString(key, null); if (languageCode == null) { languageCode = Locale.getDefault().getLanguage(); } Request request = chain.request(); HttpUrl httpUrl = request.httpUrl().newBuilder() .addQueryParameter("lang", languageCode) .addQueryParameter("appid", APP_ID) .build(); request = request.newBuilder() .url(httpUrl) .build(); return chain.proceed(request); } }); client.interceptors().add(logging); client.networkInterceptors().add(new StethoInterceptor()); client.networkInterceptors().add(new Interceptor() { @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); String cacheHeaderValue = AppUtils.isNetworkAvailable(MyApplication.getAppContext()) ? "public, max-age=900" : "public, only-if-cached, max-stale=14400"; Request request = originalRequest.newBuilder().build(); com.squareup.okhttp.Response response = chain.proceed(request); return response.newBuilder() .header("Cache-Control", cacheHeaderValue) .build(); } }); } /** * Метод для асинхронного получения текущего прогноза погоды. * * @param requestQueue коллекция типа * {@link LinkedList}, содержащая элементы {@link com.khasang.forecast.stations.WeatherStation.ResponseType}, * хранит очередность запросов (текущий прогноз, прогноз на день или неделю) * @param cityID внутренний идентификатор города. * @param coordinate объект типа {@link Coordinate}, содержащий географические координаты */ @Override
public void updateWeather(final LinkedList<ResponseType> requestQueue, final int cityID, final Coordinate
3
andrewoma/dexx
collection/src/test/java/com/github/andrewoma/dexx/collection/mutable/MutableArrayList.java
[ "public interface Builder<E, R> {\n @NotNull\n Builder<E, R> add(E element);\n\n @NotNull\n Builder<E, R> addAll(@NotNull Traversable<E> elements);\n\n @NotNull\n Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements);\n\n @NotNull\n Builder<E, R> addAll(@NotNull Iterator<E> iterator)...
import java.util.ArrayList; import java.util.Iterator; import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.BuilderFactory; import com.github.andrewoma.dexx.collection.IndexedList; import com.github.andrewoma.dexx.collection.List; import com.github.andrewoma.dexx.collection.internal.base.AbstractIndexedList; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
/* * Copyright (c) 2014 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.dexx.collection.mutable; /** * */ public class MutableArrayList<E> extends AbstractIndexedList<E> { private java.util.List<E> underlying = new ArrayList<E>(); @NotNull public static <A> BuilderFactory<A, IndexedList<A>> factory() { return new BuilderFactory<A, IndexedList<A>>() { @NotNull @Override
public Builder<A, IndexedList<A>> newBuilder() {
0
antest1/kcanotify
app/src/main/java/com/antest1/kcanotify/KcaAkashiListViewItem.java
[ "public static String getItemTranslation(String jp_name) {\n String name = jp_name;\n if (currentLocaleCode.equals(\"jp\")) {\n return jp_name;\n } else if (kcItemTranslationData.has(name)) {\n name = kcItemTranslationData.get(name).getAsString();\n }\n return name;\n}", "public stati...
import android.widget.Toast; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; import static com.antest1.kcanotify.KcaApiData.getItemTranslation; import static com.antest1.kcanotify.KcaApiData.getKcItemStatusById; import static com.antest1.kcanotify.KcaApiData.getKcShipDataById; import static com.antest1.kcanotify.KcaApiData.getShipTranslation; import static com.antest1.kcanotify.KcaApiData.removeKai; import static com.antest1.kcanotify.KcaUtils.getId; import static com.antest1.kcanotify.KcaUtils.joinStr;
package com.antest1.kcanotify; public class KcaAkashiListViewItem { private int equipId; private JsonObject equipImprovementData; private int equipIconMipmap; private String equipName = ""; private String equipSupport = ""; private String equipMaterials = ""; private String equipScrews = ""; public int getEquipId() { return equipId; } public JsonObject getEquipImprovementData() { return equipImprovementData; } public int getEquipIconMipmap() { return equipIconMipmap; } public String getEquipName() { return equipName; } public String getEquipSupport() { return equipSupport; } public String getEquipMaterials() { return equipMaterials; } public String getEquipScrews() { return equipScrews; } public void setEquipDataById(int id) { JsonObject kcItemData = getKcItemStatusById(id, "type,name"); String kcItemName = getItemTranslation(kcItemData.get("name").getAsString()); int type = kcItemData.getAsJsonArray("type").get(3).getAsInt(); int typeres = 0; try { typeres = getId(KcaUtils.format("item_%d", type), R.mipmap.class); } catch (Exception e) { typeres = R.mipmap.item_0; } equipId = id; equipIconMipmap = typeres; equipName = kcItemName; } public void setEquipImprovementData(JsonObject data) { equipImprovementData = data; } // 0: sun ~ 6: sat public void setEquipImprovementElement(int day, boolean checked) { JsonArray data = equipImprovementData.getAsJsonArray("improvement"); boolean convert_exception = equipImprovementData.has("convert_exception"); String[] material1 = new String[4]; String[] material2 = new String[4]; String[] material3 = new String[4]; String[] screw1 = new String[4]; String[] screw2 = new String[4]; String[] screw3 = new String[4]; int count = 0; List<String> screw = new ArrayList<String>(); List<String> material = new ArrayList<String>(); List<String> ship = new ArrayList<String>(); for (int i = 0; i < data.size(); i++) { JsonArray req = data.get(i).getAsJsonObject().getAsJsonArray("req"); List<String> shiplist = new ArrayList<String>(); for (int j = 0; j < req.size(); j++) { JsonArray reqitem = req.get(j).getAsJsonArray(); if (reqitem.size() == 2 && reqitem.get(0).getAsJsonArray().get(day).getAsBoolean()) { JsonElement supportInfo = reqitem.get(1); if (supportInfo.isJsonArray()) { int[] filtered = removeKai(supportInfo.getAsJsonArray(), convert_exception); for(int k = 0; k < filtered.length; k++) { JsonObject kcShipData = getKcShipDataById(filtered[k], "name"); shiplist.add(getShipTranslation(kcShipData.get("name").getAsString(), false)); } } else { shiplist.add("-"); } } } if (shiplist.size() > 0) {
ship.add(joinStr(shiplist,"/"));
6
simo415/spc
src/com/sijobe/spc/worldedit/LocalPlayer.java
[ "public interface ICUIEventHandler extends IHook {\n\n /**\n * Handles a CUI Event\n * \n * @param type - the type of CUI Event\n * @param type - the parameters of the CUI Event\n */\n public void handleCUIEvent(String type, String[] params);\n}", "public enum FontColour {\n \n BLACK(\"\\24...
import com.sijobe.spc.core.ICUIEventHandler; import com.sijobe.spc.util.FontColour; import com.sijobe.spc.util.WorldEditCUIHelper; import com.sijobe.spc.wrapper.Coordinate; import com.sijobe.spc.wrapper.Player; import com.sk89q.worldedit.ServerInterface; import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldVector; import com.sk89q.worldedit.bags.BlockBag; import com.sk89q.worldedit.cui.CUIEvent;
package com.sijobe.spc.worldedit; public class LocalPlayer extends com.sk89q.worldedit.LocalPlayer { private Player player; protected LocalPlayer(Player player, ServerInterface server) { super(server); this.player = player; } @Override public String[] getGroups() { // TODO Auto-generated method stub return null; } @Override public BlockBag getInventoryBlockBag() { // TODO Auto-generated method stub return null; } @Override public int getItemInHand() { return player.getCurrentItem(); } @Override public String getName() { return player.getPlayerName(); } @Override public double getPitch() { return player.getPitch(); } @Override public WorldVector getPosition() { Coordinate c = player.getPosition(); return new WorldVector(getWorld(), c.getX(), c.getY(), c.getZ()); } @Override public com.sk89q.worldedit.LocalWorld getWorld() { return new LocalWorld(player.getWorld()); } @Override public double getYaw() { return player.getYaw(); } @Override public void giveItem(int type, int quantity) { player.givePlayerItem(type, quantity); } @Override public boolean hasPermission(String arg0) { // TODO Check permissions return true; } @Override public void print(String message) { player.sendChatMessage(message); } @Override public void printDebug(String message) { System.out.println("WORLDEDIT-DEBUG: " + message); } @Override public void printError(String message) {
player.sendChatMessage(FontColour.RED + message);
1
dkzwm/SmoothRefreshLayout
app/src/main/java/me/dkzwm/widget/srl/sample/ui/TestQQActivityStyleActivity.java
[ "public abstract class RefreshingListenerAdapter implements SmoothRefreshLayout.OnRefreshListener {\n @Override\n public void onRefreshing() {}\n\n @Override\n public void onLoadingMore() {}\n}", "public class SmoothRefreshLayout extends ViewGroup\n implements NestedScrollingParent3, NestedScro...
import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.MenuItem; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RadioGroup; import androidx.annotation.IdRes; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.List; import me.dkzwm.widget.srl.RefreshingListenerAdapter; import me.dkzwm.widget.srl.SmoothRefreshLayout; import me.dkzwm.widget.srl.extra.footer.ClassicFooter; import me.dkzwm.widget.srl.extra.header.ClassicHeader; import me.dkzwm.widget.srl.indicator.IIndicator; import me.dkzwm.widget.srl.sample.R; import me.dkzwm.widget.srl.sample.adapter.RecyclerViewAdapter; import me.dkzwm.widget.srl.sample.header.CustomQQActivityHeader; import me.dkzwm.widget.srl.sample.utils.DataUtil;
package me.dkzwm.widget.srl.sample.ui; /** * Created by dkzwm on 2017/6/20. * * @author dkzwm */ public class TestQQActivityStyleActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener { private SmoothRefreshLayout mRefreshLayout; private RecyclerView mRecyclerView; private RecyclerViewAdapter mAdapter; private Handler mHandler = new Handler(); private RadioGroup mRadioGroup; private RadioButton mRadioButtonNormal; private RadioButton mRadioButtonActivity; private int mCount = 0; private ClassicHeader mClassicHeader; private ClassicFooter mClassicFooter; private CustomQQActivityHeader mQQActivityHeader; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_qq_activity_style); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setTitle(R.string.test_qq_activity_style); mRecyclerView = findViewById(R.id.recyclerView_test_qq_activity_style); mRadioGroup = findViewById(R.id.radioGroup_test_qq_activity_style_container); mRadioButtonNormal = findViewById(R.id.radioButton_test_qq_activity_style_normal); mRadioButtonActivity = findViewById(R.id.radioButton_test_qq_activity_style_activity); mRadioGroup.setOnCheckedChangeListener(this); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setHasFixedSize(true); mAdapter = new RecyclerViewAdapter(this, getLayoutInflater()); mRecyclerView.setAdapter(mAdapter); mRefreshLayout = findViewById(R.id.smoothRefreshLayout_test_qq_activity_style); mClassicHeader = new ClassicHeader(this); mClassicHeader.setLastUpdateTimeKey("header_last_update_time"); mClassicFooter = new ClassicFooter(this); mClassicFooter.setLastUpdateTimeKey("footer_last_update_time"); mRefreshLayout.setHeaderView(mClassicHeader); mRefreshLayout.setFooterView(mClassicFooter); mRefreshLayout.setEnableKeepRefreshView(true); mRefreshLayout.setDisableLoadMore(false); mRefreshLayout.setOnRefreshListener(
new RefreshingListenerAdapter() {
0
wrey75/WaveCleaner
src/main/java/com/oxande/xmlswing/components/JTextComponentUI.java
[ "public class AttributeDefinition {\r\n\t\r\n\tpublic final static Map<String, String> ALIGNS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CLOSE_OPERATIONS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CURSORS = new HashMap<String, String>();\r\n\tpub...
import javax.swing.text.JTextComponent; import org.w3c.dom.Element; import com.oxande.xmlswing.AttributeDefinition; import com.oxande.xmlswing.AttributesController; import com.oxande.xmlswing.Parser; import com.oxande.xmlswing.AttributeDefinition.ClassType; import com.oxande.xmlswing.UnexpectedTag; import com.oxande.xmlswing.jcode.JavaClass; import com.oxande.xmlswing.jcode.JavaMethod;
package com.oxande.xmlswing.components; /** * The JTextComponent implementation. * * @author wrey75 * @version $Rev: 85 $ * */ public class JTextComponentUI extends JComponentUI { public static final AttributeDefinition[] PROPERTIES = { new AttributeDefinition( "caretColor", "setCaretColor", ClassType.COLOR ), new AttributeDefinition( "disabledTextColor", "setDisabledTextColor", ClassType.COLOR ), new AttributeDefinition( "selectionColor", "setSelectionColor", ClassType.COLOR ), DRAGGABLE_ATTRIBUTE_DEF, new AttributeDefinition( "editable", "setEditable", ClassType.BOOLEAN ), new AttributeDefinition( "*", "setText", ClassType.TEXT ), }; public static final AttributesController CONTROLLER = new AttributesController( JComponentUI.CONTROLLER, PROPERTIES );
public String parse(JavaClass jclass, JavaMethod initMethod, Element root ) throws UnexpectedTag{
5
Samourai-Wallet/sentinel-android
app/src/main/java/com/samourai/sentinel/Network.java
[ "public class WebSocketService extends Service {\n\n private Context context = null;\n\n private Timer timer = new Timer();\n private static final long checkIfNotConnectedDelay = 15000L;\n private WebSocketHandler webSocketHandler = null;\n private final Handler handler = new Handler();\n private ...
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.samourai.sentinel.service.WebSocketService; import com.samourai.sentinel.tor.TorManager; import com.samourai.sentinel.tor.TorService; import com.samourai.sentinel.util.AppUtil; import com.samourai.sentinel.util.ConnectivityStatus; import com.samourai.sentinel.util.PrefsUtil; import java.util.Objects; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers;
package com.samourai.sentinel; public class Network extends Activity { TextView torRenewBtn; TextView torConnectionStatus; Button torButton; ImageView torConnectionIcon; int activeColor, disabledColor, waiting; CompositeDisposable disposables = new CompositeDisposable(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_network); Objects.requireNonNull(getActionBar()).setDisplayHomeAsUpEnabled(true); activeColor = ContextCompat.getColor(this, R.color.green_ui_2); disabledColor = ContextCompat.getColor(this, R.color.disabledRed); waiting = ContextCompat.getColor(this, R.color.warning_yellow); torButton = findViewById(R.id.networking_tor_btn); torRenewBtn = findViewById(R.id.networking_tor_renew); torConnectionIcon = findViewById(R.id.network_tor_status_icon); torConnectionStatus = findViewById(R.id.network_tor_status); torRenewBtn.setOnClickListener(view -> { if (TorManager.getInstance(getApplicationContext()).isConnected()) { startService(new Intent(this, TorService.class).setAction(TorService.RENEW_IDENTITY)); } }); listenToTorStatus(); // torButton.setOnClickListener(view -> { if (TorManager.getInstance(getApplicationContext()).isRequired()) { // if(DojoUtil.getInstance(NetworkDashboard.this).getDojoParams() !=null ){ // Toast.makeText(this,R.string.cannot_disable_tor_dojo,Toast.LENGTH_LONG).show(); // return; // } stopTor();
PrefsUtil.getInstance(getApplicationContext()).setValue(PrefsUtil.ENABLE_TOR, false);
5
ReplayMod/jGui
src/main/java/de/johni0702/minecraft/gui/popup/GuiInfoPopup.java
[ "public interface GuiContainer<T extends GuiContainer<T>> extends ComposedGuiElement<T> {\n\n T setLayout(Layout layout);\n Layout getLayout();\n\n void convertFor(GuiElement element, Point point);\n\n /**\n * Converts the global coordinates of the point to ones relative to the element.\n * @par...
import de.johni0702.minecraft.gui.layout.VerticalLayout; import de.johni0702.minecraft.gui.utils.Colors; import de.johni0702.minecraft.gui.utils.lwjgl.Dimension; import de.johni0702.minecraft.gui.utils.lwjgl.ReadablePoint; import de.johni0702.minecraft.gui.versions.MCVer.Keyboard; import de.johni0702.minecraft.gui.container.GuiContainer; import de.johni0702.minecraft.gui.container.GuiPanel; import de.johni0702.minecraft.gui.element.GuiButton; import de.johni0702.minecraft.gui.element.GuiElement; import de.johni0702.minecraft.gui.element.GuiLabel; import de.johni0702.minecraft.gui.function.Typeable;
/* * This file is part of jGui API, licensed under the MIT License (MIT). * * Copyright (c) 2016 johni0702 <https://github.com/johni0702> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package de.johni0702.minecraft.gui.popup; //#if MC>=11400 //#else //$$ import org.lwjgl.input.Keyboard; //#endif public class GuiInfoPopup extends AbstractGuiPopup<GuiInfoPopup> implements Typeable { public static GuiInfoPopup open(GuiContainer container, String...info) { GuiElement[] labels = new GuiElement[info.length]; for (int i = 0; i < info.length; i++) { labels[i] = new GuiLabel().setI18nText(info[i]).setColor(Colors.BLACK); } return open(container, labels); } public static GuiInfoPopup open(GuiContainer container, GuiElement... info) { GuiInfoPopup popup = new GuiInfoPopup(container).setBackgroundColor(Colors.DARK_TRANSPARENT); popup.getInfo().addElements(new VerticalLayout.Data(0.5), info); popup.open(); return popup; } private Runnable onClosed = () -> {}; private final GuiButton closeButton = new GuiButton().setSize(150, 20).onClick(() -> { close(); onClosed.run(); }).setI18nLabel("gui.back"); private final GuiPanel info = new GuiPanel().setMinSize(new Dimension(320, 50)) .setLayout(new VerticalLayout(VerticalLayout.Alignment.TOP).setSpacing(2)); { popup.setLayout(new VerticalLayout().setSpacing(10)) .addElements(new VerticalLayout.Data(0.5), info, closeButton); } private int layer; public GuiInfoPopup(GuiContainer container) { super(container); } public GuiInfoPopup setCloseLabel(String label) { closeButton.setLabel(label); return this; } public GuiInfoPopup setCloseI18nLabel(String label, Object...args) { closeButton.setI18nLabel(label, args); return this; } public GuiInfoPopup onClosed(Runnable onClosed) { this.onClosed = onClosed; return this; } @Override protected GuiInfoPopup getThis() { return this; } @Override public boolean typeKey(ReadablePoint mousePosition, int keyCode, char keyChar, boolean ctrlDown, boolean shiftDown) {
if (keyCode == Keyboard.KEY_ESCAPE) {
8
reines/game
game-server/src/main/java/com/game/server/handlers/packet/WalkHandler.java
[ "public class Packet {\n\tprivate static final Logger log = LoggerFactory.getLogger(Packet.class);\n\n\tpublic static final int HEADER_SIZE = 4 + 4; // type + size\n\n\tprotected static final CharsetDecoder stringDecoder;\n\n\tstatic {\n\t\tstringDecoder = Charset.forName(\"UTF-8\").newDecoder();\n\t}\n\n\t// X_SEN...
import com.game.common.codec.Packet; import com.game.common.model.Path; import com.game.server.Server; import com.game.server.WorldManager; import com.game.server.handlers.PacketHandler; import com.game.server.model.Player;
package com.game.server.handlers.packet; public class WalkHandler implements PacketHandler { @Override
public void handlePacket(Server server, WorldManager world, Player player, Packet packet) throws Exception {
0
IPEldorado/RemoteResources
src/com/eldorado/remoteresources/ui/model/PersistentDeviceModel.java
[ "public class CaptureManager implements ClientChangedListener {\n\n\tprivate static CaptureManager instance;\n\n\tprivate final ScreenPanel canvas;\n\n\tprivate Client client;\n\n\tprivate String deviceSerialNumber;\n\n\tprivate Device userDevice;\n\n\tprivate boolean isRunning;\n\n\tprivate EventsListener mouseLis...
import com.eldorado.remoteresources.android.client.screencapture.CaptureManager; import com.eldorado.remoteresources.i18n.RemoteResourcesLocalization; import com.eldorado.remoteresources.i18n.RemoteResourcesMessages; import com.eldorado.remoteresources.ui.DevicesContainer; import com.eldorado.remoteresources.ui.HostsContainer; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.swing.JOptionPane;
devices.put(device.getName(), device); devicesHistory.put(device.getSerialNumber(), device); } Host host = hosts.get(device.getHost()); if (!host.getDevices().contains(device)) { host.addDevice(device); } if (notifyListeners) { for (DeviceModelChangeListener listener : listeners) { listener.deviceAdded(device); } } } public void addHost(Host host) { if (hosts.get(host.getName()) == null) { hosts.put(host.getName(), host); } for (DeviceModelChangeListener listener : listeners) { listener.hostAdded(host); } for (Device device : host.getDevices()) { addDevice(device, false); } } public void removeDevice(Device device) { removeDevice(device, true); } private void removeDevice(Device device, boolean notify) { boolean disconnectDevice = true; Host h = hosts.get(device.getHost()); if (h != null) { int option = JOptionPane .showOptionDialog( null, RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.ConnectDeviceAction_RemoveDevice), RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.ConnectDeviceAction_RemoveDeviceTitle), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] { RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.ConnectDeviceAction_RemoveDeviceYes), RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.ConnectDeviceAction_RemoveDeviceNo) }, null); disconnectDevice = option == JOptionPane.YES_OPTION ? true : false; } if (disconnectDevice) { Device d = devices.remove(device.getName()); if (!d.getHost().equalsIgnoreCase(LOCALHOST)) { devicesHistory.remove(d.getSerialNumber()); } if (h != null) { h.getDevices().remove(d.getName()); } if ((d != null) && notify) { for (DeviceModelChangeListener listener : listeners) { listener.deviceRemoved(d); } } } else { Device d = devices.get(device.getName()); if ((d != null) && notify) { for (DeviceModelChangeListener listener : listeners) { if (listener instanceof DevicesContainer) { ((DevicesContainer) listener).disableCapture(d); } else if (listener instanceof HostsContainer) { ((HostsContainer) listener).disableCapture(d); } } } } } public void changeDeviceName(Device device, String oldName) { Device d = devices.get(oldName); if (d != null) { devices.remove(oldName); devices.put(device.getName(), device); for (DeviceModelChangeListener listener : listeners) { listener.deviceChangedName(device, oldName); } } } public void removeHost(String name) { Host h = hosts.remove(name); boolean disconnectHost = true; int option = JOptionPane .showConfirmDialog( null, RemoteResourcesLocalization .getMessage(RemoteResourcesMessages.HostPanel_RemoveHost), "Remove Host", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); disconnectHost = option == JOptionPane.YES_OPTION ? true : false; if (disconnectHost) { if (h != null) { for (Device device : h.getDevices()) { removeDevice(device, false);
CaptureManager.getInstance().stopCapture();
0
tkrajina/10000sentences
10000sentencesapp/src/main/java/info/puzz/a10000sentences/tasks/ImporterAsyncTask.java
[ "public class Application extends android.app.Application {\n\n public static DiComponent COMPONENT;\n\n @Override\n public void onCreate() {\n super.onCreate();\n initIconify();\n initActiveAndroid();\n initDagger();\n }\n\n private void initDagger() {\n COMPONENT ...
import android.app.ProgressDialog; import android.content.pm.ActivityInfo; import android.os.AsyncTask; import android.widget.Toast; import com.activeandroid.util.Log; import org.apache.commons.lang3.StringUtils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import info.puzz.a10000sentences.Application; import info.puzz.a10000sentences.R; import info.puzz.a10000sentences.activities.BaseActivity; import info.puzz.a10000sentences.dao.Dao; import info.puzz.a10000sentences.models.Sentence; import info.puzz.a10000sentences.models.SentenceCollection; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;
package info.puzz.a10000sentences.tasks; public class ImporterAsyncTask extends AsyncTask<String, Integer, Void> { private static final java.lang.String TAG = ImporterAsyncTask.class.getSimpleName(); public static final int PROGRESS_EVERY = 50; @Inject Dao dao; private final BaseActivity activity; private final ProgressDialog progressDialog; private final SentenceCollection collection; private final CollectionReloadedListener listener; public interface CollectionReloadedListener { void onCollectionReloaded(SentenceCollection collection); } public ImporterAsyncTask(BaseActivity activity, SentenceCollection collection, CollectionReloadedListener listener) { Application.COMPONENT.inject(this); this.activity = activity; this.collection = collection; this.listener = listener; this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); progressDialog = new ProgressDialog(activity); progressDialog.setTitle("Loading"); progressDialog.setMessage("Loading"); progressDialog.show(); } @Override protected Void doInBackground(String... strings) { String url = strings[0]; publishProgress(0); OkHttpClient httpClient = new OkHttpClient(); Call call = httpClient.newCall(new Request.Builder().url(url).get().build()); try { Response response = call.execute(); InputStream stream = response.body().byteStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
List<Sentence> sentences = new ArrayList<>();
3
darko1002001/android-rest-client
rest-client-demo/src/main/java/com/dg/examples/restclientdemo/MainActivity.java
[ "public class BlogsGoogleRequest extends RestClientRequest<ResponseModel> {\n\n public static final String TAG = BlogsGoogleRequest.class.getSimpleName();\n\n public BlogsGoogleRequest(String query) {\n super();\n setRequestMethod(RequestMethod.GET);\n setUrl(RestConstants.GOOGLE_BLOGS);\n\n setParser...
import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.dg.examples.restclientdemo.communication.requests.BlogsGoogleRequest; import com.dg.examples.restclientdemo.communication.requests.PatchRequest; import com.dg.examples.restclientdemo.domain.ResponseModel; import com.dg.libs.rest.callbacks.HttpCallback; import com.dg.libs.rest.domain.ResponseStatus; import com.dg.libs.rest.requests.RestClientRequest;
package com.dg.examples.restclientdemo; public class MainActivity extends Activity { private TextView textViewResponse; private RestClientRequest<ResponseModel> request; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewResponse = (TextView) findViewById(R.id.textViewResponse); request = new BlogsGoogleRequest("Official Google Blogs").setCallback(new GoogleBlogsCallback()); request .executeAsync();
new PatchRequest("Hello").setCallback(new HttpCallback<Void>() {
3
monkeyk/oauth2-shiro
authz/src/main/java/com/monkeyk/os/oauth/authorize/CodeAuthorizeHandler.java
[ "public class ClientDetails extends BasicClientInfo {\n\n\n /**\n * 客户端所拥有的资源ID(resource-id), 至少有一个,\n * 多个ID时使用逗号(,)分隔, 如: os,mobile\n */\n private String resourceIds;\n\n private String scope;\n\n /**\n * 客户端所支持的授权模式(grant_type),\n * 至少一个, 多个值时使用逗号(,)分隔, 如: password,refresh_token\...
import com.monkeyk.os.domain.oauth.ClientDetails; import com.monkeyk.os.web.WebUtils; import com.monkeyk.os.oauth.OAuthAuthxRequest; import com.monkeyk.os.oauth.validator.AbstractClientDetailsValidator; import com.monkeyk.os.oauth.validator.CodeClientDetailsValidator; import org.apache.oltu.oauth2.as.response.OAuthASResponse; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.apache.oltu.oauth2.common.message.OAuthResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
package com.monkeyk.os.oauth.authorize; /** * 2015/6/25 * <p/> * Handle response_type = 'code' * * @author Shengzhao Li */ public class CodeAuthorizeHandler extends AbstractAuthorizeHandler { private static final Logger LOG = LoggerFactory.getLogger(CodeAuthorizeHandler.class); public CodeAuthorizeHandler(OAuthAuthxRequest oauthRequest, HttpServletResponse response) { super(oauthRequest, response); } @Override protected AbstractClientDetailsValidator getValidator() {
return new CodeClientDetailsValidator(oauthRequest);
4
SolraBizna/jarm
src/name/bizna/jarmtest/TestDirectory.java
[ "public class AlignmentException extends Exception {\n\tstatic final long serialVersionUID = 1;\n}", "public final class BusErrorException extends Exception {\n\n\tprivate static final long serialVersionUID = 1;\n\n\tprivate final String reason;\n\tprivate final long address;\n\tprivate final AccessType accessTyp...
import java.io.EOFException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.List; import name.bizna.jarm.AlignmentException; import name.bizna.jarm.BusErrorException; import name.bizna.jarm.ByteArrayRegion; import name.bizna.jarm.CPU; import name.bizna.jarm.PhysicalMemorySpace; import name.bizna.jarm.UndefinedException; import name.bizna.jarm.UnimplementedInstructionException; import name.bizna.jarmtest.TestSpec.InvalidSpecException;
package name.bizna.jarmtest; public class TestDirectory { public static final String CODE_FILENAME = "code.elf"; public static final int MAX_PROGRAM_SPACE = 1<<30; private File path; private String name; private byte[] programBytes = null, hiBytes = null; private boolean littleEndian = false, hasEntryPoint = false; private int entryPoint = 0; private static class ProgramHeaderEntry { int p_type; int p_offset; int p_vaddr; // int p_paddr; int p_filesz; int p_memsz; // int p_flags; // int p_align; public ProgramHeaderEntry(ByteBuffer buf) { p_type = buf.getInt(); p_offset = buf.getInt(); p_vaddr = buf.getInt(); /*p_paddr =*/ buf.getInt(); p_filesz = buf.getInt(); p_memsz = buf.getInt(); /*p_flags = buf.getInt();*/ /*p_align = buf.getInt();*/ } } private void loadProgram(File path, String id) throws NonLoadableFileException { RandomAccessFile f = null; programBytes = null; hiBytes = null; littleEndian = false; entryPoint = 0; hasEntryPoint = false; try { f = new RandomAccessFile(path, "r"); byte[] headerReadArray = new byte[52]; ByteBuffer headerReadBuf = ByteBuffer.wrap(headerReadArray); f.read(headerReadArray); /*** Read the Elf32_Ehdr ***/ /* EI_MAG0-3 = backspace, ELF */ if(headerReadBuf.getInt() != 0x7F454C46) throw new NonLoadableFileException("not an ELF file", id); /* EI_CLASS = ELFCLASS32 */ if(headerReadBuf.get() != 1) throw new NonLoadableFileException("not 32-bit", id); /* EI_DATA = ELFDATA2LSB or ELFDATA2MSB */ final byte EI_DATA = headerReadBuf.get(); switch(EI_DATA) { case 1: // ELFDATA2LSB littleEndian = true; break; case 2: // ELFDATA2MSB // big endian by default break; default: throw new NonLoadableFileException("neither little-endian nor big-endian", id); } /* EI_VERSION = 1 */ if(headerReadBuf.get() != 1) throw new NonLoadableFileException("not version 1", id); /* Remainder of e_ident ignored */ if(littleEndian) headerReadBuf.order(ByteOrder.LITTLE_ENDIAN); headerReadBuf.position(16); /* e_type = ET_EXEC */ if(headerReadBuf.getShort() != 2) throw new NonLoadableFileException("not executable", id); /* e_machine = EM_ARM */ if(headerReadBuf.getShort() != 40) throw new NonLoadableFileException("not ARM", id); /* e_version = 1 */ if(headerReadBuf.getInt() != 1) throw new NonLoadableFileException("not version 1", id); /* e_entry */ entryPoint = headerReadBuf.getInt(); /* e_phoff */ int e_phoff = headerReadBuf.getInt(); if(e_phoff < 52) throw new NonLoadableFileException("impossibly small e_phoff", id); /* e_shoff ignored */ headerReadBuf.getInt(); /* e_flags */ int e_flags = headerReadBuf.getInt(); /* only accept a zero entry point if e_flags contains EF_ARM_HASENTRY (0x00000002) */ if((e_flags & 2) != 0 && entryPoint == 0) hasEntryPoint = false; else hasEntryPoint = true; /* e_ehsize */ int e_ehsize = headerReadBuf.getShort() & 0xFFFF; if(e_ehsize < 52) throw new NonLoadableFileException("has an invalid e_ehsize field", id); /* e_phentsize */ int e_phentsize = headerReadBuf.getShort() & 0xFFFF; if(e_phentsize < 32) throw new NonLoadableFileException("has an invalid e_phentsize field", id); /* e_phnum */ int e_phnum = headerReadBuf.getShort() & 0xFFFF; if(e_phnum == 0 || e_phnum == 65535) throw new NonLoadableFileException("contains no program entries", id); /* e_shentsize, e_shnum, e_shstrndx are ignored */ ProgramHeaderEntry phents[] = new ProgramHeaderEntry[e_phnum]; for(int n = 0; n < e_phnum; ++n) { f.seek(e_phoff + n * e_phentsize); headerReadBuf.rewind(); f.read(headerReadArray, 0, 32); phents[n] = new ProgramHeaderEntry(headerReadBuf); } int memtop = 0; for(ProgramHeaderEntry phent : phents) { // PT_LOAD = 1 if(phent.p_type != 1) continue; if(phent.p_vaddr < 0 && phent.p_vaddr >= -65536) { // it's a high section if(phent.p_memsz > -phent.p_vaddr) throw new NonLoadableFileException("high section is too long", id); if(hiBytes == null) { try { hiBytes = new byte[65536]; } catch(OutOfMemoryError e) { throw new NonLoadableFileException("can't even allocate 64k for hiBytes, please increase the maximum memory size of the Java VM", id); } } } else { if(phent.p_vaddr < 0 || phent.p_vaddr >= MAX_PROGRAM_SPACE) throw new NonLoadableFileException("virtual address out of range", id); if(phent.p_memsz >= MAX_PROGRAM_SPACE) throw new NonLoadableFileException("absurdly long section", id); int phent_top = phent.p_vaddr + phent.p_memsz; if(phent_top < 0 || phent_top > MAX_PROGRAM_SPACE) throw new NonLoadableFileException("absurdly long section", id); if(phent_top > memtop) memtop = phent_top; } } assert(memtop <= MAX_PROGRAM_SPACE); try { programBytes = new byte[memtop]; } catch(OutOfMemoryError e) { throw new NonLoadableFileException("too big to fit in memory, please increase the maximum memory size of the Java VM", id); } for(ProgramHeaderEntry phent : phents) { if(phent.p_type != 1) continue; if(phent.p_filesz > 0) { f.seek(phent.p_offset); if(phent.p_vaddr >= -65536 && phent.p_vaddr < 0) f.read(hiBytes, phent.p_vaddr + 65536, phent.p_filesz); else f.read(programBytes, phent.p_vaddr, phent.p_filesz); } /* byte arrays are zero-filled when created, so we don't have to zero-fill */ } } catch(EOFException e) { throw new NonLoadableFileException("unexpected EOF", id); } catch(FileNotFoundException e) { throw new NonLoadableFileException("file not found", id); } catch(IOException e) { throw new NonLoadableFileException("IO error", id); } finally { if(f != null) try { f.close(); } catch(IOException e) { e.printStackTrace(); } } } public TestDirectory(File path, String name) { this.path = path; this.name = name; } public static boolean isValidTestDir(File dir) { return new File(dir, CODE_FILENAME).exists(); } public boolean runTestWithSpec(CPU cpu, File specFile, String specId, List<String> subtestFailureList) { try { TestSpec spec; try { spec = new TestSpec(specFile); } catch(InvalidSpecException e) { throw new NonLoadableFileException("invalid spec", specId); } catch(EOFException e) { throw new NonLoadableFileException("unexpected EOF", specId); } catch(FileNotFoundException e) { throw new NonLoadableFileException("file not found", specId); } catch(IOException e) { throw new NonLoadableFileException("IO error", specId); } spec.applyInitialStateAndReset(cpu, littleEndian); if(hasEntryPoint) cpu.loadPC(entryPoint); cpu.zeroBudget(false); try { cpu.execute(1<<30); }
catch(BusErrorException e) { /* NOTREACHED */ }
1
janrain/engage.android
Jump/src/com/janrain/android/engage/JREngage.java
[ "public class JRProvider implements Serializable {\n public static final String KEY_FRIENDLY_NAME = \"friendly_name\";\n public static final String KEY_INPUT_PROMPT = \"input_prompt\";\n public static final String KEY_OPENID_IDENTIFIER = \"openid_identifier\";\n public static final String KEY_URL = \"ur...
import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.janrain.android.engage.net.async.HttpResponseHeaders; import com.janrain.android.engage.session.JRProvider; import com.janrain.android.engage.session.JRSession; import com.janrain.android.engage.session.JRSessionDelegate; import com.janrain.android.engage.types.JRActivityObject; import com.janrain.android.engage.types.JRDictionary; import com.janrain.android.engage.ui.JRCustomInterface; import com.janrain.android.engage.ui.JRFragmentHostActivity; import com.janrain.android.engage.ui.JRPublishFragment; import com.janrain.android.engage.ui.JRUiFragment; import com.janrain.android.utils.AndroidUtils; import com.janrain.android.utils.LogUtils; import com.janrain.android.utils.ThreadUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.janrain.android.R.string.jr_git_describe; import static com.janrain.android.utils.LogUtils.throwDebugException;
// * @param hostActivity The android.support.v4.app.FragmentActivity which will host the publishing fragment // * @param containerId The resource ID of a FrameLayout to embed the publishing fragment in // */ //public void showSocialSignInFragment(FragmentActivity hostActivity, // int containerId) { // showSocialSignInFragment(hostActivity, containerId, false, null, null, null, null); //} ///** // * Create a new android.support.v4.Fragment for social sign-in. Use this if you wish to manage the // * FragmentTransaction yourself. // * // * @return The created Fragment, or null upon error (caused by library configuration failure) // */ //public JRProviderListFragment createSocialSignInFragment() { // if (checkSessionDataError()) return null; // // JRProviderListFragment jplf = new JRProviderListFragment(); // // Bundle arguments = new Bundle(); // arguments.putInt(JRUiFragment.JR_FRAGMENT_FLOW_MODE, JRUiFragment.JR_FRAGMENT_FLOW_AUTH); // jplf.setArguments(arguments); // jplf.setArguments(arguments); // return jplf; //} /*@}*/ private void showFragment(Fragment fragment, FragmentActivity hostActivity, int containerId, boolean addToBackStack, Integer transit, Integer transitRes, Integer customEnterAnimation, Integer customExitAnimation) { View fragmentContainer = hostActivity.findViewById(containerId); if (!(fragmentContainer instanceof FrameLayout)) { throw new IllegalStateException("No FrameLayout with ID: " + containerId + ". Found: " + fragmentContainer); } FragmentManager fm = hostActivity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); if (transit != null) ft.setTransition(transit); if (transitRes != null) ft.setTransitionStyle(transitRes); if (customEnterAnimation != null || customExitAnimation != null) { //noinspection ConstantConditions ft.setCustomAnimations(customEnterAnimation, customExitAnimation); } ft.replace(fragmentContainer.getId(), fragment, fragment.getClass().getSimpleName()); if (addToBackStack) ft.addToBackStack(fragment.getClass().getSimpleName()); ft.commit(); } /** @anchor enableProviders **/ /** * @name Enable a Subset of Providers * Methods that configure at runtime a subset of providers to use with the JREngage dialogs. These methods * can only configure a subset of the configured and enabled providers found on your Engage application's * dashboard. **/ /*@{*/ /** * Sets the list of providers that are enabled for authentication. This does not supersede your * RP's deplyoment settings for Android sign-in, as configured on rpxnow.com, it is a supplemental * filter to that configuration. * * @param enabledProviders A list of providers which will be enabled. This set will be intersected with * the set of providers configured on the Engage Dashboard, that intersection * will be the providers that are actually available to the end-user. */ public void setEnabledAuthenticationProviders(final List<String> enabledProviders) { blockOnInitialization(); mSession.setEnabledAuthenticationProviders(enabledProviders); } /** * Convenience variant of setEnabledAuthenticationProviders(List&lt;String>) * * @param enabledProviders An array of providers which will be enabled. This set will be intersected with * the set of providers configured on the Engage Dashboard, that intersection * will be the providers that are actually available to the end-user. */ public void setEnabledAuthenticationProviders(final String[] enabledProviders) { blockOnInitialization(); mSession.setEnabledAuthenticationProviders(Arrays.asList(enabledProviders)); } /** * Sets the list of providers that are enabled for social sharing. This does not supersede your * RP's deplyoment settings for Android social sharing, as configured on rpxnow.com, it is a * supplemental filter to that configuration. * * @param enabledSharingProviders Which providers to enable for authentication, null for all providers. * A list of social sharing providers which will be enabled. This set will * be intersected with the set of providers configured on the Engage * Dashboard, that intersection will be the providers that are actually * available to the end-user. */ public void setEnabledSharingProviders(final List<String> enabledSharingProviders) { blockOnInitialization(); mSession.setEnabledSharingProviders(enabledSharingProviders); } /** * Convenience variant of setEnabledSharingProviders(List&lt;String>) * * @param enabledSharingProviders An array of social sharing providers which will be enabled. This set * will be intersected with the set of providers configured on the Engage * Dashboard, that intersection will be the providers that are actually * available to the end-user. */ public void setEnabledSharingProviders(final String[] enabledSharingProviders) { blockOnInitialization(); mSession.setEnabledSharingProviders(Arrays.asList(enabledSharingProviders)); } /*@}*/
private JRSessionDelegate mJrsd = new JRSessionDelegate.SimpleJRSessionDelegate() {
2
jeffsvajlenko/BigCloneEval
src/tasks/EvaluateRecall.java
[ "public interface CloneMatcher {\n\tpublic boolean isDetected(Clone clone) throws SQLException;\n\tpublic void close() throws SQLException;\n\t\n\tpublic static String getTableName(long toolid) {\n\t\treturn \"tool_\" + toolid + \"_clones\";\n\t}\n\t\n\tpublic static CloneMatcher load(long toolid, String clazz, Str...
import cloneMatchingAlgorithms.CloneMatcher; import cloneMatchingAlgorithms.CoverageMatcher; import database.Clones; import database.Tool; import database.Tools; import evaluate.ToolEvaluator; import picocli.CommandLine; import util.FixPath; import java.io.FileWriter; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; import java.util.concurrent.Callable; import static evaluate.ToolEvaluator.*;
package tasks; @CommandLine.Command( name = "evaluateRecall", description = "Measures the recall of the clones given. Highly configureable." + "Summarizes recall per clone type, per inter vs intra-project clones, per functionality in " + "BigCloneBench and for different syntactical similarity regions in the output tool evaluation report.", mixinStandardHelpOptions = true, versionProvider = util.Version.class) public class EvaluateRecall implements Callable<Void> { @CommandLine.Spec private CommandLine.Model.CommandSpec spec; @CommandLine.Mixin private MixinOptions.OutputFile output; @CommandLine.Mixin private MixinOptions.EvaluationOptions evaluationOptions; @CommandLine.Mixin private MixinOptions.InputFile input; private Double matcher_coverage = null; @CommandLine.Option( names = {"-m", "--matcher-coverage"}, description = "Minimum coverage of clone-matcher: [0.0,1.0].", paramLabel = "double", required = true ) private void setMatcherCoverage(double matcher_coverage) { if (matcher_coverage < 0.0 && matcher_coverage > 1.0) { throw new CommandLine.ParameterException(spec.commandLine(), "Clone matcher coverage must be in range [0.0,1.0]."); } this.matcher_coverage = matcher_coverage; } public static void main(String[] args) { new CommandLine(new EvaluateRecall()).execute(args); } @Override public Void call() { // Create Temporary Tool String name = UUID.randomUUID().toString(); String desc = UUID.randomUUID().toString(); Long toolID = null; try { // Create Tool toolID = Tools.addTool(name, desc); // Import Clones System.out.println("Importing clones..."); Clones.importClones(toolID, input.input.toPath()); // Tool Evaluator CloneMatcher matcher = new CoverageMatcher(toolID, matcher_coverage, null, null);
ToolEvaluator te = new ToolEvaluator(toolID,
7
jboss-logging/jboss-logmanager
ext/src/test/java/org/jboss/logmanager/ext/PropertyConfigurationTests.java
[ "public abstract class ExtHandler extends Handler implements AutoCloseable, Flushable {\n\n private static final ErrorManager DEFAULT_ERROR_MANAGER = new OnlyOnceErrorManager();\n private static final Permission CONTROL_PERMISSION = new LoggingPermission(\"control\", null);\n\n private volatile boolean aut...
import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Properties; import java.util.logging.ErrorManager; import java.util.logging.Filter; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.LogRecord; import java.util.logging.Logger; import org.jboss.logmanager.ExtHandler; import org.jboss.logmanager.ExtLogRecord; import org.jboss.logmanager.Level; import org.jboss.logmanager.LogContext; import org.jboss.logmanager.formatters.PatternFormatter; import org.jboss.logmanager.handlers.ConsoleHandler; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
/* * JBoss, Home of Professional Open Source. * * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.logmanager.ext; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class PropertyConfigurationTests { private static final String DEFAULT_PATTERN = "%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n";
private LogContext logContext;
2
NanYoMy/mybatis-generator
src/main/java/org/mybatis/generator/codegen/ibatis2/dao/elements/DeleteByExampleMethodGenerator.java
[ "public class FullyQualifiedJavaType implements\n Comparable<FullyQualifiedJavaType> {\n private static final String JAVA_LANG = \"java.lang\"; //$NON-NLS-1$\n private static FullyQualifiedJavaType intInstance = null;\n private static FullyQualifiedJavaType stringInstance = null;\n private static...
import java.util.Set; import java.util.TreeSet; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.api.dom.java.Interface; import org.mybatis.generator.api.dom.java.JavaVisibility; import org.mybatis.generator.api.dom.java.Method; import org.mybatis.generator.api.dom.java.Parameter; import org.mybatis.generator.api.dom.java.TopLevelClass;
/* * Copyright 2008 The Apache Software Foundation * * 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.mybatis.generator.codegen.ibatis2.dao.elements; /** * * @author Jeff Butler * */ public class DeleteByExampleMethodGenerator extends AbstractDAOElementGenerator { public DeleteByExampleMethodGenerator() { super(); } @Override public void addImplementationElements(TopLevelClass topLevelClass) { Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
Method method = getMethodShell(importedTypes);
2
rodhilton/jasome
src/main/java/org/jasome/metrics/calculators/TypeAggregatorCalculator.java
[ "public class Method extends Code {\n private final MethodDeclaration declaration;\n\n public final static Method UNKNOWN = new Method();\n\n private Method() {\n super(\"unknownMethod\");\n this.declaration = null;\n }\n\n public Method(MethodDeclaration declaration) {\n super(d...
import com.google.common.collect.ImmutableSet; import org.jasome.input.Method; import org.jasome.input.Type; import org.jasome.metrics.Calculator; import org.jasome.metrics.Metric; import org.jasome.metrics.value.NumericValue; import org.jasome.metrics.value.NumericValueSummaryStatistics; import java.util.Optional; import java.util.Set; import java.util.stream.Stream;
package org.jasome.metrics.calculators; public class TypeAggregatorCalculator implements Calculator<Type> { @Override
public Set<Metric> calculate(Type type) {
3
AEminium/AeminiumRuntime
src/aeminium/runtime/implementations/implicitworkstealing/datagroup/FifoDataGroup.java
[ "public interface DataGroup {}", "public final class Configuration {\n\tprotected static final String GLOBAL_PREFIX = \"global.\";\n\tprotected static int processorCount;\n\tprotected static String implementation;\n\tprotected static final Properties properties; \n\t\n\tstatic {\n\t\tString filename = System.gete...
import aeminium.runtime.utils.graphviz.GraphViz.Color; import aeminium.runtime.utils.graphviz.GraphViz.LineStyle; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import aeminium.runtime.DataGroup; import aeminium.runtime.implementations.Configuration; import aeminium.runtime.implementations.implicitworkstealing.ImplicitWorkStealingRuntime; import aeminium.runtime.implementations.implicitworkstealing.error.ErrorManager; import aeminium.runtime.implementations.implicitworkstealing.task.ImplicitAtomicTask; import aeminium.runtime.implementations.implicitworkstealing.task.ImplicitTask; import aeminium.runtime.utils.graphviz.DiGraphViz;
/** * Copyright (c) 2010-11 The AEminium Project (see AUTHORS file) * * This file is part of Plaid Programming Language. * * Plaid Programming Language 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. * * Plaid Programming Language 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 Plaid Programming Language. If not, see <http://www.gnu.org/licenses/>. */ package aeminium.runtime.implementations.implicitworkstealing.datagroup; /* * A DataGroup (DG) implementation that works similar to a lock. */ public final class FifoDataGroup implements ImplicitWorkStealingRuntimeDataGroup { protected static final boolean checkForDeadlocks = Configuration.getProperty(FifoDataGroup.class, "checkForDeadlocks", false); protected static final boolean graphVizEnabled = Configuration.getProperty(ImplicitWorkStealingRuntime.class, "enableGraphViz", false); protected static final boolean graphVizShowLockingOrder = Configuration.getProperty(FifoDataGroup.class, "graphVizShowLockingOrder", false); protected static AtomicInteger idGen = new AtomicInteger(); private boolean locked = false; private List<ImplicitTask> waitQueue = new LinkedList<ImplicitTask>(); protected ImplicitTask owner = null; protected ImplicitTask previousOwner; protected final int id = idGen.incrementAndGet(); // Tries to hold the lock on the DG. public final boolean trylock(ImplicitWorkStealingRuntime rt, ImplicitTask task) { synchronized (this) { if ( locked ) { waitQueue.add(task); if ( checkForDeadlocks ) { ImplicitAtomicTask atomicParent = ((ImplicitAtomicTask)task).getAtomicParent(); atomicParent.addDataGroupDependecy(this); checkForDeadlock(atomicParent, rt.getErrorManager()); } return false; } else { locked = true; owner = task; if ( graphVizEnabled && graphVizShowLockingOrder && previousOwner != null ) { DiGraphViz graphViz = rt.getGraphViz(); graphViz.addConnection(owner.hashCode(), previousOwner.hashCode(), LineStyle.DOTTED, Color.GREEN, ""+id); } return true; } } } // Releases the lock on the DG public final void unlock(ImplicitWorkStealingRuntime rt, ImplicitTask task) { ImplicitTask head = null; synchronized (this) { locked = false; previousOwner = owner; owner = null; if (!waitQueue.isEmpty()) { head = waitQueue.remove(0); if ( checkForDeadlocks ) { ImplicitAtomicTask atomicParent = ((ImplicitAtomicTask)head).getAtomicParent(); atomicParent.addDataGroupDependecy(this); } } } if ( head != null ) { rt.scheduler.scheduleTask(head); } } public final boolean checkForDeadlock(final ImplicitAtomicTask atomicParent, final ErrorManager em) {
for ( DataGroup dg : atomicParent.getDataGroupDependencies() ) {
0
OpherV/gitflow4idea
src/main/java/gitflow/ui/GitflowOpenTaskPanel.java
[ "public class GitflowBranchUtil {\n\n Project myProject;\n GitRepository myRepo;\n\n private String currentBranchName;\n private String branchnameMaster;\n private String branchnameDevelop;\n private String prefixFeature;\n private String prefixRelease;\n private String prefixHotfix;\n pr...
import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.VcsTaskHandler; import com.intellij.tasks.LocalTask; import com.intellij.tasks.Task; import com.intellij.tasks.TaskManager; import com.intellij.tasks.impl.TaskManagerImpl; import com.intellij.tasks.ui.TaskDialogPanel; import git4idea.branch.GitBranchUtil; import git4idea.repo.GitRepository; import gitflow.GitflowBranchUtil; import gitflow.GitflowBranchUtilManager; import gitflow.GitflowConfigUtil; import gitflow.GitflowState; import gitflow.actions.GitflowAction; import gitflow.actions.StartBugfixAction; import gitflow.actions.StartFeatureAction; import gitflow.actions.StartHotfixAction; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Collections; import static com.intellij.openapi.vcs.VcsTaskHandler.TaskInfo;
package gitflow.ui; public class GitflowOpenTaskPanel extends TaskDialogPanel implements ItemListener { private JRadioButton noActionRadioButton; private JRadioButton startFeatureRadioButton; private JRadioButton startHotfixRadioButton; private JTextField featureName; private JComboBox featureBaseBranch; private JTextField hotfixName; private JPanel myPanel; private JComboBox hotfixBaseBranch; private JRadioButton startBugfixRadioButton; private JTextField bugfixName; private JComboBox bugfixBaseBranch; private Project myProject; private GitRepository myRepo; private GitflowBranchUtil gitflowBranchUtil; private TaskManagerImpl myTaskManager; private VcsTaskHandler myVcsTaskHandler; private LocalTask myPreviousTask; private Task currentTask; private GitflowState gitflowState; public GitflowOpenTaskPanel(Project project, Task task, GitRepository repo){ myProject = project; currentTask = task; myRepo = repo; myTaskManager = (TaskManagerImpl) TaskManager.getManager(project); myPreviousTask = myTaskManager.getActiveTask(); VcsTaskHandler[] vcsTaskHAndlers = VcsTaskHandler.getAllHandlers(project); if (vcsTaskHAndlers.length > 0){ //todo handle case of multiple vcs handlers myVcsTaskHandler = vcsTaskHAndlers[0]; } gitflowState = ServiceManager.getService(GitflowState.class); gitflowBranchUtil = GitflowBranchUtilManager.getBranchUtil(myRepo); GitflowConfigUtil gitflowConfigUtil = GitflowConfigUtil.getInstance(project, myRepo); String defaultFeatureBranch = gitflowConfigUtil.developBranch; featureBaseBranch.setModel(gitflowBranchUtil.createBranchComboModel(defaultFeatureBranch)); String defaultHotfixBranch = gitflowConfigUtil.masterBranch; hotfixBaseBranch.setModel(gitflowBranchUtil.createBranchComboModel(defaultHotfixBranch)); String defaultBugfixBranch = gitflowConfigUtil.developBranch; bugfixBaseBranch.setModel(gitflowBranchUtil.createBranchComboModel(defaultBugfixBranch)); myRepo = GitBranchUtil.getCurrentRepository(project); String branchName = myVcsTaskHandler != null ? myVcsTaskHandler.cleanUpBranchName(myTaskManager.constructDefaultBranchName(task)) : myTaskManager.suggestBranchName(task); featureName.setText(branchName); featureName.setEditable(false); featureName.setEnabled(false); hotfixName.setText(branchName); hotfixName.setEditable(false); hotfixName.setEnabled(false); bugfixName.setText(branchName); bugfixName.setEditable(false); bugfixName.setEnabled(false); featureBaseBranch.setEnabled(false); hotfixBaseBranch.setEnabled(false); bugfixBaseBranch.setEnabled(false); //add listeners noActionRadioButton.addItemListener(this); startFeatureRadioButton.addItemListener(this); startHotfixRadioButton.addItemListener(this); startBugfixRadioButton.addItemListener(this); } @NotNull @Override public JComponent getPanel() { return myPanel; } @Override public void commit() { final GitflowBranchUtil.ComboEntry selectedFeatureBaseBranch = (GitflowBranchUtil.ComboEntry) featureBaseBranch.getModel().getSelectedItem(); final GitflowBranchUtil.ComboEntry selectedHotfixBaseBranch = (GitflowBranchUtil.ComboEntry) hotfixBaseBranch.getModel().getSelectedItem(); final GitflowBranchUtil.ComboEntry selectedBugfixBaseBranch = (GitflowBranchUtil.ComboEntry) bugfixBaseBranch.getModel().getSelectedItem(); GitflowConfigUtil gitflowConfigUtil = GitflowConfigUtil.getInstance(myProject, myRepo); if (startFeatureRadioButton.isSelected()) { final String branchName = gitflowConfigUtil.featurePrefix + featureName.getText(); attachTaskAndRunAction(new StartFeatureAction(myRepo), selectedFeatureBaseBranch.getBranchName(), branchName); } else if (startHotfixRadioButton.isSelected()) { final String branchName = gitflowConfigUtil.hotfixPrefix + hotfixName.getText(); attachTaskAndRunAction(new StartHotfixAction(myRepo), selectedHotfixBaseBranch.getBranchName(), branchName); } else if (startBugfixRadioButton.isSelected()) { final String branchName = gitflowConfigUtil.bugfixPrefix + bugfixName.getText(); attachTaskAndRunAction(new StartBugfixAction(myRepo), selectedBugfixBaseBranch.getBranchName(), branchName); } } /** * @param action instance of GitflowAction * @param baseBranchName Branch name of the branch the new one is based on * @param fullBranchName Branch name with feature/hotfix/bugfix prefix for saving to task */
private void attachTaskAndRunAction(GitflowAction action, String baseBranchName, final String fullBranchName) {
4
kontalk/desktopclient-java
src/main/java/org/kontalk/view/ContactDetails.java
[ "public final class JID {\n private static final Logger LOGGER = Logger.getLogger(JID.class.getName());\n\n static {\n // good to know. For working JID validation\n SimpleXmppStringprep.setup();\n }\n\n private final String mLocal; // escaped!\n private final String mDomain;\n privat...
import javax.swing.Box; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.Observable; import java.util.Optional; import com.alee.extended.layout.FormLayout; import com.alee.extended.panel.GroupPanel; import com.alee.extended.panel.GroupingType; import com.alee.laf.button.WebButton; import com.alee.laf.checkbox.WebCheckBox; import com.alee.laf.label.WebLabel; import com.alee.laf.optionpane.WebOptionPane; import com.alee.laf.panel.WebPanel; import com.alee.laf.separator.WebSeparator; import com.alee.laf.text.WebTextArea; import com.alee.laf.text.WebTextField; import com.alee.managers.tooltip.TooltipManager; import org.kontalk.misc.JID; import org.kontalk.model.Contact; import org.kontalk.util.Tr; import org.kontalk.view.AvatarLoader.AvatarImg; import org.kontalk.view.ComponentUtils.LabelTextField;
/* * Kontalk Java client * Copyright (C) 2016 Kontalk Devteam <devteam@kontalk.org> * * 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 <http://www.gnu.org/licenses/>. */ package org.kontalk.view; /** * Show and edit contact details. * * @author Alexander Bikadorov {@literal <bikaejkb@mail.tu-berlin.de>} */ final class ContactDetails extends WebPanel implements ObserverTrait { private static final Map<Contact, ContactDetails> CACHE = new HashMap<>(); private final View mView; private final Contact mContact; private final ComponentUtils.EditableAvatarImage mAvatarImage; private final WebTextField mNameField; private final WebLabel mSubscrStatus; private final WebButton mSubscrButton; private final WebLabel mKeyStatus; private final WebLabel mFPLabel; private final WebButton mUpdateButton; private final WebTextArea mFPArea; private final WebCheckBox mEncryptionBox; private ContactDetails(View view, Contact contact) { mView = view; mContact = contact; GroupPanel groupPanel = new GroupPanel(View.GAP_BIG, false); groupPanel.setMargin(View.MARGIN_BIG);
groupPanel.add(new WebLabel(Tr.tr("Contact details")).setBoldFont());
2
larusba/doc2graph
neo4j-json/src/main/java/org/neo4j/helpers/json/document/impl/DocumentGrapherRecursive.java
[ "public interface DocumentGrapher {\n\n\t/**\n\t * Create and re-use node and relations\n\t * @param key\n\t * @param document\n\t * @return id of root node\n\t */\n\t@SuppressWarnings(\"rawtypes\")\n\tNode upsertDocument(String key, Map document);\n\t\n\t/**\n\t * Remove non shared node and relationships regarding...
import org.neo4j.helpers.json.document.DocumentId; import org.neo4j.helpers.json.document.DocumentIdBuilder; import org.neo4j.helpers.json.document.DocumentLabelBuilder; import org.neo4j.helpers.json.document.DocumentRelationBuilder; import org.neo4j.helpers.json.document.context.DocumentGrapherExecutionContext; import org.neo4j.helpers.json.document.context.DocumentRelationContext; import org.neo4j.logging.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Label; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Result; import org.neo4j.helpers.json.document.DocumentGrapher;
/** * Copyright (c) 2017 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.neo4j.helpers.json.document.impl; /** * Recursive implementation of logic to transform document into graph (tree) * @author Omar Rampado * */ public class DocumentGrapherRecursive implements DocumentGrapher { private GraphDatabaseService db; private Log log; private DocumentIdBuilder documentIdBuilder; private DocumentRelationBuilder documentRelationBuilder;
private DocumentLabelBuilder documentLabelBuilder;
3
lesstif/jira-rest-client
src/test/java/com/lesstif/jira/services/IssueTest.java
[ "public class JsonPrettyString {\n\t\n\tfinal public String toPrettyJsonString() {\n\t\tObjectMapper mapper = new ObjectMapper();\n\n\t\tmapper.configure(SerializationFeature.INDENT_OUTPUT, true);\n\t\t\n\t\tStringWriter sw = new StringWriter();\n\t\ttry {\n\t\t\tmapper.writeValue(sw, this);\n\t\t} catch (IOExcepti...
import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import org.apache.commons.configuration.ConfigurationException; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Attachment; import com.lesstif.jira.issue.Issue; import com.lesstif.jira.issue.IssueFields; import com.lesstif.jira.issue.IssueSearchResult; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Priority; import com.lesstif.jira.util.HttpConnectionUtil; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*;
package com.lesstif.jira.services; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class IssueTest { private Logger logger = LoggerFactory.getLogger(getClass()); static String PROJECT_KEY = null; static String ISSUE_KEY = null; static String REPORTER = null; static String ASSIGNEE = null; @BeforeClass public static void beforeClass() { HttpConnectionUtil.disableSslVerification(); PROJECT_KEY = System.getProperty("jira.test.project", "TEST"); ISSUE_KEY = System.getProperty("jira.test.issue", "TEST-108"); ASSIGNEE = System.getProperty("jira.test.assignee", "lesstif"); REPORTER = System.getProperty("jira.test.reporter", "gitlab"); } @Test public void aCreateIssue() throws IOException, ConfigurationException {
Issue issue = new Issue();
2
agilie/dribbble-android-sdk
dribbble-sdk-library/src/main/java/com/agilie/dribbblesdk/service/retrofit/DribbbleWebServiceHelper.java
[ "public interface DribbbleBucketsService {\n\n /**\n * Get a bucket\n *\n * @param bucketId Bucket ID\n *\n * @return Network operation result\n */\n @GET(\"buckets/{id}\")\n Call<Bucket> getBucket(@Path(\"id\") long bucketId);\n\n /**\n * Create a bucket.\n * C...
import com.agilie.dribbblesdk.service.retrofit.services.DribbbleBucketsService; import com.agilie.dribbblesdk.service.retrofit.services.DribbbleProjectsService; import com.agilie.dribbblesdk.service.retrofit.services.DribbbleShotsService; import com.agilie.dribbblesdk.service.retrofit.services.DribbbleTeamsService; import com.agilie.dribbblesdk.service.retrofit.services.DribbbleUserService; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import android.os.Build; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.net.ssl.SSLContext; import okhttp3.ConnectionSpec; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.TlsVersion; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;
package com.agilie.dribbblesdk.service.retrofit; public class DribbbleWebServiceHelper { public static String DRIBBBLE_URL = "https://api.dribbble.com/v1/"; public static DribbbleBucketsService getDribbbleBucketService(Retrofit retrofit) { DribbbleBucketsService service = retrofit.create(DribbbleBucketsService.class); return service; } public static DribbbleProjectsService getDribbbleProjectService(Retrofit retrofit) { DribbbleProjectsService service = retrofit.create(DribbbleProjectsService.class); return service; } public static DribbbleShotsService getDribbbleShotService(Retrofit retrofit) { DribbbleShotsService service = retrofit.create(DribbbleShotsService.class); return service; }
public static DribbbleTeamsService getDribbbleTeamService(Retrofit retrofit) {
3
MCUpdater/MCUpdater
MCU-API/src/org/mcupdater/util/MCLegacyAuth.java
[ "public class Version {\n\tpublic static final int MAJOR_VERSION;\n\tpublic static final int MINOR_VERSION;\n\tpublic static final int BUILD_VERSION;\n\tpublic static final String BUILD_BRANCH;\n\tpublic static final String BUILD_LABEL;\n\tstatic {\n\t\tProperties prop = new Properties();\n\t\ttry {\n\t\t\tprop.loa...
import java.util.HashMap; import java.util.logging.Level; import org.mcupdater.Version; import org.mcupdater.model.LoginData; import org.mcupdater.util.HTTPSUtils; import org.mcupdater.util.MCLoginException; import org.mcupdater.util.MCLoginException.ResponseType;
package org.mcupdater.util; public class MCLegacyAuth { public static LoginData login(String username, String password) throws Exception { try { HashMap<String, Object> localHashMap = new HashMap<String, Object>(); localHashMap.put("user", username); localHashMap.put("password", password); localHashMap.put("version", Integer.valueOf(13)); String str = HTTPSUtils.executePost("https://login.minecraft.net/", localHashMap); if (str == null) { //showError("Can't connect to minecraft.net"); throw new MCLoginException(ResponseType.NOCONNECTION); } if (!str.contains(":")) { if (str.trim().equals("Bad login")) { throw new MCLoginException(ResponseType.BADLOGIN); } else if (str.trim().equals("Old version")) { throw new MCLoginException(ResponseType.OLDVERSION); } else if (str.trim().equals("User not premium")) { throw new MCLoginException(ResponseType.OLDLAUNCHER); } else { throw new MCLoginException(str); } }
if (!Version.isMasterBranch()) {
0
jeick/jamod
src/main/java/net/wimpi/modbus/io/ModbusBINTransport.java
[ "public interface Modbus {\n\n\t/**\n\t * JVM flag for debug mode. Can be set passing the system property\n\t * net.wimpi.modbus.debug=false|true (-D flag to the jvm).\n\t */\n\tpublic static final boolean debug = \"true\".equals(System\n\t\t\t.getProperty(\"net.wimpi.modbus.debug\"));\n\n\t/**\n\t * Defines the cl...
import net.wimpi.modbus.Modbus; import net.wimpi.modbus.ModbusCoupler; import net.wimpi.modbus.ModbusIOException; import net.wimpi.modbus.util.ModbusUtil; import net.wimpi.modbus.msg.ModbusMessage; import net.wimpi.modbus.msg.ModbusRequest; import net.wimpi.modbus.msg.ModbusResponse; import java.io.DataInputStream; import java.io.IOException; import jssc.SerialInputStream; import jssc.SerialOutputStream;
/*** * Copyright 2002-2010 jamod development team * * 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 net.wimpi.modbus.io; /** * Class that implements the Modbus/BIN transport flavor. * * @author Dieter Wimberger * @version @version@ (@date@) */ public class ModbusBINTransport extends ModbusSerialTransport { private DataInputStream m_InputStream; // used to read from private ASCIIOutputStream m_OutputStream; // used to write to private byte[] m_InBuffer; private BytesInputStream m_ByteIn; // to read message from private BytesOutputStream m_ByteInOut; // to buffer message to private BytesOutputStream m_ByteOut; // write frames /** * Constructs a new <tt>MobusBINTransport</tt> instance. */ public ModbusBINTransport() { }// constructor public void close() throws IOException { m_InputStream.close(); m_OutputStream.close(); }// close
public void writeMessage(ModbusMessage msg) throws ModbusIOException {
4
occi4java/occi4java
http/src/main/java/occi/http/OcciRestNetworkInterface.java
[ "public class OcciConfig extends XMLConfiguration {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static final Logger LOGGER = LoggerFactory\n\t\t\t.getLogger(OcciConfig.class);\n\t/**\n\t * Instance of OcciConfig\n\t */\n\tprivate static OcciConfig instance = null;\n\tprivate static ConfigurationF...
import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.UUID; import occi.config.OcciConfig; import occi.core.Kind; import occi.core.Mixin; import occi.http.check.OcciCheck; import occi.infrastructure.Network; import occi.infrastructure.Network.State; import occi.infrastructure.links.NetworkInterface; import org.restlet.Response; import org.restlet.data.Form; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
if (requestHeaders.getFirstValue(acceptCase).equals("text/occi")) { // generate header rendering occiCheck.setHeaderRendering(null, networkinterface, buffer .toString(), buffer2); // set right representation and status code getResponse().setEntity(representation); getResponse().setStatus(Status.SUCCESS_OK); return " "; } // set right representation and status code getResponse().setEntity(representation); getResponse().setStatus(Status.SUCCESS_OK, buffer.toString()); return buffer.toString(); } /** * Deletes the resource which applies to the parameters in the header. * * @return string deleted or not */ @Delete public String deleteOCCIRequest() { // set occi version info getServerInfo().setAgent( OcciConfig.getInstance().config.getString("occi.version")); LOGGER.debug("Incoming delete request at network"); try { // get network resource that should be deleted NetworkInterface networkInterface = NetworkInterface.getNetworkInterfaceList() .get(UUID.fromString(getReference().getLastSegment())); // remove it from network resource list if (NetworkInterface.getNetworkInterfaceList().remove(UUID .fromString(networkInterface.getId().toString())) == null) { throw new NullPointerException( "There is no resorce with the given ID"); } // set network resource to null networkInterface = null; getResponse().setStatus(Status.SUCCESS_OK); return " "; } catch (NullPointerException e) { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); return "UUID not found! " + e.toString() + "\n Network resource could not be deleted."; } catch (Exception e) { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); return e.toString(); } } /** * Method to create a new network instance. * * @param representation * @return string * @throws Exception */ @Post public String postOCCIRequest(Representation representation) throws Exception { LOGGER.info("Incoming POST request."); // set occi version info getServerInfo().setAgent( OcciConfig.getInstance().config.getString("occi.version")); try { // access the request headers and get the X-OCCI-Attribute Form requestHeaders = (Form) getRequest().getAttributes().get( "org.restlet.http.headers"); LOGGER.debug("Current request: " + requestHeaders); String attributeCase = OcciCheck.checkCaseSensitivity( requestHeaders.toString()).get("x-occi-attribute"); String xocciattributes = requestHeaders.getValues(attributeCase) .replace(",", " "); LOGGER.debug("Media-Type: " + requestHeaders.getFirstValue("accept", true)); // OcciCheck.countColons(xocciattributes, 2); // split the single occi attributes and put it into a (key,value) // map LOGGER.debug("Raw X-OCCI Attributes: " + xocciattributes); StringTokenizer xoccilist = new StringTokenizer(xocciattributes); HashMap<String, Object> xoccimap = new HashMap<String, Object>(); LOGGER.debug("Tokens in XOCCIList: " + xoccilist.countTokens()); while (xoccilist.hasMoreTokens()) { String[] temp = xoccilist.nextToken().split("\\="); if (temp[0] != null && temp[1] != null) { LOGGER.debug(temp[0] + " " + temp[1] + "\n"); xoccimap.put(temp[0], temp[1]); } } // put occi attributes into a buffer for the response StringBuffer buffer = new StringBuffer(); buffer.append("occi.networkinterface.interface=").append( xoccimap.get("occi.networkinterface.interface")); buffer.append(" occi.networkinterface.mac=").append( xoccimap.get("occi.networkinterface.mac")); buffer.append(" occi.networkinterface.state=").append( xoccimap.get("occi.networkinterface.state")); Set<String> set = new HashSet<String>(); set.add("summary: "); set.add(buffer.toString()); set.add(requestHeaders.getFirstValue("scheme")); if (!requestHeaders.contains("Link")) { // create new NetworkInterface instance with the given // attributes NetworkInterface networkInterface = new NetworkInterface( (String) xoccimap .get("occi.networkinterface.interface"), (String) xoccimap.get("occi.networkinterface.mac"), occi.infrastructure.links.NetworkInterface.State.inactive, null, null);
networkInterface.setKind(new Kind(null, "networkinterface",
1
protolambda/blocktopograph
app/src/main/java/com/protolambda/blocktopograph/WorldActivity.java
[ "public enum Dimension {\n\n OVERWORLD(0, \"overworld\", \"Overworld\", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE),\n NETHER(1, \"nether\", \"Nether\", 16, 16, 128, 8, MapType.NETHER),\n END(2, \"end\", \"End\", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk\n\n public final int id;\n p...
import android.app.AlertDialog; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.text.Editable; import android.view.View; import android.support.design.widget.NavigationView; 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.MenuItem; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.google.firebase.analytics.FirebaseAnalytics; import com.protolambda.blocktopograph.map.Dimension; import com.protolambda.blocktopograph.map.marker.AbstractMarker; import com.protolambda.blocktopograph.nbt.convert.NBTConstants; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.protolambda.blocktopograph.chunk.NBTChunkData; import com.protolambda.blocktopograph.map.MapFragment; import com.protolambda.blocktopograph.map.renderer.MapType; import com.protolambda.blocktopograph.nbt.EditableNBT; import com.protolambda.blocktopograph.nbt.EditorFragment; import com.protolambda.blocktopograph.nbt.convert.DataConverter; import com.protolambda.blocktopograph.nbt.tags.CompoundTag; import com.protolambda.blocktopograph.nbt.tags.Tag;
public void openMultiplayerEditor(){ //takes some time to find all players... // TODO make more responsive // TODO maybe cache player keys for responsiveness? // Or messes this too much with the first perception of present players? final String[] players = getWorld().getWorldData().getPlayers(); final View content = WorldActivity.this.findViewById(R.id.world_content); if(players.length == 0){ if(content != null) Snackbar.make(content, R.string.no_multiplayer_data_found, Snackbar.LENGTH_LONG) .setAction("Action", null).show(); return; } //spinner (drop-out list) of players; // just the database keys (loading each name from NBT could take an even longer time!) final Spinner spinner = new Spinner(this); ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, players); spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(spinnerArrayAdapter); //wrap layout in alert new AlertDialog.Builder(this) .setTitle(R.string.select_player) .setView(spinner) .setPositiveButton(R.string.open_nbt, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //new tag type int spinnerIndex = spinner.getSelectedItemPosition(); String playerKey = players[spinnerIndex]; try { final EditableNBT editableNBT = WorldActivity.this .openEditableNbtDbEntry(playerKey); changeContentFragment(new OpenFragmentCallback() { @Override public void onOpen() { try { openNBTEditor(editableNBT); } catch (Exception e){ new AlertDialog.Builder(WorldActivity.this) .setMessage(e.getMessage()) .setCancelable(false) .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { changeContentFragment( new OpenFragmentCallback() { @Override public void onOpen() { openWorldMap(); } }); } }).show(); } } }); } catch (Exception e){ e.printStackTrace(); Log.d("Failed to open player entry in DB. key: "+playerKey); if(content != null) Snackbar.make(content, String.format(getString(R.string.failed_read_player_from_db_with_key_x), playerKey), Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } } }) //or alert is cancelled .setNegativeButton(android.R.string.cancel, null) .show(); } public void openPlayerEditor(){ changeContentFragment(new OpenFragmentCallback() { @Override public void onOpen() { try { openNBTEditor(getEditablePlayer()); } catch (Exception e){ new AlertDialog.Builder(WorldActivity.this) .setMessage(e.getMessage()) .setCancelable(false) .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { changeContentFragment(new OpenFragmentCallback() { @Override public void onOpen() { openWorldMap(); } }); } }).show(); } } }); } /** Opens an editableNBT for just the subTag if it is not null. Opens the whole level.dat if subTag is null. **/ public EditableNBT openEditableNbtLevel(String subTagName){ //make a copy first, the user might not want to save changed tags.
final CompoundTag workCopy = world.level.getDeepCopy();
7
otto-de/jlineup
core/src/test/java/de/otto/jlineup/report/HTMLReportWriterTest.java
[ "@JsonDeserialize(builder = ScreenshotContext.Builder.class)\npublic final class ScreenshotContext {\n public final String url;\n public final String urlSubPath;\n public final DeviceConfig deviceConfig;\n public final List<Cookie> cookies;\n @JsonIgnore\n public final Step step;\n @JsonIgnore...
import com.google.common.collect.ImmutableMap; import de.otto.jlineup.browser.ScreenshotContext; import de.otto.jlineup.config.DeviceConfig; import de.otto.jlineup.config.JobConfig; import de.otto.jlineup.config.Step; import de.otto.jlineup.config.UrlConfig; import de.otto.jlineup.file.FileService; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import java.io.FileNotFoundException; import java.util.List; import java.util.Map; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.StringEndsWith.endsWith; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks;
package de.otto.jlineup.report; public class HTMLReportWriterTest { private HTMLReportWriter testee; @Mock private FileService fileServiceMock; private final List<ScreenshotComparisonResult> screenshotComparisonResults = singletonList(new ScreenshotComparisonResult(1887, "someurl/somepath", DeviceConfig.deviceConfig(1337,200), 1338, 0d, "before", "after", "differenceSum", 0)); private Summary summary = new Summary(true, 1d, 0.5d, 0); private Summary localSummary = new Summary(true, 2d, 0.3d, 0); private final Map<String, UrlReport> screenshotComparisonResultList = singletonMap("test", new UrlReport(screenshotComparisonResults, localSummary)); private Report report = new Report(summary, screenshotComparisonResultList, JobConfig.exampleConfig()); @Before public void setup() { initMocks(this); testee = new HTMLReportWriter(fileServiceMock);
when(fileServiceMock.getRecordedContext(anyInt())).thenReturn(ScreenshotContext.of("someUrl", "somePath", DeviceConfig.deviceConfig(1337,200), Step.before, UrlConfig.urlConfigBuilder().build()));
3
palominolabs/benchpress
examples/multi-db/mongodb/src/main/java/com/palominolabs/benchpress/example/multidb/mongodb/MongoDbTaskFactory.java
[ "public abstract class TaskFactoryBase {\n protected final ValueGeneratorFactory valueGeneratorFactory;\n protected final KeyGeneratorFactory keyGeneratorFactory;\n protected final TaskOperation taskOperation;\n protected final int numThreads;\n protected final int numQuanta;\n protected final int...
import com.google.common.collect.Lists; import com.mongodb.DB; import com.mongodb.Mongo; import com.palominolabs.benchpress.example.multidb.task.TaskFactoryBase; import com.palominolabs.benchpress.example.multidb.key.KeyGeneratorFactory; import com.palominolabs.benchpress.job.task.TaskFactory; import com.palominolabs.benchpress.job.task.TaskOperation; import com.palominolabs.benchpress.example.multidb.value.ValueGeneratorFactory; import com.palominolabs.benchpress.task.reporting.ScopedProgressClient; import javax.annotation.Nonnull; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.UUID;
package com.palominolabs.benchpress.example.multidb.mongodb; final class MongoDbTaskFactory extends TaskFactoryBase implements TaskFactory { private final String hostname; private final int port; private final String dbName; private String collectionName; private Mongo mongo; MongoDbTaskFactory(TaskOperation taskOperation, ValueGeneratorFactory valueGeneratorFactory, int batchSize, KeyGeneratorFactory keyGeneratorFactory, int numQuanta, int numThreads, String hostname, int port, String dbName, String collectionName) { super(taskOperation, valueGeneratorFactory, batchSize, keyGeneratorFactory, numQuanta, numThreads); this.hostname = hostname; this.port = port; this.dbName = dbName; this.collectionName = collectionName; } @Nonnull @Override public Collection<Runnable> getRunnables(@Nonnull UUID jobId, int sliceId, @Nonnull UUID workerId,
@Nonnull ScopedProgressClient progressClient) throws IOException {
5
copygirl/copycore
src/net/mcft/copy/core/client/gui/GuiConfigBase.java
[ "public class Config extends AbstractConfig {\n\t\n\tprivate final File file;\n\tprivate final Configuration forgeConfig;\n\t\n\tprivate final Map<Setting, Object> settingValues = new HashMap<Setting, Object>();\n\tprivate final Map<String, String> categoryComments = new HashMap<String, String>();\n\t\n\tprivate fi...
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.mcft.copy.core.config.Config; import net.mcft.copy.core.config.SettingInfo; import net.mcft.copy.core.config.setting.BooleanSetting; import net.mcft.copy.core.config.setting.DoubleSetting; import net.mcft.copy.core.config.setting.EnumSetting; import net.mcft.copy.core.config.setting.IntegerSetting; import net.mcft.copy.core.config.setting.Setting; import net.mcft.copy.core.config.setting.StringSetting; import net.minecraft.client.gui.GuiScreen; import cpw.mods.fml.client.config.ConfigGuiType; import cpw.mods.fml.client.config.DummyConfigElement; import cpw.mods.fml.client.config.DummyConfigElement.DummyCategoryElement; import cpw.mods.fml.client.config.GuiConfig; import cpw.mods.fml.client.config.GuiConfigEntries; import cpw.mods.fml.client.config.GuiConfigEntries.CategoryEntry; import cpw.mods.fml.client.config.GuiConfigEntries.IConfigEntry; import cpw.mods.fml.client.config.IConfigElement; import cpw.mods.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package net.mcft.copy.core.client.gui; @SideOnly(Side.CLIENT) public abstract class GuiConfigBase extends GuiConfig { public final Config config; public GuiConfigBase(GuiScreen parentScreen, String id, String configId, String title, Config config) { super(parentScreen, getElementsFor(config, id), configId, false, false, title); this.config = config; } public GuiConfigBase(GuiScreen parentScreen, String id, String title, Config config) { this(parentScreen, id, id, title, config); } public GuiConfigBase(GuiScreen parentScreen, String id, Config config) { this(parentScreen, id, id, config); } @Override public void initGui() { super.initGui(); FMLCommonHandler.instance().bus().register(this); } @Override public void onGuiClosed() { super.onGuiClosed(); FMLCommonHandler.instance().bus().unregister(this); } @SubscribeEvent public final void onConfigChangedEvent(OnConfigChangedEvent event) { if ((event.modID == modID) && (event.configID == configID)) config.save(); } /** Gets the config entry for a setting in this GUI. */ public IConfigEntry getEntry(Setting setting) { for (IConfigEntry entry : entryList.listEntries) if (setting.fullName.equals(entry.getName())) return entry; return null; } /** Gets the config entry for a category in this GUI. */ public CategoryElement.Entry getCategoryEntry(String category) { for (IConfigEntry entry : entryList.listEntries) if ((entry instanceof CategoryEntry) && category.equals(entry.getName())) return (CategoryElement.Entry)entry; return null; } /** Gets all config elements to display on the config screen. */ public static List<IConfigElement> getElementsFor(Config config, String modId) { List<IConfigElement> list = new ArrayList<IConfigElement>(); Map<String, List<IConfigElement>> categoryMap = new HashMap<String, List<IConfigElement>>(); // Get all static setting fields from the config class. for (SettingInfo info : config.getSettingInfos()) if (info.showInConfigGui) { IConfigElement configElement; // If the setting doesn't have a ConfigSetting annotation or its // custom config element class was not set, use the default one. if (info.configElementClass.isEmpty()) { Class<? extends IConfigEntry> entryClass = null; try { if (!info.configEntryClass.isEmpty()) entryClass = (Class<? extends IConfigEntry>)Class.forName(info.configEntryClass); } catch (Exception ex) { throw new RuntimeException(ex); } configElement = new SettingConfigElement(config, info.setting, modId, info.requiresMinecraftRestart, info.requiresWorldRestart).setConfigEntryClass(entryClass); // Otherwise try to instantiate the custom config element. } else try { configElement = (IConfigElement)Class.forName(info.configElementClass).getConstructor( Config.class, Setting.class, String.class, boolean.class, boolean.class) .newInstance(config, info.setting, modId, info.requiresMinecraftRestart, info.requiresWorldRestart); } catch (Exception ex) { throw new RuntimeException(ex); } // If the setting's category is not "general", add it to the category map. if (!info.setting.category.equals("general")) { List<IConfigElement> categoryList; if ((categoryList = categoryMap.get(info.setting.category)) == null) categoryMap.put(info.setting.category, (categoryList = new ArrayList<IConfigElement>())); categoryList.add(configElement); // Otherwise just add it to the main config screen. } else list.add(configElement); } // Create and add category elements to the main config screen. for (Map.Entry<String, List<IConfigElement>> entry : categoryMap.entrySet()) list.add(new CategoryElement(entry.getKey(), "config." + modId.toLowerCase() + ".category." + entry.getKey(), entry.getValue())); return list; } public static class SettingConfigElement<T> extends DummyConfigElement<T> { public final Config config; public final Setting<T> setting; public SettingConfigElement(Config config, Setting<T> setting, String modId, boolean reqMinecraftRestart, boolean reqWorldRestart) { super(setting.fullName, setting.defaultValue, getGuiType(setting), "config." + modId.toLowerCase() + "." + setting.fullName, getValidValues(setting), null, getMinValue(setting), getMaxValue(setting)); this.config = config; this.setting = setting; requiresMcRestart = reqMinecraftRestart; requiresWorldRestart = reqWorldRestart; } @Override public Object get() { return config.get(setting); } @Override public void set(T value) { if (setting instanceof EnumSetting) value = (T)Enum.valueOf((Class<Enum>)setting.defaultValue.getClass(), (String)value); config.set(setting, value); } public static <T> ConfigGuiType getGuiType(Setting<T> setting) {
if (setting instanceof BooleanSetting) return ConfigGuiType.BOOLEAN;
2
kinabalu/mysticpaste
web/src/main/java/com/mysticcoders/mysticpaste/web/pages/admin/OverviewPage.java
[ "@Entity(\"pastes\")\n@Message\npublic class PasteItem implements Serializable {\n private static final long serialVersionUID = -6467870857777145137L;\n private static Logger logger = LoggerFactory.getLogger(PasteItem.class);\n private static SimpleDateFormat sdf = new SimpleDateFormat(\"MM/dd/yyyy\");\n\n...
import com.mysticcoders.mysticpaste.model.PasteItem; import com.mysticcoders.mysticpaste.services.PasteService; import com.mysticcoders.mysticpaste.web.components.highlighter.HighlighterPanel; import com.mysticcoders.mysticpaste.web.pages.BasePage; import com.mysticcoders.mysticpaste.web.pages.history.HistoryDataProvider; import com.mysticcoders.mysticpaste.web.pages.history.PastePagingNavigator; import com.mysticcoders.mysticpaste.web.pages.view.ViewPublicPage; import org.apache.wicket.RestartResponseException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.authroles.authorization.strategies.role.Roles; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.pages.AccessDeniedPage; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.IRequestParameters; import org.apache.wicket.request.http.flow.AbortWithHttpErrorCodeException; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean;
package com.mysticcoders.mysticpaste.web.pages.admin; /** * Paste Admin * * @author Andrew Lombardi <andrew@mysticcoders.com> */ public class OverviewPage extends BasePage { @SpringBean PasteService pasteService; DataView historyDataView; private final int ITEMS_PER_PAGE = 50; private int itemsPerPage; protected String getTitle() { return "Paste Admin - Mystic Paste"; } public OverviewPage() { super(OverviewPage.class); IRequestParameters params = getRequestCycle().getRequest().getQueryParameters(); String pw = pasteService.getAdminPassword(); if(pw == null || params.getParameterValue("pw").isEmpty() || !params.getParameterValue("pw").toString().equals(pw)) { throw new RestartResponseException(AccessDeniedPage.class); } itemsPerPage = params.getParameterValue("itemsPerPage").toInt(ITEMS_PER_PAGE); /* if(!params.getParameterValue("itemsPerPage").isEmpty()) { } else { itemsPerPage = ITEMS_PER_PAGE; } */
final HistoryDataProvider historyDataProvider = new HistoryDataProvider(pasteService);
4
zhouruikevin/ImageLoadPK
imageloadpk/src/main/java/com/example/imageloadpk/model/MainActivity.java
[ "public class FrescoAdapter extends ImageListAdapter {\n\n\n public FrescoAdapter(Context context, WatchListener watchListener) {\n super(context, watchListener);\n Fresco.initialize(context, FrescoConfigFactory.getImagePipelineConfig(context));\n }\n\n @Override\n public RecyclerView.View...
import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.RadioButton; import android.widget.TextView; import com.example.imageloadpk.R; import com.example.imageloadpk.adapter.adapters.FrescoAdapter; import com.example.imageloadpk.adapter.adapters.GlideAdapter; import com.example.imageloadpk.adapter.adapters.ImageListAdapter; import com.example.imageloadpk.adapter.adapters.ImageLoaderAdapter; import com.example.imageloadpk.adapter.adapters.PicassoAdapter; import com.example.imageloadpk.adapter.watcher.Drawables; import com.example.imageloadpk.adapter.watcher.WatchListener; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick;
package com.example.imageloadpk.model; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Bind(R.id.recyclerView) RecyclerView mRecyclerView; @Bind(R.id.refreshLayout) SwipeRefreshLayout mRefreshLayout; @Bind(R.id.tvShowInfo) TextView mTvShowInfo; @Bind(R.id.rbGlide) RadioButton mRbGlide; @Bind(R.id.rbPicasso) RadioButton mRbPicasso; @Bind(R.id.rbImageLoad) RadioButton mRbImageLoad; @Bind(R.id.rbFresco) RadioButton mRbFresco; private GlideAdapter mAdapter; private WatchListener mWatchListener; private Handler mHandler; private Runnable mRunnable = new Runnable() { @Override public void run() { upTvShowInfo(); scheduleNextShow(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mHandler = new Handler(getMainLooper()); initView(); } @Override protected void onStart() { super.onStart(); scheduleNextShow(); } @Override protected void onStop() { super.onStop(); upTvShowInfo(); cancelScheduleRunnable(); } private void initView() { Drawables.init(getResources()); mWatchListener = new WatchListener(); mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2)); mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { clearOtherLoader(); mRefreshLayout.setRefreshing(false); } }); } private void scheduleNextShow() { mHandler.postDelayed(mRunnable, 1000); } private void cancelScheduleRunnable() { mHandler.removeCallbacks(mRunnable); } public final static long MB = 1024 * 1024; private void upTvShowInfo() { final Runtime runtime = Runtime.getRuntime(); final float totalMemory = (runtime.totalMemory()) / MB; final float heapMemory = (runtime.totalMemory() - runtime.freeMemory()) / MB; String heapStr = String.format("已使用内存:%.1f M\t总共:%.1f M\n", heapMemory, totalMemory); String formatStr = "平均请求时间:%dms\t 总共加载次数:%d\t已完成次数:%d\t取消次数:%d"; String result = String.format(formatStr, mWatchListener.getAverageRequestTime(), mWatchListener.getTotalRequests(), mWatchListener.getCompletedRequests(), mWatchListener.getCancelledRequests()); mTvShowInfo.setText(heapStr + result); } @OnClick({R.id.rbGlide, R.id.rbPicasso, R.id.rbImageLoad, R.id.rbFresco}) public void onClick(View view) { clearOtherLoader(); switch (view.getId()) { case R.id.rbGlide: loadData(new GlideAdapter(this, mWatchListener)); break; case R.id.rbPicasso: loadData(new PicassoAdapter(this, mWatchListener)); break; case R.id.rbImageLoad: loadData(new ImageLoaderAdapter(this, mWatchListener)); break; case R.id.rbFresco:
loadData(new FrescoAdapter(this, mWatchListener));
0
RedditAndroidDev/Tamagotchi
Tamagotchi/src/com/redditandroiddevelopers/tamagotchi/TamagotchiConfiguration.java
[ "public class CreatureDao {\n private CommonDatabase<Creature> db;\n private Mapper<Creature> rowMapper;\n\n public CreatureDao(CommonDatabase<Creature> database,\n Mapper<Creature> mapper) {\n db = database;\n rowMapper = mapper;\n }\n\n public Creature create(Creature creat...
import com.badlogic.gdx.Application; import com.badlogic.gdx.graphics.Color; import com.redditandroiddevelopers.tamagotchi.dao.CreatureDao; import com.redditandroiddevelopers.tamagotchi.dao.CreatureEvolutionDao; import com.redditandroiddevelopers.tamagotchi.dao.CreatureRaiseTypeDao; import com.redditandroiddevelopers.tamagotchi.dao.CreatureStateDao; import com.redditandroiddevelopers.tamagotchi.dao.ExperienceActionDao; import com.redditandroiddevelopers.tamagotchi.dao.MedicineDao; import com.redditandroiddevelopers.tamagotchi.dao.SicknessDao;
package com.redditandroiddevelopers.tamagotchi; /** * A place to store runtime configuration for use throughout the lifetime of a * {@link TamagotchiGame} object. Not to be confused with a store for game * settings. * * @author Santoso Wijaya */ public class TamagotchiConfiguration { public boolean debug = true; public boolean logFps = true; public int logLevel = Application.LOG_DEBUG; public float stageWidth = 800; public float stageHeight = 480; public Color defaultBackgroundColor = new Color(226f / 255f, 232f / 255f, 254f / 255f, 1f); public Color creatureCreationBackgroundColor = new Color(42f / 255f, 42f / 255f, 42f / 255f, 1f); // Persistence public CreatureDao creatureDao; public CreatureEvolutionDao creatureEvolutionDao; public CreatureRaiseTypeDao creatureRaiseTypeDao; public CreatureStateDao creatureStateDao; public ExperienceActionDao experienceActionDao; public MedicineDao medicineDao;
public SicknessDao sicknessDao;
6
kennylbj/concurrent-java
src/main/java/producerconsumer/Main.java
[ "public class BlockingQueueConsumer implements Consumer<Item>, Runnable {\n private final BlockingQueue<Item> buffer;\n private final Random random = new Random(System.nanoTime());\n\n public BlockingQueueConsumer(BlockingQueue<Item> buffer) {\n this.buffer = buffer;\n }\n\n @Override\n pub...
import producerconsumer.blockingqueue.BlockingQueueConsumer; import producerconsumer.blockingqueue.BlockingQueueProducer; import producerconsumer.condition.ConditionConsumer; import producerconsumer.condition.ConditionProducer; import producerconsumer.semaphore.SemaphoreConsumer; import producerconsumer.semaphore.SemaphoreProducer; import java.util.concurrent.*; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;
package producerconsumer; /** * Created by kennylbj on 16/9/10. * Implement 3 versions of P/C * 1) use Semaphore * 2) use Condition * 3) use BlockingQueue * All versions support multiple producers and consumers */ public class Main { private static final int BUFFER_SIZE = 100; private static final int PRODUCER_NUM = 3; private static final int CONSUMER_NUM = 2; public static void main(String[] args) throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); // Buffers of all P/C Buffer<Item> semaphoreBuffer = new LinkListBuffer(BUFFER_SIZE); Buffer<Item> conditionBuffer = new LinkListBuffer(BUFFER_SIZE); BlockingQueue<Item> blockingQueueBuffer = new LinkedBlockingQueue<>(BUFFER_SIZE); // Semaphores for Semaphore version of P/C Semaphore fullCount = new Semaphore(0); Semaphore emptyCount = new Semaphore(BUFFER_SIZE); // Lock and conditions for Condition version of P/C Lock lock = new ReentrantLock(); Condition full = lock.newCondition(); Condition empty = lock.newCondition(); for (int i = 0; i < PRODUCER_NUM; i++) { pool.execute(new SemaphoreProducer(semaphoreBuffer, fullCount, emptyCount)); pool.execute(new ConditionProducer(conditionBuffer, lock, full, empty)); pool.execute(new BlockingQueueProducer(blockingQueueBuffer)); } for (int i = 0; i < CONSUMER_NUM; i++) {
pool.execute(new SemaphoreConsumer(semaphoreBuffer, fullCount, emptyCount));
4
codelibs/fess-suggest
src/main/java/org/codelibs/fess/suggest/index/contents/DefaultContentsParser.java
[ "public interface SuggestAnalyzer {\n List<AnalyzeToken> analyze(String text, String field, String lang);\n\n List<AnalyzeToken> analyzeAndReading(String text, String field, String lang);\n}", "public interface ReadingConverter {\n default int getMaxReadingNum() {\n return 10;\n }\n\n void i...
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.codelibs.core.lang.StringUtil; import org.codelibs.fess.suggest.analysis.SuggestAnalyzer; import org.codelibs.fess.suggest.converter.ReadingConverter; import org.codelibs.fess.suggest.entity.SuggestItem; import org.codelibs.fess.suggest.exception.SuggesterException; import org.codelibs.fess.suggest.index.contents.querylog.QueryLog; import org.codelibs.fess.suggest.normalizer.Normalizer; import org.codelibs.fess.suggest.util.SuggestUtil; import org.opensearch.action.admin.indices.analyze.AnalyzeAction.AnalyzeToken;
/* * Copyright 2012-2022 CodeLibs Project and the Others. * * 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.codelibs.fess.suggest.index.contents; public class DefaultContentsParser implements ContentsParser { @Override
public SuggestItem parseSearchWords(final String[] words, final String[][] readings, final String[] fields, final String[] tags,
2