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 |
|---|---|---|---|---|---|---|
palominolabs/benchpress | worker-core/src/main/java/com/palominolabs/benchpress/worker/SliceRunner.java | [
"@Immutable\npublic final class JobSlice {\n private final UUID jobId;\n private final int sliceId;\n private final Task task;\n private final String progressUrl;\n private final String finishedUrl;\n\n @JsonCreator\n public JobSlice(@JsonProperty(\"jobId\") UUID jobId, @JsonProperty(\"sliceId\... | import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.palominolabs.benchpress.ipc.Ipc;
import com.palominolabs.benchpress.job.json.JobSlice;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.JobTypePluginRegistry;
import com.palominolabs.benchpress.job.task.TaskFactory;
import com.palominolabs.benchpress.task.reporting.ScopedProgressClient;
import com.palominolabs.benchpress.task.reporting.TaskProgressClient;
import java.time.Duration;
import java.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import javax.annotation.concurrent.ThreadSafe;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.palominolabs.benchpress.logging.MdcKeys.JOB_ID; | package com.palominolabs.benchpress.worker;
@Singleton
@ThreadSafe
public final class SliceRunner {
private static final Logger logger = LoggerFactory.getLogger(SliceRunner.class);
private final ExecutorService executorService = Executors.newCachedThreadPool();
private final CompletionService<Void> completionService = new ExecutorCompletionService<>(executorService);
/**
* TODO figure out a good way to worker-scope a random uuid -- @WorkerId binding annotation perhaps? Wrapper class?
*/
private final UUID workerId = UUID.randomUUID();
| private final TaskProgressClient taskProgressClient; | 5 |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/threads/DetuneThread.java | [
"public enum FrameType\n{\n\tLarge(2),\n\tDefault(1),\n\tMedium(1 / 2D),\n\tSmall(1 / 4D);\n\n\tpublic final double\tratio;\n\n\tprivate FrameType(double ratio)\n\t{\n\t\tthis.ratio = ratio;\n\t}\n}",
"public final class Preferences\n{\n\t// TODO: Try different audio sources\n\t// public static final int PCM_IN_S... | import android.content.Context;
import de.jurihock.voicesmith.FrameType;
import de.jurihock.voicesmith.Preferences;
import de.jurihock.voicesmith.Utils;
import de.jurihock.voicesmith.dsp.processors.DetuneProcessor;
import de.jurihock.voicesmith.dsp.stft.StftPostprocessor;
import de.jurihock.voicesmith.dsp.stft.StftPreprocessor;
import de.jurihock.voicesmith.io.AudioDevice; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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 de.jurihock.voicesmith.threads;
public class DetuneThread extends AudioThread
{
private final float[] buffer;
private StftPreprocessor preprocessor = null;
private StftPostprocessor postprocessor = null;
public DetuneThread(Context context, AudioDevice input, AudioDevice output)
{
super(context, input, output);
Preferences preferences = new Preferences(context);
| FrameType frameType = FrameType.Medium; | 0 |
ZSCNetSupportDept/WechatTicketSystem | src/main/java/love/sola/netsupport/wechat/handler/SubscribeHandler.java | [
"public class Attribute {\n\n public static final String AUTHORIZED = \"authorized\";\n public static final String WECHAT = \"wechat\";\n public static final String OPERATOR = \"operator\";\n public static final String USER = \"user\";\n\n}",
"@Entity\n@Table(name = \"operators\")\npublic class Operat... | import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.outxmlbuilder.TextBuilder;
import static love.sola.netsupport.config.Lang.format;
import java.util.Map;
import love.sola.netsupport.enums.Attribute;
import love.sola.netsupport.pojo.Operator;
import love.sola.netsupport.pojo.User;
import love.sola.netsupport.session.WechatSession;
import love.sola.netsupport.session.WxSession;
import love.sola.netsupport.sql.TableOperator;
import love.sola.netsupport.sql.TableUser;
import love.sola.netsupport.wechat.Command;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler; | /*
* This file is part of WechatTicketSystem.
*
* WechatTicketSystem 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.
*
* WechatTicketSystem 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 WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>.
*/
package love.sola.netsupport.wechat.handler;
/**
* @author Sola {@literal <dev@sola.love>}
*/
public class SubscribeHandler implements WxMpMessageHandler {
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
TextBuilder out = WxMpXmlOutMessage.TEXT().fromUser(wxMessage.getToUserName()).toUser(wxMessage.getFromUserName());
String fromUser = wxMessage.getFromUserName(); | User u = TableUser.getByWechat(fromUser); | 2 |
NudgeApm/nudge-elasticstack-connector | src/main/java/org/nudge/elasticstack/context/elasticsearch/builder/TransactionSerializer.java | [
"public class Configuration {\n\n\tprivate static final Logger LOG = Logger.getLogger(Configuration.class);\n\n\t// Configuration files\n\tprivate static final String CONF_FILE = \"nudge-elastic.properties\";\n\tprivate static final String NUDGE_URL = \"nudge.url\";\n\tprivate static final String NUDGE_API_TOKEN = ... | import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.log4j.Logger;
import org.nudge.elasticstack.Configuration;
import org.nudge.elasticstack.context.elasticsearch.bean.BulkFormat;
import org.nudge.elasticstack.context.elasticsearch.bean.EventType;
import org.nudge.elasticstack.context.elasticsearch.bean.LayerEvent;
import org.nudge.elasticstack.context.elasticsearch.bean.NudgeEvent;
import org.nudge.elasticstack.context.elasticsearch.bean.TransactionEvent;
import org.nudge.elasticstack.context.nudge.dto.LayerCallDTO;
import org.nudge.elasticstack.context.nudge.dto.LayerDTO;
import org.nudge.elasticstack.context.nudge.dto.TransactionDTO;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; | package org.nudge.elasticstack.context.elasticsearch.builder;
/**
* Serialize Nudge transaction into JSON object.
*/
public class TransactionSerializer {
private static final Logger LOG = Logger.getLogger(TransactionSerializer.class.getName());
private static final String lineBreak = "\n";
private Configuration config = Configuration.getInstance();
/**
* Retrieve transaction data from rawdata and add it to parse.
* @param appId
* @param transactionList
* @return
* @throws ParseException
* @throws JsonProcessingException
*/
public List<NudgeEvent> serialize(String appId, String appName, String host, String hostname, List<TransactionDTO> transactionList)
throws ParseException, JsonProcessingException {
List<NudgeEvent> events = new ArrayList<>();
for (TransactionDTO trans : transactionList) {
TransactionEvent transactionEvent = new TransactionEvent();
// build the transaction JSON object
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String date = sdf.format(trans.getStartTime());
transactionEvent.setAppId(appId);
transactionEvent.setAppName(appName);
transactionEvent.setHost(host);
transactionEvent.setHostname(hostname);
transactionEvent.setName(trans.getCode());
transactionEvent.setResponseTime(trans.getEndTime() - trans.getStartTime());
transactionEvent.setDate(date);
transactionEvent.setCount(1L);
transactionEvent.setTransactionId(trans.getId());
events.add(transactionEvent);
// handle layers - build for each layers a JSON object
events.addAll(buildLayerEvents(trans.getLayers(), transactionEvent));
}
return events;
}
/**
* Retrieve layer from transaction
*
* @param eventTrans
* @return
*/
public TransactionEvent nullLayer(TransactionEvent eventTrans) {
if (eventTrans.getLayerNameSql() == null) {
eventTrans.setResponseTimeLayerSql(0L);
eventTrans.setLayerCountSql(0L);
eventTrans.setLayerNameSql("null layer");
}
if (eventTrans.getLayerNameJaxws() == null) {
eventTrans.setResponseTimeLayerJaxws(0L);
eventTrans.setLayerCountJaxws(0L);
eventTrans.setLayerNameJaxws("null layer");
}
if (eventTrans.getLayerNameJms() == null) {
eventTrans.setLayerCountJms(0L);
eventTrans.setResponseTimeLayerJms(0L);
eventTrans.setLayerNameJms("null layer");
}
return eventTrans;
}
protected LayerEvent createLayerEvent(EventType type, LayerCallDTO layerCallDTO, TransactionEvent transaction) {
SimpleDateFormat sdfr = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String sqlTimestamp = sdfr.format(layerCallDTO.getTimestamp());
LayerEvent layerEvent = new LayerEvent(type);
layerEvent.setAppId(transaction.getAppId());
layerEvent.setAppName(transaction.getAppName());
layerEvent.setHost(transaction.getHost());
layerEvent.setHostname(transaction.getHostname());
layerEvent.setDate(sqlTimestamp);
layerEvent.setName(layerCallDTO.getCode());
layerEvent.setCount(layerCallDTO.getCount());
layerEvent.setResponseTime(layerCallDTO.getResponseTime());
layerEvent.setTransactionId(transaction.getTransactionId());
return layerEvent;
}
protected LayerEvent createJavaLayerEvent(TransactionEvent transaction, long responseTime) {
LayerEvent javaLayer = new LayerEvent(EventType.JAVA);
javaLayer.setAppId(transaction.getAppId());
javaLayer.setAppName(transaction.getAppName());
javaLayer.setHost(transaction.getHost());
javaLayer.setHostname(transaction.getHostname());
javaLayer.setDate(transaction.getDate());
javaLayer.setName(transaction.getName());
javaLayer.setCount(transaction.getCount());
javaLayer.setResponseTime(responseTime);
javaLayer.setTransactionId(transaction.getTransactionId());
return javaLayer;
}
/**
* Build layer events
*
* @param rawdataLayers
* @param transactionEvent
* @throws ParseException
* @throws JsonProcessingException
*/ | public List<LayerEvent> buildLayerEvents(List<LayerDTO> rawdataLayers, TransactionEvent transactionEvent) | 7 |
jmcampanini/gexf4j-core | src/test/java/com/ojn/gexf4j/core/impl/data/AttributeValueImplTest.java | [
"public interface Attribute {\n\n\tString getId();\n\t\n\tString getTitle();\n\tAttribute setTitle(String title);\n\t\n\tAttributeType getAttributeType();\n\t\n\tboolean hasDefaultValue();\n\tAttribute clearDefaultValue();\n\tString getDefaultValue();\n\tAttribute setDefaultValue(String defaultValue);\n\t\n\tList<S... | import java.util.UUID;
import com.ojn.gexf4j.core.data.Attribute;
import com.ojn.gexf4j.core.data.AttributeClass;
import com.ojn.gexf4j.core.data.AttributeType;
import com.ojn.gexf4j.core.data.AttributeValue;
import com.ojn.gexf4j.core.data.AttributeValueTest; | package com.ojn.gexf4j.core.impl.data;
public class AttributeValueImplTest extends AttributeValueTest {
@Override | protected Attribute newAttribute() { | 0 |
wrey75/WaveCleaner | src/main/java/com/oxande/xmlswing/components/JTreeUI.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.JTree;
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;
public class JTreeUI extends JComponentUI {
public static final String TAGNAME = "tree";
public static final AttributeDefinition[] PROPERTIES = {
DRAGGABLE_ATTRIBUTE_DEF,
new AttributeDefinition( "editable", "setEditable", ClassType.BOOLEAN ),
new AttributeDefinition( "expandsSelectedPaths", "setExpandsSelectedPaths", ClassType.BOOLEAN ),
new AttributeDefinition( "invokeStopCellEditing", "setInvokesStopCellEditing", ClassType.BOOLEAN ),
new AttributeDefinition( "largeModel", "setLargeModel", ClassType.BOOLEAN ),
new AttributeDefinition( "rootVisible", "setRootVisible", ClassType.BOOLEAN ),
new AttributeDefinition( "rowHeight", "setRowHeight", ClassType.INTEGER ),
new AttributeDefinition( "scrollOnExpand", "setScrollOnExpand", ClassType.BOOLEAN ),
new AttributeDefinition( "showRootHandles", "setShowRootHandles", ClassType.BOOLEAN ),
new AttributeDefinition( "toogleClickCount", "setToogleClickCount", ClassType.INTEGER ),
new AttributeDefinition( "visibleRowCount", "setVisibleRowCount", ClassType.INTEGER ),
};
public static final AttributesController CONTROLLER = new AttributesController( JComponentUI.CONTROLLER, PROPERTIES );
public JTreeUI(){
}
| public String parse(JavaClass jclass, JavaMethod initMethod, Element root ) throws UnexpectedTag{
| 6 |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/ui/VendorsFragment.java | [
"public class ScheduleContract {\n\n /**\n * Special value for {@link SyncColumns#UPDATED} indicating that an entry\n * has never been updated, or doesn't exist yet.\n */\n public static final long UPDATED_NEVER = -2;\n\n /**\n * Special value for {@link SyncColumns#UPDATED} indicating that... | import no.java.schedule.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.SherlockListFragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Spannable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; | /*
* Copyright 2012 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.google.android.apps.iosched.ui;
/**
* A {@link ListFragment} showing a list of developer sandbox companies.
*/
public class VendorsFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
| private static final String TAG = makeLogTag(VendorsFragment.class); | 3 |
aw20/MongoWorkBench | src/org/aw20/mongoworkbench/eclipse/view/MSystemJavaScript.java | [
"public class EventWorkBenchManager extends Object {\n\tprivate static EventWorkBenchManager thisInst;\n\t\n\tpublic static synchronized EventWorkBenchManager getInst(){\n\t\tif ( thisInst == null )\n\t\t\tthisInst = new EventWorkBenchManager();\n\n\t\treturn thisInst;\n\t}\n\n\tprivate Set<EventWorkBenchListener>\... | import java.io.IOException;
import org.aw20.mongoworkbench.EventWorkBenchManager;
import org.aw20.mongoworkbench.MongoCommandListener;
import org.aw20.mongoworkbench.MongoFactory;
import org.aw20.mongoworkbench.command.MongoCommand;
import org.aw20.mongoworkbench.command.SystemJavaScriptReadCommand;
import org.aw20.mongoworkbench.command.SystemJavaScriptValidateCommand;
import org.aw20.mongoworkbench.command.SystemJavaScriptWriteCommand;
import org.aw20.util.MSwtUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text; | /*
* MongoWorkBench is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* Free Software Foundation,version 3.
*
* MongoWorkBench 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
* If not, see http://www.gnu.org/licenses/
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with any of the JARS listed in the README.txt (or a modified version of
* (that library), containing parts covered by the terms of that JAR, the
* licensors of this Program grant you additional permission to convey the
* resulting work.
*
* https://github.com/aw20/MongoWorkBench
*
* April 2013
*/
package org.aw20.mongoworkbench.eclipse.view;
public class MSystemJavaScript extends MAbstractView implements MongoCommandListener {
private Text textBox;
private String HELPURL = "http://docs.mongodb.org/manual/tutorial/store-javascript-function-on-server/";
private Button btnValidate, btnSave; | private SystemJavaScriptReadCommand readCommand; | 4 |
Samistine/BloodMoon | src/main/java/uk/co/jacekk/bukkit/bloodmoon/feature/world/ExtendedNightListener.java | [
"public final class BloodMoon extends BasePlugin {\n\n public static boolean DEBUG = false;\n\n private ArrayList<String> activeWorlds;\n private HashMap<String, PluginConfig> worldConfig;\n protected ArrayList<String> forceWorlds;\n\n @Override\n public void onEnable() {\n super.onEnable(t... | import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDeathEvent;
import uk.co.jacekk.bukkit.baseplugin.config.PluginConfig;
import uk.co.jacekk.bukkit.baseplugin.event.BaseListener;
import uk.co.jacekk.bukkit.bloodmoon.BloodMoon;
import uk.co.jacekk.bukkit.bloodmoon.Config;
import uk.co.jacekk.bukkit.bloodmoon.Feature;
import uk.co.jacekk.bukkit.bloodmoon.event.BloodMoonEndEvent;
import uk.co.jacekk.bukkit.bloodmoon.event.BloodMoonStartEvent; | package uk.co.jacekk.bukkit.bloodmoon.feature.world;
public class ExtendedNightListener extends BaseListener<BloodMoon> {
private final HashMap<String, Integer> killCount = new HashMap<>();
private final ArrayList<EntityType> hostileTypes = new ArrayList<EntityType>() {
{
add(EntityType.SKELETON);
add(EntityType.SPIDER);
add(EntityType.CAVE_SPIDER);
add(EntityType.ZOMBIE);
add(EntityType.PIG_ZOMBIE);
add(EntityType.CREEPER);
add(EntityType.ENDERMAN);
add(EntityType.BLAZE);
add(EntityType.GHAST);
add(EntityType.MAGMA_CUBE);
add(EntityType.WITCH);
add(EntityType.ENDERMITE);
add(EntityType.ENDER_DRAGON);
add(EntityType.GUARDIAN);
add(EntityType.SILVERFISH);
}
};
public ExtendedNightListener(BloodMoon plugin) {
super(plugin);
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) | public void onStart(BloodMoonStartEvent event) { | 4 |
b0noI/AIF2 | src/main/java/io/aif/language/sentence/splitters/AbstractSentenceSplitter.java | [
"@FunctionalInterface\npublic interface ISplitter<T1, T2> extends Function<T1, List<T2>> {\n\n public List<T2> split(final T1 target);\n\n @Override\n public default List<T2> apply(final T1 t1) {\n return split(t1);\n }\n}",
"public interface ISettings {\n\n @Deprecated\n public ISettings SETTINGS = Guic... | import com.google.common.annotations.VisibleForTesting;
import com.google.inject.Guice;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import io.aif.language.common.ISplitter;
import io.aif.language.common.settings.ISettings;
import io.aif.language.common.settings.SettingsModule;
import io.aif.language.sentence.separators.classificators.ISeparatorGroupsClassifier;
import io.aif.language.sentence.separators.extractors.ISeparatorExtractor;
import io.aif.language.sentence.separators.groupers.ISeparatorsGrouper; | package io.aif.language.sentence.splitters;
public abstract class AbstractSentenceSplitter implements ISplitter<List<String>, List<String>> {
private static final Logger logger = Logger.getLogger(AbstractSentenceSplitter.class);
private final ISeparatorExtractor sentenceSeparatorExtractor;
private final ISeparatorsGrouper sentenceSeparatorsGrouper;
private final ISeparatorGroupsClassifier sentenceSeparatorGroupsClassificatory;
protected AbstractSentenceSplitter(final ISeparatorExtractor sentenceSeparatorExtractor,
final ISeparatorsGrouper sentenceSeparatorsGrouper,
final ISeparatorGroupsClassifier
sentenceSeparatorGroupsClassificatory) {
this.sentenceSeparatorExtractor = sentenceSeparatorExtractor;
this.sentenceSeparatorsGrouper = sentenceSeparatorsGrouper;
this.sentenceSeparatorGroupsClassificatory = sentenceSeparatorGroupsClassificatory;
}
@VisibleForTesting
static List<String> prepareSentences(final List<String> sentence,
final List<Character> separators) {
final List<String> preparedTokens = new ArrayList<>();
for (String token : sentence) {
preparedTokens.addAll(prepareToken(token, separators));
}
return preparedTokens;
}
@VisibleForTesting
static List<String> prepareToken(final String token, final List<Character> separators) {
final List<String> tokens = new ArrayList<>(3);
final int lastPosition = lastNonSeparatorPosition(token, separators);
final int firstPosition = firstNonSeparatorPosition(token, separators);
if (firstPosition != 0) {
tokens.add(token.substring(0, firstPosition));
}
tokens.add(token.substring(firstPosition, lastPosition));
if (lastPosition != token.length()) {
tokens.add(token.substring(lastPosition, token.length()));
}
return tokens;
}
@VisibleForTesting
static int firstNonSeparatorPosition(final String token, final List<Character> separarors) {
if (!separarors.contains(token.charAt(0))) {
return 0;
}
int i = 0;
while (i < token.length() && separarors.contains(token.charAt(i))) {
i++;
}
if (i == token.length()) {
return 0;
}
return i;
}
@VisibleForTesting
static int lastNonSeparatorPosition(final String token, final List<Character> separators) {
if (!separators.contains(token.charAt(token.length() - 1))) {
return token.length();
}
int i = token.length() - 1;
while (i > 0 && separators.contains(token.charAt(i))) {
i--;
}
i++;
if (i == 0) {
return token.length();
}
return i;
}
public List<List<String>> split(final List<String> tokens) { | final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); | 2 |
free-iot/freeiot-android | app/src/main/java/com/pandocloud/freeiot/ui/helper/ProductInfoHelper.java | [
"public class ProductApi extends AbsOpenApi {\n\t\n\t/**\n\t * get product info\n\t */\n\tprivate static final String PRODUCT_INFO = \"/v1/product/info\";\n\t\n\n\t/**\n\t * get product information by product key\n\t * \n\t * <p>Method: GET</p>\n\t * @param context\n\t * @param productKey\n\t * @param responseHandl... | import com.pandocloud.android.api.interfaces.RequestListener;
import com.pandocloud.freeiot.api.ProductApi;
import com.pandocloud.freeiot.ui.app.AppConstants;
import com.pandocloud.freeiot.ui.app.ProductInfoPrefs;
import com.pandocloud.freeiot.ui.bean.ProductInfo;
import com.pandocloud.freeiot.ui.bean.http.ProductInfoResponse;
import com.pandocloud.freeiot.utils.GsonUtils;
import org.apache.http.Header;
import android.content.Context;
import android.text.TextUtils;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.pandocloud.freeiot.utils.LogUtils; | package com.pandocloud.freeiot.ui.helper;
public class ProductInfoHelper {
private RequestListener listener;
public ProductInfoHelper(RequestListener listener) {
if (listener == null) {
throw new IllegalArgumentException("ReuqestListener not allow be null...");
}
this.listener = listener;
}
public void getProductInfo(final Context context) {
ProductApi.getProductInfo(context, AppConstants.PRODUCT_KEY, new BaseJsonHttpResponseHandler<ProductInfoResponse>() {
@Override
public void onFailure(int statusCode, Header[] headers, Throwable e,
String rawJsonResponse, ProductInfoResponse response) {
listener.onFail(new Exception(e));
}
@Override
public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse,
ProductInfoResponse response) {
if (response != null) {
ProductInfo productInfo = response.data;
if (productInfo != null && context != null) { | ProductInfoPrefs.Builder builder = new ProductInfoPrefs.Builder(context); | 2 |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/LoginActivity.java | [
"public class PrefsManager {\n private final static int CURRENT_VERSION = 2;\n\n private final static String USERNAME = \"username\";\n private final static String PASSWORD = \"password\";\n private final static String LOGIN_KEY = \"login_key\";\n private final static String SENTRY_HASH = \"sentry_ha... | import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import com.steevsapps.idledaddy.preferences.PrefsManager;
import com.steevsapps.idledaddy.steam.SteamGuard;
import com.steevsapps.idledaddy.steam.SteamService;
import com.steevsapps.idledaddy.steam.SteamWebHandler;
import com.steevsapps.idledaddy.utils.Utils;
import in.dragonbra.javasteam.enums.EOSType;
import in.dragonbra.javasteam.enums.EResult;
import in.dragonbra.javasteam.steam.handlers.steamuser.LogOnDetails;
import static com.steevsapps.idledaddy.steam.SteamService.LOGIN_EVENT; | package com.steevsapps.idledaddy;
public class LoginActivity extends BaseActivity {
private final static String TAG = LoginActivity.class.getSimpleName();
private final static String LOGIN_IN_PROGRESS = "LOGIN_IN_PROGRESS";
private final static String TWO_FACTOR_REQUIRED = "TWO_FACTOR_REQUIRED";
private boolean loginInProgress;
private boolean twoFactorRequired;
private Integer timeDifference = null;
private LoginViewModel viewModel;
// Views
private CoordinatorLayout coordinatorLayout;
private TextInputLayout usernameInput;
private TextInputEditText usernameEditText;
private TextInputLayout passwordInput;
private TextInputEditText passwordEditText;
private TextInputLayout twoFactorInput;
private TextInputEditText twoFactorEditText;
private Button loginButton;
private ProgressBar progress;
// Used to receive messages from SteamService
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (SteamService.LOGIN_EVENT.equals(intent.getAction())) {
stopTimeout();
progress.setVisibility(View.GONE);
final EResult result = (EResult) intent.getSerializableExtra(SteamService.RESULT);
if (result != EResult.OK) {
loginButton.setEnabled(true);
usernameInput.setErrorEnabled(false);
passwordInput.setErrorEnabled(false);
twoFactorInput.setErrorEnabled(false);
if (result == EResult.InvalidPassword) {
passwordInput.setError(getString(R.string.invalid_password));
} else if (result == EResult.AccountLoginDeniedNeedTwoFactor || result == EResult.AccountLogonDenied || result == EResult.AccountLogonDeniedNoMail || result == EResult.AccountLogonDeniedVerifiedEmailRequired) {
twoFactorRequired = result == EResult.AccountLoginDeniedNeedTwoFactor;
if (twoFactorRequired && timeDifference != null) {
// Fill in the SteamGuard code | twoFactorEditText.setText(SteamGuard.generateSteamGuardCodeForTime(Utils.getCurrentUnixTime() + timeDifference)); | 4 |
Idrinth/WARAddonClient | src/main/java/de/idrinth/waraddonclient/model/addon/UnknownAddon.java | [
"public class Utils {\r\n\r\n private Utils() {\r\n }\r\n\r\n public static void emptyFolder(File folder) throws IOException {\r\n if (folder == null || !folder.exists()) {\r\n return;\r\n }\r\n for (File file : Objects.requireNonNull(folder.listFiles())) {\r\n if... | import de.idrinth.waraddonclient.Utils;
import de.idrinth.waraddonclient.model.InvalidArgumentException;
import de.idrinth.waraddonclient.service.Config;
import de.idrinth.waraddonclient.service.ProgressReporter;
import de.idrinth.waraddonclient.service.logger.BaseLogger;
import de.idrinth.waraddonclient.service.Request;
import de.idrinth.waraddonclient.service.SilencingErrorHandler;
import de.idrinth.waraddonclient.service.XmlParser;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Executor;
import javax.xml.parsers.FactoryConfigurationError;
import org.apache.commons.io.FilenameUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
| package de.idrinth.waraddonclient.model.addon;
public class UnknownAddon implements Addon {
private boolean hasSettings = false;
private String file = "";
private String reason = "";
private String url = "";
private String name;
private String installed = "-";
private final Request client;
private final BaseLogger logger;
private final XmlParser parser;
private final Config config;
private final File folder;
private String defaultDescription = "";
private final Executor runner;
public UnknownAddon(File folder, Request client, BaseLogger logger, XmlParser parser, Config config, Executor runner) throws InvalidArgumentException {
this.client = client;
this.logger = logger;
this.parser = parser;
this.config = config;
this.folder = folder;
this.runner = runner;
if (new File(folder.getAbsolutePath() + config.getVersionFile()).exists()) {
throw new InvalidArgumentException("Folder is known Add-On folder.");
}
for (java.io.File fileEntry : folder.listFiles()) {
if (!fileEntry.isDirectory() && FilenameUtils.getExtension(fileEntry.getName()).equalsIgnoreCase("mod")) {
try {
Document doc = parser.parse(fileEntry, new SilencingErrorHandler(logger));
NodeList list = doc.getElementsByTagName("UiMod");
installed = list.item(0).getAttributes().getNamedItem("version").getTextContent();
name = list.item(0).getAttributes().getNamedItem("name").getTextContent();
NodeList description = doc.getElementsByTagName("Description");
if (description.getLength() > 0) {
defaultDescription = description.item(0).getAttributes().getNamedItem("text").getTextContent();
}
} catch (FactoryConfigurationError | SAXException | IOException exception) {
logger.warn(exception);
}
}
}
if (name == null) {
throw new InvalidArgumentException("Folder is no Add-On folder.");
}
refresh();
}
@Override
public ArrayList<String> getTags() {
ArrayList <String> list = new ArrayList<>();
list.add("Not Tagged");
list.add("Auto-Discovered");
return list;
}
public boolean hasTag(String tag) {
return "Not Tagged".equals(tag) || "Auto-Discovered".equals(tag);
}
public String getVersion() {
return "unknown";
}
public String getInstalled() {
return installed;
}
/**
* get the table row configuration for this addon
*
* @return String[[
*/
public Object[] getTableRow() {
Object[] row = new Object[6];
row[0] = this.getStatus();
row[1] = this.name;
row[2] = getVersion();
row[3] = this.installed;
row[4] = 0;
row[5] = 0;
return row;
}
public String getDescription(String language) {
return "<p><strong>There is currently no Description for " + name + ".</strong></p>"
+ "<p>You can help by adding the addon and one at <a href=\"http://tools.idrinth.de/addons/\">http://tools.idrinth.de/addons/</a>.</p>"
+ "<p>"+defaultDescription+"</p>";
}
public HashMap<String, String> getDescriptions() {
return new HashMap<>();
}
public String getName() {
return name;
}
| public void uninstall(ProgressReporter reporter) {
| 3 |
grt192/grtframework | src/sensor/base/GRTDriverStation.java | [
"public abstract class Sensor extends GRTLoggedProcess {\n\n //Constants\n public static final double TRUE = 1.0;\n public static final double FALSE = 0.0;\n public static final double ERROR = Double.NaN;\n //Instance variables\n private final Vector stateChangeListeners; //Collection of things ... | import core.Sensor;
import event.events.DrivingEvent;
import event.events.ShiftEvent;
import event.listeners.DrivingListener;
import event.listeners.ShiftListener;
import java.util.Enumeration;
import java.util.Vector; | package sensor.base;
/**
* Superclass for all DriverStations.
*
* @author ajc
*/
public abstract class GRTDriverStation extends Sensor {
/*
* State Keys
*/
public static final int KEY_LEFT_VELOCITY = 0;
public static final int KEY_RIGHT_VELOCITY = 1;
public static final int KEY_LEFT_SHIFT = 2;
public static final int KEY_RIGHT_SHIFT = 3;
private final Vector drivingListeners;
private final Vector shiftListeners;
/**
* Creates a new driver station.
*
* @param name name of driver station.
*/
public GRTDriverStation(String name) {
super(name, 2);
drivingListeners = new Vector();
shiftListeners = new Vector();
}
public void addDrivingListener(DrivingListener l) {
drivingListeners.addElement(l);
}
public void removeDrivingListener(DrivingListener l) {
drivingListeners.removeElement(l);
}
public void addShiftListener(ShiftListener l) {
shiftListeners.addElement(l);
}
public void removeShiftListener(ShiftListener l) {
shiftListeners.removeElement(l);
}
protected void notifyLeftDriveSpeed(double speed) {
setState(KEY_LEFT_VELOCITY, speed);
}
protected void notifyRightDriveSpeed(double speed) {
setState(KEY_RIGHT_VELOCITY, speed);
}
protected void notifyListeners(int id, double newValue) {
DrivingEvent ev; | ShiftEvent sev; | 2 |
taoneill/war | war/src/main/java/com/tommytony/war/command/SetCapturePointCommand.java | [
"public class War extends JavaPlugin {\n\tstatic final boolean HIDE_BLANK_MESSAGES = true;\n\tpublic static War war;\n\tprivate static ResourceBundle messages = ResourceBundle.getBundle(\"messages\");\n\tprivate final List<OfflinePlayer> zoneMakerNames = new ArrayList<>();\n\tprivate final List<String> commandWhite... | import com.tommytony.war.War;
import com.tommytony.war.Warzone;
import com.tommytony.war.config.TeamKind;
import com.tommytony.war.mapper.WarzoneYmlMapper;
import com.tommytony.war.structure.CapturePoint;
import com.tommytony.war.structure.Monument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.logging.Level; | package com.tommytony.war.command;
/**
* Sets a capture point
*
* @author Connor Monahan
*/
public class SetCapturePointCommand extends AbstractZoneMakerCommand {
public SetCapturePointCommand(WarCommandHandler handler, CommandSender sender, String[] args) throws NotZoneMakerException {
super(handler, sender, args);
}
@Override
public boolean handle() {
if (!(this.getSender() instanceof Player)) {
this.badMsg("You can't do this if you are not in-game.");
return true;
}
Player player = (Player) this.getSender();
if (this.args.length < 1) {
return false;
}
Warzone zone = Warzone.getZoneByLocation(player);
if (zone == null) {
return false;
} else if (!this.isSenderAuthorOfZone(zone)) {
return true;
}
if (this.args[0].equals(zone.getName())) {
return false;
}
if (zone.hasCapturePoint(this.args[0])) {
// move the existing capture point | CapturePoint cp = zone.getCapturePoint(this.args[0]); | 4 |
teisun/Android-SunmiLauncher | U3DLauncherPlugin/src/sunmi/launcher/LauncherActivity.java | [
"public class Adaptation{\n\n\tpublic static final int NOTE1 = 1;\n\t\n\tpublic static int screenHeight=0;\n\tpublic static int screenWidth=0;\n\tpublic static float screenDensity=0;\n\tpublic static int densityDpi = 0;\n\tpublic static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);\n\t\n\tpublic ... | import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import sunmi.launcher.utils.Adaptation;
import sunmi.launcher.utils.BitmapUtils;
import sunmi.launcher.utils.DeviceUtitls;
import sunmi.launcher.utils.FileUtils;
import sunmi.launcher.utils.LogUtil;
import sunmi.launcher.utils.ProcessUtils;
import sunmi.launcher.utils.UninstallUtils;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity; | package sunmi.launcher;
/**
*
* TODO主页面
*
* @author xuron
* @versionCode 1 <1>
*/
@SuppressLint("NewApi")
public class LauncherActivity extends UnityPlayerActivity {
//public class LauncherActivity extends Activity {
private static final String TAG = "LauncherActivity"; | private static final String ICON_FOLDER = FileUtils.getSDCardPath()+"/launcher_icon/"; | 3 |
BlochsTech/BitcoinCardTerminal | src/com/blochstech/bitcoincardterminal/ViewModel/ViewStateManagers/MessageManager.java | [
"public class MainActivity extends FragmentActivity {\n\t\n\tprivate NfcAdapter mAdapter;\n\tprivate PendingIntent mPendingIntent;\n\tprivate String[][] techListsArray;\n\t\n\tpublic static MainActivity instance;\n\t\n\tpublic static Context GetMainContext(){\n\t\tContext res = instance != null ? instance.getApplic... | import java.util.LinkedList;
import java.util.Queue;
import com.blochstech.bitcoincardterminal.MainActivity;
import com.blochstech.bitcoincardterminal.Interfaces.Message;
import com.blochstech.bitcoincardterminal.Interfaces.Message.MessageType;
import com.blochstech.bitcoincardterminal.Model.Model;
import com.blochstech.bitcoincardterminal.Utils.EventListener;
import com.blochstech.bitcoincardterminal.Utils.Tags;
import android.util.Log;
import android.widget.Toast; | package com.blochstech.bitcoincardterminal.ViewModel.ViewStateManagers;
//The core idea is to avoid any one View having to know all the other Views in order to update say a global status icon,
//message or page number..
public class MessageManager {
//Singleton pattern:
private static MessageManager instance = null;
public static MessageManager Instance()
{
if(instance == null)
{
instance = new MessageManager();
}
return instance;
}
private MessageManager()
{
Model.Instance().MessageEventReference().register(modelMessageListener);
}
//Singleton pattern end.
private Queue<String> messages = new LinkedList<String>();
private final int maxMessages = 500;
private EventListener<Message> modelMessageListener = new ModelMessageListener();
public void AddMessage(String msg, boolean isError){
AddMessage(msg, isError, false);
}
@SuppressWarnings("unused")
public void AddMessage(String msg, boolean isError, boolean isWarning){
//TODO: Add to list + android log... rest can wait... post log guide in this class. | if(msg != null && !msg.isEmpty() && (Tags.DEBUG || isError)){ | 5 |
optimaize/command4j | src/test/java/com/optimaize/command4j/ext/extensions/exception/exceptiontranslation/ExceptionTranslationExtensionTest.java | [
"public interface CommandExecutor {\n\n /**\n * Executes it in the current thread, and blocks until it either finishes successfully or aborts by\n * throwing an exception.\n *\n * @param <A> argument\n * @param <R> Result\n */\n @NotNull\n <A, R> Optional<R> execute(@NotNull Command... | import com.optimaize.command4j.CommandExecutor;
import com.optimaize.command4j.CommandExecutorBuilder;
import com.optimaize.command4j.Mode;
import com.optimaize.command4j.commands.BaseCommand;
import com.optimaize.command4j.commands.ThrowUnsupportedOperation;
import com.optimaize.command4j.ext.extensions.exception.ExceptionExtensions;
import org.jetbrains.annotations.NotNull;
import org.testng.annotations.Test; | package com.optimaize.command4j.ext.extensions.exception.exceptiontranslation;
/**
* @author Fabian Kessler
*/
public class ExceptionTranslationExtensionTest {
private static class MyException extends Exception {
private MyException(String message, Throwable cause) {
super(message, cause);
}
}
private static final ExceptionTranslator myExceptionTranslator = new ExceptionTranslator() {
@Override
public boolean canTranslate(@NotNull Throwable t) {
return t instanceof UnsupportedOperationException;
}
@NotNull @Override
public Exception translate(@NotNull Throwable t) throws Exception {
throw new MyException("Translated", t);
}
};
@Test(expectedExceptions=UnsupportedOperationException.class)
public void withoutTranslation() throws Exception {
CommandExecutor nakedExecutor = new CommandExecutorBuilder().build();
BaseCommand<Void,Void> cmd = new ThrowUnsupportedOperation(); | nakedExecutor.execute(cmd, Mode.create(), null); | 2 |
goodow/realtime-channel | src/main/java/com/goodow/realtime/channel/impl/WebSocketBus.java | [
"@JsType\npublic interface Bus {\n String ON_OPEN = \"@realtime/bus/onOpen\";\n String ON_CLOSE = \"@realtime/bus/onClose\";\n String ON_ERROR = \"@realtime/bus/onError\";\n\n /**\n * Close the Bus and release all resources.\n */\n void close();\n\n /* The state of the Bus. */\n State getReadyState();\n\... | import com.goodow.realtime.channel.Bus;
import com.goodow.realtime.channel.Message;
import com.goodow.realtime.channel.State;
import com.goodow.realtime.core.Handler;
import com.goodow.realtime.core.Platform;
import com.goodow.realtime.core.WebSocket;
import com.goodow.realtime.json.Json;
import com.goodow.realtime.json.JsonObject; | /*
* Copyright 2013 Goodow.com
*
* 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.goodow.realtime.channel.impl;
@SuppressWarnings("rawtypes")
public class WebSocketBus extends SimpleBus {
public static final String SESSION = "_session";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String PING_INTERVAL = "vertxbus_ping_interval";
public static final String TOPIC_CHANNEL = "realtime/channel";
public static final String TOPIC_CONNECT = TOPIC_CHANNEL + "/_CONNECT";
protected static final String BODY = "body";
protected static final String TOPIC = "address";
protected static final String REPLY_TOPIC = "replyAddress";
protected static final String TYPE = "type";
private final WebSocket.WebSocketHandler webSocketHandler;
String serverUri;
WebSocket webSocket;
private int pingInterval;
private int pingTimerID = -1;
private String sessionId;
private String username;
private String password;
final JsonObject handlerCount = Json.createObject();
public WebSocketBus(String serverUri, JsonObject options) {
webSocketHandler = new WebSocket.WebSocketHandler() {
@Override
public void onClose(JsonObject reason) {
Platform.scheduler().cancelTimer(pingTimerID);
publishLocal(ON_CLOSE, reason);
if (hook != null) {
hook.handlePostClose();
}
}
@Override
public void onError(String error) {
publishLocal(ON_ERROR, Json.createObject().set("message", error));
}
@Override
public void onMessage(String msg) {
JsonObject json = Json.<JsonObject> parse(msg);
@SuppressWarnings({"unchecked"})
MessageImpl message =
new MessageImpl(false, false, WebSocketBus.this, json.getString(TOPIC), json
.getString(REPLY_TOPIC), json.get(BODY));
internalHandleReceiveMessage(message);
}
@Override
public void onOpen() {
sendConnect();
// Send the first ping then send a ping every 5 seconds
sendPing();
pingTimerID = Platform.scheduler().schedulePeriodic(pingInterval, new Handler<Void>() {
@Override
public void handle(Void ignore) {
sendPing();
}
});
if (hook != null) {
hook.handleOpened();
}
publishLocal(ON_OPEN, null);
}
};
connect(serverUri, options);
}
public void connect(String serverUri, JsonObject options) {
this.serverUri = serverUri;
pingInterval =
options == null || !options.has(PING_INTERVAL) ? 5 * 1000 : (int) options
.getNumber(PING_INTERVAL);
sessionId = options == null || !options.has(SESSION) ? idGenerator.next(23) : options.getString(
SESSION);
username = options == null || !options.has(USERNAME) ? null : options.getString(USERNAME);
password = options == null || !options.has(PASSWORD) ? null : options.getString(PASSWORD);
webSocket = Platform.net().createWebSocket(serverUri, options);
webSocket.setListen(webSocketHandler);
}
@Override
public State getReadyState() {
return webSocket.getReadyState();
}
@Override
public String getSessionId() {
return sessionId;
}
@Override
protected void doClose() { | subscribeLocal(Bus.ON_CLOSE, new Handler<Message<JsonObject>>() { | 1 |
mguetlein/CheS-Mapper | src/main/java/org/chesmapper/view/gui/table/TreeView.java | [
"public class Cluster extends ZoomableCompoundGroup implements CompoundGroupWithProperties, DoubleNameElement,\r\n\t\tComparable<Cluster>\r\n{\r\n\tprivate ClusterData clusterData;\r\n\r\n\tHashMap<String, List<Compound>> compoundsOrderedByPropterty = new HashMap<String, List<Compound>>();\r\n\r\n\tprivate boolean ... | import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import org.chesmapper.map.data.DistanceUtil;
import org.chesmapper.map.dataInterface.CompoundData;
import org.chesmapper.map.dataInterface.CompoundProperty;
import org.chesmapper.map.dataInterface.NominalProperty;
import org.chesmapper.map.main.ScreenSetup;
import org.chesmapper.map.main.Settings;
import org.chesmapper.view.cluster.Cluster;
import org.chesmapper.view.cluster.ClusterController;
import org.chesmapper.view.cluster.Clustering;
import org.chesmapper.view.cluster.Compound;
import org.chesmapper.view.cluster.CompoundFilterImpl;
import org.chesmapper.view.cluster.Clustering.SelectionListener;
import org.chesmapper.view.gui.ComponentSize;
import org.chesmapper.view.gui.GUIControler;
import org.chesmapper.view.gui.ViewControler;
import org.mg.javalib.dist.NonNullSimilartiy;
import org.mg.javalib.dist.SimilarityMeasure;
import org.mg.javalib.dist.SimpleMatchingSimilartiy;
import org.mg.javalib.dist.TanimotoSimilartiy;
import org.mg.javalib.gui.BlockableFrame;
import org.mg.javalib.util.ArrayUtil;
import org.mg.javalib.util.CountedSet;
import org.mg.javalib.util.DoubleArraySummary;
import org.mg.javalib.util.ListUtil;
import org.mg.javalib.util.ObjectUtil;
import org.mg.javalib.util.StringUtil;
import org.mg.javalib.util.SwingUtil; | package org.chesmapper.view.gui.table;
public class TreeView extends BlockableFrame
{
private static int ICON_W = 50;
private static int ICON_H = 50;
| protected ViewControler viewControler; | 8 |
jiangqqlmj/Android-Universal-Image-Loader-Modify | sample/src/main/java/com/nostra13/universalimageloader/sample/fragment/ImageListFragment.java | [
"public final class DisplayImageOptions {\n /*图片正在加载过程中的图片*/\n\tprivate final int imageResOnLoading;\n\t/*图片地址为空,显示的图片*/\n\tprivate final int imageResForEmptyUri;\n\t/*图片加载失败,显示的图片*/\n\tprivate final int imageResOnFail;\n\t/*图片资源 正在加载的图片*/\n\tprivate final Drawable imageOnLoading;\n\t/*图片资源 图片地址为空情况*/\n\tprivate... | import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedVignetteBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.sample.Constants;
import com.nostra13.universalimageloader.sample.R;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List; | /*******************************************************************************
* Copyright 2011-2014 Sergey Tarasevich
*
* 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.nostra13.universalimageloader.sample.fragment;
/**
* @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
*/
public class ImageListFragment extends AbsListViewBaseFragment {
public static final int INDEX = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fr_image_list, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
((ListView) listView).setAdapter(new ImageAdapter(getActivity()));
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startImagePagerActivity(position);
}
});
return rootView;
}
@Override
public void onDestroy() {
super.onDestroy();
AnimateFirstDisplayListener.displayedImages.clear();
}
private static class ImageAdapter extends BaseAdapter {
private static final String[] IMAGE_URLS = Constants.IMAGES;
private LayoutInflater inflater;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private DisplayImageOptions options;
ImageAdapter(Context context) {
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new RoundedVignetteBitmapDisplayer(20,10))
.build();
}
@Override
public int getCount() {
return IMAGE_URLS.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = inflater.inflate(R.layout.item_list_image, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
| ImageLoader.getInstance().displayImage(IMAGE_URLS[position], holder.image, options, animateFirstListener); | 1 |
hawkular/hawkular-android-client | mobile/src/main/java/org/hawkular/client/android/fragment/AlertsFragment.java | [
"public final class HawkularApplication extends Application {\n\n public static Retrofit retrofit;\n private RefWatcher refWatcher;\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n setUpLogging();\n setUpDetections();\n setUpPush();\n setUpLeakCanary();... | import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.hawkular.client.android.HawkularApplication;
import org.hawkular.client.android.R;
import org.hawkular.client.android.activity.AlertDetailActivity;
import org.hawkular.client.android.adapter.AlertsAdapter;
import org.hawkular.client.android.backend.BackendClient;
import org.hawkular.client.android.backend.model.Alert;
import org.hawkular.client.android.backend.model.Resource;
import org.hawkular.client.android.backend.model.Trigger;
import org.hawkular.client.android.util.ColorSchemer;
import org.hawkular.client.android.util.ErrorUtil;
import org.hawkular.client.android.util.Fragments;
import org.hawkular.client.android.util.Intents;
import org.hawkular.client.android.util.Time;
import org.hawkular.client.android.util.ViewDirector;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.squareup.leakcanary.RefWatcher;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import icepick.Icepick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import timber.log.Timber; | /*
* Copyright 2015-2017 Red Hat, Inc. and/or its affiliates
* and other 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.hawkular.client.android.fragment;
/**
* Alerts fragment.
* <p/>
* Displays alerts as a list with menus allowing some alert-related actions, such as acknowledgement and resolving.
*/
public class AlertsFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener,
AlertsAdapter.AlertListener, SearchView.OnQueryTextListener {
@BindView(R.id.list) RecyclerView recyclerView;
@BindView(R.id.content) SwipeRefreshLayout swipeRefreshLayout;
public ArrayList<Trigger> triggers;
public ArrayList<Alert> alerts;
public ArrayList<Alert> alertsDump;
public boolean isActionPlus;
public int alertsTimeMenu;
public boolean isAlertsFragmentAvailable;
public SearchView searchView;
public String searchText;
public AlertsAdapter alertsAdapter;
private Unbinder unbinder;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
@Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
isAlertsFragmentAvailable = true;
setUpState(state);
setUpBindings();
setUpList();
setUpMenu();
isActionPlus = false;
setUpRefreshing();
setUpAlertsUi();
}
private void setUpState(Bundle state) {
Icepick.restoreInstanceState(this, state);
}
private void setUpBindings() {
ButterKnife.bind(this, getView());
}
private void setUpList() {
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
}
private void setUpMenu() {
setHasOptionsMenu(true);
}
private void setUpRefreshing() {
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(ColorSchemer.getScheme());
}
@OnClick(R.id.button_retry)
public void setUpAlertsUi() {
if (alerts == null) {
alertsTimeMenu = R.id.menu_time_hour;
setUpAlertsForced();
} else {
setUpAlerts(alertsDump);
}
}
private void setUpAlertsRefreshed() {
setUpAlerts();
}
private void setUpAlertsForced() {
showProgress();
setUpAlerts();
}
private void setUpAlerts() {
if(getResource() == null) { | BackendClient.of(this).getAlerts(getAlertsTime(), Time.current(), null, new AlertsCallback(this)); | 1 |
feldim2425/OC-Minecarts | src/main/java/mods/ocminecart/client/ClientProxy.java | [
"public class ManualRegister {\n\t\n\tpublic static void registermanual(){\n\t\tManual.addProvider(new ResourceContentProvider(OCMinecart.MODID, \"doc/\"));\n\t\tManual.addProvider(new ManualPathProvider());\n\t\t\n\t\tManual.addTab(new ItemStackTabIconRenderer(new ItemStack(ModItems.item_ComputerCartCase,1,0)), \"... | import cpw.mods.fml.client.registry.RenderingRegistry;
import mods.ocminecart.client.manual.ManualRegister;
import mods.ocminecart.client.renderer.entity.ComputerCartRenderer;
import mods.ocminecart.client.renderer.item.ComputerCartItemRenderer;
import mods.ocminecart.common.CommonProxy;
import mods.ocminecart.common.items.ModItems;
import mods.ocminecart.common.minecart.ComputerCart;
import net.minecraftforge.client.MinecraftForgeClient; | package mods.ocminecart.client;
public class ClientProxy extends CommonProxy {
public void init(){
super.init();
RenderingRegistry.registerEntityRenderingHandler(ComputerCart.class, new ComputerCartRenderer()); | MinecraftForgeClient.registerItemRenderer(ModItems.item_ComputerCart, new ComputerCartItemRenderer()); | 4 |
pakoito/SongkickInterview | app/src/main/java/com/pacoworks/dereference/screens/songkicklist/SongkickListPresenter.java | [
"public abstract class ZimplBasePresenter<T extends IUi, U extends ZimpleBaseState> {\n private final Class<U> stateClass;\n\n private final List<Subscription> pauseSubscriptions = new ArrayList<>();\n\n private final List<Subscription> destroySubscriptions = new ArrayList<>();\n\n @Inject\n @Getter(... | import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import timber.log.Timber;
import com.github.pwittchen.reactivenetwork.library.ConnectivityStatus;
import com.pacoworks.dereference.BuildConfig;
import com.pacoworks.dereference.dependencies.skeleton.ZimplBasePresenter;
import com.pacoworks.dereference.model.Artist;
import com.pacoworks.dereference.model.SearchResult;
import com.pacoworks.dereference.network.EmptyResultException;
import com.pacoworks.dereference.network.SongkickApi;
import com.pacoworks.dereference.reactive.RxActions;
import com.pacoworks.dereference.reactive.RxLog;
import com.pacoworks.dereference.reactive.RxTuples;
import com.pacoworks.dereference.reactive.tuples.Tuple; | /*
* Copyright (c) pakoito 2015
*
* 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 com.pacoworks.dereference.screens.songkicklist;
public class SongkickListPresenter extends ZimplBasePresenter<ISongkickListUI, SongkickListState> {
public static final int INPUT_DEBOUNCE_POLICY = 1;
public static final int CONNECTIVITY_DEBOUNCE_POLICY = 1;
public static final int MIN_SEARCH_POLICY = 2;
private static final int TIMEOUT_POLICY = 60;
private static final long SECOND_IN_NANOS = 1000000000l;
private static final long STALE_SECONDS = 60 * SECOND_IN_NANOS;
@Inject
Observable<ConnectivityStatus> connectivity;
@Inject
SongkickApi songkickApi;
public SongkickListPresenter() {
super(SongkickListState.class);
}
@Override
protected SongkickListState createNewState() {
return new SongkickListState();
}
@Override
public void create() {
}
@Override
public void resume() {
bindUntilPause(observeConnectivity(connectivity),
refreshData(songkickApi, TIMEOUT_POLICY, BuildConfig.API_KEY), handleClicks());
}
private Subscription observeConnectivity(Observable<ConnectivityStatus> connectivity) {
return connectivity.map(ConnectivityStatus.isEqualTo(ConnectivityStatus.OFFLINE))
.subscribe(getUi().showOfflineOverlay());
}
private Subscription refreshData(final SongkickApi songkickApi, final int timeoutPolicy,
final String apiKey) {
return Observable
.combineLatest(getProcessedConnectivityObservable(), getDebouncedSearchBoxInputs(),
RxTuples.<ConnectivityStatus, String> singleToTuple())
.observeOn(AndroidSchedulers.mainThread()).doOnNext(getUi().showLoading())
.flatMap(new Func1<Tuple<ConnectivityStatus, String>, Observable<List<Artist>>>() {
@Override
public Observable<List<Artist>> call(Tuple<ConnectivityStatus, String> status) {
if (ConnectivityStatus.isEqualTo(ConnectivityStatus.OFFLINE).call(
status.first))
return requestLocal(status.second).map(stateToCache())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(getUi().hideLoading());
else
return requestArtists(songkickApi, timeoutPolicy, status.second, apiKey)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(
RxActions.doMultiple(RxLog.logError(),
handleForErrorType()))
.onErrorReturn(provideEmptyList())
.doOnNext(getUi().hideLoading());
}
}).subscribe(getUi().swapAdapter());
}
Observable<ConnectivityStatus> getProcessedConnectivityObservable() {
return connectivity.distinctUntilChanged()
.debounce(CONNECTIVITY_DEBOUNCE_POLICY, TimeUnit.SECONDS)
.doOnNext(RxLog.logMessage("Network status changed to %s"));
}
Observable<String> getDebouncedSearchBoxInputs() {
return getUi().getSearchBoxInputs().debounce(INPUT_DEBOUNCE_POLICY, TimeUnit.SECONDS)
.filter(new Func1<CharSequence, Boolean>() {
@Override
public Boolean call(CharSequence charSequence) {
return charSequence.length() >= MIN_SEARCH_POLICY;
}
}).map(new Func1<CharSequence, String>() {
@Override
public String call(CharSequence charSequence) {
return charSequence.toString();
}
});
}
Observable<List<Artist>> requestArtists(SongkickApi songkickApi, int timeoutPolicy,
String query, String apiKey) {
return Observable
.concat(requestLocal(query),
requestNetwork(songkickApi, timeoutPolicy, query, apiKey).doOnNext(
storeState())).takeFirst(stalePolicy(query)).map(stateToCache());
}
private Func1<SongkickListState, Boolean> stalePolicy(final String query) {
return new Func1<SongkickListState, Boolean>() {
@Override
public Boolean call(SongkickListState songkickListState) {
final boolean isFresh = query.equalsIgnoreCase(songkickListState.getQuery())
&& songkickListState.getCached().size() != 0
&& System.nanoTime() - songkickListState.getLastUpdate() < STALE_SECONDS;
Timber.d("Is this cache fresh? %s", isFresh);
return isFresh;
}
};
}
Observable<SongkickListState> requestNetwork(SongkickApi songkickApi, int timeoutPolicy,
final String query, String apiKey) {
return songkickApi.getSearchResult(apiKey, query).subscribeOn(Schedulers.newThread())
.unsubscribeOn(Schedulers.computation()).timeout(timeoutPolicy, TimeUnit.SECONDS)
.flatMap(toCorrectResult()).map(new Func1<List<Artist>, SongkickListState>() {
@Override
public SongkickListState call(List<Artist> artists) {
return new SongkickListState(query, artists, System.nanoTime());
}
});
}
| private Func1<SearchResult, Observable<List<Artist>>> toCorrectResult() { | 2 |
dragonite-network/dragonite-java | dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/msg/types/HeartbeatMessage.java | [
"public class IncorrectMessageException extends DragoniteException {\n\n public IncorrectMessageException(final String msg) {\n super(msg);\n }\n\n}",
"public final class DragoniteGlobalConstants {\n\n public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION;\n\n public static ... | import com.vecsight.dragonite.sdk.exception.IncorrectMessageException;
import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants;
import com.vecsight.dragonite.sdk.msg.MessageType;
import com.vecsight.dragonite.sdk.msg.ReliableMessage;
import com.vecsight.dragonite.utils.binary.BinaryReader;
import com.vecsight.dragonite.utils.binary.BinaryWriter;
import java.nio.BufferUnderflowException; | /*
* The Dragonite Project
* -------------------------
* See the LICENSE file in the root directory for license information.
*/
package com.vecsight.dragonite.sdk.msg.types;
public class HeartbeatMessage implements ReliableMessage {
private static final byte VERSION = DragoniteGlobalConstants.PROTOCOL_VERSION;
private static final MessageType TYPE = MessageType.HEARTBEAT;
public static final int FIXED_LENGTH = 6;
private int sequence;
public HeartbeatMessage(final int sequence) {
this.sequence = sequence;
}
public HeartbeatMessage(final byte[] msg) throws IncorrectMessageException { | final BinaryReader reader = new BinaryReader(msg); | 4 |
saoj/mentabean | src/main/java/org/mentabean/sql/functions/Substring.java | [
"public interface Function extends HasParams {\n\t\n}",
"public abstract class Parametrizable implements HasParams {\n\n\tprotected List<Param> params = new ArrayList<Param>();\n\t\n\tpublic abstract String name();\n\t\n\t@Override\n\tpublic Param[] getParams() {\n\t\treturn params.toArray(new Param[0]);\n\t}\n\t... | import org.mentabean.sql.Function;
import org.mentabean.sql.Parametrizable;
import org.mentabean.sql.param.Param;
import org.mentabean.sql.param.ParamFunction;
import org.mentabean.sql.param.ParamValue; | package org.mentabean.sql.functions;
public class Substring extends Parametrizable implements Function {
private Param str, beginIndex, endIndex;
public Substring(Param str) {
this.str = str;
}
public Substring endIndex(Param param) {
endIndex = param;
return this;
}
public Substring beginIndex(Param param) {
beginIndex = param;
return this;
}
@Override
public Param[] getParams() {
if (beginIndex == null)
beginIndex = new ParamValue(0);
if (endIndex == null) | endIndex = new ParamFunction(new Length(str)); | 3 |
jaquadro/ForgeMods | HungerStrike/src/com/jaquadro/minecraft/hungerstrike/HungerStrike.java | [
"public class CommandHungerStrike extends CommandBase {\n\n @Override\n public String getCommandName () {\n return \"hungerstrike\";\n }\n\n @Override\n public int getRequiredPermissionLevel() {\n return 3;\n }\n\n @Override\n public String getCommandUsage (ICommandSender sende... | import com.jaquadro.minecraft.hungerstrike.command.CommandHungerStrike;
import com.jaquadro.minecraft.hungerstrike.network.PacketPipeline;
import com.jaquadro.minecraft.hungerstrike.network.SyncConfigPacket;
import com.jaquadro.minecraft.hungerstrike.network.SyncExtendedPlayerPacket;
import com.jaquadro.minecraft.hungerstrike.proxy.CommonProxy;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.*;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.registry.GameData;
import net.minecraft.client.Minecraft;
import net.minecraft.command.CommandHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent; | package com.jaquadro.minecraft.hungerstrike;
@Mod(modid = HungerStrike.MOD_ID, name = HungerStrike.MOD_NAME, version = HungerStrike.MOD_VERSION)
public class HungerStrike
{
public static final String MOD_ID = "hungerstrike";
static final String MOD_NAME = "Hunger Strike";
static final String MOD_VERSION = "1.7.10.4";
static final String SOURCE_PATH = "com.jaquadro.minecraft.hungerstrike.";
@Mod.Instance(MOD_ID)
public static HungerStrike instance;
@SidedProxy(clientSide = SOURCE_PATH + "proxy.ClientProxy", serverSide = SOURCE_PATH + "proxy.CommonProxy")
public static CommonProxy proxy;
public static final PacketPipeline packetPipeline = new PacketPipeline();
public static ConfigManager config = new ConfigManager();
@Mod.EventHandler
public void preInit (FMLPreInitializationEvent event) {
FMLCommonHandler.instance().bus().register(proxy);
config.setup(event.getSuggestedConfigurationFile());
}
@Mod.EventHandler
public void load (FMLInitializationEvent event) {
MinecraftForge.EVENT_BUS.register(proxy);
packetPipeline.initialise();
packetPipeline.registerPacket(SyncExtendedPlayerPacket.class);
packetPipeline.registerPacket(SyncConfigPacket.class);
}
@Mod.EventHandler
public void postInit (FMLPostInitializationEvent event) {
packetPipeline.postInitialise();
if (config.getFoodStackSize() > -1) {
for (Object obj : GameData.itemRegistry) {
Item item = (Item) obj;
if (item instanceof ItemFood)
item.setMaxStackSize(config.getFoodStackSize());
}
}
}
@Mod.EventHandler
public void serverStarted (FMLServerStartedEvent event) {
CommandHandler handler = (CommandHandler) MinecraftServer.getServer().getCommandManager(); | handler.registerCommand(new CommandHungerStrike()); | 0 |
xxonehjh/remote-files-sync | src/main/java/com/hjh/files/sync/server/SyncFileServerHandler.java | [
"public class HLogFactory {\n\n\tprivate static ILogFactory instance;\n\n\tpublic static boolean isInstanceNull() {\n\t\treturn null == instance;\n\t}\n\n\tprivate static ILog empty = new ILog() {\n\n\t\t@Override\n\t\tpublic void debug(String msg) {\n\t\t}\n\n\t\t@Override\n\t\tpublic void info(String msg) {\n\t\t... | import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.thrift.TException;
import com.hjh.files.sync.common.HLogFactory;
import com.hjh.files.sync.common.ILog;
import com.hjh.files.sync.common.RemoteFile;
import com.hjh.files.sync.common.util.RemoteFileUtil;
import tutorial.RemoteFileInfo;
import tutorial.SyncFileServer; | package com.hjh.files.sync.server;
public class SyncFileServerHandler implements SyncFileServer.Iface {
private static ILog logger = HLogFactory.create(ServerForSync.class);
private ServerForSync sync;
public SyncFileServerHandler(ServerForSync serverForSync) {
this.sync = serverForSync;
}
@Override
public String md5(String folder, String path) throws TException {
logger.info(String.format("md5 [%s] [%s]", folder, path));
return sync.get(folder).md5(path);
}
@Override
public ByteBuffer part(String folder, String path, long part, long part_size) throws TException {
logger.info(String.format("part [%s] [%s] [%d]", folder, path, part));
byte[] partData = sync.get(folder).part(path, part, part_size);
logger.info(String.format("send part data %d", partData.length));
return ByteBuffer.wrap(partData);
}
@Override
public List<RemoteFileInfo> listFiles(String folder, String path) throws TException {
logger.info(String.format("list files [%s] [%s]", folder, path == null ? "ROOT" : path));
List<RemoteFileInfo> result = new ArrayList<RemoteFileInfo>();
RemoteFile[] files = sync.get(folder).list(path);
if (null != files) {
for (RemoteFile item : files) { | result.add(RemoteFileUtil.to(item)); | 3 |
maxanier/MinecraftSecondScreenMod | src/main/java/de/maxgb/minecraft/second_screen/data/ObservingManager.java | [
"public class JSONArray {\n\n\t/**\n\t * The arrayList where the JSONArray's properties are kept.\n\t */\n\tprivate final ArrayList myArrayList;\n\n\t/**\n\t * Construct an empty JSONArray.\n\t */\n\tpublic JSONArray() {\n\t\tthis.myArrayList = new ArrayList();\n\t}\n\n\t/**\n\t * Construct a JSONArray from a Colle... | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import de.maxgb.minecraft.second_screen.Configs;
import de.maxgb.minecraft.second_screen.util.Constants;
import de.maxgb.minecraft.second_screen.util.Helper;
import de.maxgb.minecraft.second_screen.util.Logger;
import de.maxgb.minecraft.second_screen.world_observer.ObservedBlock;
| package de.maxgb.minecraft.second_screen.data;
/**
* Manages all observed blocks
* Saves and loads them and makes sure that every player gets his private and the public block infos
* @author Max
*
*/
public class ObservingManager {
private static final String TAG = "ObservingManager";
private static final String PUBLIC_USER = "msspublic";
private static HashMap<String, HashMap<String, ObservedBlock>> map;
/**
* Returns all blocks observed by that user
*
* @param username
* player
* @param publ
* if true, the public blocks are returned as well
* @return if none, an empty list is returned
*/
public static ArrayList<ObservedBlock> getObservedBlocks(String username, boolean publ) {
ArrayList<ObservedBlock> blocks = new ArrayList<ObservedBlock>();
if (map != null && map.get(username) != null) {
blocks.addAll(map.get(username).values());
}
if (publ) {
blocks.addAll(getObservedBlocks(PUBLIC_USER, false));
}
return blocks;
}
/**
* Loads the observation map from a jsonfile
*/
public static void loadObservingFile() {
ArrayList<String> lines = DataStorageDriver.readFromWorldFile(Constants.OBSERVER_FILE_NAME);
if (lines == null || lines.size() == 0) {
| Logger.w(TAG, "No saved data found");
| 5 |
jmhertlein/MCTowns | src/main/java/cafe/josh/mctowns/TownManager.java | [
"public abstract class MCTownsRegion {\n\n private static final long serialVersionUID = \"MCTOWNSREGION\".hashCode(); // DO NOT CHANGE\n private static final int VERSION = 0;\n /**\n * The name of the region, the name of the world in which the region exists\n */\n protected volatile String name,... | import cafe.josh.mctowns.region.MCTownsRegion;
import cafe.josh.mctowns.region.Plot;
import cafe.josh.mctowns.region.Town;
import cafe.josh.mctowns.region.TownLevel;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.storage.StorageException;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import cafe.josh.mctowns.command.ActiveSet;
import cafe.josh.mctowns.region.Territory;
import cafe.josh.mctowns.util.UUIDs;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player; | /*
* Copyright (C) 2013 Joshua Michael Hertlein <jmhertlein@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cafe.josh.mctowns;
/**
*
* @author joshua
*/
public class TownManager {
private final HashMap<String, Town> towns;
private final HashMap<String, MCTownsRegion> regions;
/**
* Constructs a new, empty town manager.
*/
public TownManager() {
towns = new HashMap<>();
regions = new HashMap<>();
}
/**
* Returns the towns that this manager manages
*
* @return the towns
*/
public Collection<Town> getTownsCollection() {
return towns.values();
}
/**
*
* @return
*/
public Collection<MCTownsRegion> getRegionsCollection() {
return regions.values();
}
/**
* Attempts to add a town to the town manager (effectively creating a new
* town as far as the TownManager is concerned).
*
* @param townName the desired name of the new town
* @param mayor the live player to be made the mayor of the new town
*
* @return true if town was added, false if town was not because it was
* already existing
*/
public Town addTown(String townName, Player mayor) {
Town t = new Town(townName, mayor);
if(towns.containsKey(t.getName())) {
return null;
}
towns.put(t.getName(), t);
return t;
}
public Town addTown(String townName, Player mayorName, Location spawn) {
Town t = new Town(townName, mayorName, spawn);
if(towns.containsKey(t.getName())) {
return null;
}
towns.put(t.getName(), t);
return t;
}
/**
* Creates a new territory, adds it to the manager, and registers its region
* in WorldGuard.
*
* @param fullTerritoryName the desired, formatted name of the region
* @param worldTerritoryIsIn
* @param reg the desired region for the territory to occupy, names MUST
* match
* @param parentTown the parent town of the Territory
*
* @throws InvalidWorldGuardRegionNameException if the name of the
* ProtectedRegion contains invalid characters
* @throws RegionAlreadyExistsException if the region already exists
*/
public void addTerritory(String fullTerritoryName, World worldTerritoryIsIn, ProtectedRegion reg, Town parentTown) throws InvalidWorldGuardRegionNameException, RegionAlreadyExistsException { | Territory t = new Territory(fullTerritoryName, | 5 |
hypfvieh/bluez-dbus | bluez-dbus/src/main/java/org/bluez/mesh/Management1.java | [
"@SuppressWarnings(\"serial\")\npublic class BluezMeshAlreadyExistsException extends DBusException {\n\n public BluezMeshAlreadyExistsException(String _message) {\n super(_message);\n }\n\n}",
"@SuppressWarnings(\"serial\")\npublic class BluezMeshBusyException extends DBusException {\n\n public Bl... | import java.util.Map;
import org.bluez.exceptions.mesh.BluezMeshAlreadyExistsException;
import org.bluez.exceptions.mesh.BluezMeshBusyException;
import org.bluez.exceptions.mesh.BluezMeshDoesNotExistException;
import org.bluez.exceptions.mesh.BluezMeshFailedException;
import org.bluez.exceptions.mesh.BluezMeshInProgressException;
import org.bluez.exceptions.mesh.BluezMeshInvalidArgumentsException;
import org.bluez.exceptions.mesh.BluezMeshNotAuthorizedException;
import org.freedesktop.dbus.interfaces.DBusInterface;
import org.freedesktop.dbus.types.UInt16;
import org.freedesktop.dbus.types.Variant; | package org.bluez.mesh;
/**
* File generated - 2020-12-28.<br>
* Based on bluez Documentation: mesh-api.txt.<br>
* <br>
* <b>Service:</b> org.bluez.mesh<br>
* <b>Interface:</b> org.bluez.mesh.Management1<br>
* <br>
* <b>Object path:</b><br>
* /org/bluez/mesh/node<uuid><br>
* where <uuid> is the Device UUID passed to Join(),<br>
* CreateNetwork() or Import()<br>
*/
public interface Management1 extends DBusInterface {
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application that supports<br>
* org.bluez.mesh.Provisioner1 interface to start listening<br>
* (scanning) for unprovisioned devices in the area.<br>
* <br>
* The options parameter is a dictionary with the following keys<br>
* defined:<br>
* <pre>
* uint16 Seconds
* Specifies number of seconds for scanning to be active.
* If set to 0 or if this key is not present, then the
* scanning will continue until UnprovisionedScanCancel()
* or AddNode() methods are called.
* </pre>
* <br>
* Each time a unique unprovisioned beacon is heard, the<br>
* ScanResult() method on the app will be called with the result.<br>
*
* @param _options options
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshNotAuthorizedException when not authorized
* @throws BluezMeshBusyException when already busy
*/
void UnprovisionedScan(Map<String, Variant<?>> _options) throws BluezMeshInvalidArgumentsException, BluezMeshNotAuthorizedException, BluezMeshBusyException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application that supports<br>
* org.bluez.mesh.Provisioner1 interface to stop listening<br>
* (scanning) for unprovisioned devices in the area.<br>
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshNotAuthorizedException when not authorized
*/
void UnprovisionedScanCancel() throws BluezMeshInvalidArgumentsException, BluezMeshNotAuthorizedException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application that supports<br>
* org.bluez.mesh.Provisioner1 interface to add the<br>
* unprovisioned device specified by uuid, to the Network.<br>
* <br>
* The uuid parameter is a 16-byte array that contains Device UUID<br>
* of the unprovisioned device to be added to the network.<br>
* <br>
* The options parameter is a dictionary that may contain<br>
* additional configuration info (currently an empty placeholder<br>
* for forward compatibility).<br>
*
* @param _uuid uuid (16-byte array)
* @param _options options
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshNotAuthorizedException when not authorized
*/
void AddNode(byte[] _uuid, Map<String, Variant<?>> _options) throws BluezMeshInvalidArgumentsException, BluezMeshNotAuthorizedException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to generate and add a new<br>
* network subnet key.<br>
* <br>
* The net_index parameter is a 12-bit value (0x001-0xFFF)<br>
* specifying which net key to add.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshNotAuthorizedException when not authorized
*/
void CreateSubnet(UInt16 _netIndex) throws BluezMeshInvalidArgumentsException, BluezMeshNotAuthorizedException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to add a network subnet<br>
* key, that was originally generated by a remote Config Client.<br>
* <br>
* The net_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which net key to add.<br>
* <br>
* The net_key parameter is the 16-byte value of the net key being<br>
* imported.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
* @param _netKey net_key
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshAlreadyExistsException when already exists
*/
void ImportSubnet(UInt16 _netIndex, byte[] _netKey) throws BluezMeshInvalidArgumentsException, BluezMeshFailedException, BluezMeshAlreadyExistsException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to generate a new network<br>
* subnet key, and set it's key refresh state to Phase 1.<br>
* <br>
* The net_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which net key to update. Note that the subnet must<br>
* exist prior to updating.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
*
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshDoesNotExistException when not existing
* @throws BluezMeshBusyException when already busy
*/
void UpdateSubnet(UInt16 _netIndex) throws BluezMeshFailedException, BluezMeshInvalidArgumentsException, BluezMeshDoesNotExistException, BluezMeshBusyException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application that to delete a subnet.<br>
* <br>
* The net_index parameter is a 12-bit value (0x001-0xFFF)<br>
* specifying which net key to delete. The primary net key (0x000)<br>
* may not be deleted.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
*/
void DeleteSubnet(UInt16 _netIndex) throws BluezMeshInvalidArgumentsException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used to set the master key update phase of the<br>
* given subnet. When finalizing the procedure, it is important<br>
* to CompleteAppKeyUpdate() on all app keys that have been<br>
* updated during the procedure prior to setting phase 3.<br>
* <br>
* The net_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which subnet phase to set.<br>
* <br>
* The phase parameter is used to cycle the local key database<br>
* through the phases as defined by the Mesh Profile Specification.
* <pre>
* Allowed values:
* 0 - Cancel Key Refresh (May only be called from Phase 1,
* and should never be called once the new key has
* started propagating)
* 1 - Invalid Argument (see NetKeyUpdate method)
* 2 - Go to Phase 2 (May only be called from Phase 1)
* 3 - Complete Key Refresh procedure (May only be called
* from Phase 2)
* </pre>
* This call affects the local bluetooth-meshd key database only.<br>
* It is the responsibility of the application to maintain the key<br>
* refresh phases per the Mesh Profile Specification.<br>
*
* @param _netIndex net_index
* @param _phase phase
*
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshDoesNotExistException when not existing
*/
void SetKeyPhase(UInt16 _netIndex, byte _phase) throws BluezMeshFailedException, BluezMeshInvalidArgumentsException, BluezMeshDoesNotExistException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to generate and add a new<br>
* application key.<br>
* <br>
* The net_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which net key to bind the application key to.<br>
* <br>
* The app_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which app key to add.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
* @param _appIndex app_index
*
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshAlreadyExistsException when already existing
* @throws BluezMeshDoesNotExistException when not existing
*/
void CreateAppKey(UInt16 _netIndex, UInt16 _appIndex) throws BluezMeshFailedException, BluezMeshInvalidArgumentsException, BluezMeshAlreadyExistsException, BluezMeshDoesNotExistException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to add an application<br>
* key, that was originally generated by a remote Config Client.<br>
* <br>
* The net_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which net key to bind the application key to.<br>
* <br>
* The app_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which app key to import.<br>
* <br>
* The app_key parameter is the 16-byte value of the key being<br>
* imported.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
* @param _appIndex app_index
* @param _appKey app_key
*
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshAlreadyExistsException when already existing
* @throws BluezMeshDoesNotExistException when not existing
*/
void ImportAppKey(UInt16 _netIndex, UInt16 _appIndex, byte[] _appKey) throws BluezMeshFailedException, BluezMeshInvalidArgumentsException, BluezMeshAlreadyExistsException, BluezMeshDoesNotExistException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to generate a new<br>
* application key.<br>
* <br>
* The app_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which app key to update. Note that the subnet that<br>
* the key is bound to must exist and be in Phase 1.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
* @param _appIndex app_index
*
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshDoesNotExistException when not existing
* @throws BluezMeshInProgressException when already in progress
*/ | void UpdateAppKey(UInt16 _appIndex) throws BluezMeshFailedException, BluezMeshInvalidArgumentsException, BluezMeshDoesNotExistException, BluezMeshInProgressException; | 4 |
SumoLogic/sumologic-jenkins-plugin | src/main/java/com/sumologic/jenkins/jenkinssumologicplugin/PluginDescriptorImpl.java | [
"public enum EventSourceEnum {\n\n PERIODIC_UPDATE(\"Periodic_Update\"),\n COMPUTER_ONLINE(\"Computer_Online\"),\n COMPUTER_OFFLINE(\"Computer_Offline\"),\n COMPUTER_TEMP_ONLINE(\"Computer_Temp_Online\"),\n COMPUTER_TEMP_OFFLINE(\"Computer_Temp_Offline\"),\n COMPUTER_PRE_ONLINE(\"Computer_Pre_Onli... | import com.google.gson.Gson;
import com.sumologic.jenkins.jenkinssumologicplugin.constants.EventSourceEnum;
import com.sumologic.jenkins.jenkinssumologicplugin.constants.LogTypeEnum;
import com.sumologic.jenkins.jenkinssumologicplugin.metrics.SumoMetricDataPublisher;
import com.sumologic.jenkins.jenkinssumologicplugin.model.PluginConfiguration;
import com.sumologic.jenkins.jenkinssumologicplugin.sender.LogSender;
import com.sumologic.jenkins.jenkinssumologicplugin.sender.LogSenderHelper;
import com.sumologic.jenkins.jenkinssumologicplugin.utility.SumoLogHandler;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.init.Initializer;
import hudson.init.TermMilestone;
import hudson.init.Terminator;
import hudson.model.AbstractProject;
import hudson.remoting.Channel;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import hudson.util.FormValidation;
import hudson.util.Secret;
import jenkins.model.Jenkins;
import jenkins.security.SlaveToMasterCallable;
import jenkins.util.Timer;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.StatusLine;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
import java.util.logging.Logger;
import static com.sumologic.jenkins.jenkinssumologicplugin.constants.SumoConstants.DATETIME_FORMATTER;
import static hudson.init.InitMilestone.JOB_LOADED; | package com.sumologic.jenkins.jenkinssumologicplugin;
/**
* Sumo Logic plugin for Jenkins model.
* Provides options to parametrize plugin.
* <p>
* Created by deven on 7/8/15.
* Contributors: lukasz, Sourabh Jain
*/
@Extension
public final class PluginDescriptorImpl extends BuildStepDescriptor<Publisher> {
private Secret url;
private transient SumoMetricDataPublisher sumoMetricDataPublisher;
private static LogSenderHelper logSenderHelper = null;
private String queryPortal;
private String sourceCategory;
private String metricDataPrefix;
private boolean auditLogEnabled;
private boolean keepOldConfigData;
private boolean metricDataEnabled;
private boolean periodicLogEnabled;
private boolean jobStatusLogEnabled;
private boolean jobConsoleLogEnabled;
private boolean scmLogEnabled;
public PluginDescriptorImpl() {
super(SumoBuildNotifier.class);
load();
sumoMetricDataPublisher = new SumoMetricDataPublisher();
if (metricDataEnabled && metricDataPrefix != null) {
getSumoMetricDataPublisher().stopReporter();
getSumoMetricDataPublisher().publishMetricData(metricDataPrefix);
}
if (!metricDataEnabled) {
getSumoMetricDataPublisher().stopReporter();
}
setLogSenderHelper(LogSenderHelper.getInstance());
}
private static void setLogSenderHelper(LogSenderHelper logSenderHelper) {
PluginDescriptorImpl.logSenderHelper = logSenderHelper;
}
public static PluginDescriptorImpl getInstance() {
return (PluginDescriptorImpl) Jenkins.get().getDescriptor(SumoBuildNotifier.class);
}
public static PluginConfiguration getPluginConfiguration() {
Channel channel = Channel.current();
if (channel != null) {
try {
return channel.call(new PluginConfigurationFromMain());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
PluginDescriptorImpl pluginDescriptor = (PluginDescriptorImpl) Jenkins.get().getDescriptor(SumoBuildNotifier.class);
assert pluginDescriptor != null;
return new PluginConfiguration(pluginDescriptor);
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
@Override
public String getDisplayName() {
return "Sumo Logic build logger";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
boolean configOk = super.configure(req, formData);
url = Secret.fromString(formData.getString("url"));
queryPortal = StringUtils.isNotEmpty(formData.getString("queryPortal")) ? formData.getString("queryPortal") : "service.sumologic.com";
sourceCategory = StringUtils.isNotEmpty(formData.getString("sourceCategory")) ? formData.getString("sourceCategory") : "jenkinsSourceCategory";
metricDataPrefix = StringUtils.isNotEmpty(formData.getString("metricDataPrefix")) ? formData.getString("metricDataPrefix") : "jenkinsMetricDataPrefix";
auditLogEnabled = formData.getBoolean("auditLogEnabled");
metricDataEnabled = formData.getBoolean("metricDataEnabled");
periodicLogEnabled = formData.getBoolean("periodicLogEnabled");
jobStatusLogEnabled = formData.getBoolean("jobStatusLogEnabled");
jobConsoleLogEnabled = formData.getBoolean("jobConsoleLogEnabled");
scmLogEnabled = formData.getBoolean("scmLogEnabled");
keepOldConfigData = formData.getBoolean("keepOldConfigData");
save();
if (metricDataEnabled && metricDataPrefix != null) {
getSumoMetricDataPublisher().stopReporter();
getSumoMetricDataPublisher().publishMetricData(metricDataPrefix);
}
if (!metricDataEnabled) {
getSumoMetricDataPublisher().stopReporter();
}
return configOk;
}
@Terminator(after = TermMilestone.STARTED)
@Restricted(NoExternalUse.class)
public static void shutdown() {
PluginDescriptorImpl pluginDescriptor = checkIfPluginInUse();
pluginDescriptor.getSumoMetricDataPublisher().stopReporter();
| Logger.getLogger("").removeHandler(SumoLogHandler.getInstance()); | 6 |
msokolov/lux | src/test/java/lux/junit/QueryTestCase.java | [
"public class QueryStats {\n /**\n * the number of documents that matched the lucene query. If XPath was executed (there wasn't\n * a short-circuited eval of some sort), this number of XML documents will have been retrieved\n * from the database and processed.\n */\n public int docCount;\n ... | import static org.junit.Assert.*;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import lux.Compiler;
import lux.Evaluator;
import lux.QueryStats;
import lux.XdmResultSet;
import lux.exception.LuxException;
import lux.support.SearchExtractor;
import lux.xpath.AbstractExpression;
import lux.xpath.ExpressionVisitorBase;
import lux.xpath.FunCall;
import lux.xpath.LiteralExpression;
import lux.xquery.XQuery;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.expr.sort.CodepointCollator;
import net.sf.saxon.expr.sort.GenericAtomicComparer;
import net.sf.saxon.functions.DeepEqual;
import net.sf.saxon.s9api.Axis;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.trans.XPathException;
import org.apache.commons.lang.StringUtils;
import org.junit.Ignore; | package lux.junit;
@Ignore
class QueryTestCase {
private final String name;
private final String query;
private final QueryTestResult expectedResult;
QueryTestCase (String name, String query, QueryTestResult expected) {
this.name = name;
this.query = query;
this.expectedResult = expected;
}
public XdmResultSet evaluate (Evaluator eval) {
Compiler compiler = eval.getCompiler(); | QueryStats stats = new QueryStats(); | 0 |
Spade-Editor/Spade | src/heroesgrave/spade/image/change/doc/NewLayer.java | [
"public class Document\n{\n\tpublic static int MAX_DIMENSION = 4096;\n\t\n\tprivate LinkedList<IDocChange> changes = new LinkedList<IDocChange>();\n\tprivate LinkedList<IDocChange> reverted = new LinkedList<IDocChange>();\n\t\n\tprivate int width, height;\n\tprivate File file;\n\tprivate Metadata info;\n\tprivate L... | import heroesgrave.spade.image.Document;
import heroesgrave.spade.image.Layer;
import heroesgrave.spade.image.RawImage;
import heroesgrave.spade.image.change.IDocChange;
import heroesgrave.spade.image.change.edit.ClearMaskChange;
import heroesgrave.spade.main.Spade;
import heroesgrave.utils.misc.Metadata; | // {LICENSE}
/*
* Copyright 2013-2015 HeroesGrave and other Spade developers.
*
* This file is part of Spade
*
* Spade 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 heroesgrave.spade.image.change.doc;
public class NewLayer implements IDocChange
{
private Layer layer, parent;
private int index = -1;
private RawImage image;
private String name;
private boolean floating;
public NewLayer(Layer parent)
{
this(parent, prepareImage(parent));
}
private static RawImage prepareImage(Layer parent)
{
RawImage image = new RawImage(parent.getWidth(), parent.getHeight());
image.copyMaskFrom(parent.getImage());
return image;
}
public NewLayer(Layer parent, RawImage image)
{
this(parent, image, "New Layer");
}
public NewLayer(Layer parent, RawImage image, String name)
{
this.parent = parent;
this.image = image;
this.name = name;
}
public NewLayer floating()
{
this.floating = true;
return this;
}
| public void apply(Document doc) | 0 |
EndlessCodeGroup/RPGInventory | src/main/java/ru/endlesscode/rpginventory/pet/CooldownTimer.java | [
"public class RPGInventory extends PluginLifecycle {\n private static RPGInventory instance;\n\n private Permission perms;\n private Economy economy;\n\n private BukkitLevelSystem.Provider levelSystemProvider;\n private BukkitClassSystem.Provider classSystemProvider;\n\n private FileLanguage langu... | import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable;
import ru.endlesscode.rpginventory.RPGInventory;
import ru.endlesscode.rpginventory.inventory.InventoryManager;
import ru.endlesscode.rpginventory.inventory.slot.Slot;
import ru.endlesscode.rpginventory.inventory.slot.SlotManager;
import ru.endlesscode.rpginventory.utils.ItemUtils;
import java.util.Objects; | /*
* This file is part of RPGInventory.
* Copyright (C) 2015-2017 Osip Fatkullin
*
* RPGInventory 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.
*
* RPGInventory 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 RPGInventory. If not, see <http://www.gnu.org/licenses/>.
*/
package ru.endlesscode.rpginventory.pet;
/**
* Created by OsipXD on 27.08.2015
* It is part of the RpgInventory.
* All rights reserved 2014 - 2016 © «EndlessCode Group»
*/
@Deprecated
class CooldownTimer extends BukkitRunnable {
private final Player player;
private final ItemStack petItem;
@Deprecated
public CooldownTimer(Player player, ItemStack petItem) {
this.player = player;
this.petItem = petItem;
}
@Override
public void run() {
if (!InventoryManager.playerIsLoaded(this.player)) {
this.cancel();
return;
}
Inventory inventory = InventoryManager.get(this.player).getInventory();
final boolean playerIsAlive = !this.player.isOnline() || this.player.isDead();
final boolean playerHasNotPetItem = inventory.getItem(PetManager.getPetSlotId()) == null;
if (playerIsAlive || !PetManager.isEnabled() || playerHasNotPetItem) {
this.cancel();
return;
}
int cooldown = PetManager.getCooldown(this.petItem);
if (cooldown > 1) {
ItemStack item = this.petItem.clone();
if (cooldown < 60) {
item.setAmount(cooldown);
}
ItemMeta itemMeta = item.getItemMeta();
if (itemMeta != null) {
itemMeta.setDisplayName(itemMeta.getDisplayName()
+ RPGInventory.getLanguage().getMessage("pet.cooldown", cooldown));
PetManager.addGlow(itemMeta);
item.setItemMeta(itemMeta);
}
String itemTag = ItemUtils.getTag(this.petItem, ItemUtils.PET_TAG);
if (itemTag.isEmpty()) { | Slot petSlot = Objects.requireNonNull(SlotManager.instance().getPetSlot(), "Pet slot can't be null!"); | 2 |
firepick1/FireBOM | src/main/java/org/firepick/firebom/bom/BOM.java | [
"public interface IPartComparable extends Comparable<IPartComparable> {\n Part getPart();\n}",
"public interface IRefreshableProxy {\n\n /**\n * Synchronize proxy with remote resource\n */\n void refresh();\n\n /**\n * A newly constructed proxy is not fresh until it is refreshed.\n * F... | import java.util.concurrent.ConcurrentSkipListSet;
import org.firepick.firebom.IPartComparable;
import org.firepick.firebom.IRefreshableProxy;
import org.firepick.firebom.RefreshableTimer;
import org.firepick.firebom.exception.ApplicationLimitsException;
import org.firepick.firebom.part.Part;
import org.firepick.firebom.part.PartFactory;
import org.firepick.relation.IColumnDescription;
import org.firepick.relation.IRelation;
import org.firepick.relation.IRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
import java.util.*; | package org.firepick.firebom.bom;
/*
BOM.java
Copyright (C) 2013 Karl Lew <karl@firepick.org>. 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.
*/
public class BOM implements IRelation, IRefreshableProxy {
public final static String UNRESOLVED = "(Processing...)";
private static Logger logger = LoggerFactory.getLogger(BOM.class);
private List<IColumnDescription> columnDescriptions;
private ConcurrentSkipListSet<IPartComparable> rows = new ConcurrentSkipListSet<IPartComparable>();
private int maximumParts;
private Map<BOMColumn, BOMColumnDescription> columnMap = new HashMap<BOMColumn, BOMColumnDescription>();
private URL url;
private String title;
private RefreshableTimer refreshableTimer = new RefreshableTimer(); | private Part rootPart; | 4 |
ktisha/Crucible4IDEA | src/com/jetbrains/crucible/ui/toolWindow/CruciblePanel.java | [
"public class CrucibleManager {\n private final Project myProject;\n private final Map<String, CrucibleSession> mySessions = new HashMap<String, CrucibleSession>();\n\n private static final Logger LOG = Logger.getInstance(CrucibleManager.class.getName());\n\n // implicitly constructed by pico container\n @Supp... | import com.intellij.ide.util.treeView.AbstractTreeBuilder;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.SimpleToolWindowPanel;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.LocalFilePath;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.JBSplitter;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.table.JBTable;
import com.intellij.ui.treeStructure.SimpleTree;
import com.intellij.ui.treeStructure.SimpleTreeStructure;
import com.intellij.vcsUtil.VcsUtil;
import com.jetbrains.crucible.connection.CrucibleManager;
import com.jetbrains.crucible.model.Review;
import com.jetbrains.crucible.model.ReviewItem;
import com.jetbrains.crucible.ui.DescriptionCellRenderer;
import com.jetbrains.crucible.ui.toolWindow.details.DetailsPanel;
import com.jetbrains.crucible.ui.toolWindow.tree.CrucibleRootNode;
import com.jetbrains.crucible.ui.toolWindow.tree.CrucibleTreeModel;
import com.jetbrains.crucible.utils.CrucibleBundle;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.DefaultTreeModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*; | package com.jetbrains.crucible.ui.toolWindow;
/**
* User: ktisha
* <p/>
* Main code review panel
*/
public class CruciblePanel extends SimpleToolWindowPanel {
private static final Logger LOG = Logger.getInstance(CruciblePanel.class.getName());
private final Project myProject;
private final CrucibleReviewModel myReviewModel;
private final JBTable myReviewTable;
public CrucibleReviewModel getReviewModel() {
return myReviewModel;
}
public CruciblePanel(@NotNull final Project project) {
super(false);
myProject = project;
final JBSplitter splitter = new JBSplitter(false, 0.2f);
myReviewModel = new CrucibleReviewModel(project);
myReviewTable = new JBTable(myReviewModel);
myReviewTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myReviewTable.setStriped(true);
myReviewTable.setExpandableItemsEnabled(false);
final TableColumnModel columnModel = myReviewTable.getColumnModel(); | columnModel.getColumn(1).setCellRenderer(new DescriptionCellRenderer()); | 3 |
Beloumi/PeaFactory | src/peafactory/gui/TextTypePanel.java | [
"public final class PeaFactory {\n\n\t// i18n: \t\n\tprivate static String language; \n\tprivate static Locale currentLocale;\n\tprivate static Locale defaultLocale = Locale.getDefault();\n\tprivate static ResourceBundle languageBundle;\n\tpublic static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\t\n\tpriva... | import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.*;
import javax.swing.text.rtf.RTFEditorKit;
import cologne.eck.peafactory.PeaFactory;
import cologne.eck.peafactory.peagen.*;
import cologne.eck.peafactory.peas.editor_pea.EditorType;
import cologne.eck.peafactory.peas.note_pea.NotesType;
import cologne.eck.peafactory.tools.Converter;
import cologne.eck.peafactory.tools.ReadResources;
import cologne.eck.peafactory.tools.WriteResources;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ResourceBundle;
import javax.swing.*; | package cologne.eck.peafactory.gui;
/*
* Peafactory - Production of Password Encryption Archives
* Copyright (C) 2015 Axel von dem Bruch
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* See: http://www.gnu.org/licenses/gpl-2.0.html
* You should have received a copy of the GNU General Public License
* along with this library.
*/
/**
* Panel to display and write text for text based peas.
* Displayed in MainView.
*/
@SuppressWarnings("serial")
public class TextTypePanel extends JPanel implements ActionListener {
private static JTextArea area;
private ResourceBundle languageBundle;
private TextTypePanel(ResourceBundle _languageBundle) {
this.setLayout( new BoxLayout(this, BoxLayout.Y_AXIS));
languageBundle = _languageBundle;
String openedFileName = MainView.getOpenedFileName();
DataType dataType = DataType.getCurrentType();
JPanel areaPanel = new JPanel();
areaPanel.setLayout(new BoxLayout(areaPanel, BoxLayout.Y_AXIS));
JPanel areaLabelPanel = new JPanel();
areaLabelPanel.setLayout(new BoxLayout(areaLabelPanel, BoxLayout.X_AXIS));
JLabel areaLabel = new JLabel(languageBundle.getString("area_label"));//("text to encrypt: ");
areaLabel.setPreferredSize(new Dimension(300,30));
areaLabelPanel.add(areaLabel);
areaLabelPanel.add(Box.createHorizontalGlue());
areaPanel.add(areaLabelPanel);
area = new JTextArea(30, 20);
area.setDragEnabled(true);
area.setEditable(true);
area.setLineWrap(true);
area.setWrapStyleWord(true);
area.setToolTipText(languageBundle.getString("tooltip_textarea"));
if (openedFileName != null) {
if (openedFileName.endsWith("txt")) {
byte[] clearBytes = ReadResources.readExternFile(openedFileName);
if (clearBytes == null){
clearBytes = "empty file".getBytes(PeaFactory.getCharset());
}
displayText(new String( Converter.bytes2chars(clearBytes) ) );
} else if (openedFileName.endsWith("rtf")) {
Document doc = new DefaultStyledDocument();
// get text and display in text area:
RTFEditorKit kit = new RTFEditorKit();
FileInputStream in;
try {
in = new FileInputStream(openedFileName);
kit.read(in, doc, 0);
in.close();
} catch (FileNotFoundException e) {
System.err.println("TextTypePanel: " + e);
JOptionPane.showMessageDialog(this,
"File " + openedFileName + " not found...\n." + e,
"Error",
JOptionPane.ERROR_MESSAGE);
return;
} catch (IOException e){
System.err.println("TextTypePanel: " + e);
JOptionPane.showMessageDialog(this,
"reading the file " + openedFileName + " failed (IOException)\n,"
+ e,
"Error",
JOptionPane.ERROR_MESSAGE);
return;
} catch (BadLocationException e){
System.err.println("TextTypePanel: " + e);
JOptionPane.showMessageDialog(this,
"Bad Location of file " + openedFileName + ".\n." + e,
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
String text = doc.getText(0, doc.getLength() );
//System.out.println("text: " + text);
displayText(text);
} catch (BadLocationException e1) {
System.err.println("TextTypePanel: " + e1);
JOptionPane.showMessageDialog(this,
"Bad Location of text in file " + openedFileName + ".\n." + e1,
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
// modifications would not be saved, because document was set to EditorType
area.setEditable(false);
}
} else {
if (dataType.getData() != null) { // was set by open file
if (dataType instanceof NotesType) {
area.setText(new String(dataType.getData(), PeaFactory.getCharset()));
| } else if (dataType instanceof EditorType) { | 1 |
MindscapeHQ/raygun4android | provider/src/main/java/com/raygun/raygun4android/RaygunClient.java | [
"public class RaygunLogger {\n\n public static void d(String string) {\n if (string != null) {\n Timber.tag(RaygunSettings.LOGGING_TAG).d(string);\n }\n }\n\n public static void i(String string) {\n if (string != null) {\n Timber.tag(RaygunSettings.LOGGING_TAG).i(... | import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import com.raygun.raygun4android.logging.RaygunLogger;
import com.raygun.raygun4android.logging.TimberRaygunLoggerImplementation;
import com.raygun.raygun4android.messages.crashreporting.RaygunBreadcrumbMessage;
import com.raygun.raygun4android.messages.shared.RaygunUserInfo;
import com.raygun.raygun4android.utils.RaygunFileUtils;
import java.util.List;
import java.util.Map;
import java.util.UUID; | package com.raygun.raygun4android;
/**
* The official Raygun provider for Android. This is the main class that provides functionality for
* automatically sending exceptions to the Raygun service.
*
* You should call init() on the static RaygunClient instance, passing in the application, instead
* of instantiating this class.
*/
public class RaygunClient {
private static String apiKey;
private static String version;
private static String appContextIdentifier;
private static RaygunUserInfo userInfo;
// During initialisation, either application or applicationContext will be set.
private static Application application;
private static Context applicationContext;
private static boolean crashReportingEnabled = false;
private static boolean RUMEnabled = false;
/**
* Initializes the Raygun client. This expects that you have placed the API key in your
* AndroidManifest.xml, in a meta-data element.
*
* @param application The Android application
*/
public static void init(Application application) {
init(application, null, null);
}
/**
* Initializes the Raygun client with your Android application and your Raygun API key. The version
* transmitted will be the value of the versionName attribute in your manifest element.
*
* @param application The Android application
* @param apiKey An API key that belongs to a Raygun application created in your dashboard
*/
public static void init(Application application, String apiKey) {
init(application, apiKey, null);
}
/**
* Initializes the Raygun client with an Android application context, your Raygun API key and the
* version of your application.
*
* This method is intended to be used by 3rd-party libraries such as Raygun for React Native or
* Raygun for Flutter etc.
*
* @param applicationContext The Android applicationContext
* @param apiKey An API key that belongs to a Raygun application created in your dashboard
* @param version The version of your application, format x.x.x.x, where x is a positive integer.
*/
public static void init(Context applicationContext, String apiKey, String version) {
RaygunClient.applicationContext = applicationContext;
sharedSetup(apiKey, version);
}
/**
* Initializes the Raygun client with your Android application, your Raygun API key, and the
* version of your application
*
* @param application The Android application
* @param apiKey An API key that belongs to a Raygun application created in your dashboard
* @param version The version of your application, format x.x.x.x, where x is a positive integer.
*/
public static void init(Application application, String apiKey, String version) {
RaygunClient.application = application;
sharedSetup(apiKey, version);
}
private static void sharedSetup(String apiKey, String version) {
TimberRaygunLoggerImplementation.init();
| RaygunLogger.d("Configuring Raygun4Android (v" + RaygunSettings.RAYGUN_CLIENT_VERSION + ")"); | 0 |
lrtdc/light_drtc | src/main/java/org/light/rtc/admin/AdminNodeKafkaRun.java | [
"@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\r\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-03-16\")\r\npublic class TDssService {\r\n\r\n public interface Iface {\r\n\r\n public int addMqinfoToAdminQu(List<String> uLogs) throws org.apache.thrift.TEx... | import java.util.Timer;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.light.rtc.api.TDssService;
import org.light.rtc.base.StreamLogParser;
import org.light.rtc.mq.KafkaMqCollect;
import org.light.rtc.service.RtdcAdminService;
import org.light.rtc.timer.AdminNodeTimer;
import org.light.rtc.util.ConfigProperty;
import org.light.rtc.util.Constants; | package org.light.rtc.admin;
public class AdminNodeKafkaRun {
/**
* your self defending function for parsing your data stream logs
* @param slp
*/
public void setSteamParser(StreamLogParser slp){
AdminNodeTimer.setStreamLogParser(slp);
}
private class DataCollect implements Runnable{
@Override
public void run() {
KafkaMqCollect kmc = new KafkaMqCollect();
kmc.collectMq();
}
}
public void run(){
this.adminJobTImer();
new Thread(new DataCollect()).start();
RtdcAdminService rss = new RtdcAdminService();
TDssService.Processor<RtdcAdminService> tp = new TDssService.Processor<RtdcAdminService>(rss);
TServerTransport serverTransport = null;
try {
serverTransport = new TServerSocket(Constants.adminNodePort);
} catch (TTransportException e) {
e.printStackTrace();
}
TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(serverTransport);
tArgs.maxWorkerThreads(1000);
tArgs.minWorkerThreads(10);
tArgs.processor(tp);
TCompactProtocol.Factory portFactory = new TCompactProtocol.Factory();
tArgs.protocolFactory(portFactory);
TServer tServer = new TThreadPoolServer(tArgs); | System.out.println(ConfigProperty.getCurDateTime()+"......轻量级实时计算框架任务管理节点(通过Kafka整合CN)服务启动......"); | 5 |
elixsr/FwdPortForwardingApp | app/src/main/java/com/elixsr/portforwarder/ui/rules/EditRuleActivity.java | [
"public class FwdApplication extends MultiDexApplication {\n\n private static final String TAG = \"FwdApplication\";\n private Tracker mTracker;\n\n /**\n * Gets the default {@link Tracker} for this {@link Application}.\n *\n * @return tracker\n */\n synchronized public Tracker getDefaul... | import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.elixsr.core.common.widgets.SwitchBar;
import com.elixsr.portforwarder.FwdApplication;
import com.elixsr.portforwarder.R;
import com.elixsr.portforwarder.db.RuleContract;
import com.elixsr.portforwarder.models.RuleModel;
import com.elixsr.portforwarder.db.RuleDbHelper;
import com.elixsr.portforwarder.ui.MainActivity;
import com.elixsr.portforwarder.util.RuleHelper;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.firebase.analytics.FirebaseAnalytics; | /*
* Fwd: the port forwarding app
* Copyright (C) 2016 Elixsr Ltd
*
* 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 com.elixsr.portforwarder.ui.rules;
/**
* Created by Niall McShane on 02/03/2016.
*/
public class EditRuleActivity extends BaseRuleActivity {
private static final String TAG = "EditRuleActivity";
private static final String NO_RULE_ID_FOUND_LOG_MESSAGE = "No ID was supplied to EditRuleActivity";
private static final String NO_RULE_ID_FOUND_TOAST_MESSAGE = "Could not locate rule";
private static final String ACTION_DELETE = "Delete";
private static final String LABEL_DELETE_RULE = "Delete Rule";
private static final String LABEL_UPDATE_RULE = "Rule Updated";
private FirebaseAnalytics mFirebaseAnalytics;
private RuleModel ruleModel;
private long ruleModelId;
private SQLiteDatabase db;
private Tracker tracker;
private SwitchBar switchBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// If we can't locate the id, then we can't continue | if (!getIntent().getExtras().containsKey(RuleHelper.RULE_MODEL_ID)) { | 5 |
weiboad/fiery | server/src/main/java/org/weiboad/ragnar/server/search/IndexSearchSharderManager.java | [
"@Component\n@ConfigurationProperties(prefix = \"fiery\")\npublic class FieryConfig {\n\n private int keepdataday;\n\n private String dbpath;\n\n private String indexpath;\n\n private Boolean kafkaenable;\n\n private String kafkaserver;\n\n private String kafkagroupid;\n\n private String mailfr... | import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.weiboad.ragnar.server.config.FieryConfig;
import org.weiboad.ragnar.server.struct.MetaLog;
import org.weiboad.ragnar.server.struct.ResponseJson;
import org.weiboad.ragnar.server.util.DateTimeHelper;
import org.weiboad.ragnar.server.util.FileUtil;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap; | package org.weiboad.ragnar.server.search;
@Component
@Scope("singleton")
public class IndexSearchSharderManager {
private Logger log;
@Autowired
private FieryConfig fieryConfig;
//init
private ConcurrentHashMap<String, Analyzer> analyzerList = new ConcurrentHashMap<>();
//Directory
private ConcurrentHashMap<String, FSDirectory> directorList = new ConcurrentHashMap<>();
//reader
private ConcurrentHashMap<String, DirectoryReader> readerList = new ConcurrentHashMap<>();
private MultiReader allInOneReader;
//searcher
private IndexSearcher searcher;
//init flag
private int isinit = 0;
//group searcher
//private GroupingSearch groupsearch;
public IndexSearchSharderManager() {
log = LoggerFactory.getLogger(IndexSearchSharderManager.class);
}
public Map<String, Map<String, String>> getSearchIndexInfo() {
Map<String, Map<String, String>> result = new LinkedHashMap<>();
for (Map.Entry<String, DirectoryReader> e : readerList.entrySet()) {
String dbname = e.getKey();
DirectoryReader diskReader = e.getValue();
Map<String, String> indexInfo = new LinkedHashMap<>();
indexInfo.put("count", diskReader.numDocs() + "");
result.put(dbname, indexInfo);
}
return result;
}
public int getIndexedDocCount() {
if (allInOneReader != null) {
return allInOneReader.numDocs();
}
return 0;
}
public ResponseJson searchByQuery(Long timestamp, Query query, int start, long limit, Sort sort) {
String timeSharder = String.valueOf(DateTimeHelper.getTimesMorning(timestamp));
ResponseJson responeJson = new ResponseJson();
//ignore the out of date search
if (timestamp > DateTimeHelper.getBeforeDay(fieryConfig.getKeepdataday()) && timestamp <= DateTimeHelper.getCurrentTime()) {
//fixed the index not load
if (!readerList.containsKey(timeSharder)) {
log.info("index not loaded:" + timeSharder);
boolean loadRet = this.openIndex(timeSharder, fieryConfig.getIndexpath() + "/" + timeSharder);
if(!loadRet){
responeJson.setMsg( "error load index");
responeJson.setCode (232);
return responeJson;
}
}
| ArrayList<MetaLog> metalist = new ArrayList<MetaLog>(); | 1 |
jenkinsci/github-plugin | src/test/java/org/jenkinsci/plugins/github/webhook/WebhookManagerTest.java | [
"public class GitHubPushTrigger extends Trigger<Job<?, ?>> implements GitHubTrigger {\n\n @DataBoundConstructor\n public GitHubPushTrigger() {\n }\n\n /**\n * Called when a POST is made.\n */\n @Deprecated\n public void onPost() {\n onPost(GitHubTriggerEvent.create()\n ... | import com.cloudbees.jenkins.GitHubPushTrigger;
import com.cloudbees.jenkins.GitHubRepositoryName;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import hudson.model.FreeStyleProject;
import hudson.model.Item;
import hudson.plugins.git.GitSCM;
import org.jenkinsci.plugins.github.GitHubPlugin;
import org.jenkinsci.plugins.github.config.GitHubServerConfig;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.WithoutJenkins;
import org.kohsuke.github.GHEvent;
import org.kohsuke.github.GHHook;
import org.kohsuke.github.GHRepository;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Map;
import static com.google.common.collect.ImmutableList.copyOf;
import static com.google.common.collect.Lists.asList;
import static com.google.common.collect.Lists.newArrayList;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.jenkinsci.plugins.github.test.HookSecretHelper.storeSecretIn;
import static org.jenkinsci.plugins.github.webhook.WebhookManager.forHookUrl;
import static org.junit.Assert.assertThat;
import static org.kohsuke.github.GHEvent.CREATE;
import static org.kohsuke.github.GHEvent.PULL_REQUEST;
import static org.kohsuke.github.GHEvent.PUSH;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anySetOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; |
verify(manager, times(1)).serviceWebhookFor(HOOK_ENDPOINT);
verify(manager, never()).webhookFor(HOOK_ENDPOINT);
verify(manager, times(1)).fetchHooks();
}
@Test
@WithoutJenkins
public void shouldMatchAdminAccessWhenTrue() throws Exception {
when(repo.hasAdminAccess()).thenReturn(true);
assertThat("has admin access", manager.withAdminAccess().apply(repo), is(true));
}
@Test
@WithoutJenkins
public void shouldMatchAdminAccessWhenFalse() throws Exception {
when(repo.hasAdminAccess()).thenReturn(false);
assertThat("has no admin access", manager.withAdminAccess().apply(repo), is(false));
}
@Test
@WithoutJenkins
public void shouldMatchWebHook() {
when(repo.hasAdminAccess()).thenReturn(false);
GHHook hook = hook(HOOK_ENDPOINT, PUSH);
assertThat("webhook has web name and url prop", manager.webhookFor(HOOK_ENDPOINT).apply(hook), is(true));
}
@Test
@WithoutJenkins
public void shouldNotMatchOtherUrlWebHook() {
when(repo.hasAdminAccess()).thenReturn(false);
GHHook hook = hook(ANOTHER_HOOK_ENDPOINT, PUSH);
assertThat("webhook has web name and another url prop",
manager.webhookFor(HOOK_ENDPOINT).apply(hook), is(false));
}
@Test
public void shouldMergeEventsOnRegisterNewAndDeleteOldOnes() throws IOException {
doReturn(newArrayList(repo)).when(nonactive).resolve(any(Predicate.class));
when(repo.hasAdminAccess()).thenReturn(true);
Predicate<GHHook> del = spy(Predicate.class);
when(manager.deleteWebhook()).thenReturn(del);
GHHook hook = hook(HOOK_ENDPOINT, CREATE);
GHHook prhook = hook(HOOK_ENDPOINT, PULL_REQUEST);
when(repo.getHooks()).thenReturn(newArrayList(hook, prhook));
manager.createHookSubscribedTo(copyOf(newArrayList(PUSH))).apply(nonactive);
verify(del, times(2)).apply(any(GHHook.class));
verify(manager).createWebhook(HOOK_ENDPOINT, EnumSet.copyOf(newArrayList(CREATE, PULL_REQUEST, PUSH)));
}
@Test
public void shouldNotReplaceAlreadyRegisteredHook() throws IOException {
doReturn(newArrayList(repo)).when(nonactive).resolve(any(Predicate.class));
when(repo.hasAdminAccess()).thenReturn(true);
GHHook hook = hook(HOOK_ENDPOINT, PUSH);
when(repo.getHooks()).thenReturn(newArrayList(hook));
manager.createHookSubscribedTo(copyOf(newArrayList(PUSH))).apply(nonactive);
verify(manager, never()).deleteWebhook();
verify(manager, never()).createWebhook(any(URL.class), anySetOf(GHEvent.class));
}
@Test
@Issue( "JENKINS-62116" )
public void shouldNotReplaceAlreadyRegisteredHookWithMoreEvents() throws IOException {
doReturn(newArrayList(repo)).when(nonactive).resolve(any(Predicate.class));
when(repo.hasAdminAccess()).thenReturn(true);
GHHook hook = hook(HOOK_ENDPOINT, PUSH, CREATE);
when(repo.getHooks()).thenReturn(newArrayList(hook));
manager.createHookSubscribedTo(copyOf(newArrayList(PUSH))).apply(nonactive);
verify(manager, never()).deleteWebhook();
verify(manager, never()).createWebhook(any(URL.class), anySetOf(GHEvent.class));
}
@Test
public void shouldNotAddPushEventByDefaultForProjectWithoutTrigger() throws IOException {
FreeStyleProject project = jenkins.createFreeStyleProject();
project.setScm(GIT_SCM);
manager.registerFor((Item)project).run();
verify(manager, never()).createHookSubscribedTo(anyListOf(GHEvent.class));
}
@Test
public void shouldAddPushEventByDefault() throws IOException {
FreeStyleProject project = jenkins.createFreeStyleProject();
project.addTrigger(new GitHubPushTrigger());
project.setScm(GIT_SCM);
manager.registerFor((Item)project).run();
verify(manager).createHookSubscribedTo(newArrayList(PUSH));
}
@Test
public void shouldReturnNullOnGettingEmptyEventsListToSubscribe() throws IOException {
doReturn(newArrayList(repo)).when(active).resolve(any(Predicate.class));
when(repo.hasAdminAccess()).thenReturn(true);
assertThat("empty events list not allowed to be registered",
forHookUrl(HOOK_ENDPOINT)
.createHookSubscribedTo(Collections.<GHEvent>emptyList()).apply(active), nullValue());
}
@Test
public void shouldSelectOnlyHookManagedCreds() {
GitHubServerConfig conf = new GitHubServerConfig("");
conf.setManageHooks(false); | GitHubPlugin.configuration().getConfigs().add(conf); | 2 |
legobmw99/Allomancy | src/main/java/com/legobmw99/allomancy/modules/powers/PowersSetup.java | [
"public class ClientEventHandler {\n\n\n private final Minecraft mc = Minecraft.getInstance();\n\n private final Set<Entity> metal_entities = new HashSet<>();\n private final Set<MetalBlockBlob> metal_blobs = new HashSet<>();\n private final Set<Player> nearby_allomancers = new HashSet<>();\n\n priva... | import com.legobmw99.allomancy.modules.powers.client.ClientEventHandler;
import com.legobmw99.allomancy.modules.powers.client.PowersClientSetup;
import com.legobmw99.allomancy.modules.powers.command.AllomancyPowerCommand;
import com.legobmw99.allomancy.modules.powers.command.AllomancyPowerType;
import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability;
import net.minecraft.commands.synchronization.ArgumentTypes;
import net.minecraft.commands.synchronization.EmptyArgumentSerializer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; | package com.legobmw99.allomancy.modules.powers;
public class PowersSetup {
public static void clientInit(final FMLClientSetupEvent e) {
MinecraftForge.EVENT_BUS.register(new ClientEventHandler());
PowersClientSetup.initKeyBindings();
}
public static void registerCommands(final RegisterCommandsEvent e) { | AllomancyPowerCommand.register(e.getDispatcher()); | 2 |
tesseract4java/tesseract4java | ocrevalUAtion/src/main/java/eu/digitisation/langutils/TermFrequency.java | [
"public class WarningException extends Exception {\n private static final long serialVersionUID = 1L;\n\n /**\n * Default constructor\n * @param message\n */\n public WarningException(String message) {\n super(message);\n }\n}",
"public class Messages {\n\n // private static fina... | import eu.digitisation.input.SchemaLocationException;
import eu.digitisation.input.WarningException;
import eu.digitisation.log.Messages;
import eu.digitisation.math.Counter;
import eu.digitisation.text.CharFilter;
import eu.digitisation.text.StringNormalizer;
import eu.digitisation.text.Text;
import eu.digitisation.text.WordScanner;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | /*
* Copyright (C) 2013 Universidad de Alicante
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package eu.digitisation.langutils;
/**
* Compute term frequencies in a collection
*
* @author R.C.C
*/
public class TermFrequency extends Counter<String> {
private static final long serialVersionUID = 1L;
private CharFilter filter;
/**
* Default constructor
*/
public TermFrequency() {
filter = null;
}
/**
* Basic constructor
*
* @param filter a CharFilter implementing character equivalences
*/
public TermFrequency(CharFilter filter) {
this.filter = filter;
}
/**
* Add CharFilter
*
* @param file a CSV file with character equivalences
*/
public void addFilter(File file) {
if (filter == null) {
filter = new CharFilter(file);
} else {
filter.addFilter(file);
}
}
/**
* Extract words from a file
*
* @param dir the input file or directory
* @throws eu.digitisation.input.WarningException
* @throws eu.digitisation.input.SchemaLocationException
*/
public void add(File dir) throws WarningException, SchemaLocationException {
if (dir.isDirectory()) {
addFiles(dir.listFiles());
} else {
File[] files = {dir};
addFiles(files);
}
}
/**
* Extract words from a file
*
* @param file an input files
* @throws eu.digitisation.input.WarningException
* @throws eu.digitisation.input.SchemaLocationException
*/
public void addFile(File file) throws WarningException, SchemaLocationException {
try {
Text content = new Text(file); | WordScanner scanner = new WordScanner(content.toString(), | 5 |
doanduyhai/killrvideo-java | src/main/java/killrvideo/service/RatingsService.java | [
"public static final String mergeStackTrace(Throwable throwable) {\n StringJoiner joiner = new StringJoiner(\"\\n\\t\", \"\\n\", \"\\n\");\n joiner.add(throwable.getMessage());\n Arrays.asList(throwable.getStackTrace())\n .forEach(stackTraceElement -> joiner.add(stackTraceElement.toString()));\n\n ... | import static killrvideo.utils.ExceptionUtils.mergeStackTrace;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.dse.DseSession;
import com.datastax.driver.mapping.Mapper;
import com.datastax.driver.mapping.MappingManager;
import com.google.common.eventbus.EventBus;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import killrvideo.entity.Schema;
import killrvideo.entity.VideoRating;
import killrvideo.entity.VideoRatingByUser;
import killrvideo.events.CassandraMutationError;
import killrvideo.ratings.RatingsServiceGrpc.RatingsServiceImplBase;
import killrvideo.ratings.RatingsServiceOuterClass.GetRatingRequest;
import killrvideo.ratings.RatingsServiceOuterClass.GetRatingResponse;
import killrvideo.ratings.RatingsServiceOuterClass.GetUserRatingRequest;
import killrvideo.ratings.RatingsServiceOuterClass.GetUserRatingResponse;
import killrvideo.ratings.RatingsServiceOuterClass.RateVideoRequest;
import killrvideo.ratings.RatingsServiceOuterClass.RateVideoResponse;
import killrvideo.ratings.events.RatingsEvents.UserRatedVideo;
import killrvideo.utils.FutureUtils;
import killrvideo.utils.TypeConverter;
import killrvideo.validation.KillrVideoInputValidator; | package killrvideo.service;
@Service
//public class RatingsService extends AbstractRatingsService {
public class RatingsService extends RatingsServiceImplBase {
private static final Logger LOGGER = LoggerFactory.getLogger(RatingsService.class);
@Inject
MappingManager manager;
@Inject
Mapper<VideoRating> videoRatingMapper;
@Inject
Mapper<VideoRatingByUser> videoRatingByUserMapper;
@Inject
DseSession dseSession;
@Inject
EventBus eventBus;
@Inject
KillrVideoInputValidator validator;
private String videoRatingsTableName;
private PreparedStatement rateVideo_updateRatingPrepared;
@PostConstruct
public void init(){
videoRatingsTableName = videoRatingMapper.getTableMetadata().getName();
rateVideo_updateRatingPrepared = dseSession.prepare(
QueryBuilder
.update(Schema.KEYSPACE, videoRatingsTableName)
.with(QueryBuilder.incr("rating_counter"))
.and(QueryBuilder.incr("rating_total", QueryBuilder.bindMarker()))
.where(QueryBuilder.eq("videoid", QueryBuilder.bindMarker()))
).setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
}
@Override
public void rateVideo(RateVideoRequest request, StreamObserver<RateVideoResponse> responseObserver) {
LOGGER.debug("-----Start rate video request-----");
if (!validator.isValid(request, responseObserver)) {
return;
}
final Instant time = Instant.now();
final UUID videoId = UUID.fromString(request.getVideoId().getValue());
final UUID userId = UUID.fromString(request.getUserId().getValue());
final Integer rating = request.getRating();
/**
* Increment rating_counter by 1
* Increment rating_total by amount of rating
*/
BoundStatement counterUpdateStatement = rateVideo_updateRatingPrepared.bind()
.setLong("rating_total", rating)
.setUUID("videoid", videoId);
/**
* Here, instead of using logged batch, we can insert both mutations asynchronously
* In case of error, we log the request into the mutation error log for replay later
* by another micro-service
*
* Something else to notice is I am using both a prepared statement with executeAsync()
* and a call to the mapper's saveAsync() methods. I could have kept things uniform
* and stuck with both prepared/bind statements, but I wanted to illustrate the combination
* and use the mapper for the second statement because it is a simple save operation with no
* options, increments, etc... A key point is in the case you see below both statements are actually
* prepared, the first one I did manually in a more traditional sense and in the second one the
* mapper will prepare the statement for you automagically.
*/
CompletableFuture
.allOf(
FutureUtils.buildCompletableFuture(dseSession.executeAsync(counterUpdateStatement)),
FutureUtils.buildCompletableFuture(videoRatingByUserMapper
.saveAsync(new VideoRatingByUser(videoId, userId, rating)))
)
.handle((rs, ex) -> {
if (ex == null) {
/**
* This eventBus.post() call will make its way to the SuggestedVideoService
* class to handle adding data to our graph recommendation engine
*/
eventBus.post(UserRatedVideo.newBuilder()
.setVideoId(request.getVideoId())
.setUserId(request.getUserId())
.setRating(request.getRating())
.setRatingTimestamp(TypeConverter.instantToTimeStamp(time))
.build());
responseObserver.onNext(RateVideoResponse.newBuilder().build());
responseObserver.onCompleted();
LOGGER.debug("End rate video request");
} else { | LOGGER.error("Exception rating video : " + mergeStackTrace(ex)); | 0 |
Kickflip/kickflip-android-sdk | sdk/src/main/java/io/kickflip/sdk/fragment/GlassBroadcastFragment.java | [
"public class Kickflip {\n public static final String TAG = \"Kickflip\";\n private static Context sContext;\n private static String sClientKey;\n private static String sClientSecret;\n\n private static KickflipApiClient sKickflip;\n\n // Per-Stream settings\n private static SessionConfig sSess... | import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import com.google.common.eventbus.Subscribe;
import java.io.IOException;
import io.kickflip.sdk.Kickflip;
import io.kickflip.sdk.R;
import io.kickflip.sdk.av.Broadcaster;
import io.kickflip.sdk.event.BroadcastIsBufferingEvent;
import io.kickflip.sdk.event.BroadcastIsLiveEvent;
import io.kickflip.sdk.view.GLCameraEncoderView; | package io.kickflip.sdk.fragment;
/**
* This is a drop-in broadcasting fragment.
* Currently, only one BroadcastFragment may be instantiated at a time by
* design of {@link io.kickflip.sdk.av.Broadcaster}.
*/
public class GlassBroadcastFragment extends Fragment {
private static final String TAG = "GlassBroadcastFragment";
private static final boolean VERBOSE = false;
private static GlassBroadcastFragment mFragment;
private static Broadcaster mBroadcaster; // Make static to survive Fragment re-creation | private GLCameraEncoderView mCameraView; | 4 |
TeamAmeriFrance/Guide-API | src/main/java/amerifrance/guideapi/api/IPage.java | [
"public class Book {\n\n private static final String GUITEXLOC = \"guideapi:textures/gui/\";\n\n private List<CategoryAbstract> categories = Lists.newArrayList();\n private String title = \"item.GuideBook.name\";\n private String header = title;\n private String itemName = title;\n private String ... | import amerifrance.guideapi.api.impl.Book;
import amerifrance.guideapi.api.impl.abstraction.CategoryAbstract;
import amerifrance.guideapi.api.impl.abstraction.EntryAbstract;
import amerifrance.guideapi.gui.GuiBase;
import amerifrance.guideapi.gui.GuiEntry;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | package amerifrance.guideapi.api;
public interface IPage {
@SideOnly(Side.CLIENT)
void draw(Book book, CategoryAbstract category, EntryAbstract entry, int guiLeft, int guiTop, int mouseX, int mouseY, GuiBase guiBase, FontRenderer fontRendererObj);
@SideOnly(Side.CLIENT)
void drawExtras(Book book, CategoryAbstract category, EntryAbstract entry, int guiLeft, int guiTop, int mouseX, int mouseY, GuiBase guiBase, FontRenderer fontRendererObj);
| boolean canSee(Book book, CategoryAbstract category, EntryAbstract entry, EntityPlayer player, ItemStack bookStack, GuiEntry guiEntry); | 4 |
iLexiconn/Magister.java | src/main/java/net/ilexiconn/magister/handler/ELOHandler.java | [
"public class Magister {\n public static final String VERSION = \"0.1.2\";\n\n public static final int SESSION_TIMEOUT = 1200000;\n\n public Gson gson = new GsonBuilder()\n .registerTypeAdapter(Profile.class, new ProfileAdapter())\n .registerTypeAdapter(Study[].class, new StudyAdapter... | import net.ilexiconn.magister.container.SingleStudyGuide;
import net.ilexiconn.magister.container.Source;
import net.ilexiconn.magister.container.StudyGuide;
import net.ilexiconn.magister.util.GsonUtil;
import net.ilexiconn.magister.util.HttpUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import net.ilexiconn.magister.Magister;
import net.ilexiconn.magister.adapter.ArrayAdapter;
import net.ilexiconn.magister.adapter.SingleStudyGuideAdapter; | /*
* Copyright (c) 2015 iLexiconn
*
* 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 net.ilexiconn.magister.handler;
public class ELOHandler implements IHandler {
public Gson gson; | private Magister magister; | 0 |
michelelacorte/SwipeableCard | app/src/main/java/it/michelelacorte/exampleswipeablecard/MainActivity.java | [
"@SuppressWarnings(\"unused\")\npublic class CustomCardAnimation {\n private Context mContext;\n private CardView mCardView;\n private int mStartCardPosition;\n private long mDuration = 500;\n\n /**\n * Public constructor for set-up animation\n * @param context Context\n * @param card Car... | import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.method.LinkMovementMethod;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import it.michelelacorte.swipeablecard.CustomCardAnimation;
import it.michelelacorte.swipeablecard.OptionView;
import it.michelelacorte.swipeablecard.OptionViewAdditional;
import it.michelelacorte.swipeablecard.SwipeableCard;
import it.michelelacorte.swipeablecard.SwipeableCardAdapter; | .setOnClickListenerIconButton(clickIconButton1, clickIconButton2)
.build())
.build();
final OptionView dismissableSwipe = new OptionView.Builder()
.normalCard()
.image(R.drawable.image)
.title("Dismissable Card")
.menuItem(R.menu.menu_main)
.setSwipeToDismiss(true)
.toolbarListener(toolbarListener)
.setAdditionalItem(new OptionViewAdditional.Builder()
.textButton("SHARE", "LEARN MORE")
.textColorButton(R.color.colorPrimary)
.textSize(15f)
.setOnClickListenerTextButton(clickTextButton, clickTextButton)
.build())
.build();
final OptionView mapSwipeSingleMarker = new OptionView.Builder().mapsCard()
.title("Maps Card")
.setLocation(44.4937615, 11.3430542, "MyMarker")
.setZoom(10f)
.withStreetName(true)
.menuItem(R.menu.menu_main)
.toolbarListener(toolbarListener)
.build();
final OptionView mapSwipeMultipleMarker = new OptionView.Builder().mapsCard()
.title("Maps Card")
.setLocation(new LatLng(44.48, 11.33), new LatLng(43.45, 11.32), new LatLng(45.70, 10.11))
.menuItem(R.menu.menu_main)
.toolbarListener(toolbarListener)
.build();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cardOther = (CardView) findViewById(R.id.cardOther);
swipeableCard = (SwipeableCard) findViewById(R.id.swipeCard);
rv = (RecyclerView) findViewById(R.id.rv);
singleMarker = (RadioButton) findViewById(R.id.singleMarker);
multipleMarker = (RadioButton) findViewById(R.id.multipleMarker);
settedCard = (RadioButton) findViewById(R.id.settedCard);
creationCard = (RadioButton) findViewById(R.id.creationCard);
radioGroup = (RelativeLayout) findViewById(R.id.radioGroup);
radioGroupCreditCard = (RelativeLayout) findViewById(R.id.radioGroupCreditCard);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.SingleSwipe:
/**
* Example of Single Swipeable Card.
*/
radioGroupCreditCard.setVisibility(View.GONE);
radioGroup.setVisibility(View.GONE);
rv.setVisibility(View.GONE);
cardOther.setVisibility(View.GONE);
swipeableCard.init(getApplicationContext(), singleSwipe);
swipeableCard.setVisibility(View.VISIBLE);
drawerLayout.closeDrawers();
break;
case R.id.CreditCard:
radioGroup.setVisibility(View.GONE);
radioGroupCreditCard.setVisibility(View.VISIBLE);
rv.setVisibility(View.GONE);
cardOther.setVisibility(View.GONE);
creationCard.setChecked(false);
settedCard.setChecked(true);
swipeableCard.init(getApplicationContext(), creditCardSetted);
swipeableCard.setVisibility(View.VISIBLE);
settedCard.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
swipeableCard.setVisibility(View.GONE);
if (settedCard.isChecked()) {
creationCard.setChecked(false);
swipeableCard.init(getApplicationContext(), creditCardSetted);
swipeableCard.setVisibility(View.VISIBLE);
}
}
});
creationCard.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
swipeableCard.setVisibility(View.GONE);
if (creationCard.isChecked()) {
settedCard.setChecked(false);
swipeableCard.init(getApplicationContext(), creditCardCreation);
swipeableCard.setVisibility(View.VISIBLE);
}
}
});
drawerLayout.closeDrawers();
break;
case R.id.SingleSwipeNotAutoAnimation:
/**
* Example of Single Swipeable Card with Swipe Gesture.
*/
radioGroupCreditCard.setVisibility(View.GONE);
radioGroup.setVisibility(View.GONE);
rv.setVisibility(View.GONE);
cardOther.setVisibility(View.GONE);
swipeableCard.init(getApplicationContext(), singleSwipeNotAutoAnimation);
swipeableCard.setVisibility(View.VISIBLE);
drawerLayout.closeDrawers();
break;
case R.id.OtherSwipe:
/**
* Example of Other Card Layout.
*/
radioGroupCreditCard.setVisibility(View.GONE);
radioGroup.setVisibility(View.GONE);
rv.setVisibility(View.GONE);
swipeableCard.setVisibility(View.GONE);
cardOther.setVisibility(View.VISIBLE); | final CustomCardAnimation cardAnim = new CustomCardAnimation(getApplicationContext(), cardOther, 200); | 0 |
adiyoss/StructED | src/com/structed/models/algorithms/ProbitLoss.java | [
"public class Consts {\n\n // GENERALS\n\tpublic static final String SPACE = \" \";\n public static final String TAB = \"\\t\";\n public static final String COMMA_NOTE = \",\";\n\tpublic static final String CLASSIFICATION_SPLITTER = \"-\";\n\tpublic static final String COLON_SPLITTER = \":\";\n public s... | import com.structed.models.ClassifierData;
import com.structed.constants.ErrorConstants;
import com.structed.data.entities.Example;
import com.structed.data.entities.Vector;
import com.structed.data.Logger;
import com.structed.utils.MathHelpers;
import java.util.ArrayList;
import java.util.Random;
import com.structed.constants.Consts; | /*
* The MIT License (MIT)
*
* StructED - Machine Learning Package for Structured Prediction
*
* Copyright (c) 2015 Yossi Adi, E-Mail: yossiadidrum@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.structed.models.algorithms;
/**
* Probit Loss Algorithm
* http://cs.haifa.ac.il/~tamir/papers/KeshetMcHa10.pdf
*/
public class ProbitLoss implements IUpdateRule {
//data members
double lambda;
double eta;
double numOfIteration; //indicates the number of iterations
double noiseAllVector; //indicates whether to noise all the weights vector or just one random element from it
double mean; //indicates the mean to the noise to be generated
double stDev; //indicates the standard deviation to the noise to be generated
@Override
public void init(ArrayList<Double> args) {
if(args.size() != Consts.PL_PARAMS_SIZE){
Logger.error(ErrorConstants.UPDATE_ARGUMENTS_ERROR);
return;
}
//initialize the parameters
this.eta = args.get(0);
this.lambda = args.get(1);
this.numOfIteration = args.get(2);
this.noiseAllVector = args.get(3);
this.mean = args.get(4);
this.stDev = args.get(5);
}
/**
* Implementation of the update rule
* @param currentWeights - the current weights
* @param example - a single example
* @param classifierData - all the additional data that needed such as: loss function, inference, etc.
* @return the new set of weights
*/
@Override
//eta would be at the first cell
//lambda would be at the second cell
//the number of iteration that we'll go and generate epsilon | public Vector update(Vector currentWeights, Example example, ClassifierData classifierData) { | 3 |
shibing624/crf-seg | src/main/java/org/xm/xmnlp/seg/CRFSegment.java | [
"public class Xmnlp {\n /**\n * 日志组件\n */\n private static Logger logger = LogManager.getLogger();\n\n public static final class Config {\n /**\n * 默认关闭调试\n */\n public static boolean DEBUG = false;\n /**\n * 字符类型对应表\n */\n public static S... | import org.xm.xmnlp.Xmnlp;
import org.xm.xmnlp.dictionary.other.CharTable;
import org.xm.xmnlp.model.crf.CRFSegmentModel;
import org.xm.xmnlp.model.crf.Table;
import org.xm.xmnlp.seg.domain.Nature;
import org.xm.xmnlp.seg.domain.Term;
import org.xm.xmnlp.seg.domain.Vertex;
import org.xm.xmnlp.util.CharacterHelper;
import java.util.*; | package org.xm.xmnlp.seg;
/**
* 基于CRF的分词器
*
* @author XuMing
*/
public class CRFSegment extends Segment {
@Override
protected List<Term> segSentence(char[] sentence) {
if (sentence.length == 0) return Collections.emptyList();
char[] sentenceConverted = CharTable.convert(sentence); | Table table = new Table(); | 3 |
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")))
).matches(request)
);
}
private static Stream<Arguments> queryProvider() {
return Stream.of(
arguments(new MockClientRequest().query("name", "alpha", "blah"), true),
arguments(new MockClientRequest().query("name", "alpha"), false),
arguments(new MockClientRequest(), false)
);
}
@ParameterizedTest @DisplayName("param") @MethodSource("paramProvider")
void params(final MockClientRequest request, final boolean result) {
assertEquals(
result,
RequestMatcher.param(
"email",
stringIterableMatcher(List.of(containsString("@goomail.com")))
).matches(request)
);
}
private static Stream<Arguments> paramProvider() {
final var factory = new Function<Map<String, Deque<String>>, MockClientRequest>() {
@Override public MockClientRequest apply(Map<String, Deque<String>> map) {
final var mcr = new MockClientRequest();
mcr.setBodyParameters(map);
return mcr;
}
};
return Stream.of(
arguments(new MockClientRequest(), false),
arguments(factory.apply(Map.of(
"email", new ArrayDeque<>(List.of("foo@goomail.com")),
"spam", new ArrayDeque<>(List.of("n"))
)), true),
arguments(factory.apply(Map.of(
"spam", new ArrayDeque<>(List.of("n"))
)), false)
);
}
@ParameterizedTest @DisplayName("cookie") @MethodSource("cookieProvider")
void cookie(final MockClientRequest request, final boolean result) {
assertEquals(result, RequestMatcher.cookie("id", new CookieMatcher().value(equalTo("asdf89s7g"))).matches(request));
}
private static Stream<Arguments> cookieProvider() {
return Stream.of(
arguments(new MockClientRequest().cookie("id", "asdf89s7g"), true),
arguments(new MockClientRequest().cookie("id", "assdfsdf"), false),
arguments(new MockClientRequest(), false)
);
}
@ParameterizedTest @DisplayName("body") @MethodSource("bodyProvider")
void body(final MockClientRequest request, final boolean result) {
| RequestDecoders decoders = RequestDecoders.decoders(d -> {
| 3 |
maruohon/worldutils | src/main/java/fi/dy/masa/worldutils/command/SubCommandBlockReplacePairs.java | [
"@Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.MOD_VERSION, certificateFingerprint = Reference.FINGERPRINT,\n guiFactory = \"fi.dy.masa.worldutils.config.WorldUtilsGuiFactory\",\n updateJSON = \"https://raw.githubusercontent.com/maruohon/worldutils/master/update.json\",\n ac... | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import fi.dy.masa.worldutils.WorldUtils;
import fi.dy.masa.worldutils.data.BlockTools;
import fi.dy.masa.worldutils.data.BlockTools.LoadedType;
import fi.dy.masa.worldutils.event.tasks.TaskScheduler;
import fi.dy.masa.worldutils.event.tasks.TaskWorldProcessor;
import fi.dy.masa.worldutils.util.BlockData;
import fi.dy.masa.worldutils.util.BlockUtils; | package fi.dy.masa.worldutils.command;
public class SubCommandBlockReplacePairs extends SubCommand
{
private static List<Pair<String, String>> blockPairs = new ArrayList<Pair<String, String>>();
private String preparedFrom = EMPTY_STRING;
private String preparedTo = EMPTY_STRING;
public SubCommandBlockReplacePairs(CommandWorldUtils baseCommand)
{
super(baseCommand);
this.subSubCommands.add("add");
this.subSubCommands.add("add-prepared");
this.subSubCommands.add("clear");
this.subSubCommands.add("execute-all-chunks");
this.subSubCommands.add("execute-loaded-chunks");
this.subSubCommands.add("execute-unloaded-chunks");
this.subSubCommands.add("list");
this.subSubCommands.add("prepare-from");
this.subSubCommands.add("prepare-to");
this.subSubCommands.add("remove");
this.subSubCommands.add("remove-with-spaces");
this.subSubCommands.add("stoptask");
}
@Override
public String getName()
{
return "blockreplacepairs";
}
@Override
public void printHelpGeneric(ICommandSender sender)
{
this.sendMessage(sender, "worldutils.commands.help.generic.runhelpforallcommands", this.getUsageStringCommon() + " help");
}
@Override
public void printFullHelp(ICommandSender sender, String[] args)
{
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " add <block1 | id1>[@meta1] <block2 | id2>[@meta2] Ex: minecraft:ice minecraft:wool@5"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " add <block1[prop1=val1,prop2=val2]> <block2[prop1=val1,prop2=val2]> Ex: minecraft:stone[variant=granite]"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " add-prepared (adds the prepared space-containing names)"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " clear"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " execute-all-chunks [dimension id]"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " execute-loaded-chunks [dimension id]"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " execute-unloaded-chunks [dimension id]"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " list"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " prepare-from <block specifier containing spaces>"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " prepare-to <block specifier containing spaces>"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " remove <block-from> [block-from] ..."));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " remove-with-spaces <block-from>"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " stoptask"));
}
@Override
protected List<String> getTabCompletionsSub(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
if (args.length < 1)
{
return Collections.emptyList();
}
String cmd = args[0];
args = CommandWorldUtils.dropFirstStrings(args, 1);
if (cmd.equals("add") || cmd.equals("prepare-from") || cmd.equals("prepare-to"))
{ | return CommandBase.getListOfStringsMatchingLastWord(args, BlockUtils.getAllBlockNames()); | 6 |
zetbaitsu/CodePolitan | app/src/main/java/id/zelory/codepolitan/ui/adapter/NewsAdapter.java | [
"public abstract class BenihHeaderAdapter<Data, ViewHolder extends BenihItemViewHolder<Data>,\n Header extends BenihHeaderViewHolder> extends\n BenihRecyclerAdapter<Data, BenihItemViewHolder>\n{\n protected static final int TYPE_HEADER = 0;\n protected static final int TYPE_ITEM = 1;\n protec... | import android.content.Context;
import android.os.Bundle;
import android.view.ViewGroup;
import id.zelory.benih.adapter.BenihHeaderAdapter;
import id.zelory.benih.adapter.viewholder.BenihItemViewHolder;
import id.zelory.codepolitan.R;
import id.zelory.codepolitan.data.model.Article;
import id.zelory.codepolitan.ui.adapter.viewholder.NewsHeaderViewHolder;
import id.zelory.codepolitan.ui.adapter.viewholder.NewsItemViewHolder;
import id.zelory.codepolitan.ui.adapter.viewholder.SearchFooterViewHolder; | /*
* Copyright (c) 2015 Zelory.
*
* 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 id.zelory.codepolitan.ui.adapter;
/**
* Created on : July 28, 2015
* Author : zetbaitsu
* Name : Zetra
* Email : zetra@mail.ugm.ac.id
* GitHub : https://github.com/zetbaitsu
* LinkedIn : https://id.linkedin.com/in/zetbaitsu
*/
public class NewsAdapter extends
BenihHeaderAdapter<Article, BenihItemViewHolder<Article>, NewsHeaderViewHolder>
{
private final static int TYPE_BIG = 2;
private final static int TYPE_MINI = 3;
private final static int TYPE_FOOTER = 4;
public NewsAdapter(Context context, Bundle bundle)
{
super(context, bundle);
}
@Override
protected int getHeaderResourceLayout()
{
return R.layout.list_header_news;
}
@Override
protected int getItemResourceLayout(int viewType)
{
switch (viewType)
{
case TYPE_BIG:
return R.layout.list_item_news_big;
case TYPE_FOOTER:
return R.layout.list_footer_search;
default:
return R.layout.list_item_news_mini;
}
}
@Override
protected NewsHeaderViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup, int viewType)
{
return new NewsHeaderViewHolder(getView(viewGroup, viewType), bundle);
}
@Override
public BenihItemViewHolder<Article> onCreateItemViewHolder(ViewGroup viewGroup, int viewType)
{
switch (viewType)
{
case TYPE_FOOTER: | return new SearchFooterViewHolder(getView(viewGroup, viewType), itemClickListener, longItemClickListener); | 5 |
alphadev-net/drive-mount | app/src/main/java/net/alphadev/usbstorage/DocumentProviderImpl.java | [
"public enum FileAttribute {\n FILESIZE,\n LAST_MODIFIED\n}",
"public interface FileSystemProvider {\n /**\n * Returs true if, and only if, the item represented by the given Path is a directory.\n *\n * @param path Path to check\n * @return true if is directory\n */\n boolean isDir... | import android.database.Cursor;
import android.database.MatrixCursor;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.provider.DocumentsContract.Document;
import android.provider.DocumentsContract.Root;
import android.provider.DocumentsProvider;
import android.util.Log;
import net.alphadev.usbstorage.api.filesystem.FileAttribute;
import net.alphadev.usbstorage.api.filesystem.FileSystemProvider;
import net.alphadev.usbstorage.api.filesystem.Path;
import net.alphadev.usbstorage.api.filesystem.StorageDevice;
import net.alphadev.usbstorage.util.ParcelFileDescriptorUtil;
import org.apache.tika.Tika;
import org.apache.tika.config.TikaConfig;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat; | /**
* Copyright © 2014-2015 Jan Seeger
*
* 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.alphadev.usbstorage;
public class DocumentProviderImpl extends DocumentsProvider {
private static final String[] DEFAULT_ROOT_PROJECTION = new String[]{
Root.COLUMN_ROOT_ID, Root.COLUMN_FLAGS, Root.COLUMN_ICON, Root.COLUMN_TITLE,
Root.COLUMN_DOCUMENT_ID, Root.COLUMN_AVAILABLE_BYTES, Root.COLUMN_SUMMARY
};
private static final String[] DEFAULT_DOCUMENT_PROJECTION = new String[]{
Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE, Document.COLUMN_DISPLAY_NAME,
Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE,
};
private StorageManager mStorageManager;
private static String[] resolveRootProjection(String[] projection) {
return projection != null ? projection : DEFAULT_ROOT_PROJECTION;
}
private static String[] resolveDocumentProjection(String[] projection) {
return projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION;
}
/**
* http://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc
*/
private static String readableFileSize(long size) {
if (size <= 0) {
return "0B";
}
final String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
final int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
final float roundedSize = (float) (size / Math.pow(1024, digitGroups));
return new DecimalFormat("#,##0.#").format(roundedSize) + " " + units[digitGroups];
}
@Override
public boolean onCreate() {
mStorageManager = new StorageManager(getContext());
new DeviceManager(getContext(), mStorageManager);
return true;
}
@Override
public Cursor queryRoots(final String[] requestedProjection) throws FileNotFoundException {
final String[] projection = resolveRootProjection(requestedProjection);
final MatrixCursor roots = new MatrixCursor(projection);
for (StorageDevice device : mStorageManager.getMounts()) {
createDevice(roots.newRow(), device, projection);
}
return roots;
}
private void createDevice(MatrixCursor.RowBuilder row, StorageDevice device,
String[] projection) {
for (String column : projection) {
switch (column) {
case Root.COLUMN_ROOT_ID:
row.add(Root.COLUMN_ROOT_ID, device.getId());
break;
case Root.COLUMN_DOCUMENT_ID:
row.add(Root.COLUMN_DOCUMENT_ID, device.getId());
break;
case Root.COLUMN_TITLE:
row.add(Root.COLUMN_TITLE, device.getName());
break;
case Root.COLUMN_ICON:
row.add(Root.COLUMN_ICON, R.drawable.drive_icon);
break;
case Root.COLUMN_SUMMARY:
final String sizeUnit = readableFileSize(device.getUnallocatedSpace());
final String summary = getContext().getString(R.string.free_space, sizeUnit);
row.add(Root.COLUMN_SUMMARY, summary);
break;
case Root.COLUMN_AVAILABLE_BYTES:
row.add(Root.COLUMN_AVAILABLE_BYTES, device.getUnallocatedSpace());
break;
case Root.COLUMN_FLAGS:
int flags = 0;
if (!device.isReadOnly()) {
flags |= Root.FLAG_SUPPORTS_CREATE;
}
row.add(Root.COLUMN_FLAGS, flags);
break;
default:
Log.w("Drive Mount", "Couldn't satisfy " + column + " column.");
}
}
}
@Override
public Cursor queryDocument(String documentId,
final String[] requestedProjection) throws FileNotFoundException {
final String[] projection = resolveDocumentProjection(requestedProjection);
final MatrixCursor result = new MatrixCursor(projection);
addEntry(result, new Path(documentId), projection);
return result;
}
@Override
public Cursor queryChildDocuments(String parentDocumentId, final String[] requestedProjection,
String sortOrder) throws FileNotFoundException {
final String[] projection = resolveDocumentProjection(requestedProjection);
final MatrixCursor result = new MatrixCursor(projection);
final Path parent = new Path(parentDocumentId);
final FileSystemProvider provider = getProvider(parent);
for (Path child : provider.getEntries(parent)) {
addEntry(result, child, projection);
}
return result;
}
@Override
public ParcelFileDescriptor openDocument(final String documentId, final String mode,
CancellationSignal signal) throws FileNotFoundException {
try {
final Path path = new Path(documentId);
final InputStream inputStream = getProvider(path)
.openDocument(path).readDocument();
| return ParcelFileDescriptorUtil.pipeFrom(inputStream); | 4 |
hoijui/JavaOSC | modules/core/src/main/java/com/illposed/osc/argument/handler/StringArgumentHandler.java | [
"public interface BytesReceiver {\n\n\t/**\n\t * Relative <i>put</i> method <i>(optional operation)</i>.\n\t *\n\t * <p> Writes the given byte into this buffer at the current\n\t * position, and then increments the position. </p>\n\t *\n\t * @param data\n\t * The byte to be written\n\t *\n\t * @... | import com.illposed.osc.BytesReceiver;
import com.illposed.osc.OSCParseException;
import com.illposed.osc.OSCParser;
import com.illposed.osc.OSCSerializer;
import com.illposed.osc.argument.ArgumentHandler;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.Map; | // SPDX-FileCopyrightText: 2015-2017 C. Ramakrishnan / Illposed Software
// SPDX-FileCopyrightText: 2021 Robin Vobruba <hoijui.quaero@gmail.com>
//
// SPDX-License-Identifier: BSD-3-Clause
package com.illposed.osc.argument.handler;
/**
* Parses and serializes an OSC string type.
*/
public class StringArgumentHandler implements ArgumentHandler<String>, Cloneable {
// Public API
@SuppressWarnings("WeakerAccess")
public static final char DEFAULT_IDENTIFIER = 's';
public static final String PROP_NAME_CHARSET = "charset";
private Charset charset;
// Public API
@SuppressWarnings("WeakerAccess")
public StringArgumentHandler(final Charset charset) {
this.charset = charset;
}
// Public API
@SuppressWarnings("WeakerAccess")
public StringArgumentHandler() {
this(Charset.defaultCharset());
}
// Public API
/**
* Returns the character-set used to encode and decode string arguments.
* @return the currently used character-encoding-set
*/
@SuppressWarnings("unused")
public Charset getCharset() {
return charset;
}
// Public API
/**
* Sets the character-set used to encode and decode string arguments.
* @param charset the new character-encoding-set
*/
@SuppressWarnings("WeakerAccess")
public void setCharset(final Charset charset) {
this.charset = charset;
}
@Override
public char getDefaultIdentifier() {
return DEFAULT_IDENTIFIER;
}
@Override
public Class<String> getJavaClass() {
return String.class;
}
@Override
public void setProperties(final Map<String, Object> properties) {
final Charset newCharset = (Charset) properties.get(PROP_NAME_CHARSET);
if (newCharset != null) {
setCharset(newCharset);
}
}
@Override
public boolean isMarkerOnly() {
return false;
}
@Override
@SuppressWarnings("unchecked")
public StringArgumentHandler clone() throws CloneNotSupportedException {
return (StringArgumentHandler) super.clone();
}
/**
* Get the length of the string currently in the byte stream.
*/
private int lengthOfCurrentString(final ByteBuffer rawInput) {
int len = 0;
while (rawInput.get(rawInput.position() + len) != 0) {
len++;
}
return len;
}
@Override
public String parse(final ByteBuffer input) throws OSCParseException {
final int strLen = lengthOfCurrentString(input);
final ByteBuffer strBuffer = input.slice();
((Buffer)strBuffer).limit(strLen);
final String res;
try {
res = charset.newDecoder().decode(strBuffer).toString();
} catch (final CharacterCodingException ex) {
throw new OSCParseException(
"Failed decoding a string argument", ex, input
);
}
((Buffer)input).position(input.position() + strLen);
// because strings are always padded with at least one zero,
// as their length is not given in advance, as is the case with blobs,
// we skip over the terminating zero byte (position++)
input.get();
OSCParser.align(input);
return res;
}
@Override
public void serialize(final BytesReceiver output, final String value) {
final byte[] stringBytes = value.getBytes(charset);
output.put(stringBytes); | OSCSerializer.terminateAndAlign(output); | 3 |
raffaeleguidi/DirectMemory | DirectMemory-Cache/src/main/java/org/directmemory/cache/Cache.java | [
"public class Every extends In {\r\n\r\n\tpublic Every(double measure) {\r\n\t\tsuper(measure);\r\n\t}\r\n\r\n}\r",
"public class Ram extends Sizing {\r\n\r\n}\r",
"public class MemoryManager {\r\n\tprivate static Logger logger = LoggerFactory.getLogger(MemoryManager.class);\r\n\tpublic static List<OffHeapMemor... | import java.io.EOFException;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentMap;
import org.directmemory.measures.Every;
import org.directmemory.measures.Ram;
import org.directmemory.memory.MemoryManager;
import org.directmemory.memory.OffHeapMemoryBuffer;
import org.directmemory.memory.Pointer;
import org.directmemory.misc.Format;
import org.directmemory.serialization.ProtoStuffSerializerV1;
import org.directmemory.serialization.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.MapMaker;
|
public static Pointer put(String key, Object object, int expiresIn) {
try {
byte[] payload = serializer.serialize(object, object.getClass());
Pointer ptr = putByteArray(key, payload);
ptr.clazz = object.getClass();
return ptr;
} catch (IOException e) {
logger.error(e.getMessage());
return null;
}
}
public static Pointer updateByteArray(String key, byte[] payload) {
Pointer p = map.get(key);
p = MemoryManager.update(p, payload);
return p;
}
public static Pointer update(String key, Object object) {
Pointer p = map.get(key);
try {
p = MemoryManager.update(p, serializer.serialize(object, object.getClass()));
p.clazz = object.getClass();
return p;
} catch (IOException e) {
logger.error(e.getMessage());
return null;
}
}
public static byte[] retrieveByteArray(String key) {
Pointer ptr = getPointer(key);
if (ptr == null) return null;
if (ptr.expired() || ptr.free) {
map.remove(key);
if (!ptr.free) {
MemoryManager.free(ptr);
}
return null;
} else {
return MemoryManager.retrieve(ptr);
}
}
public static Object retrieve(String key) {
Pointer ptr = getPointer(key);
if (ptr == null) return null;
if (ptr.expired() || ptr.free) {
map.remove(key);
if (!ptr.free) {
MemoryManager.free(ptr);
}
return null;
} else {
try {
return serializer.deserialize(MemoryManager.retrieve(ptr),ptr.clazz);
} catch (EOFException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
} catch (ClassNotFoundException e) {
logger.error(e.getMessage());
} catch (InstantiationException e) {
logger.error(e.getMessage());
} catch (IllegalAccessException e) {
logger.error(e.getMessage());
}
}
return null;
}
public static Pointer getPointer(String key) {
return map.get(key);
}
public static void free(String key) {
Pointer p = map.remove(key);
if (p != null) {
MemoryManager.free(p);
}
}
public static void free(Pointer pointer) {
MemoryManager.free(pointer);
}
public static void collectExpired() {
MemoryManager.collectExpired();
// still have to look for orphan (storing references to freed pointers) map entries
}
public static void collectLFU() {
MemoryManager.collectLFU();
// can possibly clear one whole buffer if it's too fragmented - investigate
}
public static void collectAll() {
Thread thread = new Thread(){
public void run(){
logger.info("begin disposal");
collectExpired();
collectLFU();
logger.info("disposal complete");
}
};
thread.start();
}
public static void clear() {
map.clear();
MemoryManager.clear();
logger.info("Cache cleared");
}
public static long entries() {
return map.size();
}
| private static void dump(OffHeapMemoryBuffer mem) {
| 3 |
caseydavenport/biermacht | src/com/biermacht/brews/xml/RecipeXmlWriter.java | [
"public class Fermentable extends Ingredient implements Parcelable {\n\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n // Name - Inherited\n // Version - Inherited\n private String type; // G... | import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.biermacht.brews.ingredient.Fermentable;
import com.biermacht.brews.ingredient.Hop;
import com.biermacht.brews.ingredient.Misc;
import com.biermacht.brews.ingredient.Water;
import com.biermacht.brews.ingredient.Yeast;
import com.biermacht.brews.recipe.BeerStyle;
import com.biermacht.brews.recipe.MashProfile;
import com.biermacht.brews.recipe.MashStep;
import com.biermacht.brews.recipe.Recipe;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; | Element colorElement = d.createElement("COLOR");
Element addAfterBoilElement = d.createElement("ADD_AFTER_BOIL");
// Assign values
nameElement.setTextContent(f.getName());
versionElement.setTextContent(f.getVersion() + "");
typeElement.setTextContent(f.getFermentableType());
amountElement.setTextContent(f.getBeerXmlStandardAmount() + "");
yieldElement.setTextContent(f.getYield() + "");
colorElement.setTextContent(f.getLovibondColor() + "");
addAfterBoilElement.setTextContent(f.isAddAfterBoil() + "");
// Attach to element.
fermentableElement.appendChild(nameElement);
fermentableElement.appendChild(versionElement);
fermentableElement.appendChild(typeElement);
fermentableElement.appendChild(amountElement);
fermentableElement.appendChild(yieldElement);
fermentableElement.appendChild(colorElement);
fermentableElement.appendChild(addAfterBoilElement);
// Attach to list of elements.
fermentablesElement.appendChild(fermentableElement);
}
return fermentablesElement;
}
public Element getMiscsChild(Document d, ArrayList<Misc> l) {
// Create the element.
Element miscsElement = d.createElement("MISCS");
for (Misc m : l) {
miscsElement.appendChild(this.getMiscChild(d, m));
}
return miscsElement;
}
public Element getMiscChild(Document d, Misc m) {
// Create the element.
Element rootElement = d.createElement("MISC");
// Create a mapping of name -> value
Map<String, String> map = new HashMap<String, String>();
map.put("NAME", m.getName());
map.put("VERSION", m.getVersion() + "");
map.put("TYPE", m.getType());
map.put("USE", m.getUse());
map.put("AMOUNT", String.format("%2.8f", m.getBeerXmlStandardAmount()));
map.put("DISPLAY_AMOUNT", m.getDisplayAmount() + " " + m.getDisplayUnits());
map.put("DISPLAY_TIME", m.getTime() + " " + m.getTimeUnits());
map.put("AMOUNT_IS_WEIGHT", m.amountIsWeight() ? "true" : "false");
map.put("NOTES", m.getShortDescription());
map.put("USE_FOR", m.getUseFor());
for (Map.Entry<String, String> e : map.entrySet()) {
String fieldName = e.getKey();
String fieldValue = e.getValue();
Element element = d.createElement(fieldName);
element.setTextContent(fieldValue);
rootElement.appendChild(element);
}
return rootElement;
}
public Element getYeastsChild(Document d, ArrayList<Yeast> l) {
// Create the element.
Element yeastsElement = d.createElement("YEASTS");
for (Yeast y : l) {
Element yeastElement = d.createElement("YEAST");
// Create fields of element
Element nameElement = d.createElement("NAME");
Element versionElement = d.createElement("VERSION");
Element typeElement = d.createElement("TYPE");
Element formElement = d.createElement("FORM");
Element amountElement = d.createElement("AMOUNT");
Element laboratoryElement = d.createElement("LABORATORY");
Element productIdElement = d.createElement("PRODUCT_ID");
Element minTempElement = d.createElement("MIN_TEMPERATURE");
Element maxTempElement = d.createElement("MAX_TEMPERATURE");
Element attenuationElement = d.createElement("ATTENUATION");
// Assign values
nameElement.setTextContent(y.getName());
versionElement.setTextContent(y.getVersion() + "");
typeElement.setTextContent(y.getType());
formElement.setTextContent(y.getForm());
amountElement.setTextContent(y.getBeerXmlStandardAmount() + "");
laboratoryElement.setTextContent(y.getLaboratory());
productIdElement.setTextContent(y.getProductId());
minTempElement.setTextContent(y.getBeerXmlStandardFermentationTemp() + "");
maxTempElement.setTextContent(y.getBeerXmlStandardFermentationTemp() + "");
attenuationElement.setTextContent(y.getAttenuation() + "");
// Attach to element.
yeastElement.appendChild(nameElement);
yeastElement.appendChild(versionElement);
yeastElement.appendChild(typeElement);
yeastElement.appendChild(amountElement);
yeastElement.appendChild(laboratoryElement);
yeastElement.appendChild(productIdElement);
yeastElement.appendChild(minTempElement);
yeastElement.appendChild(maxTempElement);
yeastElement.appendChild(attenuationElement);
// Attach to list of elements.
yeastsElement.appendChild(yeastElement);
}
return yeastsElement;
}
public Element getWatersChild(Document d, ArrayList<Water> l) {
return d.createElement("WATERS");
}
| public Element getMashChild(Document d, MashProfile m) { | 6 |
nongdenchet/android-mvvm-with-tests | app/src/androidTest/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragmentIntegrationTest.java | [
"public class ComponentBuilder {\n private AppComponent appComponent;\n\n public ComponentBuilder(AppComponent appComponent) {\n this.appComponent = appComponent;\n }\n\n public PlacesComponent placesComponent() {\n return appComponent.plus(new PlacesModule());\n }\n\n public Purchas... | import android.content.Intent;
import android.support.test.rule.ActivityTestRule;
import android.test.suitebuilder.annotation.MediumTest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
import apidez.com.android_mvvm_sample.ComponentBuilder;
import apidez.com.android_mvvm_sample.R;
import apidez.com.android_mvvm_sample.dependency.component.AppComponent;
import apidez.com.android_mvvm_sample.dependency.component.PlacesComponent;
import apidez.com.android_mvvm_sample.dependency.module.PlacesModule;
import apidez.com.android_mvvm_sample.model.api.IPlacesApi;
import apidez.com.android_mvvm_sample.utils.ApplicationUtils;
import apidez.com.android_mvvm_sample.utils.TestDataUtils;
import apidez.com.android_mvvm_sample.view.activity.EmptyActivity;
import rx.Observable;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static apidez.com.android_mvvm_sample.utils.MatcherEx.hasItemCount;
import static org.mockito.Mockito.when; | package apidez.com.android_mvvm_sample.view.fragment;
/**
* Created by nongdenchet on 10/22/15.
*/
@MediumTest
@RunWith(JUnit4.class)
public class PlacesFragmentIntegrationTest {
@Rule
public ActivityTestRule<EmptyActivity> activityTestRule =
new ActivityTestRule<>(EmptyActivity.class, true, false);
@Before
public void setUp() throws Exception {
PlacesModule mockModule = new PlacesModule() {
@Override
public IPlacesApi providePlacesApi() {
IPlacesApi placesApi = Mockito.mock(IPlacesApi.class);
when(placesApi.placesResult()) | .thenReturn(Observable.just(TestDataUtils.nearByData())); | 6 |
Lambda-3/DiscourseSimplification | src/main/java/org/lambda3/text/simplification/discourse/runner/discourse_tree/extraction/rules/LeadNPExtractor.java | [
"public enum Relation {\n\n UNKNOWN,\n\n // Coordinations\n UNKNOWN_COORDINATION, // the default for coordination\n CONTRAST,\n CAUSE_C,\n RESULT_C,\n LIST,\n DISJUNCTION,\n TEMPORAL_AFTER_C,\n TEMPORAL_BEFORE_C,\n\n // Subordinations\n UNKNOWN_SUBORDINATION, // the default for s... | import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeExtractionUtils;
import org.lambda3.text.simplification.discourse.utils.words.WordsUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import edu.stanford.nlp.ling.Word;
import edu.stanford.nlp.trees.tregex.TregexMatcher;
import edu.stanford.nlp.trees.tregex.TregexPattern;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.Relation;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.Extraction;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.ExtractionRule;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.model.Leaf;
import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeException; | /*
* ==========================License-Start=============================
* DiscourseSimplification : SubordinationPostExtractor
*
* Copyright © 2017 Lambda³
*
* GNU General Public License 3
* 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/.
* ==========================License-End==============================
*/
package org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.rules;
/**
*
*/
public class LeadNPExtractor extends ExtractionRule {
@Override | public Optional<Extraction> extract(Leaf leaf) throws ParseTreeException { | 4 |
millecker/senti-storm | src/at/illecker/sentistorm/SentiStormTopology.java | [
"public class FeatureGenerationBolt extends BaseBasicBolt {\n public static final String ID = \"feature-generation-bolt\";\n public static final String CONF_LOGGING = ID + \".logging\";\n private static final long serialVersionUID = 5340637976415982170L;\n private static final Logger LOG = LoggerFactory\n ... | import backtype.storm.topology.IRichSpout;
import backtype.storm.topology.TopologyBuilder;
import cmu.arktweetnlp.Tagger.TaggedToken;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.TreeMapSerializer;
import java.util.Arrays;
import java.util.TreeMap;
import at.illecker.sentistorm.bolt.FeatureGenerationBolt;
import at.illecker.sentistorm.bolt.POSTaggerBolt;
import at.illecker.sentistorm.bolt.PreprocessorBolt;
import at.illecker.sentistorm.bolt.SVMBolt;
import at.illecker.sentistorm.bolt.TokenizerBolt;
import at.illecker.sentistorm.commons.Configuration;
import at.illecker.sentistorm.commons.util.io.kyro.TaggedTokenSerializer;
import at.illecker.sentistorm.spout.DatasetSpout;
import at.illecker.sentistorm.spout.TwitterStreamSpout;
import backtype.storm.Config;
import backtype.storm.StormSubmitter; | /**
* 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 at.illecker.sentistorm;
public class SentiStormTopology {
public static final String TOPOLOGY_NAME = "senti-storm-topology";
public static void main(String[] args) throws Exception {
String consumerKey = "";
String consumerSecret = "";
String accessToken = "";
String accessTokenSecret = "";
String[] keyWords = null;
if (args.length > 0) {
if (args.length >= 4) {
consumerKey = args[0];
System.out.println("TwitterSpout using ConsumerKey: " + consumerKey);
consumerSecret = args[1];
accessToken = args[2];
accessTokenSecret = args[3];
if (args.length == 5) {
keyWords = args[4].split(" ");
System.out.println("TwitterSpout using KeyWords: "
+ Arrays.toString(keyWords));
}
} else {
System.out.println("Wrong argument size!");
System.out.println(" Argument1=consumerKey");
System.out.println(" Argument2=consumerSecret");
System.out.println(" Argument3=accessToken");
System.out.println(" Argument4=accessTokenSecret");
System.out.println(" [Argument5=keyWords]");
}
}
Config conf = new Config();
// Create Spout
IRichSpout spout;
String spoutID = "";
if (consumerKey.isEmpty()) {
if (Configuration.get("sentistorm.spout.startup.sleep.ms") != null) { | conf.put(DatasetSpout.CONF_STARTUP_SLEEP_MS, | 7 |
akeranen/the-one | src/ui/DTNSimUI.java | [
"public abstract class Report {\n\t/** Name space of the settings that are common to all reports ({@value}). */\n\tpublic static final String REPORT_NS = \"Report\";\n\t/** The interval (simulated seconds) of creating new settings files\n\t * -setting id ({@value}) */\n\tpublic static final String INTERVAL_SETTING ... | import java.util.Vector;
import report.Report;
import core.ApplicationListener;
import core.ConnectionListener;
import core.MessageListener;
import core.MovementListener;
import core.Settings;
import core.SettingsError;
import core.SimClock;
import core.SimError;
import core.SimScenario;
import core.UpdateListener;
import core.World; | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package ui;
/**
* Abstract superclass for user interfaces; contains also some simulation
* settings.
*/
public abstract class DTNSimUI {
/**
* Number of reports -setting id ({@value}). Defines how many reports
* are loaded.
*/
public static final String NROF_REPORT_S = "Report.nrofReports";
/**
* Report class name -setting id prefix ({@value}). Defines name(s) of
* the report classes to load. Must be suffixed with numbers starting from
* one.
*/
public static final String REPORT_S = "Report.report";
/**
* Movement model warmup time -setting id ({@value}). Defines how many
* seconds of movement simulation is run without connectivity etc. checks
* before starting the real simulation.
*/
public static final String MM_WARMUP_S =
movement.MovementModel.MOVEMENT_MODEL_NS + ".warmup";
/** report class' package name */
private static final String REPORT_PAC = "report.";
/** The World where all actors of the simulator are */
protected World world;
/** Reports that are loaded for this simulation */ | protected Vector<Report> reports; | 0 |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/service/impl/JAXBContextResolver.java | [
"@Entity\n@XmlRootElement\npublic class Domain extends PersistentObject implements Validatable,\n Identifiable<String> {\n public static final String DEFAULT_DOMAIN_NAME = Configuration\n .getInstance().getProperty(\"default.domain\", \"default\");\n\n @PrimaryKey\n private String id;\n ... | import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.plexobject.rbac.domain.Domain;
import com.plexobject.rbac.domain.Permission;
import com.plexobject.rbac.domain.Role;
import com.plexobject.rbac.domain.Subject;
import com.plexobject.rbac.repository.PagedList;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONConfiguration.MappedBuilder; | package com.plexobject.rbac.service.impl;
@Path("/jsonFormats")
@Component("jaxbContextResolver")
@Scope("singleton")
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private static final Logger LOGGER = Logger
.getLogger(JAXBContextResolver.class);
private static final Class<?>[] TYPES = new java.lang.Class[] { | PagedList.class, Domain.class, Permission.class, Role.class, | 4 |
tteguayco/JITRAX | src/es/ull/etsii/jitrax/analysis/dsl/DatabaseEvalVisitor.java | [
"public class Database {\n\n\tprivate String name;\n\tprivate ArrayList<Table> tables;\n\tprivate DbmsDriver dbmsDriver;\n\t\n\t/**\n\t * @param name name for the database.\n\t */\n\tpublic Database(String aName) {\n\t\tname = aName;\n\t\ttables = new ArrayList<Table>();\n\t}\n\t\n\tpublic Database(String aName, Ar... | import es.ull.etsii.jitrax.adt.Database;
import es.ull.etsii.jitrax.adt.Datum;
import es.ull.etsii.jitrax.adt.Attribute;
import es.ull.etsii.jitrax.adt.Row;
import es.ull.etsii.jitrax.adt.Table;
import es.ull.etsii.jitrax.adt.DataType;
import es.ull.etsii.jitrax.exceptions.DuplicateTableException;
import java.util.ArrayList; | package es.ull.etsii.jitrax.analysis.dsl;
/**
* This class allows to semantically analyze an expression which describes
* a database specification (using a DSL). It has to be syntactically correct.
*/
public class DatabaseEvalVisitor extends DatabaseBaseVisitor<Object> {
private Database database; | private ArrayList<Attribute> auxAttributeList; | 2 |
sherlok/sherlok | src/test/java/org/sherlok/mappings/BundleDefTest.java | [
"public static <T> T read(File f, Class<T> clazz) throws SherlokException {\n try {\n return MAPPER.readValue(new FileInputStream(f), clazz);\n\n } catch (FileNotFoundException io) {\n throw new SherlokException()\n .setMessage(\n clazz.getSimpleName().repla... | import static java.lang.System.currentTimeMillis;
import static org.junit.Assert.assertEquals;
import static org.sherlok.FileBased.read;
import static org.sherlok.mappings.BundleDef.BundleDependency.DependencyType.jar;
import static org.sherlok.mappings.BundleDef.BundleDependency.DependencyType.mvn;
import static org.sherlok.utils.Create.set;
import java.io.File;
import java.util.Set;
import org.junit.Test;
import org.sherlok.FileBased;
import org.sherlok.mappings.BundleDef.BundleDependency;
import org.sherlok.mappings.BundleDef.EngineDef; | /**
* Copyright (C) 2014-2015 Renaud Richardet
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sherlok.mappings;
public class BundleDefTest {
public static BundleDef getDkproOpennlpEn() {
BundleDef b = (BundleDef) new BundleDef()
.addDependency(
new BundleDependency(
mvn,
"de.tudarmstadt.ukp.dkpro.core:de.tudarmstadt.ukp.dkpro.core.stanfordnlp-gpl:1.6.2"))
.addDependency(
new BundleDependency(
mvn,
"de.tudarmstadt.ukp.dkpro.core:de.tudarmstadt.ukp.dkpro.core.opennlp-model-ner-en-organization:20100907.0"))
.addRepository(
"dkpro",
"http://zoidberg.ukp.informatik.tu-darmstadt.de/artifactory/public-model-releases-local/");
b.setName("dkpro_opennlp_en");
b.setVersion("1.6.2");
b.setDescription("all opennlp engines and models for English");
return b;
}
@Test
public void testWriteRead() throws Exception {
File bf = new File("target/bundleTest_" + currentTimeMillis() + ".json");
BundleDef b = getDkproOpennlpEn();
FileBased.write(bf, b);
BundleDef b2 = read(bf, BundleDef.class);
b2.validate("");
assertEquals(b.getName(), b2.getName());
assertEquals(b.getVersion(), b2.getVersion());
assertEquals(b.getDependencies().size(), b2.getDependencies().size());
}
// TODO test BundleDef.validate()
@Test
public void testValidateBundle() throws Exception {
new BundleDef().setName("a").setVersion("b").validate();
}
@Test(expected = SherlokException.class)
// $ in domain
public void testValidateBundle1() throws Exception {
new BundleDef().setName("a").setVersion("b").setDomain("a$b")
.validate();
}
@Test
public void testValidateBundle2() throws Exception {
new BundleDef().setName("a").setVersion("b").setDomain("a/b")
.validate();
}
@Test
public void testBundleDependencyEquality() throws Exception {
Set<BundleDependency> bdl = set();
bdl.add(new BundleDependency(mvn, "abc"));
bdl.add(new BundleDependency(jar, "abc"));
assertEquals("distinct DependencyTypes", 2, bdl.size());
bdl.add(new BundleDependency(jar, "abc"));
assertEquals("same DependencyTypes, should not increase the set", 2,
bdl.size());
}
@Test
public void testEngineNameFallback() throws Exception { | assertEquals("MyName", new EngineDef().setClassz("a.b.c.Dclass") | 4 |
opacapp/opacclient | opacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/WebOpacNet.java | [
"public class Account {\n private long id;\n private String library;\n\n private String label;\n private String name;\n private String password;\n private long cached;\n private boolean password_known_valid = false;\n private boolean supportPolicyHintSeen = false;\n\n @Override\n publi... | import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import de.geeksfactory.opacclient.i18n.StringProvider;
import de.geeksfactory.opacclient.networking.HttpClientFactory;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.Copy;
import de.geeksfactory.opacclient.objects.Detail;
import de.geeksfactory.opacclient.objects.DetailedItem;
import de.geeksfactory.opacclient.objects.Filter;
import de.geeksfactory.opacclient.objects.Filter.Option;
import de.geeksfactory.opacclient.objects.LentItem;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.ReservedItem;
import de.geeksfactory.opacclient.objects.SearchRequestResult;
import de.geeksfactory.opacclient.objects.SearchResult;
import de.geeksfactory.opacclient.objects.SearchResult.MediaType;
import de.geeksfactory.opacclient.searchfields.DropdownSearchField;
import de.geeksfactory.opacclient.searchfields.SearchField;
import de.geeksfactory.opacclient.searchfields.SearchQuery;
import de.geeksfactory.opacclient.searchfields.TextSearchField;
import de.geeksfactory.opacclient.utils.Base64;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink; | throws JSONException, IOException, OpacErrorException {
// aktion:
// 1 = make reservation
// 2 = cancel reservation
// 3 = check reservation
FormBody.Builder formData = new FormBody.Builder(Charset.forName(getDefaultEncoding()));
formData.add("aktion", aktion);
if (aktion.equals("2")) {
String medid = media.split("Z")[0].replace("dat", "");
String resid = media.split("Z")[1];
formData.add("medid", medid);
formData.add("resid", resid);
} else {
formData.add("medid", media);
formData.add("bemerkung", "");
formData.add("zws", "");
}
formData.add("biblNr", "0");
formData.add("sessionid", sessionId);
return httpPostAccount(opac_url + "/de/mobile/Res.ashx", formData.build(), acc);
}
@Override
public AccountData account(Account account) throws IOException,
JSONException, OpacErrorException {
if (sessionId == null) login(account);
FormBody.Builder formData = new FormBody.Builder(Charset.forName(getDefaultEncoding()));
formData.add("art", "7");
formData.add("rsa", "");
formData.add("sessionId", sessionId);
JSONObject response =
httpPostAccount(opac_url + "/de/mobile/Konto.ashx", formData.build(), account);
AccountData data = new AccountData(account.getId());
parseAccount(response, data);
return data;
}
static void parseAccount(JSONObject response, AccountData data) throws JSONException {
data.setValidUntil(ifNotEmpty(response.getString("gueltigbis")));
data.setPendingFees(ifNotEmpty(response.getString("gebuehren")));
DateTimeFormatter format = DateTimeFormat.forPattern("dd.MM.yyyy");
List<LentItem> lent = new ArrayList<>();
JSONArray ausleihen = response.getJSONArray("ausleihen");
for (int i = 0; i < ausleihen.length(); i++) {
LentItem item = new LentItem();
JSONObject json = ausleihen.getJSONObject(i);
item.setAuthor(json.getString("urheber"));
item.setTitle(json.getString("titelkurz").replace(item.getAuthor() + " : ", ""));
item.setCover(json.getString("imageurl"));
item.setMediaType(getMediaType(json.getString("iconurl")));
item.setStatus(ifNotEmpty(json.getString("hinweis")));
item.setProlongData(json.getString("exemplarid"));
JSONArray felder = json.getJSONArray("felder");
for (int j = 0; j < felder.length(); j++) {
String value = felder.getJSONObject(j).getString("display");
if (value.startsWith("Leihfrist: ")) {
String dateStr = value.replace("Leihfrist: ", "");
item.setDeadline(format.parseLocalDate(dateStr));
break;
}
}
lent.add(item);
}
data.setLent(lent);
List<ReservedItem> reservations = new ArrayList<>();
JSONArray reservationen = response.getJSONArray("reservationen");
for (int i = 0; i < reservationen.length(); i++) {
ReservedItem item = new ReservedItem();
JSONObject json = reservationen.getJSONObject(i);
item.setAuthor(json.getString("urheber"));
item.setTitle(json.getString("titelkurz").replace(item.getAuthor() + " : ", ""));
item.setCover(json.getString("imageurl"));
item.setMediaType(getMediaType(json.getString("iconurl")));
item.setStatus(ifNotEmpty(json.getString("hinweis")));
if (!json.getString("abholdat").equals("")) {
item.setExpirationDate(format.parseLocalDate(json.getString("abholdat")));
}
if (json.getString("status").equals("1")) {
item.setCancelData(json.getString("exemplarid"));
}
reservations.add(item);
}
data.setLent(lent);
data.setReservations(reservations);
}
private static String ifNotEmpty(String value) {
if (value == null || value.equals("")) {
return null;
} else {
return value;
}
}
private void login(Account account) throws IOException, JSONException, OpacErrorException {
String toEncrypt =
account.getName() + "|" + account.getPassword() + "|"; // + stammbibliothek + "|"
toEncrypt += randomString();
JSONObject response = new JSONObject(
httpGet(opac_url + "/de/mobile/GetRsaPublic.ashx", getDefaultEncoding()));
BigInteger key = new BigInteger(response.getString("key"), 16);
BigInteger modulus = new BigInteger(response.getString("modulus"), 16);
try {
final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic
(new RSAPublicKeySpec(key, modulus)));
byte[] result = cipher.doFinal(toEncrypt.getBytes()); | String str = Base64.encodeBytes(result); | 5 |
keeps/roda-in | src/main/java/org/roda/rodain/core/sip/creators/SipPreviewCreator.java | [
"public class ConfigurationManager {\n private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationManager.class.getName());\n\n private static final Path rodainPath = computeRodainPath();\n private static Path schemasPath, templatesPath, logPath, metadataPath, helpPath, externalConfigPath,\n ex... | import java.io.File;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Set;
import org.apache.commons.io.FilenameUtils;
import org.roda.rodain.core.ConfigurationManager;
import org.roda.rodain.core.Constants;
import org.roda.rodain.core.Constants.MetadataOption;
import org.roda.rodain.core.Controller;
import org.roda.rodain.core.rules.TreeNode;
import org.roda.rodain.core.rules.filters.ContentFilter;
import org.roda.rodain.core.schema.DescriptiveMetadata;
import org.roda.rodain.core.sip.SipPreview;
import org.roda.rodain.core.sip.SipRepresentation;
import org.roda.rodain.core.utils.TreeVisitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.roda.rodain.core.sip.creators;
/**
* @author Andre Pereira apereira@keep.pt
* @since 20-10-2015.
*/
public class SipPreviewCreator extends Observable implements TreeVisitor {
private static final Logger LOGGER = LoggerFactory.getLogger(SipPreviewCreator.class.getName());
private String startPath;
// This map is returned, in full, to the SipPreviewNode when there's an update
protected Map<String, SipPreview> sipsMap;
// This ArrayList is used to keep the SIPs ordered.
// We need them ordered because we have to keep track of which SIPs have
// already been loaded
protected List<SipPreview> sips;
protected int added = 0, returned = 0;
protected Deque<TreeNode> nodes;
protected Set<TreeNode> files;
private String id; | private Set<ContentFilter> filters; | 4 |
dperezcabrera/jpoker | src/main/java/org/poker/sample/strategies/SlowlyStrategy.java | [
"@NotThreadSafe\npublic class BetCommand {\n\n private final BetCommandType type;\n private long chips;\n\n public BetCommand(BetCommandType type) {\n this(type, 0);\n }\n\n public BetCommand(BetCommandType type, long chips) {\n ExceptionUtil.checkNullArgument(type, \"type\");\n ... | import org.poker.api.game.BetCommand;
import org.poker.api.game.GameInfo;
import org.poker.api.game.IStrategy;
import org.poker.api.game.PlayerInfo;
import org.poker.api.game.TexasHoldEmUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.poker.sample.strategies;
/**
*
* @author David Pérez Cabrera <dperezcabrera@gmail.com>
*/
public class SlowlyStrategy implements IStrategy {
private static final Logger LOGGER = LoggerFactory.getLogger(SlowlyStrategy.class);
private final String name;
public SlowlyStrategy(String name) {
this.name = "Slowly-" + name;
}
@Override
public String getName() {
return name;
}
@Override | public BetCommand getCommand(GameInfo<PlayerInfo> state) { | 0 |
njustesen/hero-aicademy | src/ai/mcts/Mcts.java | [
"public class GameState {\n\t\n\tpublic static int TURN_LIMIT = 100;\n\tpublic static boolean RANDOMNESS = false;\n\tpublic static int STARTING_AP = 3;\n\tpublic static int ACTION_POINTS = 5;\n\t\n\tprivate static final int ASSAULT_BONUS = 300;\n\tprivate static final double INFERNO_DAMAGE = 350;\n\tprivate static ... | import game.GameState;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import util.Statistics;
import action.Action;
import action.SingletonAction;
import ai.AI;
import ai.evaluation.IStateEvaluator;
import ai.util.ActionComparator;
import ai.util.ActionPruner;
import ai.util.ComplexActionComparator;
| ap--;
}
traversal.clear();
clone.imitate(state);
// SELECTION + EXPANSION
treePolicy(root, clone, traversal);
// SIMULATION
delta = defaultPolicy.eval(clone, state.p1Turn);
// BACKPROPAGATION
backupNegaMax(traversal, delta, state.p1Turn);
time = (start + budget) - System.currentTimeMillis();
rolls++;
fitnesses.put(rolls, bestMoveValue(root, state.p1Turn));
// saveTree();
}
// TODO: Runs out of memory -- of course..
/*
if (RECORD_DEPTHS){
root.depth(0, depths, new HashSet<MctsNode>());
avgDepths.add(Statistics.avgDouble(depths));
minDepths.add(Collections.min(depths));
maxDepths.add(Collections.max(depths));
depths.clear();
}
rollouts.add((double) rolls);
*/
//saveTree();
move = bestMove(state, rolls);
final Action action = move.get(0);
move.remove(0);
// Reset search
if (resetRoot)
root = null;
transTable.clear();
ends = 0;
return action;
}
private void saveTree() {
PrintWriter out = null;
try {
out = new PrintWriter("mcts.xml");
out.print(root.toXml(0, new HashSet<MctsNode>(), 12));
} catch (final FileNotFoundException e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
}
private void cut(MctsNode node, MctsEdge from, int depth, int cut) {
if (node == null)
return;
if (depth == cut) {
final MctsEdge best = best(node, false);
node.out.clear();
node.possible.clear();
if (best != null)
node.out.add(best);
node.in.clear();
if (from != null)
node.in.add(from);
} else
for (final MctsEdge edge : node.out)
cut(edge.to, edge, depth + 1, cut);
}
private MctsEdge best(MctsNode node, boolean urgent) {
double bestVal = -100000;
MctsEdge bestEdge = null;
for (final MctsEdge edge : node.out) {
final double val = uct(edge, node, urgent);
if (val > bestVal) {
bestVal = val;
bestEdge = edge;
}
}
return bestEdge;
}
/**
*
* @param edge
* takes the role as child node
* @param node
* takes the role as parent
* @param urgent
* whether to pick most urgent node or the best
* @return
*/
private double uct(MctsEdge edge, MctsNode node, boolean urgent) {
if (urgent)
return edge.avg() + 2 * c
* Math.sqrt((2 * Math.log(node.visits)) / (edge.visits));
return edge.avg();
}
private boolean collapse(MctsNode node) {
final List<MctsEdge> remove = new ArrayList<MctsEdge>();
boolean end = false;
for (final MctsEdge edge : node.out) {
| if (edge.action == SingletonAction.endTurnAction)
| 3 |
lumag/JBookReader | src/org/jbookreader/renderingengine/RenderEngineTest.java | [
"public class FB2FilesTestFilter implements FilenameFilter {\n\tpublic boolean accept(File dir, String name) {\n\t\tif (name.endsWith(\".fb2\")) {\n\t\t\treturn true;\n\t\t}\n\t\tif (name.endsWith(\".xml\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n}",
"public class TestConfig implements ITestCon... | import org.jbookreader.formatengine.IBookPainter;
import org.jbookreader.formatengine.impl.FormatEngine;
import org.jbookreader.renderingengine.RenderingEngine;
import org.jbookreader.util.TextPainter;
import org.lumag.filetest.FileTestCase;
import org.lumag.filetest.FileTestUtil;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import junit.framework.Test;
import org.jbookreader.FB2FilesTestFilter;
import org.jbookreader.TestConfig;
import org.jbookreader.book.bom.IBook;
import org.jbookreader.book.parser.FB2Parser; | /*
* JBookReader - Java FictionBook Reader
* Copyright (C) 2006 Dmitry Baryshkov
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jbookreader.renderingengine;
/**
* This class is a test case generator for the {@link org.jbookreader.formatengine.impl.FormatEngine}.
* The engine is tested via formatting with {@link org.jbookreader.util.TextPainter}.
*
* @author Dmitry Baryshkov (dbaryshkov@gmail.com)
*
*/
public class RenderEngineTest {
/**
* This is one {@link FormatEngine} <code>TestCase</code>.
*
* @author Dmitry Baryshkov (dbaryshkov@gmail.com)
*
*/
public static class RenderEngineTestCase extends FileTestCase {
@Override
protected void generateOutput(File inFile, File outFile)
throws Exception {
IBook book = FB2Parser.parse(inFile);
PrintWriter pwr = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(outFile))));
IBookPainter painter = new TextPainter(pwr, 80);
| RenderingEngine engine = new RenderingEngine(new FormatEngine()); | 5 |
JavaMoney/javamoney-shelter | retired/regions/src/main/java/org/javamoney/regions/internal/data/ISO3RegionTreeProvider.java | [
"public interface Region {\n\n\t/**\n\t * Get the region's type.\n\t * \n\t * @return the region's type, never {@code null}.\n\t */\n\tpublic RegionType getRegionType();\n\n\t/**\n\t * Access the region's code. The code is unique in combination with the\n\t * region type.\n\t * \n\t * @return the region's type, nev... | import java.util.Locale;
import java.util.Map;
import javax.inject.Singleton;
import org.javamoney.regions.Region;
import org.javamoney.regions.RegionTreeNode;
import org.javamoney.regions.RegionType;
import org.javamoney.regions.spi.BuildableRegionNode;
import org.javamoney.regions.spi.RegionProviderSpi;
import org.javamoney.regions.spi.RegionTreeProviderSpi;
import org.javamoney.regions.spi.BuildableRegionNode.Builder; | /*
* CREDIT SUISSE IS WILLING TO LICENSE THIS SPECIFICATION TO YOU ONLY UPON THE
* CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS AGREEMENT.
* PLEASE READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY. BY
* DOWNLOADING THIS SPECIFICATION, YOU ACCEPT THE TERMS AND CONDITIONS OF THE
* AGREEMENT. IF YOU ARE NOT WILLING TO BE BOUND BY IT, SELECT THE "DECLINE"
* BUTTON AT THE BOTTOM OF THIS PAGE. Specification: JSR-354 Money and Currency
* API ("Specification") Copyright (c) 2012-2013, Credit Suisse All rights
* reserved.
*/
package org.javamoney.regions.internal.data;
/**
* Region Tree provider that provides all ISO countries, defined by
* {@link java.util.Locale#getISOCountries()} using their 3-letter ISO country code under
* {@code ISO3}.
*
* @author Anatole Tresch
*/
@Singleton
public class ISO3RegionTreeProvider implements RegionTreeProviderSpi {
private BuildableRegionNode regionTree;
// ISO3/...
@Override
public String getTreeId() {
return "ISO3";
}
@Override
public void init(Map<Class, RegionProviderSpi> providers) {
Builder treeBuilder = new BuildableRegionNode.Builder(new SimpleRegion(
"ISO3"));
ISORegionProvider regionProvider = (ISORegionProvider) providers
.get(ISORegionProvider.class);
for (String country : Locale.getISOCountries()) {
Locale locale = new Locale("", country); | Region region = regionProvider.getRegion(RegionType.of("ISO"), | 0 |
magnusmickelsson/pokeraidbot | src/main/java/pokeraidbot/commands/PokemonVsCommand.java | [
"public class Utils {\n public static final DateTimeFormatter timeParseFormatter = DateTimeFormatter.ofPattern(\"H[:][.]mm\");\n public static final DateTimeFormatter dateAndTimeParseFormatter =\n DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH[:][.]mm\");\n public static final DateTimeFormatter tim... | import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.command.CommandListener;
import org.apache.commons.lang3.StringUtils;
import pokeraidbot.Utils;
import pokeraidbot.domain.config.LocaleService;
import pokeraidbot.domain.pokemon.Pokemon;
import pokeraidbot.domain.pokemon.PokemonRepository;
import pokeraidbot.domain.raid.PokemonRaidStrategyService;
import pokeraidbot.domain.raid.RaidBossCounters;
import pokeraidbot.infrastructure.CounterPokemon;
import pokeraidbot.infrastructure.jpa.config.Config;
import pokeraidbot.infrastructure.jpa.config.ServerConfigRepository;
import java.util.*;
import java.util.stream.Collectors; | package pokeraidbot.commands;
/**
* !raid vs (boss name)
*/
public class PokemonVsCommand extends ConfigAwareCommand {
private final PokemonRaidStrategyService raidInfoService;
private final LocaleService localeService;
private final PokemonRepository repo;
public PokemonVsCommand(PokemonRepository repo, PokemonRaidStrategyService raidInfoService,
LocaleService localeService, ServerConfigRepository serverConfigRepository, CommandListener commandListener) {
super(serverConfigRepository, commandListener, localeService);
this.raidInfoService = raidInfoService;
this.localeService = localeService;
this.name = "vs";
this.help = localeService.getMessageFor(LocaleService.VS_HELP, LocaleService.DEFAULT);
this.repo = repo;
}
@Override | protected void executeWithConfig(CommandEvent commandEvent, Config config) { | 7 |
feedzai/fos-core | fos-api/src/main/java/com/feedzai/fos/server/remote/api/FOSManagerAdapter.java | [
"public class FOSException extends Exception {\n public FOSException(String message) {\n super(message);\n }\n\n /**\n * Create an exception with a nested throwable and customized message\n * @param message exception message\n * @param t nested throable\n */\n public FOSException(... | import com.google.common.base.Optional;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.feedzai.fos.api.FOSException;
import com.feedzai.fos.api.KryoScorer;
import com.feedzai.fos.api.Manager;
import com.feedzai.fos.api.Model;
import com.feedzai.fos.api.ModelConfig;
import com.feedzai.fos.api.ModelDescriptor;
import com.feedzai.fos.api.Scorer;
import com.feedzai.fos.common.validation.NotBlank; | /*
* $#
* FOS API
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.server.remote.api;
/**
* FOS Remote manager local adapter.
*
* @author Miguel Duarte (miguel.duarte@feedzai.com)
* @since 0.3.0
* @since 0.3.0
*/
public class FOSManagerAdapter implements Manager {
private final KryoScorer kryoScorer;
IRemoteManager manager;
public FOSManagerAdapter(IRemoteManager manager, KryoScorer kryoScorer) {
this.manager = manager;
this.kryoScorer = kryoScorer;
}
@Override
public UUID addModel(ModelConfig modelConfig, Model binary) throws FOSException {
try {
return manager.addModel(modelConfig, binary);
} catch (RemoteException e) {
throw new FOSException(e);
}
}
@Override | public UUID addModel(ModelConfig modelConfig, @NotBlank ModelDescriptor descriptor) throws FOSException { | 5 |
jclehner/AppOpsXposed | src/at/jclehner/appopsxposed/AppListFragment.java | [
"@TargetApi(19)\npublic class AppOpsManagerWrapper extends ObjectWrapper\n{\n\t// These are all ops included in AOSP Lollipop\n\tpublic static final int OP_NONE = getOpInt(\"OP_NONE\");\n\tpublic static final int OP_COARSE_LOCATION = getOpInt(\"OP_COARSE_LOCATION\");\n\tpublic static final int OP_FINE_LOCATION = ge... | import java.lang.reflect.Field;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.app.Fragment;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.Loader;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.StrikethroughSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import at.jclehner.appopsxposed.util.AppOpsManagerWrapper;
import at.jclehner.appopsxposed.util.AppOpsManagerWrapper.OpEntryWrapper;
import at.jclehner.appopsxposed.util.AppOpsManagerWrapper.PackageOpsWrapper;
import at.jclehner.appopsxposed.util.OpsLabelHelper;
import com.android.settings.applications.AppOpsDetails;
import com.android.settings.applications.AppOpsState; | convertView = mInflater.inflate(R.layout.app_ops_item, parent, false);
holder = new ViewHolder();
holder.appIcon = (ImageView) convertView.findViewById(R.id.app_icon);
holder.appLine2 = (TextView) convertView.findViewById(R.id.op_name);
holder.appName = (TextView) convertView.findViewById(R.id.app_name);
convertView.findViewById(R.id.op_time).setVisibility(View.GONE);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.appIcon.setImageDrawable(null);
holder.appName.setText(data.label);
holder.appLine2.setText(data.line2);
if(true && !data.packageInfo.packageName.equals(holder.packageName))
{
if(holder.task != null)
holder.task.cancel(true);
holder.task = new AsyncTask<Void, Void, Object[]>() {
@Override
protected Object[] doInBackground(Void... params)
{
final Object[] result = new Object[2];
result[0] = appInfo.loadIcon(mPm);
//result[1] = appInfo.loadLabel(mPm);
return result;
}
@Override
protected void onPostExecute(Object[] result)
{
holder.appIcon.setImageDrawable((Drawable) result[0]);
/*holder.appName.setText((CharSequence) result[1]);
if(!appInfo.packageName.equals(result[1].toString()))
{
holder.appLine2.setText(appInfo.packageName);
holder.appLine2.setVisibility(View.VISIBLE);
}
else
holder.appLine2.setVisibility(View.GONE);*/
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
holder.packageName = appInfo.packageName;
}
else
{
holder.appIcon.setImageDrawable(appInfo.loadIcon(mPm));
holder.appName.setText(appInfo.loadLabel(mPm));
holder.packageName = appInfo.packageName;
}
return convertView;
}
}
static class ViewHolder
{
String packageName;
AsyncTask<Void, Void, Object[]> task;
ImageView appIcon;
TextView appName;
TextView appLine2;
}
static class LoaderDataComparator implements Comparator<PackageInfoData>
{
private static Collator sCollator = Collator.getInstance();
@Override
public int compare(PackageInfoData lhs, PackageInfoData rhs) {
return sCollator.compare(lhs.label, rhs.label);
}
}
static class PackageInfoData
{
final PackageInfo packageInfo;
final CharSequence label;
CharSequence line2;
List<OpEntryWrapper> changedOps;
PackageInfoData(PackageInfo packageInfo, CharSequence label)
{
this.packageInfo = packageInfo;
this.label = label;
line2 = packageInfo.packageName;
}
}
static class AppListLoader extends AsyncTaskLoader<List<PackageInfoData>>
{
private static String[] sOpPerms = getOpPermissions();
private final AppOpsState mState;
private final PackageManager mPm;
private List<PackageInfoData> mData;
private final boolean mRemoveAppsWithUnchangedOps;
public AppListLoader(Context context, boolean removeAppsWithUnchangedOps)
{
super(context);
mState = new AppOpsState(context);
mPm = context.getPackageManager();
mRemoveAppsWithUnchangedOps = removeAppsWithUnchangedOps;
}
@Override
public List<PackageInfoData> loadInBackground()
{
final List<PackageInfoData> data = new ArrayList<PackageInfoData>();
| final AppOpsManagerWrapper appOps = AppOpsManagerWrapper.from(getContext()); | 0 |
AlexanderMisel/gnubridge | src/main/java/org/gnubridge/core/bidding/rules/Respond1ColorWithNewSuit.java | [
"public class Hand {\n\tList<Card> cards;\n\n\t/**\n\t * Caching optimization for pruning played cards\n\t * and perhaps others\n\t */\n\tList<Card> orderedCards;\n\tSuit color;\n\tList<Card> colorInOrder;\n\n\tpublic Hand() {\n\t\tthis.cards = new ArrayList<Card>();\n\t}\n\n\tpublic Hand(Card... cards) {\n\t\tthis... | import org.gnubridge.core.Hand;
import org.gnubridge.core.bidding.Auctioneer;
import org.gnubridge.core.bidding.Bid;
import org.gnubridge.core.bidding.ResponseCalculator;
import org.gnubridge.core.deck.Clubs;
import org.gnubridge.core.deck.Diamonds;
import org.gnubridge.core.deck.NoTrump;
import org.gnubridge.core.deck.Suit; | package org.gnubridge.core.bidding.rules;
public class Respond1ColorWithNewSuit extends Response {
private ResponseCalculator pc;
private Suit unbidSuit;
| public Respond1ColorWithNewSuit(Auctioneer a, Hand h) { | 1 |
angusmacdonald/wordbrain-solver | src/test/nyc/angus/wordgrid/test/SolverTests.java | [
"public class DictionaryLoader {\n\tprivate final static Logger LOGGER = Logger.getLogger(DictionaryLoader.class.getName());\n\n\tprivate DictionaryLoader() {\n\t\t// Static methods. Should not be instantiated.\n\t}\n\n\t/**\n\t * Load the dictionary from the given location into memory.\n\t * <p>\n\t * The dictiona... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import nyc.angus.wordgrid.dictionary.DictionaryLoader;
import nyc.angus.wordgrid.dictionary.trie.TrieDictionary;
import nyc.angus.wordgrid.solver.WordGridSolver;
import nyc.angus.wordgrid.solver.solution.GridSolution;
import nyc.angus.wordgrid.ui.Printers;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; | package nyc.angus.wordgrid.test;
/**
* Tests of {@link WordGridSolver}.
*/
public class SolverTests {
private final static Logger LOGGER = Logger.getLogger(SolverTests.class.getName());
private static Set<String> wordSet; | private static TrieDictionary trieDictionary; | 1 |
cyriux/mpcmaid | MpcMaid/src/com/mpcmaid/gui/WaveformPanel.java | [
"public final class Marker implements Comparable {\n\tprivate int location;\n\n\tpublic Marker(int location) {\n\t\tthis.location = location;\n\t}\n\n\tpublic int getLocation() {\n\t\treturn location;\n\t}\n\n\tpublic void setLocation(int location) {\n\t\tthis.location = location;\n\t}\n\n\tpublic int move(final in... | import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import com.mpcmaid.audio.Marker;
import com.mpcmaid.audio.Markers;
import com.mpcmaid.audio.Sample;
import com.mpcmaid.audio.Slicer;
import com.mpcmaid.pgm.Pad;
import com.mpcmaid.pgm.Program; | package com.mpcmaid.gui;
/**
* A panel dedicated to display a waveform. It actually contains a Slicer that
* must be initialized before using any delegate method.
*
* @author cyrille martraire
*/
public class WaveformPanel extends JPanel {
private static final int AVERAGE_ENERGY_WINDOW = 43;
private static final int OVERLAP_RATIO = 1;
private static final int WINDOW_SIZE = 1024;
private static final int MIDI_PPQ = 96;
public static final String DEFAULT_FILE_DETAILS = "Drag and Drop a sample file below";
| private Slicer slicer; | 3 |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/AbsMaterialPreference.java | [
"public class MaterialPreferences {\n\n private static final MaterialPreferences instance = new MaterialPreferences();\n\n public static MaterialPreferences instance() {\n return instance;\n }\n\n public static UserInputModule getUserInputModule(Context context) {\n return instance.userInp... | import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.yarolegovich.mp.io.MaterialPreferences;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.util.CompositeClickListener;
import com.yarolegovich.mp.util.Utils; | } finally {
ta.recycle();
}
onCollectAttributes(attrs);
onConfigureSelf();
inflate(getContext(), getLayout(), this);
title = (TextView) findViewById(R.id.mp_title);
summary = (TextView) findViewById(R.id.mp_summary);
icon = (ImageView) findViewById(R.id.mp_icon);
setTitle(titleText);
setSummary(summaryText);
setIcon(iconDrawable);
if (iconTintColor != -1) {
setIconColor(iconTintColor);
}
onViewCreated();
}
public abstract T getValue();
public abstract void setValue(T value);
public void setTitle(@StringRes int textRes) {
setTitle(string(textRes));
}
public void setTitle(CharSequence text) {
title.setVisibility(visibility(text));
title.setText(text);
}
public void setSummary(@StringRes int textRes) {
setSummary(string(textRes));
}
public void setSummary(CharSequence text) {
summary.setVisibility(visibility(text));
summary.setText(text);
}
public void setIcon(@DrawableRes int drawableRes) {
setIcon(drawable(drawableRes));
}
public void setIcon(Drawable iconDrawable) {
icon.setVisibility(iconDrawable != null ? VISIBLE : GONE);
icon.setImageDrawable(iconDrawable);
}
public void setIconColorRes(@ColorRes int colorRes) {
icon.setColorFilter(color(colorRes));
}
public void setIconColor(@ColorInt int color) {
icon.setColorFilter(color);
}
public String getTitle() {
return title.getText().toString();
}
public String getSummary() {
return summary.getText().toString();
}
/*
* Returns index of listener. Index may change, so better do not rely heavily on it.
* It is not a key.
*/
public int addPreferenceClickListener(View.OnClickListener listener) {
return compositeClickListener.addListener(listener);
}
@Override
public void setOnClickListener(OnClickListener l) {
if (compositeClickListener == null) {
super.setOnClickListener(l);
} else {
compositeClickListener.addListener(l);
}
}
public void removePreferenceClickListener(View.OnClickListener listener) {
compositeClickListener.removeListener(listener);
}
public void removePreferenceClickListener(int index) {
compositeClickListener.removeListener(index);
}
public void setUserInputModule(UserInputModule userInputModule) {
this.userInputModule = userInputModule;
}
public void setStorageModule(StorageModule storageModule) {
this.storageModule = storageModule;
}
@Nullable
public String getKey() {
return key;
}
@LayoutRes
protected abstract int getLayout();
/*
* Template methods
*/
protected void onCollectAttributes(AttributeSet attrs) {
}
protected void onConfigureSelf() { | setBackgroundResource(Utils.clickableBackground(getContext())); | 4 |
mikelewis0/easyccg | src/uk/ac/ed/easyccg/rebanking/CCGBankParseReader.java | [
"public abstract class Category {\n private final String asString;\n private final int id;\n private final static String WILDCARD_FEATURE = \"X\"; \n private final static Set<String> bracketAndQuoteCategories = ImmutableSet.of(\"LRB\", \"RRB\", \"LQU\", \"RQU\");\n\n private Category(String asString, String se... | import java.util.concurrent.atomic.AtomicInteger;
import uk.ac.ed.easyccg.syntax.Category;
import uk.ac.ed.easyccg.syntax.Category.Slash;
import uk.ac.ed.easyccg.syntax.SyntaxTreeNode;
import uk.ac.ed.easyccg.syntax.SyntaxTreeNode.SyntaxTreeNodeFactory;
import uk.ac.ed.easyccg.syntax.Util; | package uk.ac.ed.easyccg.rebanking;
/**
* Reads in gold-standard parses from CCGBank.
*/
public class CCGBankParseReader
{
public final static SyntaxTreeNodeFactory factory = new SyntaxTreeNodeFactory(1000, 10000);
private final static String OPEN_BRACKET = "(<";
private final static String OPEN_LEAF = "(<L ";
private final static String SPLIT_REGEX = " |>\\)";
public static SyntaxTreeNode parse(String input) {
return parse(input, new AtomicInteger(0));
}
private static SyntaxTreeNode parse(String input, AtomicInteger wordIndex)
{
int closeBracket = Util.findClosingBracket(input, 0);
int nextOpenBracket = input.indexOf(OPEN_BRACKET, 1);
SyntaxTreeNode result;
if (input.startsWith(OPEN_LEAF))
{
//LEAF NODE
String[] parse = input.split(SPLIT_REGEX);
if (parse.length < 6) {
return null;
}
| result = factory.makeTerminal(new String(parse[4]), Category.valueOf(parse[1]), new String(parse[2]), null, 1.0, wordIndex.getAndIncrement()); | 0 |
Whiley/WhileyTheoremProver | src/main/java/wyal/util/TypeChecker.java | [
"public static interface Named extends Declaration {\n\n\tpublic Name getName();\n\n\tpublic Tuple<VariableDeclaration> getParameters();\n\n\tpublic static abstract class FunctionOrMacro extends AbstractSyntacticItem implements Named {\n\t\tpublic FunctionOrMacro(Name name, Tuple<VariableDeclaration> parameters, St... | import wybs.lang.SyntacticItem;
import static wyal.lang.WyalFile.*;
import java.util.List;
import wyal.lang.*;
import wyal.lang.WyalFile.Declaration.Named;
import wyfs.util.ArrayUtils;
import wyfs.util.Pair;
import wyfs.lang.Path;
import wytp.types.TypeInferer.Environment;
import wytp.types.util.StdTypeEnvironment;
import wytp.types.TypeSystem;
import wyal.lang.WyalFile.Expr;
import wyal.lang.WyalFile.FieldDeclaration;
import wybs.lang.CompilationUnit;
import wybs.lang.SyntacticException;
import wyal.util.NameResolver;
import wyal.util.NameResolver.ResolutionError; | // Copyright 2011 The Whiley Project Developers
//
// 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 wyal.util;
/**
* <p>
* Implements a <i>flow-sensitive</i> type checker for WyAL source files which
* performs various tasks: firstly, it checks that the various kinds of
* expression are used correctly using flow typing to help; secondly, it checks
* that declarations are "sensible"; finally, it resolves function and macro
* invocations based on their type signature. Let's consider each of these in
* turn.
* </p>
*
* <p>
* <b>Type checking expressions</b>. The primary function of the type checker is
* to check that expressions are used correctly. For example, we expect
* arithmetic operators to operator on integer types. Likewise, we cannot
* perform an "array access" on an integer. The following illustrates such an
* incorrect program:
*
* <pre>
* assert:
* forall(int i, int j):
* i[j] == i[j]
* </pre>
*
* The above program is not "type safe" because variable <code>i</code> is used
* in a position where an array is expected. Another similar example is the
* following:
*
* <pre>
* assert:
* forall(int[] xs, bool i):
* xs[i] == xs[i]
* </pre>
*
* Arrays can only be accessed using integer values and, hence, the above fails
* because we are attempting to access array <code>xs</code> using a bool.
* </p>
* <p>
* To illustrate flow-sensitive typing (a.k.a <i>flow typing</i>), consider the
* following
*
* <pre>
* forall(int|null x):
* if:
* x is int
* x > 0
* then:
* x >= 0
* </pre>
*
* If the type checker only considered the declated type of <code>x</code> when
* typing the expression <code>x gt; 0</code> then it would report an error
* (i.e. because <code>int|null</code> is not of the expected type
* <code>int</code>). To resolve this, the type checker maintains a typing
* environment at each point in the program which includes any "refinements"
* which are known to be true at that point (for example, that
* <code>x is int</code> above). The current environment is used when type
* checking a given expression, meaning that the above does indeed type check.
* </p>
*
* <p>
* <b>Sanity checking declarations</b>. When declaring a type, function, macro
* or variable, it is possible to use a type which simply doesn't make sense. In
* such case, we want the type checker to report a problem (as we might not have
* been aware of this). The following illustrates such a case:
*
* <pre>
* type empty is ((int&!int) x)
* </pre>
*
* Here, the type <code>empty</code> defines a type which is equivalent to
* <code>void</code> and, as such, it is impossible to use this type! The type
* checker simply reports an error for any such types it encounters.
* </p>
*
* <p>
* <b>Resolving function or macro invocations</b>. The WyAL language supports
* <i>overloading</i> of functions and macros. It does this primarily because
* the Whiley language (for which WyAL is designed) supports this feature and we
* wish WyAL programs to "look like" whiley programs as much as possible. A
* simple example of this would be:
*
* <pre>
* function id(int x) -> (int r)
* function id(bool b) -> (bool r)
*
* assert:
* forall(int x, int y, int[] arr):
* if:
* id(x) == id(y)
* then:
* arr[id(x)] == arr[id(y)]
* </pre>
*
* We can see here that the correct type for <code>id()</code> must be
* determined in order of the expression <code>arr[id(x)]</code> to type check.
* When deciding which is the appropriate type signature for an invocation,
* there are several factors. Firstly, any candidates which are obviously
* nonsense must be discarded (e.g. <code>id(bool)</code> above, since
* <code>x</code> has type <code>int</code>). However, it is possible that there
* are multiple candidates and the type checker will always choose the "most
* precise" (or give up with an error if none exists). The following
* illustrates:
*
* <pre>
* function id(int x) -> (int r)
* function id(int|null xn) -> (bool r)
*
* assert:
* forall(int x, int y, int[] arr):
* if:
* id(x) == id(y)
* then:
* arr[id(x)] == arr[id(y)]
* </pre>
*
* In this example, the type checker will determine the signature
* <code>id(int)</code> for the invocation. This is because that is the most
* precise type which matches the given arguments.
* </p>
*
* @author David J. Pearce
*
*/
public class TypeChecker {
/**
* The enclosing WyAL file being checked.
*/
private final WyalFile parent;
/**
* The originating source of this file (which may be itself). The need for
* this is somewhat questionable.
*/
private final Path.Entry<? extends CompilationUnit> originatingEntry;
/**
* The type system encapsulates the core algorithms for type simplification
* and subtyping testing.
*/ | private TypeSystem types; | 3 |
Tonius/E-Mobile | src/main/java/tonius/emobile/network/message/MessageCellphoneHome.java | [
"public class EMConfig {\n \n public static Configuration config;\n public static List<ConfigSection> configSections = new ArrayList<ConfigSection>();\n \n public static final ConfigSection sectionGeneral = new ConfigSection(\"General Settings\", \"general\");\n public static final ConfigSection s... | import io.netty.buffer.ByteBuf;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBed;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;
import tonius.emobile.config.EMConfig;
import tonius.emobile.item.ItemCellphone;
import tonius.emobile.session.CellphoneSessionLocation;
import tonius.emobile.session.CellphoneSessionsHandler;
import tonius.emobile.util.ServerUtils;
import tonius.emobile.util.StringUtils;
import tonius.emobile.util.TeleportUtils;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext; | package tonius.emobile.network.message;
public class MessageCellphoneHome implements IMessage, IMessageHandler<MessageCellphoneHome, IMessage> {
private String player;
public MessageCellphoneHome() {
}
public MessageCellphoneHome(String player) {
this.player = player;
}
@Override
public void fromBytes(ByteBuf buf) {
this.player = ByteBufUtils.readUTF8String(buf);
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeUTF8String(buf, this.player);
}
@Override
public IMessage onMessage(MessageCellphoneHome msg, MessageContext ctx) { | if (EMConfig.allowTeleportHome) { | 0 |
tsauvine/omr | src/omr/gui/calibration/CalibratePanel.java | [
"public class AnalyzeSheetsTask extends Task {\n\n private Project project;\n\n public AnalyzeSheetsTask(Project project, Observer observer) {\n super(observer);\n \n this.project = project;\n }\n \n @Override\n public void run() {\n SheetStructure structure = project.g... | import java.awt.BorderLayout;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import omr.AnalyzeSheetsTask;
import omr.Project;
import omr.Sheet;
import omr.Task;
import omr.Project.ThresholdingStrategy;
import omr.gui.Gui; | package omr.gui.calibration;
public class CalibratePanel extends JPanel implements ListSelectionListener, ChangeListener, Observer {
private static final long serialVersionUID = 1L;
private Gui gui; | private Project project; | 1 |
BottleRocketStudios/Android-GroundControl | GroundControlSample/app/src/main/java/com/bottlerocketstudios/groundcontrolsample/config/agent/RegionConfigurationAgent.java | [
"public class GroundControl {\n private static final String TAG = GroundControl.class.getSimpleName();\n\n private static final ConcurrentHashMap<String, ExecutionBuilderFactory> sExecutionBuilderFactoryMap = new ConcurrentHashMap<>();\n private static final ConcurrentHashMap<String, UiInformationContainer... | import android.content.Context;
import com.bottlerocketstudios.groundcontrol.convenience.GroundControl;
import com.bottlerocketstudios.groundcontrol.dependency.DependencyHandlingAgent;
import com.bottlerocketstudios.groundcontrol.listener.FunctionalAgentListener;
import com.bottlerocketstudios.groundcontrolsample.config.controller.ConfigurationController;
import com.bottlerocketstudios.groundcontrolsample.config.model.Configuration;
import com.bottlerocketstudios.groundcontrolsample.config.model.CurrentVersion;
import com.bottlerocketstudios.groundcontrolsample.config.model.RegionConfiguration; | /*
* Copyright (c) 2016 Bottle Rocket LLC.
* 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.bottlerocketstudios.groundcontrolsample.config.agent;
/**
* Fetch the RegionConfiguration from server or cache.
*/
public class RegionConfigurationAgent extends DependencyHandlingAgent<RegionConfiguration, Void> {
private final Context mContext;
private Configuration mConfiguration;
private CurrentVersion mCurrentVersion;
public RegionConfigurationAgent(Context context) {
mContext = context.getApplicationContext();
}
@Override
public String getUniqueIdentifier() {
return RegionConfigurationAgent.class.getCanonicalName();
}
@Override
public void cancel() {}
@Override
public void onProgressUpdateRequested() {}
@Override
public void run() { | addParallelDependency(GroundControl.bgAgent(getAgentExecutor(), new ConfigurationAgent(mContext)), | 0 |
Aleksey-Terzi/MerchantsTFC | src/com/aleksey/merchants/TileEntities/TileEntityAnvilDie.java | [
"public class CoinInfo\n{\n public String CoinName;\n public int DieColor;\n public String MetalName;\n public int Level;\n \n public CoinInfo(String coinName, int dieColor, String metalName, int level)\n {\n CoinName = coinName;\n DieColor = dieColor;\n MetalName = metalNa... | import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.AxisAlignedBB;
import com.aleksey.merchants.Core.CoinInfo;
import com.aleksey.merchants.Core.Constants;
import com.aleksey.merchants.Core.DieInfo;
import com.aleksey.merchants.Core.ItemList;
import com.aleksey.merchants.Helpers.CoinHelper;
import com.aleksey.merchants.Helpers.ItemHelper;
import com.bioxx.tfc.TileEntities.NetworkTileEntity;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; | {
if (_storage[i] != null)
{
NBTTagCompound itemTag = new NBTTagCompound();
itemTag.setByte("Slot", (byte) i);
_storage[i].writeToNBT(itemTag);
itemList.appendTag(itemTag);
}
}
nbt.setTag("Items", itemList);
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
_metalWeightInHundreds = nbt.getInteger("MetalWeight");
_metalMeta = nbt.getInteger("MetalMeta");
NBTTagList itemList = nbt.getTagList("Items", 10);
for (int i = 0; i < itemList.tagCount(); i++)
{
NBTTagCompound itemTag = itemList.getCompoundTagAt(i);
byte byte0 = itemTag.getByte("Slot");
if (byte0 >= 0 && byte0 < _storage.length)
setInventorySlotContents(byte0, ItemStack.loadItemStackFromNBT(itemTag));
}
}
@Override
public void handleInitPacket(NBTTagCompound nbt)
{
_metalWeightInHundreds = nbt.hasKey("MetalWeight") ? nbt.getInteger("MetalWeight"): 0;
_metalMeta = nbt.hasKey("MetalMeta") ? nbt.getInteger("MetalMeta"): 0;
this.worldObj.func_147479_m(xCoord, yCoord, zCoord);
}
@Override
public void createInitNBT(NBTTagCompound nbt)
{
nbt.setInteger("MetalWeight", _metalWeightInHundreds);
nbt.setInteger("MetalMeta", _metalMeta);
}
@Override
public void handleDataPacket(NBTTagCompound nbt)
{
if (!nbt.hasKey("Action"))
return;
byte action = nbt.getByte("Action");
switch (action)
{
case _actionId_Mint:
actionHandlerMint();
break;
}
}
@Override
public void updateEntity()
{
}
//Send action to server
public void actionMint()
{
NBTTagCompound nbt = new NBTTagCompound();
nbt.setByte("Action", _actionId_Mint);
this.broadcastPacketInRange(this.createDataPacket(nbt));
this.worldObj.func_147479_m(xCoord, yCoord, zCoord);
}
private void actionHandlerMint()
{
if(!canMint())
return;
int coinWeightIndex = CoinHelper.getCoinWeight(_storage[TrusselSlot]);
int coinWeight = (int)(CoinHelper.getWeightOz(coinWeightIndex) * 100);
int metalTotalWeight = getMetalTotalWeight();
int coinQuantity = Math.min(coinWeightIndex, metalTotalWeight / coinWeight);
ItemStack coinStack = _storage[CoinSlot];
int coinStackSize = coinStack != null ? coinStack.stackSize: 0;
if(coinQuantity + coinStackSize > _maxCoinStackSize)
coinQuantity = _maxCoinStackSize - coinStackSize;
if(coinStack == null)
_storage[CoinSlot] = getResultCoin(coinQuantity);
else
coinStack.stackSize += coinQuantity;
decrMetalTotalWeight(coinQuantity * coinWeight);
damageHammer();
this.worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
public boolean canMint()
{
ItemStack trusselStack = _storage[TrusselSlot];
if(_storage[HammerSlot] == null || trusselStack == null)
return false;
ItemStack coinStack = _storage[CoinSlot];
ItemStack resultStack = getResultCoin(1);
| if(coinStack != null && (coinStack.stackSize >= _maxCoinStackSize || !ItemHelper.areItemEquals(coinStack, resultStack))) | 4 |
reines/game | game-client/src/main/java/com/game/client/handlers/packet/ChatHandler.java | [
"public final class Client extends ClientFrame {\n\tprivate static final Logger log = LoggerFactory.getLogger(Client.class);\n\n\tpublic static final String DEFAULT_HOST = \"localhost\";\n\tpublic static final int DEFAULT_PORT = 36954;\n\tpublic static final int[] ICON_SIZES = {128, 64, 32, 16};\n\tpublic static fi... | import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.game.client.Client;
import com.game.client.WorldManager;
import com.game.client.handlers.PacketHandler;
import com.game.client.model.Player;
import com.game.client.ui.ChatMessages;
import com.game.common.codec.Packet;
import com.game.common.model.Hash; | package com.game.client.handlers.packet;
public class ChatHandler implements PacketHandler {
private static final Logger log = LoggerFactory.getLogger(ChatHandler.class);
@Override | public void handlePacket(Client client, WorldManager world, Packet packet) throws Exception { | 0 |
davidmoten/rtree | src/test/java/com/github/davidmoten/rtree/BenchmarksRTree.java | [
"static List<Entry<Object, Rectangle>> entries1000(Precision precision) {\n List<Entry<Object, Rectangle>> list = new ArrayList<Entry<Object, Rectangle>>();\n BufferedReader br = new BufferedReader(\n new InputStreamReader(BenchmarksRTree.class.getResourceAsStream(\"/1000.txt\")));\n String line... | import static com.github.davidmoten.rtree.Utilities.entries1000;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import com.github.davidmoten.rtree.fbs.SerializerFlatBuffers;
import com.github.davidmoten.rtree.geometry.Geometries;
import com.github.davidmoten.rtree.geometry.Point;
import com.github.davidmoten.rtree.geometry.Rectangle;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func1; | package com.github.davidmoten.rtree;
@State(Scope.Benchmark)
public class BenchmarksRTree {
private final static Precision precision = Precision.DOUBLE;
private final List<Entry<Object, Point>> entries = GreekEarthquakes.entriesList(precision);
| private final List<Entry<Object, Rectangle>> some = entries1000(precision); | 0 |
4FunApp/4Fun | server/4FunServer/src/com/mollychin/spider/MovieSpider.java | [
"public class MovieInfo {\n\tprivate String date;\n\tprivate String movieName;\n\tprivate double mark;\n\tprivate String pic;\n\tprivate String director;\n\tprivate String playWriter;\n\tprivate String country;\n\tprivate String briefIntro;\n\tprivate String moreInfo;\n\tprivate String pageUrl;\n\tprivate String mo... | import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import com.mollychin.bean.MovieInfo;
import com.mollychin.bean.MovieInfo.ActorInfo;
import com.mollychin.utils.ConstantsUtil;
import com.mollychin.utils.DownloadUtil;
import com.mollychin.utils.JDBCUtil;
import com.mollychin.utils.JsoupUtil;
import com.mollychin.utils.SystemUtil; | package com.mollychin.spider;
/**
* Created by mollychin on 2016/11/16.
*/
public class MovieSpider {
public final static String PICTURE4MOVIE = "Picture4Movie/";
public void movieSpider() {
try {
MovieSpider movieParser = new MovieSpider();
Document document = JsoupUtil.connect(ConstantsUtil.MOVIE_URL);
Connection conn = JDBCUtil.getConnection();
MovieInfo movieInfo = new MovieInfo(); | ActorInfo actorInfo = new ActorInfo(); | 1 |
wymarc/astrolabe-generator | src/main/java/com/wymarc/astrolabe/generator/printengines/postscript/extras/horary/EqualHours.java | [
"public class Astrolabe {\n\n public static final String[] SHOWOPTIONS = { \"Climate and mater\", \"Climate only\", \"Mater only\", \"Mater and nauticum\"};\n public static final String[] SHAPEOPTIONS = { \"Classic\", \"Octagonal\"};\n public static final String[] HOUROPTIONS = { \"Roman\", \"Arabic\", \"A... | import com.wymarc.astrolabe.Astrolabe;
import com.wymarc.astrolabe.generator.printengines.postscript.util.EPSToolKit;
import com.wymarc.astrolabe.math.AstroMath;
import com.wymarc.astrolabe.math.InterSect;
import com.wymarc.astrolabe.math.ThreePointCenter;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List; | /**
* $Id: AstrolabeGenerator.java,v 3.1
* <p/>
* The Astrolabe Generator 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.
* <p/>
* The Astrolabe Generator 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.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* <p/>
* Copyright (c) 2017 Timothy J. Mitchell
*/
package com.wymarc.astrolabe.generator.printengines.postscript.extras.horary;
/**
* This Plugin will calculate the components of an equal hours style Horary
* Quadrant and print the results to an Encapsulated PostScript (EPS) file.
* Note that this file is static with no inputs. Software is included for reference.
* <p>
* link http://astrolabeproject.com.com
* link http://www.astrolabes.org
*/
public class EqualHours {
// Note: limit is 25N to 65N
public static double NORTH_LIMIT = 65.0;
public static double SOUTH_LIMIT = 25.0;
//todo add colors, add latitude
| private Astrolabe myAstrolabe = new Astrolabe(); | 0 |
sekwah41/Advanced-Portals | src/main/java/com/sekwah/advancedportals/bukkit/listeners/Listeners.java | [
"public class AdvancedPortalsPlugin extends JavaPlugin {\n\n private Settings settings;\n\n protected boolean isProxyPluginEnabled = false;\n\n protected boolean forceRegisterProxyChannels = false;\n protected boolean disableProxyWarning = false;\n\n private boolean worldEditActive = false;\n\n pr... | import com.sekwah.advancedportals.bukkit.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.bukkit.PluginMessages;
import com.sekwah.advancedportals.bukkit.api.events.WarpEvent;
import com.sekwah.advancedportals.bukkit.config.ConfigAccessor;
import com.sekwah.advancedportals.bukkit.destinations.Destination;
import com.sekwah.advancedportals.bukkit.portals.AdvancedPortal;
import com.sekwah.advancedportals.bukkit.portals.Portal;
import org.bukkit.*;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Orientable;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID; | package com.sekwah.advancedportals.bukkit.listeners;
public class Listeners implements Listener {
private static boolean UseOnlyServerAxe = false;
private static Material WandMaterial;
private final AdvancedPortalsPlugin plugin;
public static String HAS_WARPED = "hasWarped";
public static String LAVA_WARPED = "lavaWarped";
@SuppressWarnings("deprecation")
public Listeners(AdvancedPortalsPlugin plugin) {
this.plugin = plugin;
| ConfigAccessor config = new ConfigAccessor(plugin, "config.yml"); | 3 |
spring-cloud/spring-cloud-bus | spring-cloud-bus/src/test/java/org/springframework/cloud/bus/BusAutoConfigurationTests.java | [
"@SuppressWarnings(\"serial\")\npublic class AckRemoteApplicationEvent extends RemoteApplicationEvent {\n\n\tprivate final String ackId;\n\n\tprivate final String ackDestinationService;\n\n\tprivate Class<? extends RemoteApplicationEvent> event;\n\n\t@SuppressWarnings(\"unused\")\n\tprivate AckRemoteApplicationEven... | import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.cloud.bus.event.AckRemoteApplicationEvent;
import org.springframework.cloud.bus.event.PathDestinationFactory;
import org.springframework.cloud.bus.event.RefreshRemoteApplicationEvent;
import org.springframework.cloud.bus.event.RemoteApplicationEvent;
import org.springframework.cloud.bus.event.SentApplicationEvent;
import org.springframework.cloud.bus.event.UnknownRemoteApplicationEvent;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.stream.config.BindingProperties;
import org.springframework.cloud.stream.config.BindingServiceProperties;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.cloud.bus;
public class BusAutoConfigurationTests {
private ConfigurableApplicationContext context;
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void defaultId() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--server.port=0");
assertThat(this.context.getBean(BusProperties.class).getId().startsWith("application:0:"))
.as("Wrong ID: " + this.context.getBean(BusProperties.class).getId()).isTrue();
}
@Test
public void inboundNotForSelf() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=foo",
"--server.port=0");
this.context.getBean(BusConstants.INPUT, MessageChannel.class)
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "bar", "bar")));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNull();
}
@Test
public void inboundFromSelf() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=foo",
"--server.port=0");
this.context.getBean(BusConstants.INPUT, MessageChannel.class)
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", (String) null)));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNull();
}
@Test
public void inboundNotFromSelf() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=bar",
"--server.port=0");
this.context.getBean(BusConstants.INPUT, MessageChannel.class)
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", (String) null)));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNotNull();
}
@Test
public void inboundNotFromSelfWithAck() throws Exception {
this.context = SpringApplication.run(
new Class[] { InboundMessageHandlerConfiguration.class, OutboundMessageHandlerConfiguration.class,
SentMessageConfiguration.class },
new String[] { "--spring.cloud.bus.id=bar", "--server.port=0",
"--spring.main.allow-bean-definition-overriding=true" });
this.context.getBean(BusConstants.INPUT, MessageChannel.class)
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", (String) null)));
RefreshRemoteApplicationEvent refresh = this.context.getBean(InboundMessageHandlerConfiguration.class).refresh;
assertThat(refresh).isNotNull();
TestStreamBusBridge busBridge = this.context.getBean(TestStreamBusBridge.class);
busBridge.latch.await(200, TimeUnit.SECONDS); | assertThat(busBridge.message).isInstanceOf(AckRemoteApplicationEvent.class); | 0 |
mzlogin/guanggoo-android | app/src/main/java/org/mazhuang/guanggoo/topiclist/TopicListPresenter.java | [
"public class NetworkTaskScheduler {\n\n private ExecutorService mExecutor;\n\n private static class InstanceHolder {\n private static NetworkTaskScheduler sInstance = new NetworkTaskScheduler();\n }\n\n public static NetworkTaskScheduler getInstance() {\n return InstanceHolder.sInstance;\... | import org.mazhuang.guanggoo.data.NetworkTaskScheduler;
import org.mazhuang.guanggoo.data.OnResponseListener;
import org.mazhuang.guanggoo.data.entity.ListResult;
import org.mazhuang.guanggoo.data.entity.Topic;
import org.mazhuang.guanggoo.data.task.BaseTask;
import org.mazhuang.guanggoo.data.task.GetTopicListTask;
import org.mazhuang.guanggoo.util.ConstantUtil;
import org.mazhuang.guanggoo.util.UrlUtil;
import lombok.Setter; | package org.mazhuang.guanggoo.topiclist;
/**
*
* @author mazhuang
* @date 2017/9/16
*/
public class TopicListPresenter implements TopicListContract.Presenter {
private TopicListContract.View mView;
private BaseTask mCurrentTask;
private int mPagination;
public TopicListPresenter(TopicListContract.View view) {
mView = view;
view.setPresenter(this);
}
@Override
public void getTopicList() {
if (mCurrentTask != null) {
mCurrentTask.cancel();
}
mCurrentTask = new GetTopicListTask(mView.getUrl(), | new OnResponseListener<ListResult<Topic>>() { | 2 |
CROW-NDOV/displaydirect | distribution/src/main/java/nl/crowndov/displaydirect/distribution/kv78/RealtimeMessageMapper.java | [
"public class DeleteMessage extends RealtimeMessage implements Serializable {\n\n private static final long serialVersionUID = -4335030844531563517L;\n\n private final int messageCode;\n\n public DeleteMessage(String dataOwnerCode, LocalDate date, int messageCode, String stopCode) {\n super(Type.MES... | import nl.crowndov.displaydirect.distribution.domain.travelinfo.DeleteMessage;
import nl.crowndov.displaydirect.distribution.domain.travelinfo.PassTime;
import nl.crowndov.displaydirect.distribution.domain.travelinfo.RealtimeMessage;
import nl.crowndov.displaydirect.distribution.domain.travelinfo.UpdateMessage;
import nl.crowndov.displaydirect.distribution.input.TimingPointProvider;
import nl.crowndov.displaydirect.distribution.kv78.domain.Kv78Packet;
import nl.crowndov.displaydirect.distribution.kv78.domain.Kv78Table;
import nl.crowndov.displaydirect.distribution.util.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.stream.Collectors; | package nl.crowndov.displaydirect.distribution.kv78;
/**
* Copyright 2017 CROW-NDOV
*
* This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package.
*/
public class RealtimeMessageMapper {
private static final Logger LOGGER = LoggerFactory.getLogger(RealtimeMessageMapper.class);
public static List<RealtimeMessage> toRealtimeMessage(Kv78Packet packet) {
if (packet.getTables().size() != 1) {
return new ArrayList<>();
}
Kv78Table t = packet.getTables().get(0);
if (t != null && t.getTableName() != null) {
switch (t.getTableName()) {
case "DATEDPASSTIME":
return handle(packet, t.getRecords(), RealtimeMessageMapper::passTime);
case "GENERALMESSAGEUPDATE":
LOGGER.info("Got general message update");
return handle(packet, t.getRecords(), RealtimeMessageMapper::updateMessage);
case "GENERALMESSAGEDELETE":
LOGGER.info("Got general message delete");
return handle(packet, t.getRecords(), RealtimeMessageMapper::deleteMessage);
default:
break;
}
}
return new ArrayList<>();
}
private static List<RealtimeMessage> handle(Kv78Packet packet, List<Map<String, String>> records, BiFunction<Kv78Packet, Map<String, String>, RealtimeMessage> f) {
return records.stream().map(r -> f.apply(packet, r)).collect(Collectors.toList());
}
public static RealtimeMessage passTime(Kv78Packet packet, Map<String, String> r) {
LocalDate date = LocalDate.parse(r.get("OperationDate"));
PassTime pt = new PassTime(r.get("DataOwnerCode"), date,
r.get("LinePlanningNumber"), Integer.valueOf(r.get("JourneyNumber")), r.get("UserStopCode")); | pt.setExpectedArrivalTime((int) DateTimeUtil.getTime(date, r.get("ExpectedArrivalTime")).toEpochSecond()); | 7 |
Aurilux/Cybernetica | src/main/java/com/vivalux/cyb/item/module/ModuleLexica.java | [
"@Mod(modid = CYBModInfo.MOD_ID,\n name = CYBModInfo.MOD_NAME,\n guiFactory = CYBModInfo.GUI_FACTORY,\n version = CYBModInfo.MOD_VERSION)\npublic class Cybernetica {\n\t@Instance(CYBModInfo.MOD_ID)\n\tpublic static Cybernetica instance;\n\n\t@SidedProxy(clientSide = CYBModInfo.CLIENT_PROXY, serverSide = CY... | import com.vivalux.cyb.Cybernetica;
import com.vivalux.cyb.api.Implant.ImplantType;
import com.vivalux.cyb.api.Module;
import com.vivalux.cyb.handler.GuiHandler;
import com.vivalux.cyb.init.CYBItems;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import java.util.EnumSet; | package com.vivalux.cyb.item.module;
public class ModuleLexica extends Module {
public ModuleLexica(String str, String str2) {
CYBItems.setItem(this, str, str2); | this.setCompatibles(EnumSet.of(ImplantType.TORSO)); | 1 |
AstartesGuardian/WebDAV-Server | WebDAV-Server/src/webdav/server/virtual/contentmutation/CryptedContentMutation.java | [
"public class HTTPEnvRequest\r\n{\r\n public static Builder create()\r\n {\r\n return new Builder();\r\n }\r\n public static class Builder\r\n {\r\n public Builder()\r\n { }\r\n \r\n private HTTPRequest request;\r\n private HTTPCommand command;\r\n pri... | import http.server.message.HTTPEnvRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import webdav.server.tools.Helper;
import webdav.server.crypter.CipherCrypter;
import webdav.server.crypter.AbstractCrypter;
import webdav.server.resource.IResource;
| package webdav.server.virtual.contentmutation;
public class CryptedContentMutation implements IContentMutation
{
public CryptedContentMutation(
AbstractCrypter.Algorithm algo,
String username,
String password,
| BiFunction<IResource, HTTPEnvRequest, byte[]> keyAdditionSupplier) throws Exception
| 0 |
IceReaper/DesktopAdventuresToolkit | src/net/eiveo/original/sections/todo/not_converted_yet/ZONE.java | [
"public class IZON {\r\n\tpublic short width;\r\n\tpublic short height;\r\n\tpublic short type;\r\n\tpublic short[] tiles;\r\n\tpublic Short world;\r\n\t\r\n\tpublic static IZON read(SmartByteBuffer data, boolean isYoda, short world) throws Exception {\r\n\t\tIZON instance = new IZON();\r\n\r\n\t\t// Somehow IZON i... | import java.util.ArrayList;
import java.util.List;
import net.eiveo.original.sections.IZON;
import net.eiveo.original.sections.todo.determine_values.IACT;
import net.eiveo.original.sections.todo.determine_values.IZAX;
import net.eiveo.original.sections.todo.determine_values.IZX4;
import net.eiveo.original.sections.todo.determine_values.HTSP.Hotspot;
import net.eiveo.utils.SmartByteArrayOutputStream;
import net.eiveo.utils.SmartByteBuffer;
| package net.eiveo.original.sections.todo.not_converted_yet;
public class ZONE {
public List<Zone> zones = new ArrayList<>();
public static ZONE read(SmartByteBuffer data, boolean isYoda) throws Exception {
ZONE instance = new ZONE();
int length = 0;
int lengthStart = 0;
if (!isYoda) {
length = data.getInt();
lengthStart = data.position();
}
short zoneCount = data.getShort();
for (short i = 0; i < zoneCount; i++) {
instance.zones.add(Zone.read(data, isYoda, i));
}
if (!isYoda && lengthStart + length != data.position()) {
throw new Exception("Length mismatch.");
}
return instance;
}
| public void write(SmartByteArrayOutputStream outputStream, boolean isYoda) {
| 5 |
cqjjjzr/BiliLiveLib | BiliLiveLib/src/main/java/charlie/bililivelib/capsuletoy/CapsuleToyProtocol.java | [
"public class Globals {\n private static final String BILI_PASSPORT_HOST_ROOT = \"passport.bilibili.com\";\n private static final String BILI_LIVE_HOST_ROOT = \"live.bilibili.com\";\n @Getter\n private static int CONNECTION_ALIVE_TIME_SECOND = 10;\n private static Globals instance;\n @Getter\n ... | import charlie.bililivelib.Globals;
import charlie.bililivelib.exceptions.BiliLiveException;
import charlie.bililivelib.exceptions.NetworkException;
import charlie.bililivelib.exceptions.NotLoggedInException;
import charlie.bililivelib.internalutil.net.PostArguments;
import charlie.bililivelib.user.Session;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.ToString;
import org.apache.http.cookie.Cookie;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NotNull;
import java.util.List; | package charlie.bililivelib.capsuletoy;
/**
* 用于处理扭蛋机的协议类。
*
* @author Charlie Jiang
* @since rv1
*/
public class CapsuleToyProtocol {
private static final String CAPSULE_OPEN_POST = "/api/ajaxCapsuleOpen";
private static final String CAPSULE_INFO_GET = "/api/ajaxCapsule";
private static final String EXCEPTION_KEY = "exception.capsule_toy";
private static final int STATUS_NOT_LOGGED_IN = -101;
private static final int STATUS_SUCCESS = 0;
private static final int STATUS_NOT_ENOUGH = -500;
private static final String TOKEN_COOKIE_KEY = "LIVE_LOGIN_DATA";
private Session session;
public CapsuleToyProtocol(@NotNull Session session) {
this.session = session;
}
/**
* 打开指定数量的普通扭蛋币。
*
* @param count 数量,仅能为1,10或100
* @return 扭蛋结果
* @throws NetworkException 在发生网络错误时抛出
* @throws IllegalArgumentException 在数量不为1,10或100时抛出
*/
public OpenCapsuleToyInfo openNormal(@MagicConstant(intValues = {1, 10, 100}) int count)
throws BiliLiveException {
return openCapsule("normal", count, getToken());
}
/**
* 打开指定数量的梦幻扭蛋币。
*
* @param count 数量,仅能为1,10或100
* @return 扭蛋结果
* @throws NetworkException 在发生网络错误时抛出
* @throws IllegalArgumentException 在数量不为1,10或100时抛出
*/
public OpenCapsuleToyInfo openColorful(@MagicConstant(intValues = {1, 10, 100}) int count)
throws BiliLiveException {
return openCapsule("colorful", count, getToken());
}
private OpenCapsuleToyInfo openCapsule(String type, int count, String token) throws BiliLiveException {
if (count != 1 && count != 10 && count != 100)
throw new IllegalArgumentException("count must be 1, 10 or 100.");
JsonObject rootObject = session.getHttpHelper().postBiliLiveJSON(CAPSULE_OPEN_POST,
new PostArguments()
.add("type", type)
.add("count", String.valueOf(count))
.add("token", token),
JsonObject.class, EXCEPTION_KEY);
int code = rootObject.get("code").getAsInt();
if (rootObject.get("code").getAsInt() == STATUS_NOT_LOGGED_IN) throw new NotLoggedInException();
if (rootObject.get("code").getAsInt() != STATUS_SUCCESS) return new OpenCapsuleToyInfo(code,
rootObject.get("msg").getAsString()); | return Globals.get().gson().fromJson(rootObject, OpenCapsuleToyInfo.class); | 0 |
WolfgangFahl/Mediawiki-Japi | src/test/java/com/bitplan/mediawiki/japi/TestAPI_Allpages.java | [
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Bl {\n\n @XmlAttribute(name = \"pageid\")\n protected Integer pageid;\n @XmlAttribute(name = \"ns\")\n protected Integer ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Ruft den Wert der ... | import com.bitplan.mediawiki.japi.api.Ii;
import com.bitplan.mediawiki.japi.api.Im;
import com.bitplan.mediawiki.japi.api.Img;
import com.bitplan.mediawiki.japi.api.Iu;
import com.bitplan.mediawiki.japi.api.P;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.logging.Level;
import org.junit.Test;
import com.bitplan.mediawiki.japi.api.Bl; | /**
*
* This file is part of the https://github.com/WolfgangFahl/Mediawiki-Japi open source project
*
* Copyright 2015-2021 BITPlan GmbH https://github.com/BITPlan
*
* 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.bitplan.mediawiki.japi;
/**
* test https://www.mediawiki.org/wiki/API:Allpages
*
* @author wf
*
*/
public class TestAPI_Allpages extends APITestbase {
@Test
public void testAllpages() throws Exception {
ExampleWiki lWiki = ewm.get(ExampleWiki.DEFAULT_WIKI_ID);
debug = true;
if (hasWikiUser(lWiki)) {
lWiki.login();
String apfrom = null;
int aplimit = 25000;
List<P> pages = lWiki.wiki.getAllPages(apfrom, aplimit);
if (debug) {
LOGGER.log(Level.INFO, "page #=" + pages.size());
}
assertTrue(pages.size() >= 6);
}
}
@Test
public void testGetAllImagesByTimeStamp() throws Exception {
ExampleWiki lWiki = ewm.get("bitplanwiki");
String[] expectedUsage = { "PDF Example", "Picture Example" };
String[] expected = { "Wuthering_Heights_NT.pdf",
"Radcliffe_Chastenay_-_Les_Mysteres_d_Udolphe_frontispice_T6.jpg" };
String aistart = "20210703131900";
String aiend = "20210703132500";
int ailimit = 500;
// lWiki.wiki.setDebug(true);
List<Img> images = lWiki.wiki.getAllImagesByTimeStamp(aistart, aiend, ailimit);
// debug = true;
if (debug) {
LOGGER.log(Level.INFO, "found images:" + images.size());
int i=0;
for (Img image:images) {
i++;
LOGGER.log(Level.INFO,String.format("%d: %s %s",i, image.getTimestamp(),image.getName()));
}
}
assertEquals(expected.length, images.size());
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], images.get(i).getName());
}
// lWiki.wiki.setDebug(true);
int i = 0;
for (Img img : images) {
if (!"Index.png".equals(img.getName())) { | List<Iu> ius = lWiki.wiki.getImageUsage("File:" + img.getName(), "", 50); | 4 |
arquillian/arquillian-recorder | arquillian-recorder-screenshooter-base/arquillian-recorder-screenshooter-impl-base/src/main/java/org/arquillian/extension/recorder/screenshooter/impl/ScreenshooterLifecycleObserver.java | [
"public class DefaultFileNameBuilder extends AbstractFileNameBuilder {\n\n protected ResourceMetaData metaData;\n\n protected When when;\n\n protected ResourceIdentifier<ResourceType> resourceIdentifier;\n\n public DefaultFileNameBuilder() {\n setDefaultFileIdentifier();\n }\n\n public Defa... | import org.arquillian.extension.recorder.DefaultFileNameBuilder;
import org.arquillian.extension.recorder.RecorderStrategy;
import org.arquillian.extension.recorder.RecorderStrategyRegister;
import org.arquillian.extension.recorder.When;
import org.arquillian.extension.recorder.screenshooter.AnnotationScreenshootingStrategy;
import org.arquillian.extension.recorder.screenshooter.Screenshooter;
import org.arquillian.extension.recorder.screenshooter.ScreenshooterConfiguration;
import org.arquillian.extension.recorder.screenshooter.ScreenshotMetaData;
import org.arquillian.extension.recorder.screenshooter.ScreenshotType;
import org.arquillian.extension.recorder.screenshooter.api.Blur;
import org.arquillian.extension.recorder.screenshooter.api.BlurLevel;
import org.arquillian.extension.recorder.screenshooter.api.Screenshot;
import org.arquillian.extension.recorder.screenshooter.event.AfterScreenshotTaken;
import org.arquillian.extension.recorder.screenshooter.event.BeforeScreenshotTaken;
import org.arquillian.extension.recorder.screenshooter.event.TakeScreenshot;
import org.jboss.arquillian.core.api.Event;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.test.spi.TestClass;
import org.jboss.arquillian.test.spi.TestResult;
import org.jboss.arquillian.test.spi.event.suite.AfterTestLifecycleEvent;
import org.jboss.arquillian.test.spi.event.suite.Before;
import org.jboss.arquillian.test.spi.event.suite.TestEvent;
import org.jboss.arquillian.test.spi.event.suite.TestLifecycleEvent; | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.arquillian.extension.recorder.screenshooter.impl;
/**
* @author <a href="mailto:smikloso@redhat.com">Stefan Miklosovic</a>
* @author <a href="mailto:jhuska@redhat.com">Juraj Huska</a>
*/
public class ScreenshooterLifecycleObserver {
@Inject | private Instance<RecorderStrategyRegister> recorderStrategyRegister; | 1 |
ZhangFly/WTFSocket_Server_JAVA | src/wtf/socket/WTFSocketServer.java | [
"public interface WTFSocketController {\n\n /**\n * 控制器优先级\n * 数值越低优先级越高,默认的优先级为 WTFSocketPriority.MEDIUM\n *\n * @return 优先级数值\n */\n default int priority() {\n return WTFSocketPriority.MEDIUM;\n }\n\n /**\n * 是否响应该消息\n *\n * @param msg 消息对象\n *\n * @retur... | import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import wtf.socket.controller.WTFSocketController;
import wtf.socket.controller.WTFSocketControllersGroup;
import wtf.socket.event.WTFSocketEventListenersGroup;
import wtf.socket.protocol.WTFSocketProtocolFamily;
import wtf.socket.routing.WTFSocketRouting;
import wtf.socket.schedule.WTFSocketScheduler;
import wtf.socket.secure.delegate.WTFSocketSecureDelegatesGroup;
import javax.annotation.Resource; | package wtf.socket;
/**
* WTFSocket服务器
* <p>
* Created by ZFly on 2017/4/25.
*/
public final class WTFSocketServer {
/**
* Spring 上下文
*/
private ApplicationContext spring = new ClassPathXmlApplicationContext("spring.wtf.socket.xml");
/**
* 消息调度组件
* 根据消息的头信息将消息投递到指定的目的地
*/
@Resource()
private WTFSocketScheduler scheduler;
/**
* 路由组件
* 查询和记录连接的地址
*/
@Resource
private WTFSocketRouting routing;
/**
* 协议族组件
* IO层收到数据后选择合适的解析器将数据解析为标准消息格式
*/
@Resource | private WTFSocketProtocolFamily protocolFamily; | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.