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 |
|---|---|---|---|---|---|---|
BeYkeRYkt/LightAPI | craftbukkit-nms-v1_15_R1/src/main/java/ru/beykerykt/minecraft/lightapi/bukkit/internal/handler/craftbukkit/nms/v1_15_R1/VanillaNMSHandler.java | [
"public class BukkitPlatformImpl implements IPlatformImpl, IBukkitExtension {\n\n private static final String DEFAULT_IMPL_NAME = \"craftbukkit\";\n /**\n * CONFIG\n */\n private final String CONFIG_TITLE = \"general\";\n private final String CONFIG_DEBUG = CONFIG_TITLE + \".debug\";\n privat... | import com.google.common.collect.Lists;
import net.minecraft.server.v1_15_R1.BlockPosition;
import net.minecraft.server.v1_15_R1.Chunk;
import net.minecraft.server.v1_15_R1.ChunkCoordIntPair;
import net.minecraft.server.v1_15_R1.EntityPlayer;
import net.minecraft.server.v1_15_R1.EnumSkyBlock;
import net.minecraft.server.v1_15_R1.LightEngineBlock;
import net.minecraft.server.v1_15_R1.LightEngineGraph;
import net.minecraft.server.v1_15_R1.LightEngineLayer;
import net.minecraft.server.v1_15_R1.LightEngineSky;
import net.minecraft.server.v1_15_R1.LightEngineStorage;
import net.minecraft.server.v1_15_R1.LightEngineThreaded;
import net.minecraft.server.v1_15_R1.PacketPlayOutLightUpdate;
import net.minecraft.server.v1_15_R1.SectionPosition;
import net.minecraft.server.v1_15_R1.ThreadedMailbox;
import net.minecraft.server.v1_15_R1.WorldServer;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_15_R1.CraftWorld;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import ru.beykerykt.minecraft.lightapi.bukkit.internal.BukkitPlatformImpl;
import ru.beykerykt.minecraft.lightapi.bukkit.internal.handler.craftbukkit.nms.BaseNMSHandler;
import ru.beykerykt.minecraft.lightapi.common.api.ResultCode;
import ru.beykerykt.minecraft.lightapi.common.api.engine.LightFlag;
import ru.beykerykt.minecraft.lightapi.common.internal.chunks.data.IChunkData;
import ru.beykerykt.minecraft.lightapi.common.internal.chunks.data.IntChunkData;
import ru.beykerykt.minecraft.lightapi.common.internal.engine.LightEngineType;
import ru.beykerykt.minecraft.lightapi.common.internal.engine.LightEngineVersion;
import ru.beykerykt.minecraft.lightapi.common.internal.utils.FlagUtils; | // ThreadedMailbox is closing. The light engine mailbox may also stop processing tasks.
// The light engine mailbox can be close due to server shutdown or unloading (closing) the world.
// I am not sure is it unsafe to process our tasks while the world is closing is closing,
// but will try it (one can throw exception here if it crashes the server).
if (timeToWait == -1) {
// Try to wait 3 seconds until light engine mailbox is busy.
timeToWait = System.currentTimeMillis() + 3 * 1000;
getPlatformImpl().debug("ThreadedMailbox is closing. Will wait...");
} else if (System.currentTimeMillis() >= timeToWait) {
throw new RuntimeException("Failed to enter critical section while ThreadedMailbox is closing");
}
try {
Thread.sleep(50);
} catch (InterruptedException ignored) {
}
}
}
try {
// ##### STEP 2: Safely running the task while the mailbox process is stopped. #####
task.run();
} finally {
// STEP 3: ##### Continue light engine mailbox to process its tasks. #####
// Firstly: Clearing busy flag to allow ThreadedMailbox to use it for running light engine tasks.
while (!stateFlags.compareAndSet(flags = stateFlags.get(), flags & ~2))
;
// Secondly: IMPORTANT! The main loop of ThreadedMailbox was broken. Not completed tasks may still be
// in the queue. Therefore, it is important to start the loop again to process tasks from the queue.
// Otherwise, the main server thread may be frozen due to tasks stuck in the queue.
threadedMailbox_DoLoopStep.invoke(threadedMailbox);
}
} catch (InvocationTargetException e) {
throw toRuntimeException(e.getCause());
} catch (IllegalAccessException e) {
throw toRuntimeException(e);
}
}
private void lightEngineLayer_a(LightEngineLayer<?, ?> les, BlockPosition var0, int var1) {
try {
LightEngineStorage<?> ls = (LightEngineStorage<?>) lightEngineLayer_c.get(les);
lightEngineStorage_d.invoke(ls);
lightEngineGraph_a.invoke(les, 9223372036854775807L, var0.asLong(), 15 - var1, true);
} catch (InvocationTargetException e) {
throw toRuntimeException(e.getCause());
} catch (IllegalAccessException e) {
throw toRuntimeException(e);
}
}
private IChunkData createIntChunkData(String worldName, int chunkX, int chunkZ, int sectionMaskSky,
int sectionMaskBlock) {
return new IntChunkData(worldName, chunkX, chunkZ, sectionMaskSky, sectionMaskBlock);
}
@Override
public void onInitialization(BukkitPlatformImpl impl) throws Exception {
super.onInitialization(impl);
try {
threadedMailbox_DoLoopStep = ThreadedMailbox.class.getDeclaredMethod("f");
threadedMailbox_DoLoopStep.setAccessible(true);
threadedMailbox_State = ThreadedMailbox.class.getDeclaredField("c");
threadedMailbox_State.setAccessible(true);
lightEngine_ThreadedMailbox = LightEngineThreaded.class.getDeclaredField("b");
lightEngine_ThreadedMailbox.setAccessible(true);
lightEngineLayer_c = LightEngineLayer.class.getDeclaredField("c");
lightEngineLayer_c.setAccessible(true);
lightEngineStorage_d = LightEngineStorage.class.getDeclaredMethod("d");
lightEngineStorage_d.setAccessible(true);
lightEngineGraph_a = LightEngineGraph.class.getDeclaredMethod("a", long.class, long.class, int.class,
boolean.class);
lightEngineGraph_a.setAccessible(true);
impl.info("Handler initialization is done");
} catch (Exception e) {
throw toRuntimeException(e);
}
}
@Override
public void onShutdown(BukkitPlatformImpl impl) {
}
@Override
public LightEngineType getLightEngineType() {
return LightEngineType.VANILLA;
}
@Override
public void onWorldLoad(WorldLoadEvent event) {
}
@Override
public void onWorldUnload(WorldUnloadEvent event) {
}
@Override
public boolean isLightingSupported(World world, int lightFlags) {
WorldServer worldServer = ((CraftWorld) world).getHandle();
LightEngineThreaded lightEngine = worldServer.getChunkProvider().getLightEngine();
if (FlagUtils.isFlagSet(lightFlags, LightFlag.SKY_LIGHTING)) {
return lightEngine.a(EnumSkyBlock.SKY) instanceof LightEngineSky;
} else if (FlagUtils.isFlagSet(lightFlags, LightFlag.BLOCK_LIGHTING)) {
return lightEngine.a(EnumSkyBlock.BLOCK) instanceof LightEngineBlock;
}
return false;
}
@Override
public LightEngineVersion getLightEngineVersion() {
return LightEngineVersion.V2;
}
@Override
public int setRawLightLevel(World world, int blockX, int blockY, int blockZ, int lightLevel, int flags) {
WorldServer worldServer = ((CraftWorld) world).getHandle();
final BlockPosition position = new BlockPosition(blockX, blockY, blockZ);
final LightEngineThreaded lightEngine = worldServer.getChunkProvider().getLightEngine();
final int finalLightLevel = lightLevel < 0 ? 0 : Math.min(lightLevel, 15);
if (!worldServer.getChunkProvider().isChunkLoaded(blockX >> 4, blockZ >> 4)) { | return ResultCode.CHUNK_NOT_LOADED; | 2 |
Kaysoro/KaellyBot | src/main/java/commands/classic/AlignmentCommand.java | [
"public abstract class FetchCommand extends AbstractCommand {\n\n protected DiscordException tooMuchServers;\n protected DiscordException notFoundServer;\n\n protected FetchCommand(String name, String pattern) {\n super(name, pattern);\n tooMuchServers = new TooMuchDiscordException(\"server\"... | import commands.model.FetchCommand;
import data.Guild;
import data.OrderUser;
import data.ServerDofus;
import discord4j.common.util.Snowflake;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Member;
import discord4j.core.object.entity.Message;
import discord4j.core.spec.EmbedCreateSpec;
import enums.City;
import enums.Language;
import enums.Order;
import exceptions.*;
import util.ServerUtils;
import util.Translator;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package commands.classic;
/**
* Created by steve on 08/02/2018
*/
public class AlignmentCommand extends FetchCommand {
private DiscordException notFoundFilter;
private DiscordException tooMuchFilters;
private DiscordException tooMuchCities;
private DiscordException notFoundCity;
private DiscordException tooMuchOrders;
private DiscordException notFoundOrder;
public AlignmentCommand(){
super("align", "(.*)");
setUsableInMP(false);
notFoundFilter = new NotFoundDiscordException("filter");
tooMuchFilters = new TooMuchDiscordException("filter");
tooMuchCities = new TooMuchDiscordException("city", true);
notFoundCity = new NotFoundDiscordException("city");
tooMuchOrders = new TooMuchDiscordException("order", true);
notFoundOrder = new NotFoundDiscordException("order");
}
@Override
public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
String content = m.group(1).trim();
Optional<discord4j.core.object.entity.Guild> guild = message.getGuild().blockOptional();
Optional<Member> user = message.getAuthorAsMember().blockOptional();
// Initialisation du Filtre
City city = null;
Order order = null;
if (guild.isPresent() && user.isPresent()){
ServerDofus server = ServerUtils.getDofusServerFrom(Guild.getGuild(guild.get()), message.getChannel().block());
// Consultation filtré par niveau
if ((m = Pattern.compile(">\\s+(\\d{1,3})(\\s+.+)?").matcher(content)).matches()){
int level = Integer.parseInt(m.group(1));
if (m.group(2) != null) {
ServerUtils.ServerQuery serverQuery = ServerUtils.getServerDofusFromName(m.group(2), lg);
if (serverQuery.hasSucceed())
server = serverQuery.getServer();
else {
serverQuery.getExceptions()
.forEach(e -> e.throwException(message, this, lg, serverQuery.getServersFound()));
return;
}
} else if (server == null){
notFoundServer.throwException(message, this, lg);
return;
}
| List<EmbedCreateSpec> embeds = OrderUser.getOrdersFromLevel(guild.get().getMembers() | 2 |
MagicMicky/HabitRPGJavaAPI | HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/ReviveUser.java | [
"public abstract class HabitItem {\n\tprivate String id;\n\tprivate String notes;\n\tprivate Integer priority;\n\tprivate String text;\n\tprivate double value;\n\tprivate String attribute;\n\tprivate List<String> tagsId;\n\t/**\n\t * Create a new HabitItem from what is necessary\n\t * @param id the id of the habit\... | import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.json.JSONObject;
import com.magicmicky.habitrpglibrary.habits.HabitItem;
import com.magicmicky.habitrpglibrary.habits.User;
import com.magicmicky.habitrpglibrary.onlineapi.WebServiceInteraction.Answer;
import com.magicmicky.habitrpglibrary.onlineapi.helper.ParseErrorException;
import com.magicmicky.habitrpglibrary.onlineapi.helper.ParserHelper; | package com.magicmicky.habitrpglibrary.onlineapi;
public class ReviveUser extends WebServiceInteraction {
private static final String CMD = "user/revive";
public ReviveUser(OnHabitsAPIResult callback,
HostConfig config) {
super(CMD, callback, config);
}
@Override
protected HttpRequestBase getRequest() {
return new HttpPost();
}
@Override
protected Answer findAnswer(JSONObject answer) {
return new ReviveData(answer,this.getCallback());
}
private class ReviveData extends Answer {
public ReviveData(JSONObject obj, OnHabitsAPIResult callback) {
super(obj, callback);
}
public void parse() {
try { | User us=ParserHelper.parseUser(this.getObject()); | 4 |
LyashenkoGS/analytics4github | src/main/java/com/rhcloud/analytics4github/service/CommitsService.java | [
"public enum GitHubApiEndpoints {\n COMMITS, STARGAZERS\n}",
"@ApiModel\npublic class RequestFromFrontendDto {\n @ApiParam(required = true, example = \"mewo2\", value = \"a repository author. Example: mewo2\")\n private String author;\n @ApiParam(required = true, example = \"terrain\", value = \"a rep... | import com.fasterxml.jackson.databind.JsonNode;
import com.rhcloud.analytics4github.config.GitHubApiEndpoints;
import com.rhcloud.analytics4github.dto.RequestFromFrontendDto;
import com.rhcloud.analytics4github.dto.ResponceForFrontendDto;
import com.rhcloud.analytics4github.exception.GitHubRESTApiException;
import com.rhcloud.analytics4github.util.GitHubApiIterator;
import com.rhcloud.analytics4github.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException; | package com.rhcloud.analytics4github.service;
/**
* @author lyashenkogs.
*/
@Service
public class CommitsService {
private static Logger LOG = LoggerFactory.getLogger(CommitsService.class);
@Autowired
private RestTemplate template;
public List<LocalDate> getCommitsList(RequestFromFrontendDto requestFromFrontendDto) throws URISyntaxException, ExecutionException, InterruptedException, GitHubRESTApiException {
List<LocalDate> thisMonthCommitsDateList = new LinkedList<>();
GitHubApiIterator iterator = new GitHubApiIterator(requestFromFrontendDto.getAuthor() + "/" + requestFromFrontendDto.getRepository(), template, | GitHubApiEndpoints.COMMITS, Utils.getPeriodInstant(requestFromFrontendDto.getStartPeriod()), | 5 |
kinnla/eniac | src/eniac/menu/action/OpenSkin.java | [
"public class Manager {\n\n\t/*\n\t * ========================= applet lifecycle states =======================\n\t */\n\n\tpublic enum LifeCycle {\n\n\t\t/**\n\t\t * Default lifecycle state on startup\n\t\t */\n\t\tDEFAULT,\n\n\t\t/**\n\t\t * Livecycle state indicating a successful initialization\n\t\t */\n\t\tINI... | import java.awt.event.ActionEvent;
import java.util.List;
import eniac.Manager;
import eniac.io.Proxy;
import eniac.lang.Dictionary;
import eniac.menu.action.gui.OpenSkinPanel;
import eniac.skin.SkinIO; | /*******************************************************************************
* Copyright (c) 2003-2005, 2013 Till Zoppke.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Till Zoppke - initial API and implementation
******************************************************************************/
/*
* Created on 23.02.2004
*/
package eniac.menu.action;
/**
* @author zoppke
*/
public class OpenSkin extends EAction implements Runnable {
public void actionPerformed(ActionEvent evt) {
Thread t = new Thread(this);
t.start();
}
/**
* @param e
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void run() {
// announce that we are working
Manager.getInstance().block();
// scan for proxies
List<Proxy> proxies = SkinIO.loadProxies();
// create dialog that user can choose a configDescriptor
OpenSkinPanel panel = new OpenSkinPanel(proxies);
panel.init(); | Manager.getInstance().makeDialog(panel, Dictionary.OPEN_SKIN_NAME.getText()); | 2 |
aw20/MongoWorkBench | src/org/aw20/mongoworkbench/eclipse/view/wizard/AggregateWizard.java | [
"public enum Event {\n\n\tDOCUMENT_VIEW,\n\tELEMENT_VIEW,\n\t\n\tWRITERESULT,\n\t\n\tEXCEPTION, \n\t\n\tTOWIZARD\n\t\n}",
"public class EventWorkBenchManager extends Object {\n\tprivate static EventWorkBenchManager thisInst;\n\t\n\tpublic static synchronized EventWorkBenchManager getInst(){\n\t\tif ( thisInst == ... | import java.io.IOException;
import org.aw20.mongoworkbench.Event;
import org.aw20.mongoworkbench.EventWorkBenchManager;
import org.aw20.mongoworkbench.MongoFactory;
import org.aw20.mongoworkbench.command.AggregateMongoCommand;
import org.aw20.mongoworkbench.command.MongoCommand;
import org.aw20.mongoworkbench.eclipse.view.WizardParentI;
import org.aw20.util.JSONFormatter;
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.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject; | /*
* 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
* Original fork: https://github.com/Kanatoko/MonjaDB
*
*/
package org.aw20.mongoworkbench.eclipse.view.wizard;
public class AggregateWizard extends Composite implements WizardCommandI {
private String HELPURL = "http://docs.mongodb.org/manual/reference/method/db.collection.aggregate";
private Text textPipe;
private TabFolder tabFolder;
private Button btnRemovePipe;
private WizardParentI wizardparent;
public AggregateWizard(WizardParentI wizardparent, Composite parent, int style) {
super(parent, style);
this.wizardparent = wizardparent;
setLayout(new GridLayout(5, false));
tabFolder = new TabFolder(this, SWT.NONE);
tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1));
TabItem tbtmPipe = new TabItem(tabFolder, SWT.NONE);
tbtmPipe.setText("Pipe#1");
| textPipe = MSwtUtil.createText( tabFolder ); | 7 |
oantajames/mdb-android-application | app/src/main/java/mdb/com/view/moviesgrid/MoviesGridActivity.java | [
"public class MovieEntity implements Parcelable {\n\n @SerializedName(\"vote_count\")\n @Expose\n public Integer voteCount;\n @SerializedName(\"id\")\n @Expose\n public Integer id;\n @SerializedName(\"video\")\n @Expose\n public Boolean video;\n @SerializedName(\"vote_average\")\n @... | import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import mdb.com.R;
import mdb.com.data.api.entity.MovieEntity;
import mdb.com.di.HasComponent;
import mdb.com.di.component.DaggerMoviesGridComponent;
import mdb.com.di.component.MoviesGridComponent;
import mdb.com.di.module.MoviesGridModule;
import mdb.com.util.rx.DisposableManager;
import mdb.com.util.Sort;
import mdb.com.view.base.BaseActivity;
import mdb.com.view.moviedetails.MovieDetailsActivity;
import mdb.com.view.moviesgrid.util.OnItemSelectedListener;
import java.util.ArrayList;
import java.util.List; | package mdb.com.view.moviesgrid;
public class MoviesGridActivity extends BaseActivity
implements HasComponent<MoviesGridComponent>, OnItemSelectedListener {
public static Intent getCallingIntent(Context context) {
return new Intent(context, MoviesGridActivity.class);
}
public static String MOVIE_ENTITY = "movie_entity";
@Bind(R.id.viewpager)
ViewPager viewPager;
@Bind(R.id.tabs)
TabLayout tabLayout;
private DaggerMoviesGridComponent moviesGridComponent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setTabLayoutListener();
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
initTabIcons();
//default position
viewPager.setCurrentItem(1);
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
inject();
}
@Override
protected void onDestroy() {
DisposableManager.dispose();
super.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
private void inject() {
moviesGridComponent = (DaggerMoviesGridComponent) DaggerMoviesGridComponent.builder()
.applicationComponent(getApplicationComponent()) | .moviesGridModule(new MoviesGridModule()) | 3 |
gjhutchison/pixelhorrorjam2016 | core/src/com/kowaisugoi/game/rooms/RoomHallway.java | [
"public class AudioManager implements Disposable {\n private static final Map<SoundId, Sound> _soundMap = new HashMap<SoundId, Sound>();\n private static final Map<MusicId, Music> _musicMap = new HashMap<MusicId, Music>();\n\n private static MusicId _currentSong = MusicId.NONE;\n\n public static void in... | import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.kowaisugoi.game.audio.AudioManager;
import com.kowaisugoi.game.audio.MusicId;
import com.kowaisugoi.game.audio.SoundId;
import com.kowaisugoi.game.interactables.passages.DirectionalPassage;
import com.kowaisugoi.game.interactables.passages.Passage;
import com.kowaisugoi.game.screens.PlayGame;
import com.kowaisugoi.game.system.GameUtil;
import static com.kowaisugoi.game.control.flags.FlagId.*; | package com.kowaisugoi.game.rooms;
public class RoomHallway extends StandardRoom {
private static final String ROOM_URL = "rooms/hallway/hallway.png";
private static final String ROOM_URL2 = "rooms/hallway/hallway_night.png";
private static final String OH_HI = "rooms/hallway/hallway_hai.png";
private final Sprite _roomSprite1 = new Sprite(new Texture(ROOM_URL));
private final Sprite _roomSprite2 = new Sprite(new Texture(ROOM_URL2));
private final Sprite _hiSprite = new Sprite(new Texture(OH_HI));
public RoomHallway() {
super(new Sprite(new Texture(ROOM_URL)));
_hiSprite.setSize(PlayGame.GAME_WIDTH, PlayGame.GAME_HEIGHT);
Passage passageMainRoom = new DirectionalPassage(RoomId.HALLWAY,
RoomId.MAIN_HALL,
new Rectangle(51, 0, 54, 10), | GameUtil.Direction.DOWN) { | 6 |
mgilangjanuar/GoSCELE | app/src/main/java/com/mgilangjanuar/dev/goscele/modules/main/presenter/HomePresenter.java | [
"public class BasePresenter {\n}",
"public class HomeRecyclerViewAdapter extends BaseRecyclerViewAdapter<HomeRecyclerViewAdapter.ViewHolder> {\n\n private List<HomeModel> list;\n\n public HomeRecyclerViewAdapter(List<HomeModel> list) {\n this.list = list;\n }\n\n @Override\n public ViewHolde... | import com.mgilangjanuar.dev.goscele.base.BasePresenter;
import com.mgilangjanuar.dev.goscele.modules.main.adapter.HomeRecyclerViewAdapter;
import com.mgilangjanuar.dev.goscele.modules.main.listener.HomeListener;
import com.mgilangjanuar.dev.goscele.modules.main.model.HomeModel;
import com.mgilangjanuar.dev.goscele.modules.main.provider.HomeProvider;
import java.util.List; | package com.mgilangjanuar.dev.goscele.modules.main.presenter;
/**
* Created by mgilangjanuar (mgilangjanuar@gmail.com)
*
* @since 2017
*/
public class HomePresenter extends BasePresenter {
private HomeListener listener;
public HomePresenter(HomeListener listener) {
this.listener = listener;
}
public void runProvider(boolean force) {
List<HomeModel> models = new HomeModel().find().execute();
if (!force && models.size() > 0) {
listener.onRetrieve(new HomeRecyclerViewAdapter(models));
} else { | new HomeProvider(listener).run(); | 4 |
SamuelGjk/GComic | app/src/main/java/moe/yukinoneko/gcomic/module/download/tasks/DownloadTasksPresenter.java | [
"public abstract class BasePresenter<T extends IBaseView> {\n protected CompositeSubscription mCompositeSubscription;\n protected Context mContext;\n protected T iView;\n\n public BasePresenter(Context context, T iView) {\n this.mContext = context;\n this.iView = iView;\n }\n\n publi... | import moe.yukinoneko.gcomic.utils.FileUtlis;
import moe.yukinoneko.gcomic.utils.Utils;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
import moe.yukinoneko.gcomic.R;
import moe.yukinoneko.gcomic.base.BasePresenter;
import moe.yukinoneko.gcomic.data.ComicData;
import moe.yukinoneko.gcomic.database.GComicDB;
import moe.yukinoneko.gcomic.database.model.DownloadTaskModel;
import moe.yukinoneko.gcomic.database.model.ReadHistoryModel;
import moe.yukinoneko.gcomic.download.DownloadTasksManager;
import moe.yukinoneko.gcomic.network.GComicApi; | /*
* Copyright (C) 2016 SamuelGjk <samuel.alva@outlook.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 moe.yukinoneko.gcomic.module.download.tasks;
/**
* Created by SamuelGjk on 2016/5/13.
*/
public class DownloadTasksPresenter extends BasePresenter<IDownloadTasksView> {
public DownloadTasksPresenter(Context context, IDownloadTasksView iView) {
super(context, iView);
}
void fetchDownloadTasks(int comicId) { | Subscription subscription = DownloadTasksManager.getInstance(mContext) | 5 |
gibffe/fuse | src/main/java/com/sulaco/fuse/FuseServerImpl.java | [
"public interface AnnotationScanner {\n\n public void scan();\n}",
"public class RouteFinderActor extends FuseEndpointActor {\r\n\r\n @Autowired protected RoutesConfig routes;\r\n \r\n @Override\r\n protected void onRequest(final FuseRequestMessage message) {\r\n \r\n String uri = mes... | import com.sulaco.fuse.config.AnnotationScanner;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.routing.RoundRobinRouter;
import com.sulaco.fuse.akka.actor.RouteFinderActor;
import com.sulaco.fuse.akka.syslog.SystemLogActor;
import com.sulaco.fuse.config.ConfigSource;
import com.sulaco.fuse.config.actor.ActorFactory;
import com.sulaco.fuse.netty.FuseChannelInitializer;
import com.typesafe.config.Config;
| package com.sulaco.fuse;
@Component
public class FuseServerImpl implements FuseServer, InitializingBean, ApplicationContextAware {
protected ExecutorService exe = Executors.newSingleThreadExecutor();
protected ActorSystem actorSystem;
protected ApplicationContext appContext;
| @Autowired protected ActorFactory actorFactory;
| 4 |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/Agent.java | [
"@Getter\npublic enum AgentConfiguration {\n\n INSTANCE;\n\n //版本不能大于 x.9\n public static final float VERSION = (float) 11.8;\n\n /**\n * quartz配置文件路径\n */\n private String quartzConfPath = null;\n /**\n * push到falcon的地址\n */\n private String agentPushUrl = null;\n\n /**\n ... | import com.yiji.falcon.agent.config.AgentConfiguration;
import com.yiji.falcon.agent.jmx.JMXConnection;
import com.yiji.falcon.agent.plugins.util.PluginExecute;
import com.yiji.falcon.agent.plugins.util.PluginLibraryHelper;
import com.yiji.falcon.agent.util.*;
import com.yiji.falcon.agent.vo.HttpResult;
import com.yiji.falcon.agent.watcher.ConfDirWatcher;
import com.yiji.falcon.agent.watcher.PluginPropertiesWatcher;
import com.yiji.falcon.agent.web.HttpServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.PropertyConfigurator;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.DirectSchedulerFactory;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Collection; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent;
/*
* 修订记录:
* guqiu@yiji.com 2016-06-22 17:48 创建
*/
/**
* agent服务
* @author guqiu@yiji.com
*/
@Slf4j
public class Agent extends Thread{
public static final PrintStream OUT = System.out;
public static final PrintStream ERR = System.err;
public static int falconAgentPid = 0;
private ServerSocketChannel serverSocketChannel; | private HttpServer httpServer = null; | 7 |
jiang111/ZhiHu-TopAnswer | app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/RecyclerViewFragment.java | [
"public abstract class BaseAdapter extends RecyclerView.Adapter<BaseViewHolder> {\n\n\n @Override\n public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n final BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false));\n... | import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jiang.android.architecture.adapter.BaseAdapter;
import com.jiang.android.architecture.adapter.BaseViewHolder;
import com.jiang.android.architecture.utils.L;
import com.jiang.android.architecture.view.LoadMoreRecyclerView;
import com.jiang.android.architecture.view.MultiStateView;
import com.jiang.android.zhihu_topanswer.R;
import com.jiang.android.zhihu_topanswer.activity.AnswersActivity;
import com.jiang.android.zhihu_topanswer.model.TopicAnswers;
import com.jiang.android.zhihu_topanswer.utils.JSoupUtils;
import com.trello.rxlifecycle.android.FragmentEvent;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers; | package com.jiang.android.zhihu_topanswer.fragment;
/**
* Created by jiang on 2016/12/23.
*/
public class RecyclerViewFragment extends BaseFragment {
private static final String TAG = "RecyclerViewFragment";
public static final int PAGE_START = 1;
private int mPage = PAGE_START;
private static final java.lang.String BUNDLE_ID = "bundle_id";
private int mTopic; | private LoadMoreRecyclerView mRecyclerView; | 3 |
CagataySonmez/EdgeCloudSim | src/edu/boun/edgecloudsim/applications/sample_app4/FuzzyExperimentalNetworkModel.java | [
"public class SimManager extends SimEntity {\r\n\tprivate static final int CREATE_TASK = 0;\r\n\tprivate static final int CHECK_ALL_VM = 1;\r\n\tprivate static final int GET_LOAD_LOG = 2;\r\n\tprivate static final int PRINT_PROGRESS = 3;\r\n\tprivate static final int STOP_SIMULATION = 4;\r\n\t\r\n\tprivate String s... | import org.cloudbus.cloudsim.core.CloudSim;
import edu.boun.edgecloudsim.core.SimManager;
import edu.boun.edgecloudsim.core.SimSettings;
import edu.boun.edgecloudsim.edge_client.Task;
import edu.boun.edgecloudsim.network.NetworkModel;
import edu.boun.edgecloudsim.utils.Location;
import edu.boun.edgecloudsim.utils.SimLogger; | /*
* Title: EdgeCloudSim - M/M/1 Queue model implementation
*
* Description:
* MM1Queue implements M/M/1 Queue model for WLAN and WAN communication
*
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
* Copyright (c) 2017, Bogazici University, Istanbul, Turkey
*/
package edu.boun.edgecloudsim.applications.sample_app4;
public class FuzzyExperimentalNetworkModel extends NetworkModel {
public static enum NETWORK_TYPE {WLAN, LAN};
public static enum LINK_TYPE {DOWNLOAD, UPLOAD};
public static double MAN_BW = 1300*1024; //Kbps
@SuppressWarnings("unused")
private int manClients;
private int[] wanClients;
private int[] wlanClients;
private double lastMM1QueeuUpdateTime;
private double ManPoissonMeanForDownload; //seconds
private double ManPoissonMeanForUpload; //seconds
private double avgManTaskInputSize; //bytes
private double avgManTaskOutputSize; //bytes
//record last n task statistics during MM1_QUEUE_MODEL_UPDATE_INTEVAL seconds to simulate mmpp/m/1 queue model
private double totalManTaskInputSize;
private double totalManTaskOutputSize;
private double numOfManTaskForDownload;
private double numOfManTaskForUpload;
public static final double[] experimentalWlanDelay = {
/*1 Client*/ 88040.279 /*(Kbps)*/,
/*2 Clients*/ 45150.982 /*(Kbps)*/,
/*3 Clients*/ 30303.641 /*(Kbps)*/,
/*4 Clients*/ 27617.211 /*(Kbps)*/,
/*5 Clients*/ 24868.616 /*(Kbps)*/,
/*6 Clients*/ 22242.296 /*(Kbps)*/,
/*7 Clients*/ 20524.064 /*(Kbps)*/,
/*8 Clients*/ 18744.889 /*(Kbps)*/,
/*9 Clients*/ 17058.827 /*(Kbps)*/,
/*10 Clients*/ 15690.455 /*(Kbps)*/,
/*11 Clients*/ 14127.744 /*(Kbps)*/,
/*12 Clients*/ 13522.408 /*(Kbps)*/,
/*13 Clients*/ 13177.631 /*(Kbps)*/,
/*14 Clients*/ 12811.330 /*(Kbps)*/,
/*15 Clients*/ 12584.387 /*(Kbps)*/,
/*15 Clients*/ 12135.161 /*(Kbps)*/,
/*16 Clients*/ 11705.638 /*(Kbps)*/,
/*17 Clients*/ 11276.116 /*(Kbps)*/,
/*18 Clients*/ 10846.594 /*(Kbps)*/,
/*19 Clients*/ 10417.071 /*(Kbps)*/,
/*20 Clients*/ 9987.549 /*(Kbps)*/,
/*21 Clients*/ 9367.587 /*(Kbps)*/,
/*22 Clients*/ 8747.625 /*(Kbps)*/,
/*23 Clients*/ 8127.663 /*(Kbps)*/,
/*24 Clients*/ 7907.701 /*(Kbps)*/,
/*25 Clients*/ 7887.739 /*(Kbps)*/,
/*26 Clients*/ 7690.831 /*(Kbps)*/,
/*27 Clients*/ 7393.922 /*(Kbps)*/,
/*28 Clients*/ 7297.014 /*(Kbps)*/,
/*29 Clients*/ 7100.106 /*(Kbps)*/,
/*30 Clients*/ 6903.197 /*(Kbps)*/,
/*31 Clients*/ 6701.986 /*(Kbps)*/,
/*32 Clients*/ 6500.776 /*(Kbps)*/,
/*33 Clients*/ 6399.565 /*(Kbps)*/,
/*34 Clients*/ 6098.354 /*(Kbps)*/,
/*35 Clients*/ 5897.143 /*(Kbps)*/,
/*36 Clients*/ 5552.127 /*(Kbps)*/,
/*37 Clients*/ 5207.111 /*(Kbps)*/,
/*38 Clients*/ 4862.096 /*(Kbps)*/,
/*39 Clients*/ 4517.080 /*(Kbps)*/,
/*40 Clients*/ 4172.064 /*(Kbps)*/,
/*41 Clients*/ 4092.922 /*(Kbps)*/,
/*42 Clients*/ 4013.781 /*(Kbps)*/,
/*43 Clients*/ 3934.639 /*(Kbps)*/,
/*44 Clients*/ 3855.498 /*(Kbps)*/,
/*45 Clients*/ 3776.356 /*(Kbps)*/,
/*46 Clients*/ 3697.215 /*(Kbps)*/,
/*47 Clients*/ 3618.073 /*(Kbps)*/,
/*48 Clients*/ 3538.932 /*(Kbps)*/,
/*49 Clients*/ 3459.790 /*(Kbps)*/,
/*50 Clients*/ 3380.649 /*(Kbps)*/,
/*51 Clients*/ 3274.611 /*(Kbps)*/,
/*52 Clients*/ 3168.573 /*(Kbps)*/,
/*53 Clients*/ 3062.536 /*(Kbps)*/,
/*54 Clients*/ 2956.498 /*(Kbps)*/,
/*55 Clients*/ 2850.461 /*(Kbps)*/,
/*56 Clients*/ 2744.423 /*(Kbps)*/,
/*57 Clients*/ 2638.386 /*(Kbps)*/,
/*58 Clients*/ 2532.348 /*(Kbps)*/,
/*59 Clients*/ 2426.310 /*(Kbps)*/,
/*60 Clients*/ 2320.273 /*(Kbps)*/,
/*61 Clients*/ 2283.828 /*(Kbps)*/,
/*62 Clients*/ 2247.383 /*(Kbps)*/,
/*63 Clients*/ 2210.939 /*(Kbps)*/,
/*64 Clients*/ 2174.494 /*(Kbps)*/,
/*65 Clients*/ 2138.049 /*(Kbps)*/,
/*66 Clients*/ 2101.604 /*(Kbps)*/,
/*67 Clients*/ 2065.160 /*(Kbps)*/,
/*68 Clients*/ 2028.715 /*(Kbps)*/,
/*69 Clients*/ 1992.270 /*(Kbps)*/,
/*70 Clients*/ 1955.825 /*(Kbps)*/,
/*71 Clients*/ 1946.788 /*(Kbps)*/,
/*72 Clients*/ 1937.751 /*(Kbps)*/,
/*73 Clients*/ 1928.714 /*(Kbps)*/,
/*74 Clients*/ 1919.677 /*(Kbps)*/,
/*75 Clients*/ 1910.640 /*(Kbps)*/,
/*76 Clients*/ 1901.603 /*(Kbps)*/,
/*77 Clients*/ 1892.566 /*(Kbps)*/,
/*78 Clients*/ 1883.529 /*(Kbps)*/,
/*79 Clients*/ 1874.492 /*(Kbps)*/,
/*80 Clients*/ 1865.455 /*(Kbps)*/,
/*81 Clients*/ 1833.185 /*(Kbps)*/,
/*82 Clients*/ 1800.915 /*(Kbps)*/,
/*83 Clients*/ 1768.645 /*(Kbps)*/,
/*84 Clients*/ 1736.375 /*(Kbps)*/,
/*85 Clients*/ 1704.106 /*(Kbps)*/,
/*86 Clients*/ 1671.836 /*(Kbps)*/,
/*87 Clients*/ 1639.566 /*(Kbps)*/,
/*88 Clients*/ 1607.296 /*(Kbps)*/,
/*89 Clients*/ 1575.026 /*(Kbps)*/,
/*90 Clients*/ 1542.756 /*(Kbps)*/,
/*91 Clients*/ 1538.544 /*(Kbps)*/,
/*92 Clients*/ 1534.331 /*(Kbps)*/,
/*93 Clients*/ 1530.119 /*(Kbps)*/,
/*94 Clients*/ 1525.906 /*(Kbps)*/,
/*95 Clients*/ 1521.694 /*(Kbps)*/,
/*96 Clients*/ 1517.481 /*(Kbps)*/,
/*97 Clients*/ 1513.269 /*(Kbps)*/,
/*98 Clients*/ 1509.056 /*(Kbps)*/,
/*99 Clients*/ 1504.844 /*(Kbps)*/,
/*100 Clients*/ 1500.631 /*(Kbps)*/
};
public static final double[] experimentalWanDelay = {
/*1 Client*/ 20703.973 /*(Kbps)*/,
/*2 Clients*/ 12023.957 /*(Kbps)*/,
/*3 Clients*/ 9887.785 /*(Kbps)*/,
/*4 Clients*/ 8915.775 /*(Kbps)*/,
/*5 Clients*/ 8259.277 /*(Kbps)*/,
/*6 Clients*/ 7560.574 /*(Kbps)*/,
/*7 Clients*/ 7262.140 /*(Kbps)*/,
/*8 Clients*/ 7155.361 /*(Kbps)*/,
/*9 Clients*/ 7041.153 /*(Kbps)*/,
/*10 Clients*/ 6994.595 /*(Kbps)*/,
/*11 Clients*/ 6653.232 /*(Kbps)*/,
/*12 Clients*/ 6111.868 /*(Kbps)*/,
/*13 Clients*/ 5570.505 /*(Kbps)*/,
/*14 Clients*/ 5029.142 /*(Kbps)*/,
/*15 Clients*/ 4487.779 /*(Kbps)*/,
/*16 Clients*/ 3899.729 /*(Kbps)*/,
/*17 Clients*/ 3311.680 /*(Kbps)*/,
/*18 Clients*/ 2723.631 /*(Kbps)*/,
/*19 Clients*/ 2135.582 /*(Kbps)*/,
/*20 Clients*/ 1547.533 /*(Kbps)*/,
/*21 Clients*/ 1500.252 /*(Kbps)*/,
/*22 Clients*/ 1452.972 /*(Kbps)*/,
/*23 Clients*/ 1405.692 /*(Kbps)*/,
/*24 Clients*/ 1358.411 /*(Kbps)*/,
/*25 Clients*/ 1311.131 /*(Kbps)*/
};
public FuzzyExperimentalNetworkModel(int _numberOfMobileDevices, String _simScenario) {
super(_numberOfMobileDevices, _simScenario);
}
@Override
public void initialize() { | wanClients = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()]; //we have one access point for each datacenter | 1 |
WeDevelopTeam/HeroVideo-master | app/src/main/java/com/github/bigexcalibur/herovideo/mvp/live/ui/HomeLiveFragment.java | [
"public class LiveAppIndexAdapter extends RecyclerView.Adapter\n{\n\n private Context context;\n\n private LiveAppIndexInfo mLiveAppIndexInfo;\n\n private int entranceSize;\n\n //直播分类入口\n private static final int TYPE_ENTRANCE = 0;\n\n //直播Item\n private static final int TYPE_LIVE_ITEM = 1;\n\n... | import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.github.bigexcalibur.herovideo.LiveAppIndexAdapter;
import com.github.bigexcalibur.herovideo.R;
import com.github.bigexcalibur.herovideo.mvp.common.ui.RxLazyFragment;
import com.github.bigexcalibur.herovideo.network.RetrofitHelper;
import com.github.bigexcalibur.herovideo.ui.widget.CustomEmptyView;
import com.github.bigexcalibur.herovideo.util.SnackbarUtil;
import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers; | package com.github.bigexcalibur.herovideo.mvp.live.ui;
/**
* 首页直播界面
*/
public class HomeLiveFragment extends RxLazyFragment
{
@BindView(R.id.recycle)
RecyclerView mRecyclerView;
@BindView(R.id.swipe_refresh_layout)
SwipeRefreshLayout mSwipeRefreshLayout;
@BindView(R.id.empty_layout)
CustomEmptyView mCustomEmptyView;
private LiveAppIndexAdapter mLiveAppIndexAdapter;
public static HomeLiveFragment newIntance()
{
return new HomeLiveFragment();
}
@Override
public int getLayoutResId()
{
return R.layout.fragment_home_live;
}
@Override
public void finishCreateView(Bundle state)
{
isPrepared = true;
onLazyLoad();
}
@Override
public void onLazyLoad()
{
if (!isPrepared || !isVisible)
return;
initRefreshLayout();
initRecyclerView();
isPrepared = false;
}
protected void initRecyclerView()
{
mLiveAppIndexAdapter = new LiveAppIndexAdapter(getActivity());
mRecyclerView.setAdapter(mLiveAppIndexAdapter);
GridLayoutManager layout = new GridLayoutManager(getActivity(), 12);
layout.setOrientation(LinearLayoutManager.VERTICAL);
layout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup()
{
@Override
public int getSpanSize(int position)
{
return mLiveAppIndexAdapter.getSpanSize(position);
}
});
mRecyclerView.setLayoutManager(layout);
}
protected void initRefreshLayout()
{
mSwipeRefreshLayout.setColorSchemeResources(R.color.theme_color_primary);
mSwipeRefreshLayout.setOnRefreshListener(this::loadData);
mSwipeRefreshLayout.post(() -> {
mSwipeRefreshLayout.setRefreshing(true);
loadData();
});
}
@Override
public void loadData()
{
| RetrofitHelper.getLiveAPI() | 2 |
jaquadro/ForgeMods | ModularPots/src/com/jaquadro/minecraft/modularpots/client/renderer/LargePotRenderer.java | [
"public class BlockLargePot extends BlockContainer\n{\n public static final String[] subTypes = new String[] { \"default\", \"raw\" };\n\n public enum Direction {\n North (1 << 0),\n East (1 << 1),\n South (1 << 2),\n West (1 << 3),\n NorthWest (1 << 4),\n NorthEast (... | import com.jaquadro.minecraft.modularpots.block.BlockLargePot;
import com.jaquadro.minecraft.modularpots.client.ClientProxy;
import com.jaquadro.minecraft.modularpots.tileentity.TileEntityLargePot;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import org.lwjgl.opengl.GL11;
import static com.jaquadro.minecraft.modularpots.block.BlockLargePot.Direction;
import static com.jaquadro.minecraft.modularpots.block.BlockLargePot.Direction.*; | package com.jaquadro.minecraft.modularpots.client.renderer;
public class LargePotRenderer implements ISimpleBlockRenderingHandler
{
private float[] baseColor = new float[3];
private float[] activeRimColor = new float[3];
private float[] activeInWallColor = new float[3];
private float[] activeBottomColor = new float[3];
private float[] activeSubstrateColor = new float[3];
@Override
public void renderInventoryBlock (Block block, int metadata, int modelId, RenderBlocks renderer) {
if (!(block instanceof BlockLargePot))
return;
renderInventoryBlock((BlockLargePot) block, metadata, modelId, renderer);
}
private void renderInventoryBlock (BlockLargePot block, int metadata, int modelId, RenderBlocks renderer) {
Tessellator tessellator = Tessellator.instance;
int damage = metadata;
metadata &= 15;
block.setBlockBoundsForItemRender();
renderer.setRenderBoundsFromBlock(block);
GL11.glRotatef(90, 0, 1, 0);
GL11.glTranslatef(-.5f, -.5f, -.5f);
// Bottom
tessellator.startDrawingQuads();
tessellator.setNormal(0, -1, 0);
renderer.renderFaceYNeg(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 0, metadata));
tessellator.draw();
// Sides
tessellator.startDrawingQuads();
tessellator.setNormal(0, 0, -1);
renderer.renderFaceZNeg(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 2, metadata));
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(0, 0, 1);
renderer.renderFaceZPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 3, metadata));
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(-1, 0, 0);
renderer.renderFaceXNeg(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 4, metadata));
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(1, 0, 0);
renderer.renderFaceXPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 5, metadata));
tessellator.draw();
boolean blendEnabled = GL11.glIsEnabled(GL11.GL_BLEND);
if (!blendEnabled)
GL11.glEnable(GL11.GL_BLEND);
// Overlay
if ((damage & 0xFF00) != 0) {
IIcon icon = block.getOverlayIcon((damage >> 8) & 255);
tessellator.startDrawingQuads();
tessellator.setNormal(0, 0, -1);
renderer.renderFaceZNeg(block, 0, 0, 0, icon);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(0, 0, 1);
renderer.renderFaceZPos(block, 0, 0, 0, icon);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(-1, 0, 0);
renderer.renderFaceXNeg(block, 0, 0, 0, icon);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(1, 0, 0);
renderer.renderFaceXPos(block, 0, 0, 0, icon);
tessellator.draw();
}
if (!blendEnabled)
GL11.glDisable(GL11.GL_BLEND);
// Top Lip
tessellator.startDrawingQuads();
tessellator.setNormal(0, 1, 0);
float dim = .0625f;
renderer.setRenderBounds(0, 0, 0, 1, 1, dim);
renderer.renderFaceYPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata));
renderer.setRenderBounds(0, 0, 1 - dim, 1, 1, 1);
renderer.renderFaceYPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata));
renderer.setRenderBounds(0, 0, 0, dim, 1, 1);
renderer.renderFaceYPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata));
renderer.setRenderBounds(1 - dim, 0, 0, 1, 1, 1);
renderer.renderFaceYPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata));
tessellator.draw();
block.setBlockBoundsForItemRender();
renderer.setRenderBoundsFromBlock(block);
// Interior Sides
tessellator.startDrawingQuads();
tessellator.setNormal(0, 0, -1);
renderer.renderFaceZNeg(block, 0, 0, 1 - dim, renderer.getBlockIconFromSideAndMetadata(block, 2, metadata));
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(0, 0, 1);
renderer.renderFaceZPos(block, 0, 0, dim - 1, renderer.getBlockIconFromSideAndMetadata(block, 3, metadata));
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(-1, 0, 0);
renderer.renderFaceXNeg(block, 1 - dim, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 4, metadata));
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.setNormal(1, 0, 0);
renderer.renderFaceXPos(block, dim - 1, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 5, metadata));
tessellator.draw();
// Interior Bottom
tessellator.startDrawingQuads();
tessellator.setNormal(0, 1, 0);
renderer.renderFaceYPos(block, 0, dim - 1, 0, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata));
tessellator.draw();
GL11.glTranslatef(.5f, .5f, .5f);
}
@Override
public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) {
if (!(block instanceof BlockLargePot))
return false;
try {
if (ClientProxy.renderPass == 0)
return renderWorldBlockPass0(world, x, y, z, (BlockLargePot) block, modelId, renderer);
else if (ClientProxy.renderPass == 1)
return renderWorldBlockPass1(world, x, y, z, (BlockLargePot) block, modelId, renderer);
}
catch (Exception e) { }
return false;
}
private void renderEmptyPlane (Block block, int x, int y, int z, RenderBlocks renderer) {
renderer.setRenderBounds(0, 0, 0, 0, 0, 0);
renderer.renderFaceYNeg(block, x, y, z, Blocks.hardened_clay.getIcon(0, 0));
}
private boolean renderWorldBlockPass1 (IBlockAccess world, int x, int y, int z, BlockLargePot block, int modelId, RenderBlocks renderer) { | TileEntityLargePot tileEntity = block.getTileEntity(world, x, y, z); | 2 |
daquexian/chaoli-forum-for-android-2 | app/src/main/java/com/daquexian/chaoli/forum/utils/SignUpUtils.java | [
"public class ChaoliApplication extends Application {\n private static Context appContext;\n @Override\n public void onCreate() {\n super.onCreate();\n // train classifier on app start\n CodeProcessor.init(this);\n ChaoliApplication.appContext = getApplicationContext();\n ... | import android.util.Log;
import com.daquexian.chaoli.forum.ChaoliApplication;
import com.daquexian.chaoli.forum.meta.Constants;
import com.daquexian.chaoli.forum.model.BusinessQuestion;
import com.daquexian.chaoli.forum.model.Question;
import com.daquexian.chaoli.forum.network.MyOkHttp;
import com.daquexian.chaoli.forum.network.MyRetrofit;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; | package com.daquexian.chaoli.forum.utils;
/**
* Created by jianhao on 16-3-27.
*/
public class SignUpUtils {
private static final String TAG = "SignUpUtils";
public static final Map<String, String> subjectTags = new HashMap<String, String>(){{
put("数学", "math");
put("生物", "bio");
put("化学", "chem");
put("物理", "phys");
put("综合", "");
}};
public static int ANSWERS_WRONG = -1;
public static void getQuestionObjList(final GetQuestionObserver observer, String subject){
MyRetrofit.getService()
.getQuestion(subject)
.enqueue(new Callback<ArrayList<Question>>() {
@Override
public void onResponse(Call<ArrayList<Question>> call, Response<ArrayList<Question>> response) { | observer.onGetQuestionObjList(BusinessQuestion.fromList(response.body())); | 2 |
DeFuture/AmazeFileManager-master | src/main/java/com/amaze/filemanager/adapters/Recycleradapter.java | [
"public class Main extends android.support.v4.app.Fragment {\n public File[] file;\n public ArrayList<Layoutelements> list;\n public ArrayList<SmbFile> smbFiles;\n public Recycleradapter adapter;\n public Futils utils;\n public boolean selection;\n public boolean results = false,smbMode=false;\... | import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import com.amaze.filemanager.R;
import com.amaze.filemanager.fragments.Main;
import com.amaze.filemanager.utils.Icons;
import com.amaze.filemanager.utils.Layoutelements;
import com.amaze.filemanager.utils.MimeTypes;
import com.amaze.filemanager.utils.RoundedImageView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import java.io.File;
import java.util.ArrayList; | package com.amaze.filemanager.adapters;
/**
* Created by Arpit on 11-04-2015.
*/
public class Recycleradapter extends RecyclerArrayAdapter<String, RecyclerView.ViewHolder>
implements StickyRecyclerHeadersAdapter<RecyclerView.ViewHolder> {
Main main;
ArrayList<Layoutelements> items;
Context context;
private SparseBooleanArray myChecked = new SparseBooleanArray();
ColorMatrixColorFilter colorMatrixColorFilter;
LayoutInflater mInflater;
int filetype=-1;
int item_count;
public Recycleradapter(Main m,ArrayList<Layoutelements> items,Context context){
this.main=m;
this.items=items;
this.context=context;
for (int i = 0; i < items.size(); i++) {
myChecked.put(i, false);
}
colorMatrixColorFilter=main.colorMatrixColorFilter;
mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
item_count=items.size()+(main.islist?2:3);
}
public void toggleChecked(int position) {
if (myChecked.get(position)) {
myChecked.put(position, false);
} else {
myChecked.put(position, true);
}
notifyDataSetChanged();
if (main.selection == false || main.mActionMode == null) {
main.selection = true;
/*main.mActionMode = main.getActivity().startActionMode(
main.mActionModeCallback);*/
main.mActionMode = main.mainActivity.toolbar.startActionMode(main.mActionModeCallback);
}
main.mActionMode.invalidate();
if (getCheckedItemPositions().size() == 0) {
main.selection = false;
main.mActionMode.finish();
main.mActionMode = null;
}
}
public void toggleChecked(boolean b,String path) {
int a; if(path.equals("/") || !main.gobackitem)a=0;else a=1;
for (int i = a; i < items.size(); i++) {
myChecked.put(i, b);
}
notifyDataSetChanged();
if(main.mActionMode!=null)
main.mActionMode.invalidate();
if (getCheckedItemPositions().size() == 0) {
main.selection = false;
if(main.mActionMode!=null)
main.mActionMode.finish();
main.mActionMode = null;
}
}
public void toggleChecked(boolean b) {
int a=0;
for (int i = a; i < items.size(); i++) {
myChecked.put(i, b);
}
notifyDataSetChanged();
if(main.mActionMode!=null)main.mActionMode.invalidate();
if (getCheckedItemPositions().size() == 0) {
main.selection = false;
if(main.mActionMode!=null)
main.mActionMode.finish();
main.mActionMode = null;
}
}
public ArrayList<Integer> getCheckedItemPositions() {
ArrayList<Integer> checkedItemPositions = new ArrayList<Integer>();
for (int i = 0; i < myChecked.size(); i++) {
if (myChecked.get(i)) {
(checkedItemPositions).add(i);
}
}
return checkedItemPositions;
}
public boolean areAllChecked(String path) {
boolean b = true;
int a; if(path.equals("/") || !main.gobackitem)a=0;else a=1;
for (int i = a; i < myChecked.size(); i++) {
if (!myChecked.get(i)) {
b = false;
}
}
return b;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case | public RoundedImageView viewmageV; | 4 |
sathipal/lwm2m_over_mqtt | src/com/ibm/lwm2m/client/LwM2MClient.java | [
"public class LwM2MServerObject extends MQTTResource {\n\t\n\tpublic static final String RESOURCE_NAME = \"1\";\n\tObserveSpec observeSpec = new ObserveSpec();\n\tprivate static final AtomicInteger instanceCounter = new AtomicInteger(0); \n\t\n\tpublic LwM2MServerObject(String name, boolean bInstance) {\n\t\tsuper(... | import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ibm.lwm2m.objects.LwM2MServerObject;
import com.ibm.lwm2m.objects.TemperatureSensorObject;
import com.ibm.mqttv3.binding.AbstractRequestObserver;
import com.ibm.mqttv3.binding.MQTTWrapper;
import com.ibm.mqttv3.binding.MqttV3MessageReceiver;
import com.ibm.mqttv3.binding.Request;
import com.ibm.mqttv3.binding.Resource;
import com.ibm.mqttv3.binding.Response; | System.out.println(" >> IPSO temperature Object - <3303/0> ");
System.out.println(" >> 3303/0/5700 - SensorValue ");
System.out.println(" >> 3303/0/5601 - Minimum Measured Value ");
System.out.println(" >> 3303/0/5602 - Maximum Measured Value ");
System.out.println(" >> 3303/0/5603 - Min Range Value ");
System.out.println(" >> 3303/0/5604 - Max Range Value ");
}
void userAction() {
list();
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("Enter the command ");
String input = in.nextLine();
String[] parameters = input.split(" ");
try {
switch (parameters[0]) {
case "register":
if (registerLocationID == null) {
this.register();
} else {
System.out.println("This client is already registered in the server");
}
break;
case "deregister":
if (registerLocationID != null) {
this.deregister();
} else {
System.out.println("This client is either not registered "
+ "or already de-registered from the server");
}
in.close();
System.exit(0);
break;
case "update-register":
this.updateRegisteration();
break;
case "get":
if (parameters.length == 2) {
LocalResource resource = ((LocalResource) getResource(parameters[1]));
if (resource != null) {
System.out.println(resource.getValue());
} else {
System.out.println("Resource - " + parameters[1]
+ " not found!");
}
} else {
System.out
.println("Please specify the command as get <resource-id>");
}
break;
case "update":
if (parameters.length == 3) {
LocalResource resource = (LocalResource) getResource(parameters[1]);
if (resource != null) {
resource.setValue(parameters[2]);
} else {
System.out.println("Resource - " + parameters[1]
+ " not found!");
}
} else {
System.out
.println("Please specify the command as update <resource-id> <value>");
}
break;
default:
list();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String getServerId() {
Resource resource = mqttClient.getRoot();
// Get the server object
resource = resource.getChild("1");
// Get the server object instance
resource = resource.getChild("0");
// get the server id resource
resource = resource.getChild("0");
return ((LocalResource) resource).getValue();
}
private void setServerId(String id) {
Resource resource = mqttClient.getRoot();
// Get the server object
resource = resource.getChild("1");
// Get the server object instance
resource = resource.getChild("0");
// get the server id resource
resource = resource.getChild("0");
((LocalResource) resource).setValue(id);
}
public synchronized static LwM2MClient getClient() {
if(client == null) {
client = new LwM2MClient();
}
return client;
}
public static Resource getRootResource() {
return client.mqttClient.getRoot();
}
private abstract class SyncRequestObserver<T> extends | AbstractRequestObserver { | 2 |
HackGSU/mobile-android | app/src/main/java/com/hackgsu/fall2016/android/HackGSUApplication.java | [
"public class FullscreenWebViewActivity extends AppCompatActivity {\n\tpublic static final String EXTRA_URL = \"extra_url\";\n\tprivate ContentLoadingProgressBar progressBar;\n\tprivate WebView webView;\n\n\t@Override\n\tprotected void onCreate (Bundle savedInstanceState) {\n\t\tsuper.onCreate(sav... | import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.*;
import com.hackgsu.fall2016.android.activities.FullscreenWebViewActivity;
import com.hackgsu.fall2016.android.controllers.AnnouncementController;
import com.hackgsu.fall2016.android.events.AnnouncementsUpdatedEvent;
import com.hackgsu.fall2016.android.events.ScheduleUpdatedEvent;
import com.hackgsu.fall2016.android.model.Announcement;
import com.hackgsu.fall2016.android.model.ScheduleEvent;
import com.hackgsu.fall2016.android.services.FirebaseService;
import com.hackgsu.fall2016.android.utils.BusUtils;
import net.danlew.android.joda.JodaTimeAndroid;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import java.util.ArrayList;
import java.util.Collections; | package com.hackgsu.fall2016.android;
/**
* Created by Joshua King on 9/27/16.
*/
public class HackGSUApplication extends Application {
public static final String IS_IN_DEV_MODE = "is_in_dev_mode";
public static final String NOTIFICATIONS_ENABLED = "notifications_enabled";
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
public static boolean areNotificationsEnabled (Context context) {
return getPrefs(context).getBoolean(NOTIFICATIONS_ENABLED, true);
}
@NonNull
private static Announcement convertDataSnapshotToAnnouncement (DataSnapshot child) {
Announcement announcement = child.getValue(Announcement.class);
announcement.setFirebaseKey(child.getKey());
return announcement;
}
public static float convertDpToPx (float dp, Context context) {
return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
public static void delayRunnableOnUI (final long millsToDelay, final Runnable runnableToRun) {
new Thread(new Runnable() {
public void run () {
try {
Thread.sleep(millsToDelay);
} catch (InterruptedException ignored) {}
(new Handler(Looper.getMainLooper())).post(runnableToRun);
}
}).start();
}
public static LocalDateTime getDateTimeOfHackathon (int dayIndex, int hour, int minute) {
return getDateTimeOfHackathon().plusDays(dayIndex).withHourOfDay(hour).withMinuteOfHour(minute);
}
@NonNull
public static LocalDateTime getDateTimeOfHackathon () {
return new LocalDateTime().withDate(2017, 3, 31).withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(30).withHourOfDay(19);
}
public static SharedPreferences getPrefs (Context context) {
return PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
}
public static DateTimeFormatter getTimeFormatter24OrNot (Context context) {
return getTimeFormatter24OrNot(context, new DateTimeFormatterBuilder());
}
public static DateTimeFormatter getTimeFormatter24OrNot (Context context, DateTimeFormatterBuilder dateTimeFormatterBuilder) {
if (DateFormat.is24HourFormat(context)) {
dateTimeFormatterBuilder.appendHourOfDay(2).appendLiteral(":").appendMinuteOfHour(2);
}
else {
dateTimeFormatterBuilder.appendHourOfHalfday(1).appendLiteral(":").appendMinuteOfHour(2).appendLiteral(" ").appendPattern("a");
}
return dateTimeFormatterBuilder.toFormatter();
}
@NonNull
public static Runnable getUrlRunnable (final Context context, final String url, final boolean openInApp) {
return new Runnable() {
@Override
public void run () {
openWebUrl(context, url, openInApp);
}
};
}
public static void hideKeyboard (View parentViewToGetFocus, Context context) {
View view = parentViewToGetFocus.findFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public static boolean isInDevMode (Context context) { return getPrefs(context).getBoolean(IS_IN_DEV_MODE, false); }
public static boolean isNullOrEmpty (String s) {
return s == null || s.equals("");
}
public static boolean isOneFalse (boolean... b) {
for (boolean bool : b) {
if (!bool) { return true; }
}
return false;
}
public static void openWebUrl (Context context, String url, boolean withinApp) {
if (withinApp) {
Intent codeOfConductViewIntent = new Intent(context, FullscreenWebViewActivity.class);
codeOfConductViewIntent.putExtra(FullscreenWebViewActivity.EXTRA_URL, url);
codeOfConductViewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(codeOfConductViewIntent);
}
else {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
}
}
public static void parseDataSnapshotForAnnouncements (Context context, DataSnapshot snapshot) {
ArrayList<Announcement> announcements = new ArrayList<>();
for (DataSnapshot child : snapshot.getChildren()) {
Announcement announcement = convertDataSnapshotToAnnouncement(child);
announcements.add(announcement);
}
Collections.sort(announcements);
DataStore.setAnnouncements(context, announcements);
BusUtils.post(new AnnouncementsUpdatedEvent(announcements));
}
public static void refreshAnnouncements (final Context context) {
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
dbRef.child(AnnouncementController.getAnnouncementsTableString(context)).getRef().addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange (DataSnapshot snapshot) {
parseDataSnapshotForAnnouncements(context, snapshot);
}
@Override
public void onCancelled (DatabaseError databaseError) { }
});
}
public static void refreshSchedule () {
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(); | final ArrayList<ScheduleEvent> scheduleEvents = new ArrayList<>(); | 5 |
timpalpant/java-genomics-toolkit | src/edu/unc/genomics/wigmath/ValueDistribution.java | [
"public abstract class CommandLineTool {\n\n /**\n * The default bite-size to use for applications that process files in chunks\n * TODO Read from a configuration file\n */\n public static final int DEFAULT_CHUNK_SIZE = 10_000_000;\n\n /**\n * Do the main computation of this tool\n * \n * @throws IOE... | import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.log4j.Logger;
import com.beust.jcommander.Parameter;
import edu.unc.genomics.CommandLineTool;
import edu.unc.genomics.CommandLineToolException;
import edu.unc.genomics.Interval;
import edu.unc.genomics.ReadablePathValidator;
import edu.unc.genomics.io.WigFileReader;
import edu.unc.genomics.io.WigFileException;
import edu.unc.genomics.ngs.Autocorrelation;
import edu.unc.utils.FloatHistogram; | package edu.unc.genomics.wigmath;
/**
* Make a histogram of the values in a Wig file
*
* @author timpalpant
*
*/
public class ValueDistribution extends CommandLineTool {
private static final Logger log = Logger.getLogger(Autocorrelation.class);
@Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class)
public Path inputFile;
@Parameter(names = { "-l", "--min" }, description = "Minimum bin value")
public Float min;
@Parameter(names = { "-h", "--max" }, description = "Maximum bin value")
public Float max;
@Parameter(names = { "-n", "--bins" }, description = "Number of bins")
public int numBins = 40;
@Parameter(names = { "-o", "--output" }, description = "Output file")
public Path outputFile;
FloatHistogram hist;
double mean, stdev, skewness, kurtosis;
long N;
public void run() throws IOException {
try (WigFileReader reader = WigFileReader.autodetect(inputFile)) {
log.debug("Generating histogram of Wig values");
if (min == null) {
min = (float) reader.min();
}
if (max == null) {
max = (float) reader.max();
}
hist = new FloatHistogram(numBins, min, max);
N = reader.numBases();
mean = reader.mean();
stdev = reader.stdev();
// Also compute the skewness and kurtosis while going through the values
double sumOfCubeOfDeviances = 0;
double sumOfFourthOfDeviances = 0;
for (String chr : reader.chromosomes()) {
int start = reader.getChrStart(chr);
int stop = reader.getChrStop(chr);
log.debug("Processing chromosome " + chr + " region " + start + "-" + stop);
// Process the chromosome in chunks
int bp = start;
while (bp < stop) {
int chunkStart = bp;
int chunkStop = Math.min(bp + DEFAULT_CHUNK_SIZE - 1, stop);
Interval chunk = new Interval(chr, chunkStart, chunkStop);
log.debug("Processing chunk " + chunk);
try {
float[] data = reader.query(chunk).getValues();
for (int i = 0; i < data.length; i++) {
if (!Float.isNaN(data[i]) && !Float.isInfinite(data[i])) {
hist.addValue(data[i]);
double deviance = data[i] - mean;
double cubeOfDeviance = Math.pow(deviance, 3);
sumOfCubeOfDeviances += cubeOfDeviance;
sumOfFourthOfDeviances += deviance * cubeOfDeviance;
}
}
} catch (WigFileException e) {
log.error("Error getting data from Wig file for chunk " + chunk); | throw new CommandLineToolException("Error getting data from Wig file for chunk " + chunk); | 1 |
wakaleo/maven-schemaspy-plugin | src/main/java/net/sourceforge/schemaspy/view/DotFormatter.java | [
"public class Config\r\n{\r\n private static Config instance;\r\n private final List<String> options;\r\n private Map<String, String> dbSpecificOptions;\r\n private Map<String, String> originalDbSpecificOptions;\r\n private boolean helpRequired;\r\n private boolean dbHelpRequired;\r\n private F... | import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import net.sourceforge.schemaspy.Config;
import net.sourceforge.schemaspy.Revision;
import net.sourceforge.schemaspy.model.Database;
import net.sourceforge.schemaspy.model.ForeignKeyConstraint;
import net.sourceforge.schemaspy.model.Table;
import net.sourceforge.schemaspy.model.TableColumn;
import net.sourceforge.schemaspy.util.Dot;
import net.sourceforge.schemaspy.util.LineWriter;
import net.sourceforge.schemaspy.view.DotNode.DotNodeConfig;
| /*
* This file is a part of the SchemaSpy project (http://schemaspy.sourceforge.net).
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 John Currier
*
* SchemaSpy 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 2.1 of the License, or (at your option) any later version.
*
* SchemaSpy 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.sourceforge.schemaspy.view;
/**
* Format table data into .dot format to feed to Graphvis' dot program.
*
* @author John Currier
*/
public class DotFormatter {
private static DotFormatter instance = new DotFormatter();
private final int fontSize = Config.getInstance().getFontSize();
/**
* Singleton - prevent creation
*/
private DotFormatter() {
}
public static DotFormatter getInstance() {
return instance;
}
/**
* Write real relationships (excluding implied) associated with the given table.<p>
* Returns a set of the implied constraints that could have been included but weren't.
*/
| public Set<ForeignKeyConstraint> writeRealRelationships(Table table, boolean twoDegreesOfSeparation, WriteStats stats, LineWriter dot) throws IOException {
| 2 |
anroOfCode/hijack-infinity | android/freqSweep-app/src/umich/framjack/apps/freqsweep/MainActivity.java | [
"public class FramingEngine {\n\tprivate IncomingPacketListener _incomingListener;\n\tprivate OutgoingByteListener _outgoingListener;\n\t\n\tprivate final int _receiveMax = 18;\n\t\n\tprivate enum ReceiveState { START, SIZE, DATA, DATA_ESCAPE};\n\tprivate ReceiveState _receiveState = ReceiveState.START;\n\tprivate ... | import umich.framjack.core.FramingEngine;
import umich.framjack.core.OnByteSentListener;
import umich.framjack.core.OnBytesAvailableListener;
import umich.framjack.core.SerialDecoder;
import umich.framjack.core.FramingEngine.IncomingPacketListener;
import umich.framjack.core.FramingEngine.OutgoingByteListener;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText; | package umich.framjack.apps.freqsweep;
public class MainActivity extends Activity {
private SerialDecoder _serialDecoder;
private FramingEngine _framer;
private boolean _nextFlag = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_framer = new FramingEngine();
_serialDecoder = new SerialDecoder();
_serialDecoder.registerBytesAvailableListener(_bytesAvailableListener);
_serialDecoder.registerByteSentListener(_byteSentListener);
_framer.registerIncomingPacketListener(_incomingPacketListener);
_framer.registerOutgoingByteListener(_outgoingByteListener);
final Button b1 = (Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText startFreqEditText = (EditText)findViewById(R.id.startFreq);
EditText endFreqEditText = (EditText)findViewById(R.id.endFreq);
EditText msStepEditText = (EditText)findViewById(R.id.stepMs);
EditText hzStepEditText = (EditText)findViewById(R.id.stepHz);
final int startFreq = Integer.parseInt(startFreqEditText.getText().toString());
final int endFreq = Integer.parseInt(endFreqEditText.getText().toString());
final int msStep = Integer.parseInt(msStepEditText.getText().toString());
final int hzStep = Integer.parseInt(hzStepEditText.getText().toString());
b1.setText("Running...");
Thread t = new Thread(new Runnable() {
@Override
public void run() {
int currentFreq = startFreq;
while (currentFreq <= endFreq) {
_serialDecoder.setFreq(currentFreq);
currentFreq += hzStep;
if (msStep == 0) {
while (!_nextFlag) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
_nextFlag = false;
}
else {
try {
Thread.sleep(msStep);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
b1.setText("Start");
}
});
}
});
t.start();
}
});
final Button b2 = (Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
_nextFlag = true;
}
});
}
@Override
public void onPause() {
_serialDecoder.stop();
super.onPause();
}
@Override
public void onResume() {
_serialDecoder.start();
super.onResume();
}
///////////////////////////////////////////////
// Listeners
///////////////////////////////////////////////
private OutgoingByteListener _outgoingByteListener = new OutgoingByteListener() {
public void OutgoingByteTransmit(int[] outgoingRaw) {
synchronized (MainActivity.this) {
//_pendingTransmitBytes += outgoingRaw.length;
}
for (int i = 0; i < outgoingRaw.length; i++) {
_serialDecoder.sendByte(outgoingRaw[i]);
}
}
};
private IncomingPacketListener _incomingPacketListener = new IncomingPacketListener() {
public void IncomingPacketReceive(int[] packet) {
for (int i = 0; i < packet.length; i++) {
System.out.print(Integer.toHexString(packet[i]) + " ");
}
System.out.println();
//decodeAndUpdate(packet);
}
};
| private OnByteSentListener _byteSentListener = new OnByteSentListener() { | 1 |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/data/DataManager.java | [
"public class BaseGankData implements Serializable {\n\n // 发布人\n @SerializedName(\"who\") public String who;\n\n // 发布时间\n @SerializedName(\"publishedAt\") public Date publishedAt;\n\n // 标题\n @SerializedName(\"desc\") public String desc;\n\n // 类型, 一般都是\"福利\"\n @SerializedName(\"type\") pu... | import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import com.camnter.easygank.bean.BaseGankData;
import com.camnter.easygank.bean.GankDaily;
import com.camnter.easygank.model.impl.DailyModel;
import com.camnter.easygank.model.impl.DataModel;
import com.camnter.easygank.presenter.MainPresenter;
import com.camnter.easygank.utils.RxUtils; | /*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.data;
/**
* Description:DataManager
* Created by:CaMnter
* Time:2016-01-13 13:45
*/
public class DataManager {
private static DataManager dataManager;
private DailyModel dailyModel; | private DataModel dataModel; | 3 |
edouardhue/comeon | src/main/java/comeon/ui/actions/AddMediaAction.java | [
"public interface Core {\n\n String EXTERNAL_METADATA_KEY = \"external\";\n\n String[] PICTURE_EXTENSIONS = { \"jpg\", \"jpeg\" };\n\n String[] AUDIO_EXTENSIONS = { \"ogg\", \"flac\", \"wav\" };\n\n void addMedia(final File[] files, final Template defautTemplate, final ExternalMetadataSource<?> external... | import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import comeon.core.Core;
import comeon.templates.Templates;
import comeon.templates.TemplatesChangedEvent;
import comeon.ui.add.AddMediaDialog;
import comeon.ui.add.AdderWorker;
import javax.swing.*;
import java.awt.event.ActionEvent; | package comeon.ui.actions;
@Singleton
public final class AddMediaAction extends BaseAction {
private static final long serialVersionUID = 1L;
private final Templates templates;
private final Core core;
@Inject
public AddMediaAction(final Templates templates, final Core core) {
super("addmedia");
this.templates = templates;
this.core = core;
if (templates.getTemplates().isEmpty()) {
this.setEnabled(false);
}
}
@Override
public void actionPerformed(final ActionEvent e) {
SwingUtilities.invokeLater(() -> {
final AddMediaDialog dialog = new AddMediaDialog(templates);
final int value = dialog.showDialog();
if (value == JOptionPane.OK_OPTION) {
new AdderWorker(dialog.getModel(), core).execute();
}
});
}
@Subscribe | public void handleTemplatesChanged(final TemplatesChangedEvent event) { | 2 |
gizwits/GizOpenSource_AppKit_Android | src/com/gizwits/opensource/appkit/sharingdevice/SharedDeviceListAcitivity.java | [
"public class GosBaseActivity extends FragmentActivity {\n\n\t/** 设备热点默认密码 */\n\tpublic static String SoftAP_PSW = \"123456789\";\n\n\t/** 设备热点默认前缀 */\n\tpublic static String SoftAP_Start = \"XPG-GAgent\";\n\n\t/** 存储器默认名称 */\n\tpublic static final String SPF_Name = \"set\";\n\n\t/** Toast time */\n\tpublic int toa... | import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.gizwits.gizwifisdk.api.GizDeviceSharing;
import com.gizwits.gizwifisdk.api.GizDeviceSharingInfo;
import com.gizwits.gizwifisdk.api.GizMessage;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingType;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener;
import com.gizwits.opensource.appkit.R;
import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity;
import com.gizwits.opensource.appkit.CommonModule.GosConstant;
import com.gizwits.opensource.appkit.CommonModule.NoScrollViewPager;
import com.gizwits.opensource.appkit.sharingdevice.ViewPagerIndicator.PageChangeListener;
import com.gizwits.opensource.appkit.sharingdevice.mySharedFragment2.myadapter;
import com.gizwits.opensource.appkit.utils.DateUtil;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast; | package com.gizwits.opensource.appkit.sharingdevice;
public class SharedDeviceListAcitivity extends GosBaseActivity {
private List<String> tabList;
private List<Fragment> myfragmentlist;
private String token;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gos_shared_device_list);
setActionBar(true, true, R.string.sharedlist);
initData();
initView();
}
// 初始化tab标签中应该显示的文字
private void initData() {
SharedPreferences spf = getSharedPreferences("set", Context.MODE_PRIVATE);
token = spf.getString("Token", "");
myfragmentlist = new ArrayList<Fragment>();
mySharedFragment ment1 = new mySharedFragment();
mySharedFragment2 ment2 = new mySharedFragment2();
myfragmentlist.add(ment1);
myfragmentlist.add(ment2);
tabList = new ArrayList<String>();
tabList.add(getResources().getString(R.string.shared));
tabList.add(getResources().getString(R.string.invited));
}
private void initView() {
com.gizwits.opensource.appkit.sharingdevice.ViewPagerIndicator indicator = (ViewPagerIndicator) findViewById(
R.id.vpi_indicator);
indicator.setVisibleTabCount(2);
indicator.setTabItemTitles(tabList);
NoScrollViewPager vp_shared = (NoScrollViewPager) findViewById(R.id.vp_shared_list);
vp_shared.setNoScroll(true);
vp_shared.setAdapter(new myFragmentAdapter(getSupportFragmentManager()));
indicator.setViewPager(vp_shared, 0);
indicator.setOnPageChangeListener(new PageChangeListener() {
@Override
public void onPageSelected(int position) {
GosConstant.nowPager = position;
switch (GosConstant.nowPager) {
case 0:
break;
case 1:
GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingToMe, null);
break;
default:
break;
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
class myFragmentAdapter extends FragmentStatePagerAdapter {
public myFragmentAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
if (arg0 == 0) {
mySharedFragment shared = new mySharedFragment();
return shared;
} else {
mySharedFragment2 shared = (mySharedFragment2) myfragmentlist.get(arg0);
return shared;
}
}
@Override
public int getCount() {
return 2;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
initListener();
}
// 初始化接口数据
private void initListener() {
GizDeviceSharing.setListener(new GizDeviceSharingListener() {
@Override
public void didGetDeviceSharingInfos(GizWifiErrorCode result, String deviceID,
List<GizDeviceSharingInfo> deviceSharingInfos) {
super.didGetDeviceSharingInfos(result, deviceID, deviceSharingInfos);
if (deviceSharingInfos != null) {
Collections.sort(deviceSharingInfos, new Comparator<GizDeviceSharingInfo>() {
@Override
public int compare(GizDeviceSharingInfo arg0, GizDeviceSharingInfo arg1) {
String updatedAt = DateUtil.utc2Local(arg0.getUpdatedAt());
String updatedAt2 = DateUtil.utc2Local(arg1.getUpdatedAt());
int diff = (int) DateUtil.getDiff(updatedAt2, updatedAt);
return diff;
}
});
}
GosConstant.newmydeviceSharingInfos = deviceSharingInfos;
mySharedFragment2 fragment = (mySharedFragment2) myfragmentlist.get(1);
TextView myview = fragment.getmyview();
if (deviceSharingInfos.size() == 0) {
myview.setVisibility(View.VISIBLE);
myview.setText(getResources().getString(R.string.you_have_no_invited_message));
} else {
myview.setVisibility(View.GONE);
}
| myadapter getmyadapter = fragment.getmyadapter(); | 4 |
nloko/SyncMyPix | src/com/nloko/android/syncmypix/MainActivity.java | [
"public class PhotoStore {\n\n private final String TAG = PhotoStore.class.getSimpleName();\n\n // Directory name under the root directory for photo storage.\n private final String DIRECTORY = \"photos\";\n\n /** Map of keys to entries in the directory. */\n private final Map<Long, Entry> mEntries;\n... | import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import com.android.providers.contacts.PhotoStore;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.nloko.android.Log;
import com.nloko.android.LogCollector;
import com.nloko.android.LogCollectorNotifier;
import com.nloko.android.Utils;
import com.nloko.android.syncmypix.views.ConfirmSyncDialog;
import com.nloko.android.syncmypix.facebook.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener; | fbClient.authorize(self, new DialogListener() {
public void onComplete(Bundle values) {sync();}
public void onFacebookError(FacebookError error) {try
{
loggedIn = false;
Toast.makeText(self, "Error on facebook sync again!", Toast.LENGTH_SHORT).show();
fbClient.logout(self);
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}}
public void onError(DialogError e) {try
{
loggedIn = false;
Toast.makeText(self, "Error on facebook sync again!", Toast.LENGTH_SHORT).show();
fbClient.logout(self);
}
catch(MalformedURLException e1)
{
e1.printStackTrace();
}
catch(IOException e1)
{
e1.printStackTrace();
}}
public void onCancel() {loggedIn = false;}
});
}
else
sync();
//}
}
});
ImageButton settings = (ImageButton) findViewById(R.id.settingsButton);
settings.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(i);
}
});
ImageButton results = (ImageButton) findViewById(R.id.resultsButton);
results.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showResults();
}
});
ImageButton about = (ImageButton) findViewById(R.id.aboutButton);
about.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(ABOUT_DIALOG);
}
});
mHelpButton = (ImageButton) findViewById(R.id.help);
mHelpButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.help_link)));
startActivity(i);
}
});
mDeleteButton = (ImageButton) findViewById(R.id.delete);
mDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DELETE_DIALOG);
loggedIn = false;
if(fbClient != null)
try
{
fbClient.logout(self);
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
switch(requestCode) {
case SOCIAL_NETWORK_LOGIN:
sync();
break;
}
}
// TODO This is needless filler, REMOVE
private void logout()
{
Utils.setString(getSharedPreferences(SettingsActivity.PREFS_NAME, 0), "session_key", null);
Utils.setString(getSharedPreferences(SettingsActivity.PREFS_NAME, 0), "secret", null);
Utils.setString(getSharedPreferences(SettingsActivity.PREFS_NAME, 0), "uid", null);
}
private void sendLog()
{ | final LogCollector collector = new LogCollector(); | 4 |
maksim-m/Popular-Movies-App | app/src/main/java/me/maxdev/popularmoviesapp/ui/detail/MovieDetailFragment.java | [
"public class PopularMoviesApp extends Application {\n\n private NetworkComponent networkComponent;\n\n @Override\n public void onCreate() {\n super.onCreate();\n networkComponent = DaggerNetworkComponent.builder()\n .appModule(new AppModule(this))\n .networkModu... | import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.trello.rxlifecycle.components.support.RxFragment;
import java.util.ArrayList;
import java.util.Locale;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.maxdev.popularmoviesapp.PopularMoviesApp;
import me.maxdev.popularmoviesapp.R;
import me.maxdev.popularmoviesapp.api.MovieReviewsResponse;
import me.maxdev.popularmoviesapp.api.MovieVideosResponse;
import me.maxdev.popularmoviesapp.api.TheMovieDbService;
import me.maxdev.popularmoviesapp.data.Movie;
import me.maxdev.popularmoviesapp.data.MovieReview;
import me.maxdev.popularmoviesapp.data.MovieVideo;
import me.maxdev.popularmoviesapp.ui.ItemOffsetDecoration;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers; | }
private void updateMovieReviewsCard() {
if (reviewsAdapter == null || reviewsAdapter.getItemCount() == 0) {
cardMovieReviews.setVisibility(View.GONE);
} else {
cardMovieReviews.setVisibility(View.VISIBLE);
}
}
private void setupCardElevation(View view) {
ViewCompat.setElevation(view,
convertDpToPixel(getResources().getInteger(R.integer.movie_detail_content_elevation_in_dp)));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (videosAdapter.getItemCount() != 0) {
outState.putParcelableArrayList(MOVIE_VIDEOS_KEY, videosAdapter.getMovieVideos());
}
if (reviewsAdapter.getItemCount() != 0) {
outState.putParcelableArrayList(MOVIE_REVIEWS_KEY, reviewsAdapter.getMovieReviews());
}
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
videosAdapter.setMovieVideos(savedInstanceState.getParcelableArrayList(MOVIE_VIDEOS_KEY));
reviewsAdapter.setMovieReviews(savedInstanceState.getParcelableArrayList(MOVIE_REVIEWS_KEY));
}
}
private void loadMovieVideos() {
theMovieDbService.getMovieVideos(movie.getId())
.compose(bindToLifecycle())
.subscribeOn(Schedulers.newThread())
.map(MovieVideosResponse::getResults)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ArrayList<MovieVideo>>() {
@Override
public void onCompleted() {
// do nothing
}
@Override
public void onError(Throwable e) {
Log.e(LOG_TAG, e.getMessage());
updateMovieVideosCard();
}
@Override
public void onNext(ArrayList<MovieVideo> movieVideos) {
videosAdapter.setMovieVideos(movieVideos);
updateMovieVideosCard();
}
});
}
private void loadMovieReviews() {
theMovieDbService.getMovieReviews(movie.getId())
.compose(bindToLifecycle())
.subscribeOn(Schedulers.newThread())
.map(MovieReviewsResponse::getResults)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ArrayList<MovieReview>>() {
@Override
public void onCompleted() {
// do nothing
}
@Override
public void onError(Throwable e) {
Log.e(LOG_TAG, e.getMessage());
updateMovieReviewsCard();
}
@Override
public void onNext(ArrayList<MovieReview> movieReviews) {
reviewsAdapter.setMovieReviews(movieReviews);
updateMovieReviewsCard();
}
});
}
private void initViews() {
Glide.with(this)
.load(POSTER_IMAGE_BASE_URL + POSTER_IMAGE_SIZE + movie.getPosterPath())
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(movieImagePoster);
movieOriginalTitle.setText(movie.getOriginalTitle());
movieUserRating.setText(String.format(Locale.US, "%.1f", movie.getAverageVote()));
movieUserRating.setTextColor(getRatingColor(movie.getAverageVote()));
String releaseDate = String.format(getString(me.maxdev.popularmoviesapp.R.string.movie_detail_release_date),
movie.getReleaseDate());
movieReleaseDate.setText(releaseDate);
movieOverview.setText(movie.getOverview());
}
@ColorInt
private int getRatingColor(double averageVote) {
if (averageVote >= VOTE_PERFECT) {
return ContextCompat.getColor(getContext(), R.color.vote_perfect);
} else if (averageVote >= VOTE_GOOD) {
return ContextCompat.getColor(getContext(), R.color.vote_good);
} else if (averageVote >= VOTE_NORMAL) {
return ContextCompat.getColor(getContext(), R.color.vote_normal);
} else {
return ContextCompat.getColor(getContext(), R.color.vote_bad);
}
}
private void initVideosList() {
videosAdapter = new MovieVideosAdapter(getContext());
videosAdapter.setOnItemClickListener((itemView, position) -> onMovieVideoClicked(position));
movieVideos.setAdapter(videosAdapter);
movieVideos.setItemAnimator(new DefaultItemAnimator()); | movieVideos.addItemDecoration(new ItemOffsetDecoration(getActivity(), R.dimen.movie_item_offset)); | 7 |
bit-man/SwissArmyJavaGit | javagit/src/main/java/edu/nyu/cs/javagit/client/cli/CliGitCheckout.java | [
"public final class JavaGitConfiguration {\n\n /*\n * The path to our git binaries. Default to null, which means that the git command is available\n * via the system PATH environment variable.\n */\n private static File gitPath = null;\n\n /*\n * The version string fpr the locally-installed git binaries.... | import java.util.List;
import java.util.Scanner;
import edu.nyu.cs.javagit.api.JavaGitConfiguration;
import edu.nyu.cs.javagit.api.JavaGitException;
import edu.nyu.cs.javagit.api.Ref;
import edu.nyu.cs.javagit.api.Ref.RefType;
import edu.nyu.cs.javagit.api.commands.GitCheckoutOptions;
import edu.nyu.cs.javagit.api.commands.GitCheckoutResponse;
import edu.nyu.cs.javagit.client.GitCheckoutResponseImpl;
import edu.nyu.cs.javagit.client.IGitCheckout;
import edu.nyu.cs.javagit.utilities.CheckUtilities;
import edu.nyu.cs.javagit.utilities.ExceptionMessageMap;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList; | throw new JavaGitException(120, "Both --notrack and --track options are set");
}
if (options.optTrack()) {
command.add("--track");
}
if (options.optNoTrack()) {
command.add("--no-track");
}
command.add("-b");
command.add(newBranch.getName());
}
if (options.optL()) {
command.add("-l");
}
if (options.optM()) {
command.add("-m");
}
}
/**
* Parser class to parse the output generated by <git-checkout> and return a
* <code>GitCheckoutResponse</code> object.
*/
public static class GitCheckoutParser implements IParser {
private static final char QUOTE_CHAR = '"';
private static final char SINGLE_QUOTE_CHAR = '\'';
private int lineNum;
private GitCheckoutResponseImpl response;
private List<ErrorDetails> errors;
public GitCheckoutParser() {
lineNum = 0;
response = new GitCheckoutResponseImpl();
errors = new ArrayList<ErrorDetails>();
}
public void parseLine(String line) {
if (line == null || line.length() == 0) {
return;
}
++lineNum;
if (!isErrorLine(line)) {
parseSwitchedToBranchLine(line);
parseFilesInfo(line);
}
}
private boolean isErrorLine(String line) {
if (line.startsWith("error") || line.startsWith("fatal")) {
setError(lineNum, line);
return true;
}
return false;
}
public void parseSwitchedToBranchLine(String line) {
if (line.startsWith("Switched to branch")) {
getSwitchedToBranch(line);
} else if (line.startsWith("Switched to a new branch")) {
getSwitchedToNewBranch(line);
}
}
private void getSwitchedToBranch(String line) {
String branchName = extractBranchName(line);
Ref branch = Ref.createBranchRef(branchName);
response.setBranch(branch);
}
private void getSwitchedToNewBranch(String line) {
String newBranchName = extractBranchName(line);
Ref newBranch = Ref.createBranchRef(newBranchName);
response.setNewBranch(newBranch);
}
private String extractBranchName(String line) {
int startIndex = line.indexOf(QUOTE_CHAR);
int endIndex = line.indexOf(QUOTE_CHAR, startIndex + 1);
return (startIndex == -1 || endIndex == -1) ? extractBranchName(line, SINGLE_QUOTE_CHAR) : extractBranchName(line, QUOTE_CHAR);
}
private String extractBranchName(String line, char delim) {
int startIndex = line.indexOf(delim);
int endIndex = line.indexOf(delim, startIndex + 1);
return line.substring(startIndex, endIndex + 1);
}
private void parseFilesInfo(String line) {
if (Pattern.MODIFIED.matches(line)) {
File file = new File(extractFileName(line));
response.addModifiedFile(file);
return;
}
if (Pattern.DELETED.matches(line)) {
File file = new File(extractFileName(line));
response.addDeletedFile(file);
return;
}
if (Pattern.ADDED.matches(line)) {
File file = new File(extractFileName(line));
response.addAddedFile(file);
}
}
private String extractFileName(String line) {
String filename = null;
Scanner scanner = new Scanner(line);
while (scanner.hasNext()) {
filename = scanner.next();
}
return filename;
}
public void processExitCode(int code) {
}
public GitCheckoutResponse getResponse() throws JavaGitException {
if (errors.size() > 0) { | throw new JavaGitException(406000, ExceptionMessageMap.getMessage("406000") + | 6 |
zeromq/jzmq-api | src/main/java/org/zeromq/api/Context.java | [
"public class CloneClientBuilder {\n public class Spec {\n public String primaryAddress;\n public String backupAddress;\n public int primaryPort;\n public int backupPort;\n public String subtree;\n public long heartbeatInterval = 1000L;\n }\n\n private ManagedConte... | import org.zeromq.jzmq.beacon.BeaconReactorBuilder;
import org.zeromq.jzmq.bstar.BinaryStarReactorBuilder;
import org.zeromq.jzmq.bstar.BinaryStarSocketBuilder;
import org.zeromq.jzmq.clone.CloneClientBuilder;
import org.zeromq.jzmq.clone.CloneServerBuilder;
import org.zeromq.jzmq.device.DeviceBuilder;
import org.zeromq.jzmq.poll.PollerBuilder;
import org.zeromq.jzmq.reactor.ReactorBuilder;
import org.zeromq.jzmq.sockets.SocketBuilder;
import java.io.Closeable;
import java.nio.channels.SelectableChannel; | package org.zeromq.api;
/**
* A ØMQ context is thread safe and may be shared among as many application threads as necessary, without any additional
* locking required on the part of the caller.
*/
public interface Context extends Closeable {
/**
* Create a ØMQ Socket of type SocketType
*
* @param type socket type
* @return A builder for constructing and connecting ØMQ Sockets
*/
SocketBuilder buildSocket(SocketType type);
/**
* @return The ØMQ version, in a pretty-printed String.
*/
String getVersionString();
/**
* @return The ØMQ version, in integer form.
*/
int getFullVersion();
/**
* Create a new Poller, which will allow callback-based polling of Sockets.
*
* @return A builder for constructing ØMQ Pollers
* @see Pollable
* @see PollerType
*/
PollerBuilder buildPoller();
/**
* Create a new Reactor, which will allow event-driven and timer-based
* polling of Sockets.
*
* @return A builder for constructing a Reactor
*/
ReactorBuilder buildReactor();
/**
* Create a new BinaryStarReactor, which will create one half of an HA-pair
* with event-driven polling of a client Socket.
*
* @return A builder for constructing a BinaryStarReactor
*/
BinaryStarReactorBuilder buildBinaryStarReactor();
/**
* Create a ØMQ Socket, backed by a background agent that is connecting
* to a BinaryStarReactor HA-pair.
*
* @return A builder for constructing connecting a BinaryStarReactor client Socket
*/
BinaryStarSocketBuilder buildBinaryStarSocket();
/**
* Create a new CloneServer, which will create one half of an HA-pair
* for distributing key/value data to clients.
*
* @return A builder for constructing a CloneServer
*/
CloneServerBuilder buildCloneServer();
/**
* Create a new CloneClient, connected to an HA-pair, for publishing key/value data
* to anonymous peers.
*
* @return A builder for constructing a CloneClient
*/ | CloneClientBuilder buildCloneClient(); | 0 |
karthicks/gremlin-ogm | gremlin-objects/src/main/java/org/apache/tinkerpop/gremlin/object/reflect/Label.java | [
"@Data\n@ToString\n@NoArgsConstructor\n@Accessors(fluent = true, chain = true)\n@EqualsAndHashCode(callSuper = true, of = {})\npublic abstract class Edge extends Element {\n\n /**\n * The object representation of the \"from\" vertex.\n */\n @Hidden\n private Vertex from;\n /**\n * The object representatio... | import org.apache.commons.lang3.text.WordUtils;
import org.apache.tinkerpop.gremlin.object.model.Alias;
import org.apache.tinkerpop.gremlin.object.structure.Edge;
import org.apache.tinkerpop.gremlin.object.structure.Element;
import static org.apache.tinkerpop.gremlin.object.reflect.Classes.is;
import static org.apache.tinkerpop.gremlin.object.reflect.Classes.name;
import static org.apache.tinkerpop.gremlin.object.reflect.Fields.alias; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.object.reflect;
/**
* The label of a vertex (or edge) object can be obtained through the {@link Label#of} methods.
*
* <p>
* By default, the label of a vertex is the same as it's object's simple class name, and that of an
* edge is the same, except it's uncapitalized. If you wish to override this default naming
* convention, you may annotate the class with a {@link Alias#label()} value.
*
* @author Karthick Sankarachary (http://github.com/karthicks)
*/
public final class Label {
private Label() {}
@SuppressWarnings("PMD.ShortMethodName")
public static String of(Element element) {
return of(element.getClass());
}
@SuppressWarnings("PMD.ShortMethodName")
public static String of(Class<? extends Element> elementType) {
String label = alias(elementType, Alias::label);
if (label == null) { | label = name(elementType); | 3 |
5GSD/AIMSICDL | AIMSICD/src/main/java/zz/aimsicd/lite/ui/fragments/CellInfoFragment.java | [
"public class BaseInflaterAdapter<T> extends BaseAdapter {\n\n private final List<T> m_items = new ArrayList<>();\n\n private IAdapterViewInflater<T> m_viewInflater;\n\n public BaseInflaterAdapter(IAdapterViewInflater<T> viewInflater) {\n m_viewInflater = viewInflater;\n }\n\n public BaseInfla... | import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;
import android.support.v4.widget.SwipeRefreshLayout;
import java.util.List;
import java.util.concurrent.TimeUnit;
import zz.aimsicd.lite.R;
import zz.aimsicd.lite.adapters.BaseInflaterAdapter;
import zz.aimsicd.lite.adapters.CardItemData;
import zz.aimsicd.lite.adapters.CellCardInflater;
import zz.aimsicd.lite.rilexecutor.RilExecutor;
import zz.aimsicd.lite.service.AimsicdService;
import zz.aimsicd.lite.service.CellTracker;
import zz.aimsicd.lite.utils.Cell;
import zz.aimsicd.lite.utils.Helpers;
import io.freefair.android.injection.annotation.InjectView;
import io.freefair.android.injection.annotation.XmlLayout;
import io.freefair.android.injection.app.InjectionFragment; | /* Android IMSI-Catcher Detector | (c) AIMSICD Privacy Project
* -----------------------------------------------------------
* LICENSE: http://git.io/vki47 | TERMS: http://git.io/vki4o
* -----------------------------------------------------------
*/
/* This was introduced by Aussie in the Pull Request Commit:
* https://github.com/xLaMbChOpSx/Android-IMSI-Catcher-Detector/commit/6d8719ab356a3ecbd0b526a9ded0cabb17ab2021
*
* Where he writes:
* ""
* Advanced Cell Fragment added to display the Neighbouring Cell information in two ways firstly
* through telephony manager methods which does not work on Samsung Devices, a fallback is available
* through the methods developed by Alexey and will display if these are successful.
* Ciphering Indicator also uses Alexey's methods and will display on Samsung devices.
* ""
*/
package zz.aimsicd.lite.ui.fragments;
/**
* Description: This class updates the CellInfo fragment. This is also known as
* the Neighboring Cells info, which is using the MultiRilClient to
* show neighboring cells on the older Samsung Galaxy S2/3 series.
* It's refresh rate is controlled in the settings by:
*
* arrays.xml:
* pref_refresh_entries (the names)
* pref_refresh_values (the values in seconds)
*
*
* Dependencies: Seem that this is intimately connected to: CellTracker.java service...
*
* ToDo:
* [ ] (1) Use an IF check, in order not to run the MultiRilClient on non supported devices
* as this will cause excessive logcat spam.
* [ ] (2) Might wanna make the refresh rate lower/higher depending on support
*
*/
@XmlLayout(zz.aimsicd.lite.R.layout.fragment_cell_info)
public class CellInfoFragment extends InjectionFragment implements SwipeRefreshLayout.OnRefreshListener {
public static final int STOCK_REQUEST = 1;
public static final int SAMSUNG_MULTIRIL_REQUEST = 2;
private AimsicdService mAimsicdService;
private RilExecutor rilExecutor;
private boolean mBound;
private Context mContext;
private final Handler timerHandler = new Handler();
private List<Cell> neighboringCells;
@InjectView(zz.aimsicd.lite.R.id.list_view)
private ListView lv;
@InjectView(zz.aimsicd.lite.R.id.swipeRefreshLayout)
private SwipeRefreshLayout swipeRefreshLayout;
private BaseInflaterAdapter<CardItemData> mBaseInflaterAdapter;
private CellInfoAdapter mCellInfoAdapter;
private final Runnable timerRunnable = new Runnable() {
@Override
public void run() {
updateUI();
timerHandler.postDelayed(this, CellTracker.REFRESH_RATE);
}
};
@Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
}
@Override
public void onResume() {
super.onResume();
if (!mBound) {
// Bind to LocalService
Intent intent = new Intent(mContext, AimsicdService.class);
mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
// Refresh display if preference (pref_refresh_values) is not set to manual (0)
// For automatic it is "1" and defined in:
// CellTracker.java :: onSharedPreferenceChanged()
if (CellTracker.REFRESH_RATE != 0) {
timerHandler.postDelayed(timerRunnable, 0); | Helpers.msgShort(mContext, mContext.getString(zz.aimsicd.lite.R.string.refreshing_every) + " " + | 7 |
ypresto/miniguava | miniguava-collect-immutables/src/main/java/net/ypresto/miniguava/collect/immutables/ImmutableList.java | [
"public static int checkElementIndex(int index, int size) {\n return checkElementIndex(index, size, \"index\");\n}",
"public static void checkPositionIndexes(int start, int end, int size) {\n // Carefully optimized for execution by hotspot (explanatory comment above)\n if (start < 0 || end < start || end > siz... | import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;
import javax.annotation.Nullable;
import static net.ypresto.miniguava.base.Preconditions.checkElementIndex;
import static net.ypresto.miniguava.base.Preconditions.checkPositionIndexes;
import static net.ypresto.miniguava.collect.immutables.ObjectArrays.arraysCopyOf;
import static net.ypresto.miniguava.collect.immutables.ObjectArrays.checkElementsNotNull;
import static net.ypresto.miniguava.collect.immutables.RegularImmutableList.EMPTY;
import net.ypresto.miniguava.collect.UnmodifiableIterator;
import net.ypresto.miniguava.collect.UnmodifiableListIterator;
import net.ypresto.miniguava.collect.internal.AbstractIndexedListIterator;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection; | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.ypresto.miniguava.collect.immutables;
/**
* A {@link List} whose contents will never change, with many other important properties detailed at
* {@link ImmutableCollection}.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @see ImmutableMap
* @see ImmutableSet
* @author Kevin Bourrillion
* @since 2.0
*/
// miniguava: Removed copyOf(Iterable) and copyOf(Iterator).
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableList<E> extends ImmutableCollection<E>
implements List<E>, RandomAccess {
/**
* Returns the empty immutable list. This set behaves and performs comparably
* to {@link Collections#emptyList}, and is preferable mainly for consistency
* and maintainability of your code.
*/
// Casting to any type is safe because the list will never hold any elements.
@SuppressWarnings("unchecked")
public static <E> ImmutableList<E> of() {
return (ImmutableList<E>) EMPTY;
}
/**
* Returns an immutable list containing a single element. This list behaves
* and performs comparably to {@link Collections#singleton}, but will not
* accept a null element. It is preferable mainly for consistency and
* maintainability of your code.
*
* @throws NullPointerException if {@code element} is null
*/
public static <E> ImmutableList<E> of(E element) {
return new SingletonImmutableList<E>(element);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2) {
return construct(e1, e2);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
return construct(e1, e2, e3);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
return construct(e1, e2, e3, e4);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
return construct(e1, e2, e3, e4, e5);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
return construct(e1, e2, e3, e4, e5, e6);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
return construct(e1, e2, e3, e4, e5, e6, e7);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) {
return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11);
}
// These go up to eleven. After that, you just get the varargs form, and
// whatever warnings might come along with it. :(
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any element is null
* @since 3.0 (source-compatible since 2.0)
*/
public static <E> ImmutableList<E> of(
E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12, E... others) {
Object[] array = new Object[12 + others.length];
array[0] = e1;
array[1] = e2;
array[2] = e3;
array[3] = e4;
array[4] = e5;
array[5] = e6;
array[6] = e7;
array[7] = e8;
array[8] = e9;
array[9] = e10;
array[10] = e11;
array[11] = e12;
System.arraycopy(others, 0, array, 12, others.length);
return construct(array);
}
/**
* Returns an immutable list containing the given elements, in order.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* <p>Note that if {@code list} is a {@code List<String>}, then {@code
* ImmutableList.copyOf(list)} returns an {@code ImmutableList<String>}
* containing each of the strings in {@code list}, while
* ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>}
* containing one element (the given list itself).
*
* <p>This method is safe to use even when {@code elements} is a synchronized
* or concurrent collection that is currently being modified by another
* thread.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) {
if (elements instanceof ImmutableCollection) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList();
return list.isPartialView() ? ImmutableList.<E>asImmutableList(list.toArray()) : list;
}
return construct(elements.toArray());
}
/**
* Returns an immutable list containing the given elements, in order.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 3.0
*/
public static <E> ImmutableList<E> copyOf(E[] elements) {
switch (elements.length) {
case 0:
return ImmutableList.of();
case 1:
return new SingletonImmutableList<E>(elements[0]);
default:
return new RegularImmutableList<E>(checkElementsNotNull(elements.clone()));
}
}
/**
* Views the array as an immutable list. Checks for nulls; does not copy.
*/
private static <E> ImmutableList<E> construct(Object... elements) {
return asImmutableList(checkElementsNotNull(elements));
}
/**
* Views the array as an immutable list. Does not check for nulls; does not copy.
*
* <p>The array must be internally created.
*/
static <E> ImmutableList<E> asImmutableList(Object[] elements) {
return asImmutableList(elements, elements.length);
}
/**
* Views the array as an immutable list. Copies if the specified range does not cover the complete
* array. Does not check for nulls.
*/
static <E> ImmutableList<E> asImmutableList(Object[] elements, int length) {
switch (length) {
case 0:
return of();
case 1:
@SuppressWarnings("unchecked") // collection had only Es in it
ImmutableList<E> list = new SingletonImmutableList<E>((E) elements[0]);
return list;
default:
if (length < elements.length) { | elements = arraysCopyOf(elements, length); | 2 |
atolcd/alfresco-audit-share | audit-share-platform/src/main/java/com/atolcd/alfresco/repo/jscript/ShareStats.java | [
"public class AtolVolumetryEntry {\n\tprivate long id = 0;\n\tprivate String siteId = \"\";\n\tprivate long siteSize = 0;\n\tprivate int folderCount = 0;\n\tprivate int fileCount = 0;\n\tprivate long atTime = 0;\n\n\tpublic AtolVolumetryEntry() {\n\t}\n\n\tpublic AtolVolumetryEntry(String siteId, long siteSize, int... | import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.domain.node.ContentDataWithId;
import org.alfresco.repo.jscript.BaseScopableProcessorExtension;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.LimitBy;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.ResultSetRow;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.site.SiteInfo;
import org.alfresco.service.cmr.site.SiteService;
import org.alfresco.util.ISO9075;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import com.atolcd.alfresco.AtolVolumetryEntry;
import com.atolcd.alfresco.AuditCount;
import com.atolcd.alfresco.AuditEntry;
import com.atolcd.alfresco.AuditQueryParameters;
import com.atolcd.alfresco.web.scripts.shareStats.InsertAuditPost;
import com.atolcd.alfresco.web.scripts.shareStats.SelectAuditsGet;
import com.atolcd.auditshare.repo.service.AuditShareReferentielService;
import com.atolcd.auditshare.repo.xml.Group; | /*
* Copyright (C) 2018 Atol Conseils et Développements.
* http://www.atolcd.com/
*
* This program 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.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.atolcd.alfresco.repo.jscript;
public class ShareStats extends BaseScopableProcessorExtension implements InitializingBean {
// Logger
private static final Log logger = LogFactory.getLog(ShareStats.class);
private InsertAuditPost wsInsertAudits;
private SiteService siteService;
private SearchService searchService;
private int batchSize;
// SqlMapClientTemplate for MyBatis calls
private SqlSessionTemplate sqlSessionTemplate;
// For the user groups referentiel services
private AuditShareReferentielService auditShareReferentielService;
public SiteService getSiteService() {
return siteService;
}
public void setSiteService(SiteService siteService) {
this.siteService = siteService;
}
public SearchService getSearchService() {
return searchService;
}
public void setSearchService(SearchService searchService) {
this.searchService = searchService;
}
public int getBatchSize() {
return batchSize;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
public void setWsInsertAudits(InsertAuditPost wsInsertAudits) {
this.wsInsertAudits = wsInsertAudits;
}
public AuditShareReferentielService getAuditShareReferentielService() {
return auditShareReferentielService;
}
public void setAuditShareReferentielService(AuditShareReferentielService auditShareReferentielService) {
this.auditShareReferentielService = auditShareReferentielService;
}
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(siteService);
Assert.notNull(searchService);
Assert.notNull(wsInsertAudits);
Assert.notNull(auditShareReferentielService);
Assert.notNull(sqlSessionTemplate);
}
public List<Group> getReferentiel(String refGroup) {
// Referentiel
return auditShareReferentielService.parseRefentielForNodeUUID(refGroup);
}
public void insertAuditEntry(long id, String auditUserId, String auditSite, String auditAppName, String auditActionName,
String auditObject, long auditTime, String auditNodeType) throws SQLException, JSONException {
AuditEntry auditSample = new AuditEntry();
auditSample.setId(id);
auditSample.setAuditUserId(auditUserId);
auditSample.setAuditAppName(auditAppName);
auditSample.setAuditActionName(auditActionName);
auditSample.setAuditObject(auditObject);
auditSample.setAuditTime(auditTime);
auditSample.setAuditSite(StringUtils.isNotBlank(auditSite) ? auditSite : InsertAuditPost.SITE_REPOSITORY);
if (StringUtils.isNotBlank(auditNodeType)) {
auditSample.setAuditNodeType(auditNodeType);
}
sqlSessionTemplate.insert(InsertAuditPost.INSERT_ENTRY, auditSample);
logger.info("Entry successfully inserted: " + auditSample.toJSON());
}
public List<AuditCount> selectByRead(String auditAppNames, String auditActionNames, String auditUserIds, String auditSites,
String auditObject, Long dateFrom, Long dateTo, String auditNodeTypes) throws SQLException, JSONException {
return this.selectAuditCount(SelectAuditsGet.SELECT_BY_VIEW, auditAppNames, auditActionNames, auditUserIds, auditSites, auditObject,
dateFrom, dateTo, auditNodeTypes);
}
public List<AuditCount> selectByCreated(String auditAppNames, String auditActionNames, String auditUserIds, String auditSites,
String auditObject, Long dateFrom, Long dateTo, String auditNodeTypes) throws SQLException, JSONException {
return this.selectAuditCount(SelectAuditsGet.SELECT_BY_CREATED, auditAppNames, auditActionNames, auditUserIds, auditSites, auditObject,
dateFrom, dateTo, auditNodeTypes);
}
public List<AuditCount> selectByUpdated(String auditAppNames, String auditActionNames, String auditUserIds, String auditSites,
String auditObject, Long dateFrom, Long dateTo, String auditNodeTypes) throws SQLException, JSONException {
return this.selectAuditCount(SelectAuditsGet.SELECT_BY_UPDATED, auditAppNames, auditActionNames, auditUserIds, auditSites, auditObject,
dateFrom, dateTo, auditNodeTypes);
}
public List<AuditCount> selectByDeleted(String auditAppNames, String auditActionNames, String auditUserIds, String auditSites,
String auditObject, Long dateFrom, Long dateTo, String auditNodeTypes) throws SQLException, JSONException {
return this.selectAuditCount(SelectAuditsGet.SELECT_BY_DELETED, auditAppNames, auditActionNames, auditUserIds, auditSites, auditObject,
dateFrom, dateTo, auditNodeTypes);
}
private List<AuditCount> selectAuditCount(String queryType, String auditAppNames, String auditActionNames, String auditUserIds,
String auditSites, String auditObject, Long dateFrom, Long dateTo, String auditNodeTypes) throws SQLException, JSONException { | AuditQueryParameters params = new AuditQueryParameters(); | 1 |
googleapis/google-oauth-java-client | samples/dailymotion-cmdline-sample/src/main/java/com/google/api/services/samples/dailymotion/cmdline/DailyMotionSample.java | [
"public class AuthorizationCodeFlow {\n\n /**\n * Method of presenting the access token to the resource server (for example {@link\n * BearerToken#authorizationHeaderAccessMethod}).\n */\n private final AccessMethod method;\n\n /** HTTP transport. */\n private final HttpTransport transport;\n\n /** JSON ... | import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import java.io.File;
import java.io.IOException;
import java.util.Arrays; | /*
* Copyright (c) 2011 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.api.services.samples.dailymotion.cmdline;
/**
* A sample application that demonstrates how the Google OAuth2 library can be used to authenticate
* against Daily Motion.
*
* @author Ravi Mistry
*/
public class DailyMotionSample {
/** Directory to store user credentials. */
private static final File DATA_STORE_DIR =
new File(System.getProperty("user.home"), ".store/dailymotion_sample");
/**
* Global instance of the {@link DataStoreFactory}. The best practice is to make it a single
* globally shared instance across your application.
*/
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** OAuth 2 scope. */
private static final String SCOPE = "read";
/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
/** Global instance of the JSON factory. */
static final JsonFactory JSON_FACTORY = new GsonFactory();
private static final String TOKEN_SERVER_URL = "https://api.dailymotion.com/oauth/token";
private static final String AUTHORIZATION_SERVER_URL =
"https://api.dailymotion.com/oauth/authorize";
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
OAuth2ClientCredentials.errorIfNotSpecified();
// set up authorization code flow
AuthorizationCodeFlow flow =
new AuthorizationCodeFlow.Builder(
BearerToken.authorizationHeaderAccessMethod(),
HTTP_TRANSPORT,
JSON_FACTORY,
new GenericUrl(TOKEN_SERVER_URL),
new ClientParametersAuthentication(
OAuth2ClientCredentials.API_KEY, OAuth2ClientCredentials.API_SECRET),
OAuth2ClientCredentials.API_KEY,
AUTHORIZATION_SERVER_URL)
.setScopes(Arrays.asList(SCOPE))
.setDataStoreFactory(DATA_STORE_FACTORY)
.build();
// authorize | LocalServerReceiver receiver = | 5 |
ResearchStack/ResearchStack | backbone/src/main/java/org/researchstack/backbone/ui/step/layout/SurveyStepLayout.java | [
"public abstract class ResourcePathManager {\n private static Gson gson = new GsonBuilder().setDateFormat(\"MMM yyyy\").create();\n\n private static ResourcePathManager instance;\n\n /**\n * Initializes the ResourcePathManager singleton. It is best to call this method inside your\n * {@link Applica... | import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.text.Html;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.researchstack.backbone.R;
import org.researchstack.backbone.ResourcePathManager;
import org.researchstack.backbone.result.StepResult;
import org.researchstack.backbone.step.QuestionStep;
import org.researchstack.backbone.step.Step;
import org.researchstack.backbone.ui.ViewWebDocumentActivity;
import org.researchstack.backbone.ui.callbacks.StepCallbacks;
import org.researchstack.backbone.ui.step.body.BodyAnswer;
import org.researchstack.backbone.ui.step.body.StepBody;
import org.researchstack.backbone.ui.views.FixedSubmitBarLayout;
import org.researchstack.backbone.ui.views.SubmitBar;
import org.researchstack.backbone.utils.LogExt;
import org.researchstack.backbone.utils.TextUtils;
import java.lang.reflect.Constructor; | package org.researchstack.backbone.ui.step.layout;
public class SurveyStepLayout extends FixedSubmitBarLayout implements StepLayout {
public static final String TAG = SurveyStepLayout.class.getSimpleName();
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Data used to initializeLayout and return
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
private QuestionStep questionStep;
private StepResult stepResult;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Communicate w/ host
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
private StepCallbacks callbacks;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Child Views
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
private LinearLayout container;
private StepBody stepBody;
public SurveyStepLayout(Context context) {
super(context);
}
public SurveyStepLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SurveyStepLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void initialize(Step step) {
initialize(step, null);
}
@Override
public void initialize(Step step, StepResult result) {
if (!(step instanceof QuestionStep)) {
throw new RuntimeException("Step being used in SurveyStep is not a QuestionStep");
}
this.questionStep = (QuestionStep) step;
this.stepResult = result;
initializeStep();
}
@Override
public View getLayout() {
return this;
}
/**
* Method allowing a step to consume a back event.
*
* @return
*/
@Override
public boolean isBackEventConsumed() {
callbacks.onSaveStep(StepCallbacks.ACTION_PREV, getStep(), stepBody.getStepResult(false));
return false;
}
@Override
public void setCallbacks(StepCallbacks callbacks) {
this.callbacks = callbacks;
}
@Override
public int getContentResourceId() {
return R.layout.rsb_step_layout;
}
public void initializeStep() {
initStepLayout();
initStepBody();
}
public void initStepLayout() {
LogExt.i(getClass(), "initStepLayout()");
container = (LinearLayout) findViewById(R.id.rsb_survey_content_container);
TextView title = (TextView) findViewById(R.id.rsb_survey_title);
TextView summary = (TextView) findViewById(R.id.rsb_survey_text);
SubmitBar submitBar = (SubmitBar) findViewById(R.id.rsb_submit_bar);
submitBar.setPositiveAction(v -> onNextClicked());
if (questionStep != null) {
if (!TextUtils.isEmpty(questionStep.getTitle())) {
title.setVisibility(View.VISIBLE);
title.setText(questionStep.getTitle());
}
if (!TextUtils.isEmpty(questionStep.getText())) {
summary.setVisibility(View.VISIBLE);
summary.setText(Html.fromHtml(questionStep.getText()));
summary.setMovementMethod(new TextViewLinkHandler() {
@Override
public void onLinkClick(String url) {
String path = ResourcePathManager.getInstance().
generateAbsolutePath(ResourcePathManager.Resource.TYPE_HTML, url);
Intent intent = ViewWebDocumentActivity.newIntentForPath(getContext(),
questionStep.getTitle(),
path);
getContext().startActivity(intent);
}
});
}
if (questionStep.isOptional()) {
submitBar.setNegativeTitle(R.string.rsb_step_skip);
submitBar.setNegativeAction(v -> onSkipClicked());
} else {
submitBar.getNegativeActionView().setVisibility(View.GONE);
}
}
}
public void initStepBody() {
LogExt.i(getClass(), "initStepBody()");
LayoutInflater inflater = LayoutInflater.from(getContext());
stepBody = createStepBody(questionStep, stepResult);
View body = stepBody.getBodyView(StepBody.VIEW_TYPE_DEFAULT, inflater, this);
if (body != null) {
View oldView = container.findViewById(R.id.rsb_survey_step_body);
int bodyIndex = container.indexOfChild(oldView);
container.removeView(oldView);
container.addView(body, bodyIndex);
body.setId(R.id.rsb_survey_step_body);
}
}
@NonNull
private StepBody createStepBody(QuestionStep questionStep, StepResult result) {
try {
Class cls = questionStep.getStepBodyClass();
Constructor constructor = cls.getConstructor(Step.class, StepResult.class);
return (StepBody) constructor.newInstance(questionStep, result);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Parcelable onSaveInstanceState() {
callbacks.onSaveStep(StepCallbacks.ACTION_NONE, getStep(), stepBody.getStepResult(false));
return super.onSaveInstanceState();
}
protected void onNextClicked() { | BodyAnswer bodyAnswer = stepBody.getBodyAnswerState(); | 4 |
inouire/baggle | baggle-client/src/inouire/baggle/client/gui/ConnectionPanel.java | [
"public class Language {\n\n static String[] tooltip_fr = new String[]{\n \"Lister les serveurs sur le réseau officiel\",//0\n \"Lister les serveurs en réseau local\",//1\n };\n static String[] tooltip_en = new String[]{\n \"List servers of the official network\",//0\n \"List se... | import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import inouire.baggle.client.Language;
import inouire.baggle.client.Main;
import inouire.baggle.client.gui.modules.LANDiscoverPanel;
import inouire.baggle.client.gui.modules.OfficialServersPanel;
import inouire.baggle.client.gui.modules.SideConnectionPanel;
import inouire.baggle.client.threads.LANDiscoverThread; | package inouire.baggle.client.gui;
/**
*
* @author Edouard de Labareyre
*/
public class ConnectionPanel extends JPanel{
public SideConnectionPanel sideConnectionPane;
public OfficialServersPanel officialServersPane;
public LANDiscoverPanel lanDiscoverPane;
private NetworkTypeSelectionPanel networkTypePane;
private JButton about_button;
private JPanel networksPane;
private CardLayout networksLayout;
public static GridBagConstraints CENTERED = new GridBagConstraints (0, 0, 1, 1, 0, 0,
GridBagConstraints.CENTER,
GridBagConstraints.CENTER,
new Insets (0,0,0,0), 0, 0);
private boolean local_showed=false;
public ConnectionPanel(){
super();
//selection buttons
networkTypePane = new NetworkTypeSelectionPanel();
JPanel network_type_wrapper = new JPanel(new GridBagLayout ());
network_type_wrapper.add(networkTypePane,CENTERED);
network_type_wrapper.setOpaque(false);
//top banner
JLabel brand_label = new JLabel();
brand_label.setIcon(new ImageIcon(getClass().getResource("/inouire/baggle/client/icons/banner.png")));
brand_label.setText(Main.VERSION);
brand_label.setFont(new Font("Serial", Font.BOLD, 16));
brand_label.setForeground(Color.WHITE);
about_button = new JButton();
about_button.setIcon(new ImageIcon(getClass().getResource("/inouire/baggle/client/icons/info.png")));
about_button.setToolTipText(Language.getString(28));
about_button.setPreferredSize(new Dimension(42,42));
about_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
aboutPressed();
}
});
JPanel about_button_wrapper = new JPanel(new GridBagLayout ());
about_button_wrapper.add (about_button,CENTERED);
about_button_wrapper.setOpaque(false);
about_button_wrapper.setPreferredSize(new Dimension(58,50));
JPanel top_panel = new JPanel(new BorderLayout());
top_panel.add(brand_label,BorderLayout.WEST);
top_panel.add(about_button_wrapper,BorderLayout.EAST);
top_panel.add(network_type_wrapper,BorderLayout.CENTER);
top_panel.setBackground(ColorFactory.GREEN_BOARD);
JLabel non_dispo = new JLabel("Non disponible pour le moment");
non_dispo.setHorizontalAlignment(SwingConstants.CENTER);
sideConnectionPane = new SideConnectionPanel();
officialServersPane = new OfficialServersPanel();
lanDiscoverPane = new LANDiscoverPanel();
networksPane=new JPanel();
networksLayout=new CardLayout();
networksPane.setLayout(networksLayout);
networksPane.add(officialServersPane,"official");
networksPane.add(lanDiscoverPane,"local");
networksLayout.show(networksPane, "official");
this.setLayout(new BorderLayout());
this.add(top_panel,BorderLayout.NORTH);
this.add(sideConnectionPane,BorderLayout.WEST);
this.add(networksPane,BorderLayout.CENTER);
}
public void showOfficial(){
networksLayout.show(networksPane, "official");
local_showed = false;
}
public void showLocal(){
networksLayout.show(networksPane, "local");
local_showed = true; | new LANDiscoverThread(lanDiscoverPane).start(); | 5 |
moxious/neoprofiler | src/main/java/org/mitre/neoprofiler/html/HTMLMaker.java | [
"public class MarkdownMaker {\n\tpublic MarkdownMaker() {\n\t\t\n\t}\n\t\n\tpublic String link(String text, String url) { return \"[\" + text + \"](\" + url + \")\"; } \n\tpublic String h1(String content) { return \"\\n# \" + content + \"\\n\"; }\n\tpublic String h2(String content) { return \"\\n## \" + content + \... | import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.List;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.mitre.neoprofiler.markdown.MarkdownMaker;
import org.mitre.neoprofiler.profile.DBProfile;
import org.mitre.neoprofiler.profile.LabelProfile;
import org.mitre.neoprofiler.profile.NeoProfile;
import org.mitre.neoprofiler.profile.RelationshipTypeProfile; | package org.mitre.neoprofiler.html;
/**
* Class that renders a DBProfile as HTML.
* The general approach is to write a graph structure in JSON rendered via D3.js, and to populate the rest
* of the page with regular markdown from the MarkdownGenerator, rendered to HTML by strapdown.js.
* @author moxious
*/
public class HTMLMaker {
public HTMLMaker() { ; }
public String generateGraph(DBProfile profile) {
StringBuffer b = new StringBuffer("var links = [\n");
| for(NeoProfile p : profile.getProfiles()) { | 3 |
NanYoMy/mybatis-generator | src/main/java/org/mybatis/generator/config/Context.java | [
"public class GeneratedXmlFile extends GeneratedFile {\n private Document document;\n\n private String fileName;\n\n private String targetPackage;\n\n private boolean isMergeable;\n \n private XmlFormatter xmlFormatter;\n\n /**\n * \n * @param document\n * @param fileName\n * @p... | import static org.mybatis.generator.internal.util.StringUtility.composeFullyQualifiedTableName;
import static org.mybatis.generator.internal.util.StringUtility.isTrue;
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.JavaFormatter;
import org.mybatis.generator.api.Plugin;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.JavaTypeResolver;
import org.mybatis.generator.api.ProgressCallback;
import org.mybatis.generator.api.XmlFormatter;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.internal.ObjectFactory;
import org.mybatis.generator.internal.PluginAggregator;
import org.mybatis.generator.internal.db.ConnectionFactory;
import org.mybatis.generator.internal.db.DatabaseIntrospector; | /*
* Copyright 2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.generator.config;
/**
* @author Jeff Butler
*/
public class Context extends PropertyHolder {
private String id;
private JDBCConnectionConfiguration jdbcConnectionConfiguration;
private SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration;
private JavaTypeResolverConfiguration javaTypeResolverConfiguration;
private JavaModelGeneratorConfiguration javaModelGeneratorConfiguration;
private JavaClientGeneratorConfiguration javaClientGeneratorConfiguration;
private ArrayList<TableConfiguration> tableConfigurations;
private ModelType defaultModelType;
private String beginningDelimiter = "\""; //$NON-NLS-1$
private String endingDelimiter = "\""; //$NON-NLS-1$
private CommentGeneratorConfiguration commentGeneratorConfiguration;
private CommentGenerator commentGenerator;
private PluginAggregator pluginAggregator;
private List<PluginConfiguration> pluginConfigurations;
private String targetRuntime;
private String introspectedColumnImpl;
private Boolean autoDelimitKeywords;
private JavaFormatter javaFormatter;
private XmlFormatter xmlFormatter;
/**
* Constructs a Context object.
*
* @param defaultModelType
* - may be null
*/
public Context(ModelType defaultModelType) {
super();
if (defaultModelType == null) {
this.defaultModelType = ModelType.CONDITIONAL;
} else {
this.defaultModelType = defaultModelType;
}
tableConfigurations = new ArrayList<TableConfiguration>();
pluginConfigurations = new ArrayList<PluginConfiguration>();
}
public void addTableConfiguration(TableConfiguration tc) {
tableConfigurations.add(tc);
}
public JDBCConnectionConfiguration getJdbcConnectionConfiguration() {
return jdbcConnectionConfiguration;
}
public JavaClientGeneratorConfiguration getJavaClientGeneratorConfiguration() {
return javaClientGeneratorConfiguration;
}
public JavaModelGeneratorConfiguration getJavaModelGeneratorConfiguration() {
return javaModelGeneratorConfiguration;
}
public JavaTypeResolverConfiguration getJavaTypeResolverConfiguration() {
return javaTypeResolverConfiguration;
}
public SqlMapGeneratorConfiguration getSqlMapGeneratorConfiguration() {
return sqlMapGeneratorConfiguration;
}
public void addPluginConfiguration(
PluginConfiguration pluginConfiguration) {
pluginConfigurations.add(pluginConfiguration);
}
/**
* This method does a simple validate, it makes sure that all required
* fields have been filled in. It does not do any more complex operations
* such as validating that database tables exist or validating that named
* columns exist
*/
public void validate(List<String> errors) {
if (!stringHasValue(id)) {
errors.add(getString("ValidationError.16")); //$NON-NLS-1$
}
if (jdbcConnectionConfiguration == null) {
errors.add(getString("ValidationError.10", id)); //$NON-NLS-1$
} else {
jdbcConnectionConfiguration.validate(errors);
}
if (javaModelGeneratorConfiguration == null) {
errors.add(getString("ValidationError.8", id)); //$NON-NLS-1$
} else {
javaModelGeneratorConfiguration.validate(errors, id);
}
if (javaClientGeneratorConfiguration != null) {
javaClientGeneratorConfiguration.validate(errors, id);
}
| IntrospectedTable it = null; | 3 |
immopoly/android | src/org/immopoly/android/app/UserLoginActivity.java | [
"public class C2DMessaging {\n\tpublic static final String EXTRA_SENDER = \"sender\";\n\tpublic static final String EXTRA_APPLICATION_PENDING_INTENT = \"app\";\n\tpublic static final String REQUEST_UNREGISTRATION_INTENT = \"com.google.android.c2dm.intent.UNREGISTER\";\n\tpublic static final String REQUEST_REGISTRAT... | import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import org.immopoly.android.R;
import org.immopoly.android.c2dm.C2DMessaging;
import org.immopoly.android.constants.Const;
import org.immopoly.android.helper.Settings;
import org.immopoly.android.helper.TrackingManager;
import org.immopoly.android.helper.WebHelper;
import org.immopoly.android.model.ImmopolyException;
import org.immopoly.android.model.ImmopolyUser;
import org.immopoly.android.tasks.Result;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast; | package org.immopoly.android.app;
public class UserLoginActivity extends Activity {
public static final int RESULT_REGISTER = 4321;
private GoogleAnalyticsTracker tracker;
private Handler toggleProgressHandler;
public static final int MIN_PASSWORTH_LENGTH = 4;
private static final int MIN_USERNAME_LENGTH = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker in manual dispatch mode...
| tracker.startNewSession(TrackingManager.UA_ACCOUNT, | 3 |
3pillarlabs/socialauth | socialauth/src/main/java/org/brickred/socialauth/provider/SalesForceImpl.java | [
"public abstract class AbstractProvider implements AuthProvider, Serializable {\n\n\tprivate static final long serialVersionUID = -7827145708317886744L;\n\n\tprivate Map<Class<? extends Plugin>, Class<? extends Plugin>> pluginsMap;\n\n\tprivate final Log LOG = LogFactory.getLog(this.getClass());\n\n\tpublic Abstrac... | import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.brickred.socialauth.AbstractProvider;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.Contact;
import org.brickred.socialauth.Permission;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.exception.AccessTokenExpireException;
import org.brickred.socialauth.exception.SocialAuthException;
import org.brickred.socialauth.exception.UserDeniedPermissionException;
import org.brickred.socialauth.oauthstrategy.OAuth2;
import org.brickred.socialauth.oauthstrategy.OAuthStrategyBase;
import org.brickred.socialauth.util.AccessGrant;
import org.brickred.socialauth.util.Constants;
import org.brickred.socialauth.util.MethodType;
import org.brickred.socialauth.util.OAuthConfig;
import org.brickred.socialauth.util.Response;
import org.json.JSONObject; | /*
===========================================================================
Copyright (c) 2010 BrickRed Technologies Limited
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, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===========================================================================
*/
package org.brickred.socialauth.provider;
/**
* Provider implementation for SalesForce
*
*
*/
public class SalesForceImpl extends AbstractProvider implements AuthProvider,
Serializable {
private static final long serialVersionUID = 6929330230703360670L;
private static final Map<String, String> ENDPOINTS;
private final Log LOG = LogFactory.getLog(SalesForceImpl.class);
| private OAuthConfig config; | 6 |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/config/OrderInsertProcessorConfiguration.java | [
"public class DisruptorLifeCycleContainer implements SmartLifecycle {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(DisruptorLifeCycleContainer.class);\n\n private volatile boolean running = false;\n\n private final String disruptorName;\n private final Disruptor disruptor;\n private final i... | import com.lmax.disruptor.dsl.Disruptor;
import me.chanjar.jms.base.lifecycle.DisruptorLifeCycleContainer;
import me.chanjar.jms.server.StartupOrderConstants;
import me.chanjar.jms.server.command.infras.CommandDispatcher;
import me.chanjar.jms.server.command.infras.disruptor.*;
import me.chanjar.jms.server.command.order.OrderInsertCommand;
import me.chanjar.jms.server.command.order.OrderInsertCommandBuffer;
import me.chanjar.jms.server.command.order.OrderInsertCommandExecutor;
import me.chanjar.jms.server.command.order.OrderInsertCommandProcessor;
import me.chanjar.jms.base.utils.BeanRegisterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.concurrent.Executors; | package me.chanjar.jms.server.config;
@Configuration
@EnableConfigurationProperties(OrderInsertProcessorConfiguration.Conf.class)
public class OrderInsertProcessorConfiguration implements ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderInsertProcessorConfiguration.class);
@Autowired
private Conf conf;
@Autowired
private CommandDispatcher commandDispatcher;
@Autowired
private JdbcTemplate jdbcTemplate;
private ApplicationContext applicationContext;
@Bean
public OrderInsertCommandProcessor courseTakeInsertCmdProcessor() {
LOGGER.info("Configure OrderInsertCommandProcessor");
CommandEventProducer<OrderInsertCommand>[] commandEventProducerList = new CommandEventProducer[conf.getNum()];
for (int i = 0; i < conf.getNum(); i++) {
OrderInsertCommandBuffer cmdBuffer = new OrderInsertCommandBuffer(conf.getSqlBufferSize());
OrderInsertCommandExecutor cmdExecutor = new OrderInsertCommandExecutor(jdbcTemplate);
Disruptor<CommandEvent<OrderInsertCommand>> disruptor = new Disruptor<>(
new CommandEventFactory(),
conf.getQueueSize(),
Executors.defaultThreadFactory());
disruptor
.handleEventsWith(new CommandEventDbHandler(cmdBuffer, cmdExecutor))
.then(new CommandEventGcHandler())
;
// disruptor 的异常处理是这样的,
// 不论这种形式 A->B, 还是这种形式 A,B->C,D, 只有抛出异常的那个handler会中断执行
disruptor.setDefaultExceptionHandler(new CommandEventExceptionHandler());
commandEventProducerList[i] = new CommandEventProducer<>(disruptor.getRingBuffer());
| BeanRegisterUtils.registerSingleton( | 7 |
aeshell/aesh-extensions | aesh/src/test/java/org/aesh/extensions/rm/RmTest.java | [
"@CommandDefinition(name = \"cat\", description = \"concatenate files and print on the standard output\")\npublic class Cat implements Command<CommandInvocation> {\n\n @Option(shortName = 'A', name = \"show-all\", hasValue = false, description = \"equivalent to -vET\")\n private boolean showAll;\n\n @Optio... | import org.aesh.extensions.touch.Touch;
import org.aesh.readline.terminal.Key;
import org.aesh.terminal.utils.Config;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import org.aesh.command.registry.CommandRegistryException;
import org.aesh.extensions.cat.Cat;
import org.aesh.extensions.cd.Cd;
import org.aesh.extensions.common.AeshTestCommons;
import org.aesh.extensions.ls.Ls;
import org.aesh.extensions.mkdir.Mkdir; | /*
* JBoss, Home of Professional Open Source
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* 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.aesh.extensions.rm;
/**
* @author <a href="mailto:00hf11@gmail.com">Helio Frota</a>
*/
@Ignore
public class RmTest extends AeshTestCommons {
private Path tempDir;
@Before
public void before() throws IOException {
tempDir = createTempDirectory();
}
@After
public void after() throws IOException {
deleteRecursiveTempDirectory(tempDir);
}
@Test
public void testRm() throws IOException, CommandRegistryException {
| prepare(Touch.class, Mkdir.class, Cd.class, Cat.class, Ls.class, Rm.class); | 0 |
handexing/geekHome | geekHome-web-ui/src/main/java/com/geekhome/controller/LabelController.java | [
"public enum ErrorCode {\n\t\n\tEXCEPTION(\"程序异常\", \"00001\"),\n\tUSER_NOT_EXIST(\"用户未注册\", \"00002\"),\n VERIFY_CODE_WRONG(\"验证码错误\",\"00003\"),\n OLD_PWD_WRONG(\"旧密码错误\",\"00004\"),\n USERNAME_PASSWORD_WRONG(\"用户名或密码错误\",\"00005\"),\n TODAY_HAVE_SIGN(\"今日已签到\",\"00006\");\n\n\tprivate String errorMsg... | import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.geekhome.common.vo.ErrorCode;
import com.geekhome.common.vo.ExecuteResult;
import com.geekhome.common.vo.TreeView;
import com.geekhome.entity.Label;
import com.geekhome.entity.dao.LabelDao;
import com.geekhome.entity.service.LabelService; | package com.geekhome.controller;
@RestController
@RequestMapping("label")
public class LabelController {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired | LabelService labelService; | 5 |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/generator/EClassifierGenerator.java | [
"public class ExternalTypeHierarchy extends EPackageHierarchy {\n\n /**\n * Simple constructor, builds the base for the hierarchy.\n * @param root is the root {@link EPackage} of the metamodel.\n * @param properties is the instance of the {@link ExtractionProperties} class.\n */\n public Exter... | import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EGenericType;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcoreFactory;
import eme.generator.hierarchies.ExternalTypeHierarchy;
import eme.model.ExtractedClass;
import eme.model.ExtractedEnum;
import eme.model.ExtractedEnumConstant;
import eme.model.ExtractedInterface;
import eme.model.ExtractedType;
import eme.model.IntermediateModel;
import eme.model.datatypes.ExtractedDataType; | package eme.generator;
/**
* Generator class for Ecore classifiers ({@link EClassifier}s).
* @author Timur Saglam
*/
public class EClassifierGenerator {
private static final Logger logger = LogManager.getLogger(EClassifierGenerator.class.getName());
private final Map<EClass, ExtractedType> bareEClasses;
private final Map<String, EClassifier> eClassifierMap;
private final EcoreFactory ecoreFactory;
private final ExternalTypeHierarchy externalTypes;
private final EMemberGenerator memberGenerator;
private final IntermediateModel model;
private final SelectionHelper selector;
private final EDataTypeGenerator typeGenerator;
/**
* Basic constructor.
* @param model is the {@link IntermediateModel} which is used to extract a metamodel.
* @param root is the root {@link EPackage} of the metamodel.
* @param selector is the {@link SelectionHelper} instance.
*/
public EClassifierGenerator(IntermediateModel model, EPackage root, SelectionHelper selector) {
this.model = model;
this.selector = selector;
ecoreFactory = EcoreFactory.eINSTANCE;
eClassifierMap = new HashMap<String, EClassifier>();
bareEClasses = new HashMap<EClass, ExtractedType>();
externalTypes = new ExternalTypeHierarchy(root, selector.getProperties());
typeGenerator = new EDataTypeGenerator(model, eClassifierMap, externalTypes);
memberGenerator = new EMemberGenerator(typeGenerator, selector, eClassifierMap);
}
/**
* Completes the generation of the {@link EClassifier} objects. Adds methods and attributes to {@link EClass}
* objects, adds type parameters and super interfaces and sorts the external types.
*/
public void completeEClassifiers() {
for (EClass eClass : bareEClasses.keySet()) { // for every generated EClass
ExtractedType extractedType = bareEClasses.get(eClass);
typeGenerator.addTypeParameters(eClass, extractedType); // IMPORTANT: call after EClassifiers are created.
memberGenerator.addFields(extractedType, eClass); // add attributes
memberGenerator.addOperations(extractedType, eClass); // add methods
addSuperInterfaces(extractedType, eClass); // IMPORTANT: needs to be called after type parameters are built
}
externalTypes.sort();
}
/**
* Generates a dummy {@link EClassifier}, which is a simple {@link EClass}.
* @param name is the name of the dummy.
* @return the dummy {@link EClassifier}, which is an empty {@link EClass}.
*/
public EClass generateDummy(String name) {
EClass dummy = ecoreFactory.createEClass();
dummy.setName(name);
return dummy;
}
/**
* Generates an {@link EClassifier} from an ExtractedType, if the type was not already generated.
* @param type is the {@link ExtractedType}.
* @return the {@link EClassifier}, which is either an {@link EClass}, an {@link ExtractedInterface} or an
* {@link EEnum}.
*/
public EClassifier generateEClassifier(ExtractedType type) {
String fullName = type.getFullName();
if (eClassifierMap.containsKey(fullName)) { // if already created:
return eClassifierMap.get(fullName); // just return from map.
}
EClassifier eClassifier = null; // TODO (LOW) Use visitor pattern.
if (type.getClass() == ExtractedInterface.class) { // build interface:
eClassifier = generateEClass(type, true, true);
} else if (type.getClass() == ExtractedClass.class) { // build class:
EClass eClass = generateEClass(type, ((ExtractedClass) type).isAbstract(), false);
addSuperClass((ExtractedClass) type, eClass); // IMPORTANT: needs to be called after type params are built
eClassifier = eClass; | } else if (type.getClass() == ExtractedEnum.class) { // build enum: | 2 |
lazyparser/xbot_head | app/src/main/java/cn/ac/iscas/xlab/droidfacedog/mvp/commentary/CommentaryFragment.java | [
"public class ImagePreviewAdapter extends\n RecyclerView.Adapter<RecyclerView.ViewHolder> {\n\n // Store the context for later use\n private Context context;\n\n private ArrayList<Bitmap> bitmaps;\n private int check = 0;\n\n private ViewHolder.OnItemClickListener onItemClickListener;\n\n /... | import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.FaceDetector;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import cn.ac.iscas.xlab.droidfacedog.ImagePreviewAdapter;
import cn.ac.iscas.xlab.droidfacedog.R;
import cn.ac.iscas.xlab.droidfacedog.RosConnectionService;
import cn.ac.iscas.xlab.droidfacedog.entity.FaceResult;
import cn.ac.iscas.xlab.droidfacedog.util.ImageUtils;
import cn.ac.iscas.xlab.droidfacedog.util.Util; | public void setPresenter(CommentaryContract.Presenter presenter) {
this.presenter = presenter;
}
private void initCallbackAndListeners() {
cameraCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice camera) {
log("CameraStateCallback -- onOpened()");
cameraDevice = camera;
//startPreview();
}
@Override
public void onDisconnected(@NonNull CameraDevice camera) {
log("CameraStateCallback -- onDisconnected()");
if (cameraDevice != null) {
cameraDevice.close();
}
}
@Override
public void onError(@NonNull CameraDevice camera,int error) {
log("CameraStateCallback -- onOpened()");
}
};
surfaceTextureListener = new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
log("TextureView.SurfaceTextureListener -- onSurfaceTextureAvailable()");
surfaceTexture = surface;
startPreview();
startTimerTask();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
log("TextureView.SurfaceTextureListener -- onSurfaceTextureSizeChanged()");
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
log("TextureView.SurfaceTextureListener -- onSurfaceTextureDestroyed()");
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
Log.v(TAG,"TextureView.SurfaceTextureListener -- onSurfaceTextureUpdated()");
}
};
captureCallback = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
Log.v(TAG,"CameraCaptureSession.CaptureCallback -- onCaptureStarted()");
super.onCaptureStarted(session, request, timestamp, frameNumber);
}
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
Log.v(TAG,"CameraCaptureSession.CaptureCallback -- onCaptureCompleted()");
super.onCaptureCompleted(session, request, result);
}
};
captureSessionCallback = new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
log("CameraCaptureSession.StateCallback -- onConfigured");
if (cameraDevice == null) {
return;
}
cameraCaptureSession = session;
captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
CaptureRequest request = captureBuilder.build();
try {
cameraCaptureSession.setRepeatingRequest(request, captureCallback, backgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
log("CameraCaptureSession.StateCallback -- onConfigureFailed");
}
};
textureView.setSurfaceTextureListener(surfaceTextureListener);
}
private void initCamera() {
cameraId = "" + CameraCharacteristics.LENS_FACING_BACK;
cameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
try {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getContext(), "没有相机权限", Toast.LENGTH_SHORT).show();
} else {
cameraManager.openCamera(cameraId, cameraCallback, backgroundHandler);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void startPreview() {
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap configMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
| Size previewSize = Util.getPreferredPreviewSize( | 4 |
vanniktech/espresso-utils | espresso-core-utils/src/androidTest/java/com/vanniktech/espresso/core/utils/AttributeMatcherTest.java | [
"@CheckResult public static AttributeMatcher withAttr(@AttrRes final int attr, @ColorInt final int color) {\n return new AttributeMatcher(attr, null, ColorChecker.from(color));\n}",
"@CheckResult public static AttributeMatcher withAttrRes(@AttrRes final int attr, @ColorRes final int colorRes) {\n return new Att... | import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.rule.ActivityTestRule;
import com.vanniktech.espresso.core.utils.test.R;
import junit.framework.AssertionFailedError;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import static android.graphics.Color.BLUE;
import static android.graphics.Color.GREEN;
import static android.graphics.Color.RED;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static com.vanniktech.espresso.core.utils.AttributeMatcher.withAttr;
import static com.vanniktech.espresso.core.utils.AttributeMatcher.withAttrRes;
import static com.vanniktech.espresso.core.utils.AttributeMatcher.withColorAccent;
import static com.vanniktech.espresso.core.utils.AttributeMatcher.withColorAccentRes;
import static com.vanniktech.espresso.core.utils.AttributeMatcher.withColorButtonNormal;
import static com.vanniktech.espresso.core.utils.AttributeMatcher.withColorButtonNormalRes;
import static com.vanniktech.espresso.core.utils.AttributeMatcherActivity.VIEW_ID; | package com.vanniktech.espresso.core.utils;
@RunWith(AndroidJUnit4.class) public final class AttributeMatcherTest {
@Rule public final ExpectedException expectedException = ExpectedException.none();
@Rule public final ActivityTestRule<AttributeMatcherActivity> activityTestRule = new ActivityTestRule<>(AttributeMatcherActivity.class);
@Test public void withAttrResMatches() { | onView(withId(VIEW_ID)).check(matches(withAttrRes(R.attr.colorError, R.color.blue))); | 6 |
Gikkman/Java-Twirk | src/main/java/com/gikk/twirk/types/usernotice/DefaultUsernoticeBuilder.java | [
"public interface TagMap extends Map<String, String>{\n //***********************************************************\n\t// \t\t\t\tPUBLIC\n\t//***********************************************************\n\t/**Fetches a certain field value that might have been present in the tag.\n\t * If the field was not prese... | import com.gikk.twirk.types.TagMap;
import com.gikk.twirk.types.TwitchTags;
import com.gikk.twirk.types.emote.Emote;
import com.gikk.twirk.types.twitchMessage.TwitchMessage;
import com.gikk.twirk.types.usernotice.subtype.Raid;
import com.gikk.twirk.types.usernotice.subtype.Ritual;
import com.gikk.twirk.types.usernotice.subtype.Subscription;
import java.util.List; | package com.gikk.twirk.types.usernotice;
class DefaultUsernoticeBuilder implements UsernoticeBuilder{
String rawLine;
List<Emote> emotes;
String messageID;
int roomID;
long sentTimestamp;
String systemMessage;
Subscription subscription;
Raid raid;
Ritual ritual;
String message;
@Override
public Usernotice build(TwitchMessage message) {
this.rawLine = message.getRaw();
this.emotes = message.getEmotes();
| TagMap map = message.getTagMap(); | 0 |
cchao1024/TouchNews | app/src/main/java/com/github/cchao/touchnews/ui/fragment/JokeImageListFragments.java | [
"public interface JokeImageListContract {\n interface View {\n /**\n * 获取数据\n *\n * @param newsList newsList\n */\n void onRefreshData(List<Contentlist> newsList);\n\n /**\n * 添加数据\n *\n * @param newsList add newsList\n */\n ... | import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import com.apkfuns.logutils.LogUtils;
import com.github.cchao.touchnews.R;
import com.github.cchao.touchnews.contract.JokeImageListContract;
import com.github.cchao.touchnews.javaBean.joke.JokeImageRoot;
import com.github.cchao.touchnews.presenter.JokeImageListPresenter;
import com.github.cchao.touchnews.ui.adapter.JokeImageListRecyclerAdapter;
import com.github.cchao.touchnews.ui.fragment.base.BaseFragment;
import com.github.cchao.touchnews.util.Constant;
import com.github.cchao.touchnews.util.NetUtil;
import com.github.cchao.touchnews.util.SnackBarUtil;
import com.github.cchao.touchnews.widget.VaryViewWidget;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind; | package com.github.cchao.touchnews.ui.fragment;
/**
* Created by cchao on 2016/3/30.
* E-mail: cchao1024@163.com
* Description: 开心一刻- 图片类Fragment
*/
public class JokeImageListFragments extends BaseFragment implements JokeImageListContract.View, SwipeRefreshLayout.OnRefreshListener {
@Bind(R.id.swipe_refresh_joke_image_list)
SwipeRefreshLayout mSwipeRefreshLayout;
@Bind(R.id.recycle_view_joke_image)
RecyclerView mRecyclerView;
View mRootView;
List<JokeImageRoot.Contentlist> mContentList;
JokeImageListRecyclerAdapter mRecyclerAdapter;
JokeImageListContract.Presenter mPresenter;
VaryViewWidget mVaryViewWidget;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onFirstUserVisible() {
super.onFirstUserVisible();
initViews();
mPresenter = new JokeImageListPresenter(this);
mPresenter.getRefreshData();
}
private void initViews() {
mContentList = new ArrayList<>();
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
mRecyclerAdapter = new JokeImageListRecyclerAdapter(mContext, mContentList);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
private int lastVisibleItem;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE
&& lastVisibleItem + 1 == mRecyclerAdapter.getItemCount()) {
//加载更多
LogUtils.d(getClass().getSimpleName(), "info_loading more data");
mPresenter.getMoreData();
}
}
});
mRecyclerView.setAdapter(mRecyclerAdapter);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark);
mSwipeRefreshLayout.setOnRefreshListener(this);
}
@Override
protected int getLayoutId() {
return R.layout.fragment_joke_image;
}
@Override
public void onRefresh() {
mPresenter.getRefreshData();
}
/**
* 刷新数据
*
* @param newsList newsList
*/
@Override
public void onRefreshData(List<JokeImageRoot.Contentlist> newsList) {
mContentList.clear();
mContentList.addAll(newsList);
mRecyclerAdapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
if (mContentList.size() < 7) {
mPresenter.getMoreData();
}
}
/**
* 上拉添加数据
*
* @param newsList add newsList
*/
@Override
public void onReceiveMoreListData(List<JokeImageRoot.Contentlist> newsList) {
mContentList.addAll(newsList);
mRecyclerAdapter.notifyDataSetChanged();
if (mContentList.size() < 7) {
mPresenter.getMoreData();
}
}
/**
* @param INFOType 枚举值 e.g. 没有网络、正在加载、异常
* @param infoText infoText 提示的文本内容
*/
@Override
public void showInfo(Constant.INFO_TYPE INFOType, String infoText) {
if (mVaryViewWidget == null) {
mVaryViewWidget = new VaryViewWidget(mSwipeRefreshLayout);
}
View infoView = null;
switch (INFOType) {
case LOADING:
infoView = LayoutInflater.from(mContext).inflate(R.layout.info_loading, null);
break;
case NO_NET:
//已有数据(那就是刷新或者加载更多)-> 那么在底部snack检测网络设置
if (mContentList.size() > 1) { | SnackBarUtil.showLong(mRootView, R.string.none_net_show_action).setAction(R.string.set, new View.OnClickListener() { | 7 |
otale/tale | src/main/java/com/tale/service/CommentsService.java | [
"public class TaleConst {\n\n public static final String CLASSPATH = new File(AdminApiController.class.getResource(\"/\").getPath()).getPath() + File.separatorChar;\n\n public static final String REMEMBER_IN_COOKIE = \"remember_me\";\n public static final String LOGIN_ERROR_COUNT = \"login_error... | import com.blade.exception.ValidatorException;
import com.blade.ioc.annotation.Bean;
import com.blade.kit.BladeKit;
import com.blade.kit.DateKit;
import com.tale.bootstrap.TaleConst;
import com.tale.extension.Commons;
import com.tale.model.dto.Comment;
import com.tale.model.entity.Comments;
import com.tale.model.entity.Contents;
import com.tale.model.params.CommentParam;
import com.tale.utils.TaleUtils;
import com.vdurmont.emoji.EmojiParser;
import io.github.biezhi.anima.Anima;
import io.github.biezhi.anima.enums.OrderBy;
import io.github.biezhi.anima.page.Page;
import java.util.ArrayList;
import java.util.List;
import static com.tale.bootstrap.TaleConst.*;
import static io.github.biezhi.anima.Anima.select;
import static io.github.biezhi.anima.Anima.update; | package com.tale.service;
/**
* 评论Service
*
* @author biezhi
* @since 1.3.1
*/
@Bean
public class CommentsService {
/**
* 保存评论
*
* @param comments
*/
public void saveComment(Comments comments) {
comments.setAuthor(TaleUtils.cleanXSS(comments.getAuthor()));
comments.setContent(TaleUtils.cleanXSS(comments.getContent()));
comments.setAuthor(EmojiParser.parseToAliases(comments.getAuthor()));
comments.setContent(EmojiParser.parseToAliases(comments.getContent()));
Contents contents = select().from(Contents.class).byId(comments.getCid());
if (null == contents) {
throw new ValidatorException("不存在的文章");
}
try {
comments.setOwnerId(contents.getAuthorId());
comments.setAuthorId(null == comments.getAuthorId() ? 0 : comments.getAuthorId());
comments.setCreated(DateKit.nowUnix());
comments.setParent(null == comments.getCoid() ? 0 : comments.getCoid());
comments.setCoid(null);
comments.save();
new Contents().set(Contents::getCommentsNum, contents.getCommentsNum() + 1).updateById(contents.getCid());
} catch (Exception e) {
throw e;
}
}
/**
* 删除评论,暂时没用
*
* @param coid
* @param cid
* @throws Exception
*/
public void delete(Integer coid, Integer cid) {
Anima.delete().from(Comments.class).deleteById(coid);
Contents contents = select().from(Contents.class).byId(cid);
if (null != contents && contents.getCommentsNum() > 0) {
update().from(Contents.class).set(Contents::getCommentsNum, contents.getCommentsNum() - 1).updateById(cid);
}
}
/**
* 获取文章下的评论
*
* @param cid
* @param page
* @param limit
* @return
*/ | public Page<Comment> getComments(Integer cid, int page, int limit) { | 2 |
kevinmmarlow/Dreamer | volley/src/main/java/com/android/fancyblurdemo/volley/toolbox/StringRequest.java | [
"public class NetworkResponse {\n /**\n * Creates a new network response.\n * @param statusCode the HTTP status code\n * @param data Response body\n * @param headers Headers returned with this response, or null for none\n * @param notModified True if the server returned a 304 and the data was... | import com.android.fancyblurdemo.volley.NetworkResponse;
import com.android.fancyblurdemo.volley.Request;
import com.android.fancyblurdemo.volley.Response;
import com.android.fancyblurdemo.volley.Response.ErrorListener;
import com.android.fancyblurdemo.volley.Response.Listener;
import java.io.UnsupportedEncodingException; | /*
* Copyright (C) 2011 The Android Open Source Project
*
* 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.android.fancyblurdemo.volley.toolbox;
/**
* A canned request for retrieving the response body at a given URL as a String.
*/
public class StringRequest extends Request<String> {
private final Listener<String> mListener;
/**
* Creates a new request with the given method.
*
* @param method the request {@link Method} to use
* @param url URL to fetch the string at
* @param listener Listener to receive the String response
* @param errorListener Error listener, or null to ignore errors
*/
public StringRequest(int method, String url, Listener<String> listener,
ErrorListener errorListener) {
super(method, url, errorListener);
mListener = listener;
}
/**
* Creates a new GET request.
*
* @param url URL to fetch the string at
* @param listener Listener to receive the String response
* @param errorListener Error listener, or null to ignore errors
*/
public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) {
this(Method.GET, url, listener, errorListener);
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
@Override | protected Response<String> parseNetworkResponse(NetworkResponse response) { | 0 |
larusba/neo4j-jdbc | neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/BoltNeo4jStatementTest.java | [
"public abstract class Neo4jStatement implements Statement, Loggable {\n\n\tprotected Neo4jConnection connection;\n\tprotected ResultSet currentResultSet;\n\tprotected int currentUpdateCount;\n\tprotected List<String> batchStatements;\n\tprotected boolean debug;\n\tprotected int ... | import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.internal.util.reflection.Whitebox;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.summary.ResultSummary;
import org.neo4j.driver.v1.summary.SummaryCounters;
import org.neo4j.jdbc.Neo4jStatement;
import org.neo4j.jdbc.bolt.data.StatementData;
import org.neo4j.jdbc.bolt.impl.BoltNeo4jConnectionImpl;
import org.neo4j.jdbc.bolt.utils.Mocker;
import org.neo4j.jdbc.utils.Neo4jInvocationHandler;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.lang.reflect.Proxy;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import static org.neo4j.jdbc.bolt.utils.Mocker.*;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic; | /*
* Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it]
* <p>
* This file is part of the "LARUS Integration Framework for Neo4j".
* <p>
* The "LARUS Integration Framework for Neo4j" is licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* <p>
* Created on 19/02/16
*/
package org.neo4j.jdbc.bolt;
/**
* @author AgileLARUS
* @since 3.0.0
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ BoltNeo4jStatement.class, BoltNeo4jResultSet.class, Session.class })
public class BoltNeo4jStatementTest {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
private BoltNeo4jResultSet mockedRS;
@Before public void interceptBoltResultSetConstructor() throws Exception {
mockedRS = mock(BoltNeo4jResultSet.class);
doNothing().when(mockedRS).close();
mockStatic(BoltNeo4jResultSet.class);
PowerMockito.when(BoltNeo4jResultSet.newInstance(anyBoolean(), any(Neo4jStatement.class), any(StatementResult.class))).thenReturn(mockedRS);
}
/*------------------------------*/
/* close */
/*------------------------------*/
@Test public void closeShouldCloseExistingResultSet() throws Exception {
Statement statement = BoltNeo4jStatement.newInstance(false, mockConnectionOpenWithTransactionThatReturns(null));
statement.executeQuery(StatementData.STATEMENT_MATCH_ALL);
statement.close();
verify(mockedRS, times(1)).close();
}
@Test public void closeShouldNotCallCloseOnAnyResultSet() throws Exception {
Statement statement = BoltNeo4jStatement.newInstance(false, mockConnectionOpenWithTransactionThatReturns(null));
statement.close();
verify(mockedRS, never()).close();
}
@Test public void closeMultipleTimesIsNOOP() throws Exception {
Statement statement = BoltNeo4jStatement.newInstance(false, mockConnectionOpenWithTransactionThatReturns(null));
statement.executeQuery(StatementData.STATEMENT_MATCH_ALL);
statement.close();
statement.close();
statement.close();
verify(mockedRS, times(1)).close();
}
@Test public void closeShouldNotTouchTheTransaction() throws Exception {
Transaction mockTransaction = mock(Transaction.class);
| BoltNeo4jConnectionImpl mockConnection = mockConnectionOpen(); | 2 |
Xilef11/runesofwizardry-classics | src/main/java/xilef11/mc/runesofwizardry_classics/runes/entity/RuneEntityProtection.java | [
"public final class Refs {\n\tprivate Refs(){}\n\tpublic static final String MODID = \"runesofwizardry_classics\";\n\tpublic static final String VERSION = \"@VERSION@\";\n\tpublic static final String NAME=\"Runes of Wizardry - Classic Dusts Pack\";\n\tpublic static final String GUI_FACTORY=\"xilef11.mc.runesofwizar... | import java.util.List;
import java.util.Set;
import com.zpig333.runesofwizardry.tileentity.TileEntityDustActive;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.monster.IMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import xilef11.mc.runesofwizardry_classics.Refs;
import xilef11.mc.runesofwizardry_classics.items.EnumDustTypes;
import xilef11.mc.runesofwizardry_classics.runes.RuneProtection;
import xilef11.mc.runesofwizardry_classics.utils.Utils;
import xilef11.mc.runesofwizardry_classics.utils.Utils.Coords; | package xilef11.mc.runesofwizardry_classics.runes.entity;
public class RuneEntityProtection extends FueledRuneEntity {
public RuneEntityProtection(ItemStack[][] actualPattern, EnumFacing facing, | Set<BlockPos> dusts, TileEntityDustActive entity, RuneProtection creator) { | 2 |
Keridos/FloodLights | src/main/java/de/keridos/floodlights/tileentity/TileEntityMetaFloodlight.java | [
"public class NetworkDataList extends NonNullList<Object> {\n\n public NetworkDataList() {\n super();\n }\n}",
"public class ConfigHandler {\n private static ConfigHandler instance = null;\n\n public static boolean electricFloodlight;\n public static boolean smallElectricFloodlight;\n pub... | import de.keridos.floodlights.core.NetworkDataList;
import de.keridos.floodlights.handler.ConfigHandler;
import de.keridos.floodlights.init.ModBlocks;
import de.keridos.floodlights.reference.Names;
import de.keridos.floodlights.util.MathUtil;
import io.netty.buffer.ByteBuf;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemAir;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IThreadListener;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import static de.keridos.floodlights.block.BlockPhantomLight.UPDATE;
import static de.keridos.floodlights.util.GeneralUtil.getPosFromPosFacing;
import static de.keridos.floodlights.util.GeneralUtil.safeLocalize; | package de.keridos.floodlights.tileentity;
/**
* Created by Keridos on 06.05.2015.
* This Class
*/
@SuppressWarnings({"WeakerAccess", "NullableProblems"})
public abstract class TileEntityMetaFloodlight extends TileEntityFL implements ITickable {
protected boolean active;
protected boolean wasActive;
protected boolean hasRedstone;
protected int timeout;
protected ItemStackHandler inventory;
protected Block lightBlock = ModBlocks.blockPhantomLight;
protected int rangeStraight = ConfigHandler.rangeStraightFloodlight;
protected int rangeCone = ConfigHandler.rangeConeFloodlight;
protected int currentRange = rangeStraight;
protected int lightBlockStep = 2;
protected int floodlightId = new Random().nextInt();
private AtomicBoolean executorActive = new AtomicBoolean(false);
private boolean hasLight;
public TileEntityMetaFloodlight() {
super();
inventory = createInventory();
}
public void setHasRedstoneSignal(boolean hasSignal) {
// Light blocks are managed in the update() method
hasRedstone = hasSignal;
active = hasRedstone ^ inverted;
syncData();
}
public void toggleInverted() {
inverted = !inverted;
active = hasRedstone ^ inverted;
syncData();
}
/**
* Notifies this machine that a container block has been removed and the tile entity is about to be destroyed.
*/
public void notifyBlockRemoved() {
if (world.isRemote)
return;
lightSource(true);
}
/**
* Creates new phantom light (depending on the {@link #lightBlock} field) at given position.
*/
@SuppressWarnings("ConstantConditions")
protected void createPhantomLight(BlockPos pos) {
if (world.setBlockState(pos, lightBlock.getDefaultState(), 19)) {
TileEntityPhantomLight light = (TileEntityPhantomLight) world.getTileEntity(pos);
light.addSource(this.pos, floodlightId);
}
}
@Override
public void update() {
if (world.isRemote)
return;
if (timeout > 0) {
timeout--;
return;
}
// Energy itself is handled in one of the derived classes
if (active && hasEnergy() && (wasActive != active || !hasLight)) {
// Spawn phantom lights
lightSource(false);
wasActive = active;
} else if ((active && !hasEnergy()) || (!active && wasActive)) {
// A floodlight just run out of energy or was shut down - deactivate it
lightSource(true);
timeout = ConfigHandler.timeoutFloodlights + 10;
wasActive = false;
}
}
/**
* Returns whether this machine is ready - no active timeouts etc.
*/
protected boolean isCooledDown() {
return timeout == 0 && !executorActive.get();
}
/**
* Whether this machine has electric, heat or any other energy type required to operate.
*/
protected boolean hasEnergy() {
return false;
}
/**
* Whether this machine can perform any task at the moment. Used in the {@link #update()} method.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
protected boolean isReady() {
return timeout == 0;
}
protected ItemStackHandler createInventory() {
return new ItemStackHandler(getInventorySize()) {
@Override
protected void onContentsChanged(int slot) {
if (slot == 1 && supportsCloak()) {
Item item = getStackInSlot(slot).getItem();
if (item instanceof ItemAir) {
setCloak(null);
} else if (item instanceof ItemBlock && (getCloak() == null || !Block.isEqualTo(((ItemBlock) item).getBlock(), getCloak().getBlock()))) {
setCloak(((ItemBlock) item).getBlock().getDefaultState());
}
}
super.onContentsChanged(slot);
markDirty();
}
};
}
protected int getInventorySize() {
return 1;
}
@Override
public void readOwnFromNBT(NBTTagCompound nbtTagCompound) {
super.readOwnFromNBT(nbtTagCompound); | if (nbtTagCompound.hasKey(Names.NBT.WAS_ACTIVE)) | 3 |
cuberact/cuberact-json | src/main/java/org/cuberact/json/parser/JsonScanner.java | [
"public class JsonException extends RuntimeException {\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n public JsonException(String message) {\r\n super(message);\r\n }\r\n\r\n public JsonException(Throwable t) {\r\n super(t);\r\n }\r\n\r\n public JsonException(String... | import org.cuberact.json.JsonException;
import org.cuberact.json.JsonNumber;
import org.cuberact.json.input.JsonInput;
import static org.cuberact.json.input.JsonInput.END_OF_INPUT;
import static org.cuberact.json.optimize.CharTable.hexBitShift;
import static org.cuberact.json.optimize.CharTable.toInt;
| /*
* Copyright 2017 Michal Nikodim
*
* 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.cuberact.json.parser;
/**
* @author Michal Nikodim (michal.nikodim@gmail.com)
*/
final class JsonScanner {
private final JsonInput input;
private final char[] buffer = new char[4096];
char lastReadChar;
JsonScanner(JsonInput input) {
this.input = input;
}
private char nextChar() {
return lastReadChar = input.nextChar();
}
char nextImportantChar() {
for (; ; ) {
nextChar();
if (!(lastReadChar == ' ' || lastReadChar == '\n' || lastReadChar == '\r' || lastReadChar == '\t')) {
return lastReadChar;
}
}
}
String consumeString() {
StringBuilder token = null;
int count = 0;
for (; ; ) {
nextChar();
if (lastReadChar == '"') {
nextImportantChar();
if (token == null) return new String(buffer, 0, count);
token.append(buffer, 0, count);
return token.toString();
} else if (lastReadChar == '\\') {
nextChar();
switch (lastReadChar) {
case 'b':
lastReadChar = '\b';
break;
case 'f':
lastReadChar = '\f';
break;
case 'n':
lastReadChar = '\n';
break;
case 'r':
lastReadChar = '\r';
break;
case 't':
lastReadChar = '\t';
break;
case 'u':
lastReadChar = consumeUnicodeChar();
break;
}
} else if (lastReadChar == END_OF_INPUT) {
break;
}
buffer[count++] = lastReadChar;
if (count == 4096) {
count = 0;
if (token == null) {
token = new StringBuilder(8000);
}
token.append(buffer);
}
}
throw jsonException("Expected \"");
}
void consumeTrue() {
if (nextChar() == 'r' && nextChar() == 'u' && nextChar() == 'e') {
nextImportantChar();
return;
}
throw jsonException("Expected true");
}
void consumeFalse() {
if (nextChar() == 'a' && nextChar() == 'l' && nextChar() == 's' && nextChar() == 'e') {
nextImportantChar();
return;
}
throw jsonException("Expected false");
}
void consumeNull() {
if (nextChar() == 'u' && nextChar() == 'l' && nextChar() == 'l') {
nextImportantChar();
return;
}
throw jsonException("Expected null");
}
| JsonNumber consumeNumber() {
| 1 |
MiniDigger/projecttd | core/src/me/minidigger/projecttd/screens/GameScreen.java | [
"public class GameGestureProcessor extends GestureDetector.GestureAdapter {\n\n private GameScreen gameScreen;\n\n public GameGestureProcessor(GameScreen gameScreen) {\n this.gameScreen = gameScreen;\n }\n\n @Override\n public boolean pan(float x, float y, float deltaX, float deltaY) {\n ... | import com.badlogic.ashley.core.PooledEngine;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.kotcrab.vis.ui.VisUI;
import me.minidigger.projecttd.GameGestureProcessor;
import me.minidigger.projecttd.GameInputProcessor;
import me.minidigger.projecttd.entities.Minion;
import me.minidigger.projecttd.entities.Tower;
import me.minidigger.projecttd.level.Level;
import me.minidigger.projecttd.scenes.HudScene;
import me.minidigger.projecttd.systems.*;
import me.minidigger.projecttd.utils.ArcRenderer;
import me.minidigger.projecttd.utils.CoordinateUtil; | package me.minidigger.projecttd.screens;
/**
* Created by Martin on 01.04.2017.
*/
public class GameScreen implements Screen {
private TiledMap map;
private OrthogonalTiledMapRenderer tiledMapRenderer;
private OrthographicCamera camera;
private ShapeRenderer shapeRenderer = new ShapeRenderer();
private ArcRenderer arcRenderer = new ArcRenderer();
private BitmapFont font = new BitmapFont();
private SpriteBatch spriteBatch = new SpriteBatch();
private HudScene hud;
private int mapHeight;
private int mapWidth;
private int tilewidth;
private PooledEngine engine;
private Sprite minionSprite;
private Sprite towerSprite;
private Vector2 touchPoint = new Vector2();
private Vector2 spawnPoint = new Vector2();
private boolean debugRendering = false;
private PathFindingSystem pathFindingSystem;
private TurretSystem turretSystem;
public Level level;
public static GameScreen INSTANCE;
public GameScreen() {
INSTANCE = this;
}
@Override
public void show() {
// ui
hud = new HudScene(spriteBatch, shapeRenderer, arcRenderer);
//input
InputMultiplexer multiplexer = new InputMultiplexer();
multiplexer.addProcessor(hud.getStage()); | multiplexer.addProcessor(new GestureDetector(new GameGestureProcessor(this))); | 0 |
heroku/heroku.jar | heroku-api/src/main/java/com/heroku/api/request/team/TeamAppCreate.java | [
"public class App implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n String id;\n String name;\n Domain domain_name;\n String created_at;\n App.Owner owner;\n String web_url;\n App.Stack stack;\n String requested_stack;\n String git_url;\n String buil... | import com.heroku.api.App;
import com.heroku.api.Heroku;
import com.heroku.api.TeamApp;
import com.heroku.api.exception.RequestFailedException;
import com.heroku.api.http.Http;
import com.heroku.api.request.Request;
import com.heroku.api.request.RequestConfig;
import java.util.Collections;
import java.util.Map;
import static com.heroku.api.parser.Json.parse; | package com.heroku.api.request.team;
/**
* TODO: Javadoc
*
* @author Naaman Newbold
*/
public class TeamAppCreate implements Request<TeamApp> {
private final RequestConfig config;
public TeamAppCreate(TeamApp app) {
RequestConfig builder = new RequestConfig(); | builder = builder.with(Heroku.RequestKey.Team, app.getTeam().getName()); | 1 |
rprobinson/MediPi | MediPiPatient/MediPi/src/main/java/org/medipi/devices/drivers/Omron708BT.java | [
"public class MediPiMessageBox {\r\n\r\n private MediPi medipi;\r\n private HashMap<String, Alert> liveMessages = new HashMap<>();\r\n\r\n private MediPiMessageBox() {\r\n }\r\n\r\n /**\r\n * returns the one and only instance of the singleton\r\n *\r\n * @return singleton instance\r\n ... | import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Arrays;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.concurrent.Task;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import org.medipi.MediPiMessageBox;
import org.medipi.devices.BloodPressure;
import org.medipi.devices.drivers.domain.ContinuaBloodPressure;
import org.medipi.devices.drivers.domain.ContinuaData;
import org.medipi.devices.drivers.domain.ContinuaManager;
import org.medipi.devices.drivers.domain.ContinuaMeasurement;
| /*
Copyright 2016 Richard Robinson @ NHS Digital <rrobinson@nhs.net>
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.medipi.devices.drivers;
/**
* A concrete implementation of a specific device - Omron708BT Blood Pressure
* meter
*
* The class uses the Continua Manager class which uses Antidote IEEE 11073 Library to retrieve
* the data via the stdout of the script.
*
* This class defines the device which is to be connected, defines the data to
* be collected and passes this forward to the generic device class
*
*
* @author rick@robinsonhq.com
*/
@SuppressWarnings("restriction")
public class Omron708BT extends BloodPressure {
private static final String MAKE = "Omron";
private static final String MODEL = "708-BT";
private static final String DISPLAYNAME = "Omron 708-BT Blood Pressure Meter";
private static final String STARTBUTTONTEXT = "Start";
// The number of increments of the progress bar - a value of 0 removes the progBar
private static final Double PROGBARRESOLUTION = 60D;
private ImageView stopImg;
private Task<String> task = null;
private Process process = null;
String pythonScript;
private ImageView graphic;
/**
* Constructor for BeurerBM55
*/
public Omron708BT() {
}
// initialise and load the configuration data
@Override
public String init() throws Exception {
progressBarResolution = PROGBARRESOLUTION;
stopImg = medipi.utils.getImageView("medipi.images.no", 20, 20);
graphic = medipi.utils.getImageView("medipi.images.arrow", 20, 20);
graphic.setRotate(90);
initialGraphic = graphic;
initialButtonText = STARTBUTTONTEXT;
// define the data to be collected
columns.add("iso8601time");
columns.add("systol");
columns.add("diastol");
columns.add("pulserate");
columns.add("MAP");
columns.add("irregularHeartBeat");
format.add("DATE");
format.add("INTEGER");
format.add("INTEGER");
format.add("INTEGER");
format.add("INTEGER");
format.add("BOOLEAN");
units.add("NONE");
units.add("mmHg");
units.add("mmHg");
units.add("BPM");
units.add("NONE");
units.add("NONE");
return super.init();
}
/**
* Method to to download the data from the device. This data is digested by
* the generic device class
*/
@Override
public void downloadData(VBox v) {
if (task == null || !task.isRunning()) {
resetDevice();
processData();
} else {
Platform.runLater(() -> {
task.cancel();
});
}
}
protected void processData() {
task = new Task<String>() {
ArrayList<ArrayList<String>> data = new ArrayList<>();
ContinuaManager continuaManager = null;
@Override
protected String call() throws Exception {
try {
continuaManager = ContinuaManager.getInstance();
continuaManager.reset();
setButton2Name("Stop", stopImg);
// input datastream from the device driver
BufferedReader stdInput = continuaManager.callIEEE11073Agent("0x1007");
if (stdInput != null) {
String readData = new String();
while ((readData = stdInput.readLine()) != null) {
System.out.println(readData);
if (continuaManager.parse(readData)) {
ContinuaData cd = continuaManager.getData();
if (!cd.getManufacturer().equals("OMRON HEALTHCARE")) {
return "Expected device manufacturer is OMRON HEALTHCARE but returned device manufacturer is: "+cd.getManufacturer();
}
if (!cd.getModel().equals("HEM-7081-IT")) {
return "Expected device model is HEM-7081-IT but returned device model is: "+cd.getModel();
}
int setId = 0;
while (cd.getDataSetCounter() >= setId) {
String sys = null;
String dia = null;
String mean = null;
String heartRate = null;
String irregular = null;
String time = null;
for (ContinuaMeasurement cm : cd.getMeasurements()) {
if (cm.getMeasurementSetID() == setId) {
| if (cm.getReportedIdentifier() == ContinuaBloodPressure.MMHG) {
| 2 |
pugwoo/nimble-orm | src/main/java/com/pugwoo/dbhelper/impl/part/P5_DeleteOp.java | [
"public class DBHelperInterceptor {\n\n\t/**\n\t * select前执行。不会拦截getCount计算总数和getAllKey只查询key这2个接口。\n\t * @param clazz 查询的对象\n\t * @param sql 查询的完整sql\n\t * @param args 查询的完整参数。理论上,拦截器就有可能修改args里面的object的值的,请小心。不建议修改args的值。\n\t * @return 返回true,则查询继续; 返回false将终止查询并抛出NotAllowQueryException\n\t */\n\tpublic boolean b... | import com.pugwoo.dbhelper.DBHelperInterceptor;
import com.pugwoo.dbhelper.annotation.Column;
import com.pugwoo.dbhelper.exception.InvalidParameterException;
import com.pugwoo.dbhelper.exception.MustProvideConstructorException;
import com.pugwoo.dbhelper.exception.NotAllowQueryException;
import com.pugwoo.dbhelper.exception.NullKeyValueException;
import com.pugwoo.dbhelper.sql.SQLAssert;
import com.pugwoo.dbhelper.sql.SQLUtils;
import com.pugwoo.dbhelper.utils.DOInfoReader;
import com.pugwoo.dbhelper.utils.PreHandleObject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; | package com.pugwoo.dbhelper.impl.part;
public abstract class P5_DeleteOp extends P4_InsertOrUpdateOp {
/////// 拦截器
protected void doInterceptBeforeDelete(List<Object> tList) {
for (DBHelperInterceptor interceptor : interceptors) {
boolean isContinue = interceptor.beforeDelete(tList);
if (!isContinue) { | throw new NotAllowQueryException("interceptor class:" + interceptor.getClass()); | 3 |
mgilangjanuar/GoSCELE | app/src/main/java/com/mgilangjanuar/dev/goscele/modules/forum/list/provider/ForumSearchProvider.java | [
"public abstract class BaseProvider extends AsyncTask<String, Integer, List<Elements>> {\n\n protected Map<String, String> cookies = new HashMap<>();\n\n public BaseProvider() {\n super();\n }\n\n @Override\n @Deprecated\n protected List<Elements> doInBackground(String... params) {\n ... | import com.mgilangjanuar.dev.goscele.base.BaseProvider;
import com.mgilangjanuar.dev.goscele.modules.common.model.CookieModel;
import com.mgilangjanuar.dev.goscele.modules.forum.list.adapter.ForumListRecyclerViewAdapter;
import com.mgilangjanuar.dev.goscele.modules.forum.list.listener.ForumListListener;
import com.mgilangjanuar.dev.goscele.modules.forum.list.model.ForumModel;
import com.mgilangjanuar.dev.goscele.utils.Constant;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | package com.mgilangjanuar.dev.goscele.modules.forum.list.provider;
/**
* Created by mgilangjanuar (mgilangjanuar@gmail.com)
*
* @since 2017
*/
public class ForumSearchProvider extends BaseProvider {
private ForumListListener listener;
private String query;
public ForumSearchProvider(ForumListListener listener, String query) {
this.listener = listener;
this.query = query;
}
@Override
public Map<String, String> cookies() {
return CookieModel.getCookiesMap();
}
@Override
public void run() {
execute("#region-main");
}
@Override
public String url() {
try { | return Constant.BASE_URL + "mod/forum/search.php?id=1&perpage=50&search=" + URLEncoder.encode(query, "UTF-8"); | 5 |
lijunyandev/MeetMusic | app/src/main/java/com/lijunyan/blackmusic/adapter/PlaylistAdapter.java | [
"public class DBManager {\n\n private static final String TAG = DBManager.class.getName();\n private DatabaseHelper helper;\n private SQLiteDatabase db;\n private static DBManager instance = null;\n\n\n /* 因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0,mFactory);\n * 需要一个context... | import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.lijunyan.blackmusic.R;
import com.lijunyan.blackmusic.database.DBManager;
import com.lijunyan.blackmusic.entity.MusicInfo;
import com.lijunyan.blackmusic.entity.PlayListInfo;
import com.lijunyan.blackmusic.service.MusicPlayerService;
import com.lijunyan.blackmusic.util.Constant;
import com.lijunyan.blackmusic.util.MyMusicUtil;
import java.util.List; | package com.lijunyan.blackmusic.adapter;
/**
* Created by lijunyan on 2017/3/28.
*/
public class PlaylistAdapter extends RecyclerView.Adapter<PlaylistAdapter.ViewHolder> {
private static final String TAG = PlaylistAdapter.class.getName();
private List<MusicInfo> musicInfoList;
private Context context;
private DBManager dbManager;
private PlayListInfo playListInfo;
private PlaylistAdapter.OnItemClickListener onItemClickListener ;
static class ViewHolder extends RecyclerView.ViewHolder{
View swipeContent;
LinearLayout contentLl;
TextView musicIndex;
TextView musicName;
TextView musicSinger;
ImageView menuIv;
Button deleteBtn;
public ViewHolder(View itemView) {
super(itemView);
this.swipeContent = (View) itemView.findViewById(R.id.swipemenu_layout);
this.contentLl = (LinearLayout) itemView.findViewById(R.id.local_music_item_ll);
this.musicName = (TextView) itemView.findViewById(R.id.local_music_name);
this.musicIndex = (TextView) itemView.findViewById(R.id.local_index);
this.musicSinger = (TextView) itemView.findViewById(R.id.local_music_singer);
this.menuIv = (ImageView) itemView.findViewById(R.id.local_music_item_never_menu);
this.deleteBtn = (Button) itemView.findViewById(R.id.swip_delete_menu_btn);
}
}
public PlaylistAdapter(Context context, PlayListInfo playListInfo,List<MusicInfo> musicInfoList) {
this.context = context;
this.playListInfo = playListInfo;
this.dbManager = DBManager.getInstance(context);
this.musicInfoList = musicInfoList;
}
@Override
public int getItemCount() {
return musicInfoList.size();
}
@Override
public PlaylistAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.local_music_item,parent,false);
PlaylistAdapter.ViewHolder viewHolder = new PlaylistAdapter.ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(final PlaylistAdapter.ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: position = "+position);
final MusicInfo musicInfo = musicInfoList.get(position);
holder.musicName.setText(musicInfo.getName());
holder.musicIndex.setText("" + (position + 1));
holder.musicSinger.setText(musicInfo.getSinger()); | if (musicInfo.getId() == MyMusicUtil.getIntShared(Constant.KEY_ID)){ | 4 |
snowhow/cordova-plugin-gpstrack | src/android/org/java_websocket/WebSocketListener.java | [
"public abstract class Draft {\n\n\t/**\n\t * Enum which represents the states a handshake may be in\n\t */\n\tpublic enum HandshakeState {\n\t\t/** Handshake matched this Draft successfully */\n\t\tMATCHED,\n\t\t/** Handshake is does not match this Draft */\n\t\tNOT_MATCHED\n\t}\n\t/**\n\t * Enum which represents ... | import org.java_websocket.framing.CloseFrame;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.Handshakedata;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.handshake.ServerHandshakeBuilder;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import org.java_websocket.drafts.Draft;
import org.java_websocket.exceptions.InvalidDataException; | /*
* Copyright (c) 2010-2017 Nathan Rajlich
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.java_websocket;
/**
* Implemented by <tt>WebSocketClient</tt> and <tt>WebSocketServer</tt>.
* The methods within are called by <tt>WebSocket</tt>.
* Almost every method takes a first parameter conn which represents the source of the respective event.
*/
public interface WebSocketListener {
/**
* Called on the server side when the socket connection is first established, and the WebSocket
* handshake has been received. This method allows to deny connections based on the received handshake.<br>
* By default this method only requires protocol compliance.
*
* @param conn
* The WebSocket related to this event
* @param draft
* The protocol draft the client uses to connect
* @param request
* The opening http message send by the client. Can be used to access additional fields like cookies.
* @return Returns an incomplete handshake containing all optional fields
* @throws InvalidDataException
* Throwing this exception will cause this handshake to be rejected
*/
ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request ) throws InvalidDataException;
/**
* Called on the client side when the socket connection is first established, and the WebSocketImpl
* handshake response has been received.
*
* @param conn
* The WebSocket related to this event
* @param request
* The handshake initially send out to the server by this websocket.
* @param response
* The handshake the server sent in response to the request.
* @throws InvalidDataException
* Allows the client to reject the connection with the server in respect of its handshake response.
*/ | void onWebsocketHandshakeReceivedAsClient( WebSocket conn, ClientHandshake request, ServerHandshake response ) throws InvalidDataException; | 3 |
gambitproject/gte | lib-algo/src/lse/math/games/matrix/BimatrixSolver.java | [
"public class Rational \r\n{\r\n\tpublic static final Rational ZERO = new Rational(BigInteger.ZERO, BigInteger.ONE);\r\n\tpublic static final Rational ONE = new Rational(BigInteger.ONE, BigInteger.ONE);\r\n\tpublic static final Rational NEGONE = new Rational(BigInteger.ONE.negate(), BigInteger.ONE);\r\n\tpublic Big... | import java.io.PrintWriter;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;
import lse.math.games.Rational;
import lse.math.games.lrs.Lrs;
import lse.math.games.lrs.HPolygon;
import lse.math.games.lrs.VPolygon;
import lse.math.games.lcp.LCP;
import lse.math.games.lcp.LemkeAlgorithm;
import lse.math.games.lcp.LemkeAlgorithm.LemkeException;
| package lse.math.games.matrix;
public class BimatrixSolver
{
private static final Logger log = Logger.getLogger(BimatrixSolver.class.getName());
public Rational[] computePriorBeliefs(int size, Random prng)
{
Rational[] priors = null;
if (prng != null) {
priors = Rational.probVector(size, prng);
} else {
priors = new Rational[size];
Rational prob = Rational.ONE.divide(Rational.valueOf(size));
for (int i = 0; i < size; ++i) {
priors[i] = prob;
}
}
return priors;
}
public Equilibrium findOneEquilibrium(LemkeAlgorithm lemke, Rational[][] a, Rational[][] b, Rational[] xPriors, Rational[] yPriors, PrintWriter out)
throws LemkeException
{
// 1. Adjust the payoffs to be strictly negative (max = -1)
Rational payCorrectA = BimatrixSolver.correctPaymentsNeg(a);
Rational payCorrectB = BimatrixSolver.correctPaymentsNeg(b);
// 2. Generate the LCP from the two payoff matrices and the priors
| LCP lcp = BimatrixSolver.generateLCP(a, b, xPriors, yPriors);
| 4 |
jramoyo/quickfix-messenger | src/main/java/com/jramoyo/qfixmessenger/ui/ProjectDialog.java | [
"public class ProjectTreeCellEditor extends DefaultTreeCellEditor\r\n{\r\n\tpublic ProjectTreeCellEditor(JTree tree)\r\n\t{\r\n\t\tsuper(tree, null);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isCellEditable(EventObject event)\r\n\t{\r\n\t\tif (super.isCellEditable(event))\r\n\t\t{\r\n\t\t\tObject value = tree.g... | import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.TreeSelectionModel;
import com.jramoyo.fix.xml.MessageType;
import com.jramoyo.fix.xml.ProjectType;
import com.jramoyo.qfixmessenger.ui.editors.ProjectTreeCellEditor;
import com.jramoyo.qfixmessenger.ui.listeners.ProjectTreeMouseListener;
import com.jramoyo.qfixmessenger.ui.models.ProjectTreeModel;
import com.jramoyo.qfixmessenger.ui.renderers.ProjectTreeCellRenderer;
import com.jramoyo.qfixmessenger.ui.util.IconBuilder;
| /*
* Copyright (c) 2011, Jan Amoyo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* ProjectDialog.java
* Sep 23, 2012
*/
package com.jramoyo.qfixmessenger.ui;
/**
* ProjectDialog
*
* @author jramoyo
*/
public class ProjectDialog extends JDialog
{
private static final long serialVersionUID = -1653220967743151936L;
private final QFixMessengerFrame frame;
private final ProjectType xmlProjectType;
private JPanel mainPanel;
private JTree projectTree;
public ProjectDialog(QFixMessengerFrame frame, ProjectType xmlProjectType)
{
this.frame = frame;
this.xmlProjectType = xmlProjectType;
}
/**
* Launches the frame
*/
public void launch()
{
initDialog();
initComponents();
positionFrame();
setVisible(true);
}
/**
* Reloads the project tree
*/
public void reload()
{
| ((ProjectTreeModel) projectTree.getModel()).update();
| 2 |
OasisDigital/nges | src/test/java/com/oasisdigital/nges/event/EventStoreITest.java | [
"public interface MessageGroup {\n\n /**\n * Publish a message to the group.\n */\n public abstract void publish(Object message);\n\n /**\n * Register a subscriber for messages from the group. See documentation for a particular implementation to\n * learn more about its specifics.\n */\... | import static com.jayway.awaitility.Awaitility.await;
import static com.oasisdigital.nges.event.EventStore.AUTO_GENERATE_SEQUENCE;
import static com.oasisdigital.nges.event.EventStore.NEW_STREAM;
import static java.util.Arrays.asList;
import static java.util.UUID.randomUUID;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.oasisdigital.nges.cluster.MessageGroup;
import com.oasisdigital.nges.event.EventStoreConflict;
import com.oasisdigital.nges.event.EventStream;
import com.oasisdigital.nges.event.Lease;
import com.oasisdigital.nges.event.Event;
import com.oasisdigital.nges.event.EventStore;
import com.oasisdigital.nges.event.EventStoreException;
import com.oasisdigital.nges.event.config.EventStoreContext;
import com.oasisdigital.nges.event.jdbc.BaseITest; | IntStream.range(0, 10).parallel().forEach(i -> {
try {
save(textAppended(String.valueOf(i)), AUTO_GENERATE_SEQUENCE);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
// Then expect it to write them all successfully
List<Event> events = eventStore.getEventsForStream(streamId, 0, 100);
assertThat(events.size(), is(10));
}
@Test
public void shouldSerializeConcurrentBatchAppendingToDifferentStreams() throws Exception {
List<UUID> streamIds = Stream.generate(() -> UUID.randomUUID()).limit(10).collect(toList());
// Initialize some streams
streamIds.forEach(streamId -> save(textAppended(streamId, "-")));
long lastEventId = eventStore.getLastEventId().orElse(0L);
// Append to them in parallel - this is a separate call, so that we don't interfere with stream
// initialization (which may involve locking). The goal of the test is to verify that just appending
// to existing stream yields consistent blocks.
// @formatter:off
streamIds.stream()
.parallel()
.forEach(streamId -> save(asList(textAppended(streamId, "a"),
textAppended(streamId, "b"),
textAppended(streamId, "c")),
1));
// @formatter:on0
List<Event> events = eventStore.getEventsForAllStreams(lastEventId, 100);
assertThat(events.size(), is(30));
List<UUID> savedStreamIdsInOrder = events.stream().map(e -> e.getStreamId()).collect(toList());
assertThat(savedStreamIdsInOrder, consistsOfConsistentBlocks(10, 3));
}
//
// LEASE
//
@Test
public void shouldPreventLeaseToAnotherOwner() {
String leaseKey = randomKey("Lease");
String ownerKey1 = randomKey("Owner1");
String ownerKey2 = randomKey("Owner2");
assertThat(eventStore.lease(leaseKey, ownerKey1, 2000).getOwnerKey(), is(ownerKey1));
assertThat(eventStore.lease(leaseKey, ownerKey2, 2000).getOwnerKey(), is(ownerKey1));
}
@Test
public void shouldRenewLeaseToCurrentOwnerWithLease() {
String leaseKey = randomKey("Lease");
String ownerKey = randomKey("Owner");
Lease first = eventStore.lease(leaseKey, ownerKey, 2000);
Lease second = eventStore.lease(leaseKey, ownerKey, 2000);
assertThat(second.getOwnerKey(), is(ownerKey));
assertThat(second.getExpirationDate(), is(after(first.getExpirationDate())));
}
@Test
public void shouldLeaseToAnotherOwnerAfterOwnerReleases() {
String leaseKey = randomKey("Lease");
String ownerKey1 = randomKey("Owner1");
String ownerKey2 = randomKey("Owner2");
assertThat(eventStore.lease(leaseKey, ownerKey1, 2000).getOwnerKey(), is(ownerKey1));
eventStore.release(leaseKey, ownerKey1);
assertThat(eventStore.lease(leaseKey, ownerKey2, 2000).getOwnerKey(), is(ownerKey2));
}
@Test
public void shouldIgnoreReleaseFromNonOwner() {
String leaseKey = randomKey("Lease");
String ownerKey1 = randomKey("Owner1");
String ownerKey2 = randomKey("Owner2");
assertThat(eventStore.lease(leaseKey, ownerKey1, 2000).getOwnerKey(), is(ownerKey1));
eventStore.release(leaseKey, ownerKey2);
assertThat(eventStore.lease(leaseKey, ownerKey2, 2000).getOwnerKey(), is(ownerKey1));
}
@Test
public void shouldLeaseDifferentKeysToDifferentProcesses() {
String leaseKey1 = randomKey("Lease1");
String leaseKey2 = randomKey("Lease2");
String ownerKey1 = randomKey("Owner1");
String ownerKey2 = randomKey("Owner2");
assertThat(eventStore.lease(leaseKey1, ownerKey1, 2000).getOwnerKey(), is(ownerKey1));
assertThat(eventStore.lease(leaseKey2, ownerKey2, 2000).getOwnerKey(), is(ownerKey2));
}
@Test
public void shouldLeaseMultipleKeysToOneOwner() {
String leaseKey1 = randomKey("Lease1");
String leaseKey2 = randomKey("Lease2");
String ownerKey = randomKey("Owner");
assertThat(eventStore.lease(leaseKey1, ownerKey, 2000).getOwnerKey(), is(ownerKey));
assertThat(eventStore.lease(leaseKey2, ownerKey, 2000).getOwnerKey(), is(ownerKey));
}
@Test
public void shouldLeaseToAnotherOwnerAfterExpiration() throws Exception {
String leaseKey = randomKey("Lease");
String ownerKey1 = randomKey("Owner1");
String ownerKey2 = randomKey("Owner2");
eventStore.lease(leaseKey, ownerKey1, 150);
Thread.sleep(151);
assertThat(eventStore.lease(leaseKey, ownerKey2, 2000).getOwnerKey(), is(ownerKey2));
}
| @Test(expectedExceptions = EventStoreException.class) | 6 |
UweTrottmann/MovieTracker | SeriesGuideMovies/src/com/uwetrottmann/movies/util/TraktCredentialsDialogFragment.java | [
"public class ServiceManager {\n /** API key. */\n private String apiKeyValue;\n /** User email. */\n private String username;\n /** User password. */\n private String password_sha;\n /** Connection timeout (in milliseconds). */\n private Integer connectionTimeout;\n /** Read timeout (in ... | import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.jakewharton.apibuilder.ApiException;
import com.jakewharton.trakt.ServiceManager;
import com.jakewharton.trakt.TraktException;
import com.jakewharton.trakt.entities.Response;
import com.uwetrottmann.androidutils.AndroidUtils;
import com.uwetrottmann.movies.R;
import com.uwetrottmann.movies.entities.TraktStatus;
import com.uwetrottmann.movies.ui.AppPreferences; | /*
* Copyright 2012 Uwe Trottmann
*
* 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.uwetrottmann.movies.util;
/**
* Dialog to gather and verify as well as clear trakt.tv credentials.
*
* @author Uwe Trottmann
*/
public class TraktCredentialsDialogFragment extends SherlockDialogFragment {
public static TraktCredentialsDialogFragment newInstance() {
TraktCredentialsDialogFragment f = new TraktCredentialsDialogFragment();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().setTitle(R.string.pref_traktcredentials);
final Context context = getActivity().getApplicationContext();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final View layout = inflater.inflate(R.layout.trakt_credentials_dialog, null);
// restore the username from settings
final String username = Utils.getTraktUsername(context);
((EditText) layout.findViewById(R.id.username)).setText(username);
// new account toggle
final View mailviews = layout.findViewById(R.id.mailviews);
mailviews.setVisibility(View.GONE);
((CheckBox) layout.findViewById(R.id.checkNewAccount))
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mailviews.setVisibility(View.VISIBLE);
} else {
mailviews.setVisibility(View.GONE);
}
}
});
// status strip
final TextView status = (TextView) layout.findViewById(R.id.status);
final View progressbar = layout.findViewById(R.id.progressbar);
final View progress = layout.findViewById(R.id.progress);
progress.setVisibility(View.GONE);
final Button connectbtn = (Button) layout.findViewById(R.id.connectbutton);
final Button disconnectbtn = (Button) layout.findViewById(R.id.disconnectbutton);
// disable disconnect button if there are no saved credentials
if (username.length() == 0) {
disconnectbtn.setEnabled(false);
}
connectbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// prevent multiple instances
connectbtn.setEnabled(false);
disconnectbtn.setEnabled(false);
final String username = ((EditText) layout.findViewById(R.id.username)).getText()
.toString();
final String passwordHash = Utils.toSHA1(((EditText) layout
.findViewById(R.id.password)).getText().toString().getBytes());
final String email = ((EditText) layout.findViewById(R.id.email)).getText()
.toString();
final boolean isNewAccount = ((CheckBox) layout.findViewById(R.id.checkNewAccount))
.isChecked();
final String traktApiKey = getResources().getString(R.string.trakt_apikey);
AsyncTask<String, Void, Response> accountValidatorTask = new AsyncTask<String, Void, Response>() {
@Override
protected void onPreExecute() {
progress.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.VISIBLE);
status.setText(R.string.waitplease);
}
@Override
protected Response doInBackground(String... params) {
// check if we have any usable data
if (username.length() == 0 || passwordHash == null) {
return null;
}
// check for connectivity
if (!AndroidUtils.isNetworkConnected(context)) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = context.getString(R.string.offline);
return r;
}
// use a separate ServiceManager here to avoid
// setting wrong credentials | final ServiceManager manager = new ServiceManager(); | 0 |
kihira/Tails | src/main/java/uk/kihira/tails/client/render/FallbackRenderHandler.java | [
"public class Model implements IDisposable\n{\n private final ArrayList<Node> allNodes;\n private final ArrayList<Node> rootNodes;\n private final HashMap<String, Animation> animations;\n private final ArrayList<ResourceLocation> textures;\n\n public Model(ArrayList<Node> allNodes, ArrayList<Node> ro... | import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.renderer.model.ModelRenderer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import uk.kihira.gltf.Model;
import uk.kihira.tails.client.MountPoint;
import uk.kihira.tails.client.outfit.OutfitPart;
import uk.kihira.tails.client.PartRegistry;
import uk.kihira.tails.client.outfit.Outfit;
import uk.kihira.tails.common.Tails;
import java.util.Optional;
import java.util.UUID;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.vertex.IVertexBuilder; | package uk.kihira.tails.client.render;
/**
* Legacy renderer that uses the player render event.
* This is used for compatibility with certain mods
*/
public class FallbackRenderHandler
{
private static RenderPlayerEvent.Pre currentEvent = null;
private static Outfit currentOutfit = null;
private static ResourceLocation currentPlayerTexture = null;
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerRenderTick(RenderPlayerEvent.Pre e)
{
UUID uuid = e.getPlayer().getGameProfile().getId();
if (Tails.proxy.hasActiveOutfit(uuid) && !e.getPlayer().isInvisible())
{
currentOutfit = Tails.proxy.getActiveOutfit(uuid);
currentPlayerTexture = ((ClientPlayerEntity) e.getPlayer()).getLocationSkin();
currentEvent = e;
}
}
@SubscribeEvent()
public void onPlayerRenderTickPost(RenderPlayerEvent.Post e)
{
//Reset to null after rendering the current tail
currentOutfit = null;
currentPlayerTexture = null;
currentEvent = null;
}
public static class ModelRendererWrapper extends ModelRenderer
{
private final MountPoint mountPoint;
public ModelRendererWrapper(net.minecraft.client.renderer.model.Model model, MountPoint mountPoint)
{
super(model);
this.mountPoint = mountPoint;
addBox(0, 0, 0, 0, 0, 0); //Adds in a blank box as it's required in certain cases such as rendering arrows in entities
}
@Override
public void render(MatrixStack matrixStackIn, IVertexBuilder bufferIn, int packedLightIn, int packedOverlayIn)
{
if (currentEvent != null && currentOutfit != null && currentPlayerTexture != null)
{ | for (OutfitPart part : currentOutfit.parts) | 2 |
ppicas/android-clean-architecture-mvp | app/src/main/java/cat/ppicas/cleanarch/ui/presenter/CityListItemPresenter.java | [
"public class City {\n\n private String mId;\n private String mName;\n private String mCountry;\n private CurrentWeatherPreview mCurrentWeatherPreview;\n\n public City(String id, String name, String country) {\n mId = id;\n mName = name;\n mCountry = country;\n }\n\n public... | import cat.ppicas.cleanarch.model.City;
import cat.ppicas.cleanarch.task.GetElevationTask;
import cat.ppicas.cleanarch.text.NumberFormat;
import cat.ppicas.cleanarch.ui.vista.CityListItemVista;
import cat.ppicas.framework.task.SuccessTaskCallback;
import cat.ppicas.framework.task.TaskExecutor;
import cat.ppicas.framework.ui.Presenter; | /*
* Copyright (C) 2015 Pau Picas Sans <pau.picas@gmail.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 cat.ppicas.cleanarch.ui.presenter;
public class CityListItemPresenter extends Presenter<CityListItemVista> {
private TaskExecutor mTaskExecutor;
private City mCity;
private int mElevation = -1;
private GetElevationTask mGetElevationTask;
public CityListItemPresenter(TaskExecutor taskExecutor, City city) {
mTaskExecutor = taskExecutor;
mCity = city;
}
@Override
public void onStart(CityListItemVista vista) {
updateVista();
if (mElevation > -1) {
vista.setLoadingElevation(false);
vista.setElevation(mElevation);
} else {
vista.setLoadingElevation(true);
if (!mTaskExecutor.isRunning(mGetElevationTask)) {
mGetElevationTask = new GetElevationTask(mCity);
mTaskExecutor.execute(mGetElevationTask, new GetElevationTaskCallback());
}
}
}
@Override
public void onDestroy() {
if (mTaskExecutor.isRunning(mGetElevationTask)) {
mGetElevationTask.cancel();
}
}
public void setCity(City city) {
if (mCity.getId().equals(city.getId()) && mCity.getName().equals(city.getName())) {
return;
}
mCity = city;
updateVista();
if (mTaskExecutor.isRunning(mGetElevationTask)) {
mGetElevationTask.cancel();
}
if (getVista() != null) {
getVista().setLoadingElevation(true);
}
mElevation = -1;
mGetElevationTask = new GetElevationTask(city);
mTaskExecutor.execute(mGetElevationTask, new GetElevationTaskCallback());
}
private void updateVista() {
CityListItemVista vista = getVista();
if (vista == null) {
return;
}
vista.setCityName(mCity.getName());
vista.setCountry(mCity.getCountry());
double temp = mCity.getCurrentWeatherPreview().getCurrentTemp(); | vista.setCurrentTemp(NumberFormat.formatTemperature(temp)); | 2 |
irengrig/fossil4idea | src/org/github/irengrig/fossil4idea/checkin/CheckinUtil.java | [
"public class FossilConfigurable implements Configurable {\n private final Project myProject;\n private JPanel myPanel;\n private TextFieldWithBrowseButton myCommandLine;\n\n public FossilConfigurable(final Project project) {\n myProject = project;\n createUI();\n }\n\n private void createUI() {\n my... | import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.util.PopupUtil;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.ObjectsConvertor;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.actions.VcsQuickListPopupAction;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ui.UIUtil;
import org.github.irengrig.fossil4idea.FossilConfigurable;
import org.github.irengrig.fossil4idea.FossilConfiguration;
import org.github.irengrig.fossil4idea.FossilVcs;
import org.github.irengrig.fossil4idea.commandLine.FCommandName;
import org.github.irengrig.fossil4idea.commandLine.FossilSimpleCommand;
import org.github.irengrig.fossil4idea.local.MoveWorker;
import org.github.irengrig.fossil4idea.FossilException;
import org.github.irengrig.fossil4idea.pull.FossilUpdateConfigurable;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.util.*; | package org.github.irengrig.fossil4idea.checkin;
/**
* Created with IntelliJ IDEA.
* User: Irina.Chernushina
* Date: 2/24/13
* Time: 2:59 PM
*/
public class CheckinUtil {
public static final String QUESTION = "Commit anyhow (a=all/c=convert/y/N)?";
public static final String BREAK_SEQUENCE = "contains CR/NL line endings";
public static final String PUSH_TO = "Push to";
private final Project myProject;
public static final String PREFIX = "New_Version: ";
public CheckinUtil(final Project project) {
myProject = project;
}
public void push() {
final FossilVcs fossil = FossilVcs.getInstance(myProject);
final VirtualFile[] roots = ProjectLevelVcsManager.getInstance(myProject).getRootsUnderVcs(fossil);
if (roots.length == 0) {
// PopupUtil.showBalloonForActiveComponent("Error occurred while pushing: No roots under Fossil found.", MessageType.ERROR);
return;
}
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
@Override
public void run() {
final List<FilePath> filePaths = ObjectsConvertor.vf2fp(Arrays.asList(roots)); | final FossilUpdateConfigurable configurable = (FossilUpdateConfigurable) fossil.getUpdateEnvironment().createConfigurable(filePaths); | 7 |
lukas-krecan/JsonUnit | json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java | [
"public static Object jsonSource(Object json, String pathPrefix) {\n return jsonSource(json, pathPrefix, emptyList());\n}",
"public static Object missingNode() {\n return Node.MISSING_NODE;\n}",
"public static Node wrapDeserializedObject(Object source) {\n return GenericNodeBuilder.wrapDeserializedObje... | import com.jayway.jsonpath.EvaluationListener;
import com.jayway.jsonpath.PathNotFoundException;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import static com.jayway.jsonpath.Configuration.defaultConfiguration;
import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource;
import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode;
import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject;
import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation;
import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue; | /**
* Copyright 2009-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
*
* 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.javacrumbs.jsonunit.jsonpath;
/**
* Adapts json-path to json-unit.
*/
public final class JsonPathAdapter {
private JsonPathAdapter() {
}
public static Object inPath(@NotNull Object json, @NotNull String path) {
String normalizedPath = fromBracketNotation(path);
try {
MatchRecordingListener recordingListener = new MatchRecordingListener();
Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path);
return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths());
} catch (PathNotFoundException e) { | return jsonSource(missingNode(), normalizedPath); | 1 |
onyxbits/TradeTrax | src/main/java/de/onyxbits/tradetrax/pages/edit/NameEditor.java | [
"@Entity\n@Table(name = \"bookmarks\")\npublic class Bookmark implements Serializable{\n\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Reference to {@link Stock} id.\n\t */\n\t@Id\n\t@Column(name = \"id\", unique = true)\n\tprivate long id;\n\n\t/**\n\t * @return the id\n\t */\n\tpublic long ge... | import java.util.List;
import org.apache.tapestry5.alerts.AlertManager;
import org.apache.tapestry5.alerts.Duration;
import org.apache.tapestry5.alerts.Severity;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.Validate;
import org.apache.tapestry5.corelib.components.EventLink;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import de.onyxbits.tradetrax.entities.Bookmark;
import de.onyxbits.tradetrax.entities.Name;
import de.onyxbits.tradetrax.entities.Stock;
import de.onyxbits.tradetrax.pages.Index;
import de.onyxbits.tradetrax.pages.tools.LabelManager;
import de.onyxbits.tradetrax.services.EventLogger; | package de.onyxbits.tradetrax.pages.edit;
/**
* A simple editor page for changing or deleting a {@link Name} object and
* returning to the main page afterwards.
*
* @author patrick
*
*/
@Import(library = "context:js/mousetrap.min.js")
public class NameEditor {
@Property
private long nameId;
@Property
@Validate("required,minlength=3")
private String name;
@Property
private String status;
@Component(id = "nameField")
private TextField nameField;
@Component(id = "editForm")
private Form form;
@Inject
private Session session;
@Inject
private AlertManager alertManager;
@Inject
private Messages messages;
@Inject
private EventLogger eventLogger;
@InjectPage
private Index index;
private boolean eventDelete;
@Component(id = "show")
private EventLink show;
@Inject
private JavaScriptSupport javaScriptSupport;
protected Object onShow() {
Name n = (Name) session.get(Name.class, nameId);
if (n != null) {
index.withNoFilters().withFilterName(n.getLabel());
}
return index;
}
protected void onActivate(Long nameId) {
this.nameId = nameId;
}
protected void setupRender() {
Name n = (Name) session.get(Name.class, nameId);
if (n != null) {
name = n.getLabel();
status = messages.format("status-count",
session.createCriteria(Stock.class).add(Restrictions.eq("name.id", this.nameId))
.setProjection(Projections.rowCount()).uniqueResult());
}
}
protected Long onPassivate() {
return nameId;
}
public void onValidateFromEditForm() {
if (name == null) {
form.recordError(messages.get("validate-not-empty"));
}
else {
if (name.trim().length() < name.length()) {
form.recordError(messages.get("validate-not-trimmed"));
}
}
}
public void onSelectedFromDelete() {
eventDelete = true;
}
public void onSelectedFromSave() {
eventDelete = false;
}
@CommitAfter
public Object onSuccess() {
if (eventDelete) {
doDelete();
}
else {
doSave();
}
return LabelManager.class;
}
private void doSave() {
try {
Name n = (Name) session.load(Name.class, nameId);
String s = n.getLabel();
n.setLabel(name);
session.update(n);
alertManager.alert(Duration.SINGLE, Severity.INFO, messages.format("renamed", s, name));
eventLogger.rename(s, name);
}
catch (Exception e) {
// TODO: Figure out how we got here and give the user better feedback
alertManager.alert(Duration.SINGLE, Severity.WARN, messages.format("exception", e));
}
}
private void doDelete() {
try {
Name bye = (Name) session.load(Name.class, nameId);
@SuppressWarnings("unchecked")
List<Stock> lst = session.createCriteria(Stock.class).add(Restrictions.eq("name", bye))
.list();
for (Stock s : lst) { | Bookmark bm = (Bookmark) session.get(Bookmark.class, s.getId()); | 0 |
GlitchCog/ChatGameFontificator | src/main/java/com/glitchcog/fontificator/gui/emoji/EmojiLoadProgressPanel.java | [
"public class ConfigEmoji extends Config\n{\n private static final Logger logger = Logger.getLogger(ConfigEmoji.class);\n\n public static final int MIN_SCALE = 10;\n public static final int MAX_SCALE = 500;\n\n public static final int MIN_BADGE_OFFSET = -32;\n public static final int MAX_BADGE_OFFSET... | import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import org.apache.log4j.Logger;
import com.glitchcog.fontificator.config.ConfigEmoji;
import com.glitchcog.fontificator.emoji.EmojiJob;
import com.glitchcog.fontificator.emoji.EmojiOperation;
import com.glitchcog.fontificator.gui.chat.ChatPanel;
import com.glitchcog.fontificator.gui.controls.panel.ControlPanelBase;
import com.glitchcog.fontificator.gui.controls.panel.ControlPanelEmoji;
import com.glitchcog.fontificator.gui.controls.panel.LogBox; | blankAllValues();
reset();
handleButtonEnables();
}
else if (report.isError())
{
emojiLogBox.log(report.getMessage());
blankAllValues();
if (currentWorker != null)
{
currentWorker.haltCurrentJob();
}
currentWorker = null;
initiateNextWork();
}
else
{
bar.setValue(report.getPercentComplete());
percentValue.setText(report.getPercentText());
if (report.isComplete())
{
emojiLogBox.log(report.getMessage());
if (currentWorker != null)
{
emojiConfig.setWorkCompleted(currentWorker.getEmojiJob());
}
initiateNextWork();
}
}
repaint();
}
/**
* Reverts the panel to its ready state
*/
synchronized private void reset()
{
cancelButton.setEnabled(false);
blankAllValues();
workerTaskListLoad.clear();
workerTaskListCache.clear();
currentWorker = null;
}
/**
* Removes all labels and values from the display
*/
synchronized private void blankAllValues()
{
percentValue.setText(EMPTY_VALUE_TEXT);
bar.setValue(0);
}
/**
* Call to add work
*
* @param label
* @param emojiWorker
* @param initialReport
*/
synchronized public void addWorkToQueue(EmojiWorker emojiWorker)
{
ConcurrentLinkedQueue<EmojiWorker> taskList = getTaskList(emojiWorker.getEmojiJob());
for (EmojiWorker worker : taskList)
{
if (!worker.isCancelled() && worker.getEmojiJob().equals(emojiWorker.getEmojiJob()))
{
// Already exists in a non-canceled way, so don't add it
return;
}
}
taskList.add(emojiWorker);
}
/**
* Call to initiate work
*/
synchronized public void initiateWork()
{
ConcurrentLinkedQueue<EmojiWorker> taskList = getTaskList();
if (!taskList.isEmpty())
{
currentWorker = taskList.poll();
setLocation(getParent().getLocation().x + (getParent().getWidth() - getWidth()) / 2, getParent().getLocation().y + (getParent().getHeight() - getHeight()) / 2);
cancelButton.setEnabled(true);
update(currentWorker.getInitialReport());
currentWorker.execute();
}
}
/**
* Kick off the next worker when the current worker is done
*/
synchronized private void initiateNextWork()
{
this.percentValue.setText(EMPTY_VALUE_TEXT);
ConcurrentLinkedQueue<EmojiWorker> taskList = getTaskList();
this.currentWorker = taskList.poll();
chat.repaint();
if (currentWorker == null)
{
reset();
handleButtonEnables();
}
else
{
currentWorker.execute();
}
}
/**
* Take any worker containing a job that matches the specified job off the queue of workers to be executed. Also
* cancels the currently running worker if it matches.
*
* @param job
*/ | synchronized public void removeWorkFromQueue(EmojiJob job) | 1 |
bitkylin/BitkyShop | Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/userfragment/UserFragment.java | [
"public class KyUser extends BmobUser {\n private String pwdResumeQuestion;\n private String pwdResumeAnswer;\n private Boolean haveDetailInfo;\n\n public Boolean getHaveDetailInfo() {\n return haveDetailInfo;\n }\n\n public void setHaveDetailInfo(Boolean haveDetailInfo) {\n this.haveDetailInfo = haveDe... | import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import cc.bitky.bitkyshop.R;
import cc.bitky.bitkyshop.bean.cart.KyUser;
import cc.bitky.bitkyshop.fragment.userfragment.addressactivity.AddressOptionActivity;
import cc.bitky.bitkyshop.fragment.userfragment.loginfragment.LoginActivity;
import cc.bitky.bitkyshop.fragment.userfragment.orderactivity.OrderManagerActivity;
import cc.bitky.bitkyshop.utils.tools.KyBmobHelper;
import cc.bitky.bitkyshop.utils.tools.KyPattern;
import cc.bitky.bitkyshop.utils.tools.KySet;
import cn.bmob.v3.BmobUser; | package cc.bitky.bitkyshop.fragment.userfragment;
public class UserFragment extends Fragment implements View.OnClickListener {
private TextView textViewUserNameShow;
private TextView textViewUserLogOut;
private Button btnLogout;
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_user, container, false);
textViewUserNameShow = (TextView) view.findViewById(R.id.userFragment_userName_show);
btnLogout = (Button) view.findViewById(R.id.userfragment_button_logout);
textViewUserLogOut = (TextView) view.findViewById(R.id.userFragment_userName_logout);
LinearLayout cardViewAddress =
(LinearLayout) view.findViewById(R.id.userFragment_addressCardView);
LinearLayout cardViewOrder = (LinearLayout) view.findViewById(R.id.userFragment_orderCardView);
textViewUserNameShow.setOnClickListener(this);
textViewUserLogOut.setOnClickListener(this);
btnLogout.setOnClickListener(this);
cardViewAddress.setOnClickListener(this);
cardViewOrder.setOnClickListener(this);
initCurrentUser();
return view;
}
/**
* 读取本地缓存的已登录用户
*/
private void initCurrentUser() {
KyUser kyUser = KyBmobHelper.getCurrentUser();
if (kyUser != null) {
String username = kyUser.getUsername();
if (KyPattern.checkPhoneNumber(username)) {
textViewUserNameShow.setText(username.substring(0, 3) + "****" + username.substring(7, 11));
} else {
textViewUserNameShow.setText(username);
}
textViewUserLogOut.setVisibility(View.VISIBLE);
btnLogout.setVisibility(View.VISIBLE);
} else {
textViewUserNameShow.setText("点击登录");
textViewUserLogOut.setVisibility(View.GONE);
btnLogout.setVisibility(View.GONE);
}
}
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case KySet.USER_RESULT_LOG_IN:
initCurrentUser();
break;
}
}
@Override public void onClick(View v) {
if (textViewUserNameShow.getText().toString().trim().equals("点击登录")
|| KyBmobHelper.getCurrentUser() == null) { | Intent intent = new Intent(getContext(), LoginActivity.class); | 2 |
koendeschacht/count-db | count-db-run/src/main/java/be/bagofwords/db/interfaces/rocksdb/RocksDBDataInterfaceFactory.java | [
"public abstract class CoreDataInterface<T> extends BaseDataInterface<T> {\n\n protected final UpdateListenerCollection<T> updateListenerCollection = new UpdateListenerCollection<>();\n\n public CoreDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer... | import be.bagofwords.db.CoreDataInterface;
import be.bagofwords.db.DataInterface;
import be.bagofwords.db.combinator.Combinator;
import be.bagofwords.db.impl.BaseDataInterfaceFactory;
import be.bagofwords.db.methods.ObjectSerializer;
import be.bagofwords.minidepi.ApplicationContext;
import be.bagofwords.util.Utils;
import org.rocksdb.RocksDB;
import java.io.File; | package be.bagofwords.db.interfaces.rocksdb;
/**
* Created by Koen Deschacht (koendeschacht@gmail.com) on 9/17/14.
*/
public class RocksDBDataInterfaceFactory extends BaseDataInterfaceFactory {
private final String directory;
private final boolean usePatch;
public RocksDBDataInterfaceFactory(ApplicationContext applicationContext, boolean usePatch) {
super(applicationContext);
this.directory = applicationContext.getProperty("data_directory");
this.usePatch = usePatch;
File libFile = findLibFile();
if (libFile == null) {
throw new RuntimeException("Could not find librocksdbjni.so");
}
Utils.addLibraryPath(libFile.getParentFile().getAbsolutePath());
RocksDB.loadLibrary();
}
private File findLibFile() {
File libFile = new File("./lib/rocksdb/linux-x86_64/librocksdbjni.so");
if (libFile.exists()) {
return libFile;
}
libFile = new File("./count-db/lib/rocksdb/linux-x86_64/librocksdbjni.so");
if (libFile.exists()) {
return libFile;
}
return null;
}
@Override | protected <T> CoreDataInterface<T> createBaseDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean isTemporaryDataInterface) { | 0 |
AstartesGuardian/WebDAV-Server | WebDAV-Server/src/webdav/server/commands/light/WDL_Propfind.java | [
"public class FileSystemPath\r\n{\r\n public FileSystemPath(String fileName, FileSystemPath parent)\r\n {\r\n this.fileName = fileName;\r\n this.parent = parent;\r\n this.fileSystemPathManager = parent.fileSystemPathManager;\r\n }\r\n public FileSystemPath(String fileName, FileSyste... | import http.FileSystemPath;
import http.StringJoiner;
import http.server.HTTPCommand;
import http.server.message.HTTPResponse;
import java.time.Instant;
import webdav.server.resource.IResource;
import http.server.exceptions.NotFoundException;
import http.server.exceptions.UserRequiredException;
import http.server.message.HTTPEnvRequest;
| package webdav.server.commands.light;
public class WDL_Propfind extends HTTPCommand
{
public WDL_Propfind()
{
super("lightpropfind");
}
private static String addString(String name, String value)
{
return "<" + name + ">" + value + "</" + name + ">";
}
private static String addString(String name, long value)
{
return addString(name, String.valueOf(value));
}
| private String getInfo(IResource resource, FileSystemPath path, String host, HTTPEnvRequest environment) throws UserRequiredException
| 7 |
nchambers/probschemas | src/main/java/nate/probschemas/EventPairScores.java | [
"public class Pair<A,B> {\n A first;\n B second;\n\n public Pair(A one, B two) {\n first = one;\n second = two;\n }\n\n public A first() { return first; }\n public B second() { return second; }\n public void setFirst(A obj) { first = obj; }\n public void setSecond(B obj) { second = obj; }\n \n publi... | import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nate.util.Pair;
import nate.WordEvent;
import nate.WordIndex;
import nate.util.SortableScore;
import nate.util.Util; | float bestscore = 0.0f;
for( String str : _scores.keySet() ) {
Map<String,Float> events = _scores.get(str);
for( String str2 : events.keySet() ) {
Float score = events.get(str2);
if( score > bestscore ) {
bestscore = score;
best = str;
}
}
}
return best;
}
public Set<String> keySet() {
return getSingleEvents();
}
/**
* @return All of the event strings involved in any pairs this class has.
*/
public Set<String> getSingleEvents() {
Set<String> events = new HashSet<String>();
for( Map.Entry<String,Map<String,Float>> entry : _scores.entrySet() ) {
events.add(entry.getKey());
for( String sib : entry.getValue().keySet() )
events.add(sib);
}
return events;
}
/**
* Saves the score of an event pair key1 and key2.
*/
public void addScore(String key1, String key2, float score) {
Map<String,Float> counts;
if( _scores.containsKey(key1) ) counts = _scores.get(key1);
else {
counts = new HashMap<String, Float>();
_scores.put(key1,counts);
}
counts.put(key2,score);
}
public void setScore(String key1, String key2, float score) {
addScoreSorted(key1, key2, score);
}
/**
* Saves the score of an event pair key1 and key2 in sorted order.
*/
public void addScoreSorted(String key1, String key2, float score) {
if( key1.compareTo(key2) > 0 )
addScore(key2, key1, score);
else
addScore(key1, key2, score);
}
/**
* Removes any pairs that contain the given key.
*/
public void removeKey(String key) {
// Remove all pairs starting with the key.
_scores.remove(key);
// Remove all pairs ending with the key.
for( Map.Entry<String,Map<String,Float>> entry : _scores.entrySet() ) {
Map<String,Float> scores = entry.getValue();
scores.remove(key);
}
}
public void clear() {
_scores.clear();
}
public int size() {
return _scores.size();
}
/**
* Print the pairs with their scores in sorted order.
*/
public void printSorted() {
printSorted(Integer.MAX_VALUE);
}
public void printSorted(int maxpairs) {
List<SortableScore> scores = new ArrayList<SortableScore>();
for( Map.Entry<String,Map<String,Float>> entry : _scores.entrySet() ) {
for( Map.Entry<String,Float> entry2 : entry.getValue().entrySet() ) {
String pair = entry.getKey() + "\t" + entry2.getKey();
scores.add(new SortableScore(entry2.getValue(), pair));
}
}
System.out.println("Num pairs: " + scores.size());
// Sort and Print.
SortableScore[] arr = new SortableScore[scores.size()];
arr = scores.toArray(arr);
Arrays.sort(arr);
int num = 0;
for( SortableScore scored : arr ) {
if( scored.score() > 0.0f ) {
System.out.printf("%s\t%.1f\n", scored.key(), scored.score());
num++;
}
if( num >= maxpairs ) break;
}
}
/**
* Main: Just for debugging.
*/
public static void main(String[] args) {
EventPairScores scores = new EventPairScores();
scores.fromFile(args[0], null, 0.0f, 0, true);
// testing... | Util.reportMemory(); | 4 |
MFlisar/StorageManager | lib/src/main/java/com/michaelflisar/storagemanager/utils/StorageDebugUtil.java | [
"public class StorageManager\n{\n public static final String TAG = StorageManager.class.getName();\n\n private static StorageManager INSTANCE = null;\n\n public static StorageManager get()\n {\n if (INSTANCE == null)\n INSTANCE = new StorageManager();\n return INSTANCE;\n }\n... | import com.michaelflisar.storagemanager.StorageManager;
import com.michaelflisar.storagemanager.StoragePermissionManager;
import com.michaelflisar.storagemanager.StorageUtil;
import com.michaelflisar.storagemanager.data.MediaStoreFileData;
import com.michaelflisar.storagemanager.interfaces.IFile;
import com.michaelflisar.storagemanager.interfaces.IFolder;
import java.io.File;
import java.util.ArrayList; | package com.michaelflisar.storagemanager.utils;
/**
* Created by flisar on 10.03.2016.
*/
public class StorageDebugUtil
{
public static final ArrayList<String> debugAvailableInfos()
{
ArrayList<String> messages = new ArrayList<>();
// 1) add paths | IFolder sdCard = StorageManager.get().getSDCardRoot(); | 0 |
caligin/tinytypes | jackson/src/main/java/tech/anima/tinytypes/jackson/TinyTypesDeserializers.java | [
"public class BooleanTinyTypes implements MetaTinyType<BooleanTinyType> {\n\n public static boolean includes(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n\n return BooleanTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public... | import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.Deserializers;
import java.io.IOException;
import tech.anima.tinytypes.meta.BooleanTinyTypes;
import tech.anima.tinytypes.meta.ByteTinyTypes;
import tech.anima.tinytypes.meta.IntTinyTypes;
import tech.anima.tinytypes.meta.LongTinyTypes;
import tech.anima.tinytypes.meta.MetaTinyTypes;
import tech.anima.tinytypes.meta.ShortTinyTypes;
import tech.anima.tinytypes.meta.StringTinyTypes; | package tech.anima.tinytypes.jackson;
public class TinyTypesDeserializers extends Deserializers.Base {
@Override
public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException {
Class<?> candidateTT = type.getRawClass();
if (MetaTinyTypes.isTinyType(candidateTT)) {
return new TinyTypesDeserializer(candidateTT);
}
return null;
}
public static class TinyTypesDeserializer<T> extends JsonDeserializer<T> {
private final Class<T> type;
public TinyTypesDeserializer(Class<T> type) {
if (type == null || !MetaTinyTypes.isTinyType(type)) {
throw new IllegalArgumentException(String.format("not a tinytype: %s", type == null ? "null" : type.getCanonicalName()));
}
this.type = type;
}
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return MetaTinyTypes.metaFor(type).newInstance(type, extractValue(p));
}
private Object extractValue(JsonParser p) throws IOException {
if (StringTinyTypes.includes(type)) {
return p.getText();
}
if (BooleanTinyTypes.includes(type)) {
return p.getBooleanValue();
}
if (ByteTinyTypes.includes(type)) {
return p.getByteValue();
}
if (ShortTinyTypes.includes(type)) {
return p.getShortValue();
}
if (IntTinyTypes.includes(type)) {
return p.getIntValue();
} | if (LongTinyTypes.includes(type)) { | 3 |
cettia/asity | example-spring-webflux5/src/main/java/io/cettia/asity/example/spring/webflux5/EchoServer.java | [
"@FunctionalInterface\npublic interface Action<T> {\n\n /**\n * Some action is taken.\n */\n void on(T object);\n\n}",
"public class AsityHandlerFunction implements HandlerFunction<ServerResponse> {\n\n private Actions<ServerHttpExchange> httpActions = new ConcurrentActions<>();\n\n @Override\n public Mo... | import io.cettia.asity.action.Action;
import io.cettia.asity.bridge.spring.webflux5.AsityHandlerFunction;
import io.cettia.asity.bridge.spring.webflux5.AsityWebSocketHandler;
import io.cettia.asity.example.echo.HttpEchoServer;
import io.cettia.asity.example.echo.WebSocketEchoServer;
import io.cettia.asity.http.ServerHttpExchange;
import io.cettia.asity.websocket.ServerWebSocket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.config.EnableWebFlux;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.springframework.web.reactive.function.server.RequestPredicates.headers;
import static org.springframework.web.reactive.function.server.RequestPredicates.path; | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.cettia.asity.example.spring.webflux5;
@SpringBootApplication
@EnableWebFlux
public class EchoServer {
@Bean
public Action<ServerHttpExchange> httpAction() {
return new HttpEchoServer();
}
@Bean
public Action<ServerWebSocket> wsAction() {
return new WebSocketEchoServer();
}
@Bean
public RouterFunction<ServerResponse> httpMapping() { | AsityHandlerFunction asityHandlerFunction = new AsityHandlerFunction().onhttp(httpAction()); | 1 |
Ohohcakester/Any-Angle-Pathfinding | src/main/TextOutputVisualisation.java | [
"public class GridAndGoals {\r\n\tpublic final GridGraph gridGraph;\r\n\tpublic final StartGoalPoints startGoalPoints;\r\n\t\r\n\tpublic GridAndGoals(GridGraph gridGraph, StartGoalPoints startGoalPoints) {\r\n\t\tthis.gridGraph = gridGraph;\r\n\t\tthis.startGoalPoints = startGoalPoints;\r\n\t}\r\n\t\r\n\tpublic Gri... | import grid.GridAndGoals;
import grid.GridGraph;
import grid.StartGoalPoints;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import uiandio.GraphImporter;
import algorithms.datatypes.SnapshotItem;
import draw.DrawCanvas;
import draw.GridLineSet;
import draw.GridObjects; | package main;
public class TextOutputVisualisation {
public static void run() {
loadDefault();
//loadFromFile("anyacont2b.txt");
}
private static void loadFromFile(String mazeFileName) {
String textData = readStandardInput();
| GridGraph gridGraph = GraphImporter.importGraphFromFile(mazeFileName); | 3 |
ls1110924/ImmerseMode | immerse/src/main/java/com/yunxian/immerse/impl/TlSbNNbImmerseMode.java | [
"public final class ImmerseConfiguration {\n\n final ImmerseType mImmerseTypeInKK;\n final ImmerseType mImmerseTypeInL;\n\n public final boolean lightStatusBar;\n public final boolean coverCompatMask;\n public final int coverMaskColor;\n\n private ImmerseConfiguration(@NonNull ImmerseType immerseT... | import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import com.yunxian.immerse.ImmerseConfiguration;
import com.yunxian.immerse.R;
import com.yunxian.immerse.manager.ImmerseGlobalConfig;
import com.yunxian.immerse.utils.DrawableUtils;
import com.yunxian.immerse.utils.ViewUtils;
import com.yunxian.immerse.utils.WindowUtils;
import com.yunxian.immerse.widget.ConsumeInsetsFrameLayout;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.KITKAT;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; | package com.yunxian.immerse.impl;
/**
* 半透明状态栏普通导航栏
* <p>半透明状态栏支持到4.4及以上,普通导航栏着色支持到5.0及以上</p>
*
* @author AShuai
* @email ls1110924@gmail.com
* @date 17/1/31 下午2:42
*/
@TargetApi(KITKAT)
public class TlSbNNbImmerseMode extends AbsImmerseMode {
private final View mCompatStatusBarView;
public TlSbNNbImmerseMode(@NonNull Activity activity, @NonNull ImmerseConfiguration immerseConfiguration) {
super(activity, immerseConfiguration);
Window window = activity.getWindow();
WindowUtils.clearWindowFlags(window, FLAG_TRANSLUCENT_NAVIGATION);
WindowUtils.addWindowFlags(window, FLAG_TRANSLUCENT_STATUS);
if (immerseConfiguration.lightStatusBar && SDK_INT >= Build.VERSION_CODES.M) {
ViewUtils.addSystemUiFlags(window.getDecorView(), View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
mCompatStatusBarView = setupView(activity);
}
@Override
public void setStatusColor(@ColorInt int color) {
mCompatStatusBarView.setBackgroundColor(generateCompatStatusBarColor(color));
}
@Override
public void setStatusColorRes(@ColorRes int colorRes) {
Activity activity = mActivityRef.get();
if (activity != null) {
int color = ContextCompat.getColor(activity, colorRes);
setStatusColor(color);
}
}
@Override
public boolean setStatusDrawable(@Nullable Drawable drawable) {
DrawableUtils.setViewBackgroundDrawable(mCompatStatusBarView, drawable);
return true;
}
@Override
public boolean setStatusDrawableRes(@DrawableRes int drawableRes) {
Activity activity = mActivityRef.get();
if (activity != null) {
Drawable drawable = ContextCompat.getDrawable(activity, drawableRes);
setStatusDrawable(drawable);
}
return true;
}
@Override
public void setNavigationColor(@ColorInt int color) {
Activity activity = mActivityRef.get();
if (activity != null && SDK_INT >= LOLLIPOP) {
activity.getWindow().setNavigationBarColor(color);
}
}
@Override
public void setNavigationColorRes(@ColorRes int colorRes) {
Activity activity = mActivityRef.get();
if (activity != null) {
int color = ContextCompat.getColor(activity, colorRes);
setNavigationColor(color);
}
}
@Override
public boolean setNavigationDrawable(@Nullable Drawable drawable) {
return false;
}
@Override
public boolean setNavigationDrawableRes(@DrawableRes int drawableRes) {
return false;
}
@NonNull
@Override
public Rect getInsetsPadding() {
return new Rect(0, 0, 0, 0);
}
@Override
public void setOnInsetsChangeListener(boolean operation, | @Nullable ConsumeInsetsFrameLayout.OnInsetsChangeListener listener) { | 5 |
matburt/mobileorg-android | MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java | [
"public static class Files implements FilesColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build();\n\n\tpublic static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME,\n\t\t\tCOMMENT, NODE_ID };\n\tpublic static final String DEFAULT_SORT = NAME + \... | import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import com.matburt.mobileorg.orgdata.OrgContract.Files;
import com.matburt.mobileorg.orgdata.OrgContract.OrgData;
import com.matburt.mobileorg.orgdata.OrgContract.Priorities;
import com.matburt.mobileorg.orgdata.OrgContract.Tags;
import com.matburt.mobileorg.orgdata.OrgContract.Timestamps;
import com.matburt.mobileorg.orgdata.OrgContract.Todos;
import com.matburt.mobileorg.util.OrgFileNotFoundException;
import com.matburt.mobileorg.util.OrgNodeNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List; | package com.matburt.mobileorg.orgdata;
public class OrgProviderUtils {
/**
*
* @param context
* @return the list of nodes corresponding to a file
*/
public static List<OrgNode> getFileNodes(Context context){
return OrgProviderUtils.getOrgNodeChildren(-1, context.getContentResolver());
}
public static ArrayList<String> getFilenames(ContentResolver resolver) {
ArrayList<String> result = new ArrayList<String>();
Cursor cursor = resolver.query(Files.CONTENT_URI, Files.DEFAULT_COLUMNS,
null, null, Files.DEFAULT_SORT);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
OrgFile orgFile = new OrgFile();
try {
orgFile.set(cursor);
result.add(orgFile.filename);
} catch (OrgFileNotFoundException e) {}
cursor.moveToNext();
}
cursor.close();
return result;
}
/**
* Query the DB for the list of files
* @param resolver
* @return
*/
public static ArrayList<OrgFile> getFiles(ContentResolver resolver) {
ArrayList<OrgFile> result = new ArrayList<>();
Cursor cursor = resolver.query(Files.CONTENT_URI, Files.DEFAULT_COLUMNS,
null, null, Files.DEFAULT_SORT);
if(cursor == null) return result;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
OrgFile orgFile = new OrgFile();
try {
orgFile.set(cursor);
result.add(orgFile);
} catch (OrgFileNotFoundException e) {}
cursor.moveToNext();
}
cursor.close();
return result;
}
public static String getNonNullString(Cursor cursor, int index){
String result = cursor.getString(index);
return result!=null ? result : "";
}
public static void addTodos(HashMap<String, Boolean> todos,
ContentResolver resolver) {
if(todos == null) return;
for (String name : todos.keySet()) {
ContentValues values = new ContentValues();
values.put(Todos.NAME, name);
values.put(Todos.GROUP, 0);
if (todos.get(name))
values.put(Todos.ISDONE, 1);
try{
resolver.insert(Todos.CONTENT_URI, values);
} catch (Exception e){
e.printStackTrace();
}
}
}
public static ArrayList<String> getTodos(ContentResolver resolver) {
Cursor cursor = resolver.query(Todos.CONTENT_URI, new String[] { Todos.NAME }, null, null, Todos.ID);
if(cursor==null) return new ArrayList<>();
ArrayList<String> todos = cursorToArrayList(cursor);
return todos;
}
public static void setPriorities(ArrayList<String> priorities, ContentResolver resolver) { | resolver.delete(Priorities.CONTENT_URI, null, null); | 2 |
dgomezferro/pasc-paxos | src/main/java/com/yahoo/pasc/paxos/handlers/acceptor/AcceptorAccept.java | [
"public class Accept extends PaxosMessage implements Serializable, CloneableDeep<Accept>, EqualsDeep<Accept> {\n\n private static final long serialVersionUID = -3781061394615967506L;\n\n public static class Descriptor implements PaxosDescriptor, EqualsDeep<Descriptor> {\n\n private long iid;\n\n ... | import com.yahoo.pasc.paxos.state.IidRequest;
import com.yahoo.pasc.paxos.state.PaxosState;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yahoo.pasc.Message;
import com.yahoo.pasc.paxos.handlers.PaxosHandler;
import com.yahoo.pasc.paxos.handlers.proposer.ProposerRequest;
import com.yahoo.pasc.paxos.messages.Accept;
import com.yahoo.pasc.paxos.messages.Accepted;
import com.yahoo.pasc.paxos.messages.PaxosDescriptor;
import com.yahoo.pasc.paxos.state.ClientTimestamp;
import com.yahoo.pasc.paxos.state.IidAcceptorsCounts; | /**
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. See accompanying LICENSE file.
*/
package com.yahoo.pasc.paxos.handlers.acceptor;
public class AcceptorAccept extends PaxosHandler<Accept> {
private static final Logger LOG = LoggerFactory.getLogger(ProposerRequest.class);
@Override
public List<PaxosDescriptor> processMessage(Accept message, PaxosState state) {
if (state.getIsLeader())
return null;
int ballot = message.getBallot();
int currentBallot = state.getBallotAcceptor();
if (ballot < currentBallot) {
LOG.trace("Rejecting accept. msg ballot: {} current ballot: {}", ballot, currentBallot);
// We promised not to accept ballots lower than our current ballot
return null;
}
long iid = message.getIid();
long firstInstanceId = state.getFirstInstanceId();
if (firstInstanceId <= iid && iid < firstInstanceId + state.getMaxInstances()) {
ClientTimestamp[] cts = message.getValues();
byte[][] requests = message.getRequests();
int arraySize = message.getArraySize();
int countReceivedRequests = 0;
for (int i = 0; i < arraySize; ++i) {
if (requests != null && requests[i] != null) {
state.setReceivedRequest(cts[i], new IidRequest(iid, requests[i]));
countReceivedRequests++;
} else {
IidRequest request = state.getReceivedRequest(cts[i]);
if (request == null || (request.getIid() != -1 && request.getIid() < firstInstanceId)) {
request = new IidRequest(iid);
state.setReceivedRequest(cts[i], request);
} else if (request.getRequest() != null && request.getIid() == -1) {
request.setIid(iid);
countReceivedRequests++;
} else {
LOG.warn("The acceptor created this request. Duplicated accept?");
}
}
} | IidAcceptorsCounts accepted = state.getAcceptedElement(iid); | 3 |
mikkeliamk/osa | src/fi/mamk/osa/stripes/RoleAction.java | [
"public class AccessRight implements Serializable {\n\t\n private static final long serialVersionUID = -8302724810061640050L;\n\n public static final int ACCESSRIGHTLEVEL_DENY_META = -1;\n public static final int ACCESSRIGHTLEVEL_READ_META = 10;\n public static final int ACCESSRIGHTLEVEL... | import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import fi.mamk.osa.auth.AccessRight;
import fi.mamk.osa.auth.LdapManager;
import fi.mamk.osa.auth.Role;
import fi.mamk.osa.auth.LdapManager.EntryType;
import fi.mamk.osa.auth.User;
import fi.mamk.osa.core.Osa;
import fi.mamk.osa.utils.RoleComparator;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger; | package fi.mamk.osa.stripes;
/**
* Role Action
*/
@UrlBinding("/Role.action")
public class RoleAction extends OsaBaseActionBean
{
private static final Logger logger = Logger.getLogger(RoleAction.class);
private String roleName;
private String roleOrganization;
private String messageAddSuccess;
private String messageAddFail;
private String sEcho;
private String roleDn;
private Vector<String> entryDns;
Vector<AccessRight> accessrights = new Vector<AccessRight>();
@HandlesEvent("addRole")
public Resolution addRole() {
// get complete path for pids
handleAccessrightPaths();
| boolean added = Osa.authManager.createRole(roleName, roleOrganization, accessrights); | 5 |
occi4java/occi4java | http/src/test/java/de/occi/test/TestRestCompute.java | [
"public class OcciConfig extends XMLConfiguration {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static final Logger LOGGER = LoggerFactory\n\t\t\t.getLogger(OcciConfig.class);\n\t/**\n\t * Instance of OcciConfig\n\t */\n\tprivate static OcciConfig instance = null;\n\tprivate static ConfigurationF... | import org.restlet.Response;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.naming.NamingException;
import occi.config.OcciConfig;
import occi.http.occiApi;
import occi.infrastructure.Compute;
import occi.infrastructure.Compute.Architecture;
import occi.infrastructure.Compute.State;
import org.restlet.Request;
| /**
* Copyright (C) 2010-2011 Sebastian Heckmann, Sebastian Laag
*
* Contact Email: <sebastian.heckmann@udo.edu>, <sebastian.laag@udo.edu>
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.occi.test;
/**
* Class to test the compute interface. The test class starts the occi api and
* connects to it via client resource.
*
* Test cases are: HTTP POST HTTP GET HTTP DELETE HTTP PUT
*
* @author Sebastian Laag
* @author Sebastian Heckmann
*/
public class TestRestCompute {
private ClientResource clientResource = new ClientResource(
OcciConfig.getInstance().config.getString("occi.server.location"));
@BeforeTest
public void setUp() {
try {
// start occi api
| occiApi.main(null);
| 1 |
moovida/STAGE | eu.hydrologis.stage.treeslicesviewer/src/eu/hydrologis/stage/treeslicesviewer/TreeSlicesViewerEntryPoint.java | [
"public class StageLogger {\n\n public static final boolean LOG_INFO = true;\n public static final boolean LOG_DEBUG = false;\n public static final boolean LOG_ERROR = true;\n\n private static final String SEP = \":: \";\n\n private static SimpleDateFormat f = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:... | import static java.lang.Math.max;
import static java.lang.Math.min;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.rap.rwt.application.AbstractEntryPoint;
import org.eclipse.rap.rwt.widgets.BrowserCallback;
import org.eclipse.rap.rwt.widgets.BrowserUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.BrowserFunction;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
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.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.jgrasstools.gears.utils.files.FileUtilities;
import org.json.JSONArray;
import org.json.JSONObject;
import eu.hydrologis.stage.libs.log.StageLogger;
import eu.hydrologis.stage.libs.utils.StageUtils;
import eu.hydrologis.stage.libs.utilsrap.DownloadUtils;
import eu.hydrologis.stage.libs.utilsrap.LoginDialog;
import eu.hydrologis.stage.libs.workspace.StageWorkspace;
import eu.hydrologis.stage.libs.workspace.User; | public void completed( ProgressEvent event ) {
addMapBrowserFunctions();
Rectangle clientArea = mapBrowser.getClientArea();
int w = clientArea.width;
int h = clientArea.height;
mapBrowser.evaluate("createMap(" + w + ", " + h + ")");
}
public void changed( ProgressEvent event ) {
System.out.println();
}
});
}
private void selectPlot( String selectedText ) {
File plotFile = new File(selectedFile, selectedText + ".json");
id2TreeJsonMap.clear();
if (plotFile.exists()) {
plotObjectTransfer = new JSONObject();
try {
String fileJson = FileUtilities.readFile(plotFile);
JSONObject plotObject = new JSONObject(fileJson);
JSONObject plotData = plotObject.getJSONObject(JSON_PLOT_DATA);
JSONArray plotsArray = plotData.getJSONArray(JSON_PLOTS);
JSONObject selectedJsonPlot = plotsArray.getJSONObject(0);
String id = selectedJsonPlot.getString(JSON_PLOT_ID);
double lon = selectedJsonPlot.getDouble(JSON_PLOT_CENTERLON);
double lat = selectedJsonPlot.getDouble(JSON_PLOT_CENTERLAT);
double radius = selectedJsonPlot.getDouble(JSON_PLOT_RADIUS);
double radiusLL = selectedJsonPlot.getDouble(JSON_PLOT_RADIUSDEG);
plotObjectTransfer.put(JSON_PLOT_ID, id);
plotObjectTransfer.put(JSON_PLOT_CENTERLAT, lat);
plotObjectTransfer.put(JSON_PLOT_CENTERLON, lon);
plotObjectTransfer.put(JSON_PLOT_RADIUSDEG, radiusLL);
StringBuilder plotInfoSB = new StringBuilder();
plotInfoSB.append("<b>PLOT INFORMATION</b><br/>\n");
plotInfoSB.append("id = " + id + "<br/>");
plotInfoSB.append("lon = " + llFormatter.format(lon) + "<br/>");
plotInfoSB.append("lat = " + llFormatter.format(lat) + "<br/>");
plotInfoSB.append("radius = " + radiusFormatter.format(radius) + " m<br/>");
int fpCount = 0;
int fnCount = 0;
int matchedCount = 0;
minHeight = Double.POSITIVE_INFINITY;
minDiam = Double.POSITIVE_INFINITY;
maxHeight = Double.NEGATIVE_INFINITY;
maxDiam = Double.NEGATIVE_INFINITY;
JSONArray treesArrayTransfer = new JSONArray();
int index = 0;
plotObjectTransfer.put(JSON_PLOT_TREES, treesArrayTransfer);
JSONArray treesArray = selectedJsonPlot.getJSONArray(JSON_PLOT_TREES);
for( int i = 0; i < treesArray.length(); i++ ) {
JSONObject treeObject = treesArray.getJSONObject(i);
String treeId = treeObject.getString(JSON_TREE_ID);
id2TreeJsonMap.put(treeId, treeObject);
double treeHeight = treeObject.getDouble(JSON_TREE_HEIGHT);
minHeight = min(minHeight, treeHeight);
maxHeight = max(maxHeight, treeHeight);
boolean hasDiam = false;
boolean hasMatch = false;
double diamLL = 0;
double diam = 0;
if (treeObject.has(JSON_TREE_DIAM)) {
hasDiam = true;
diam = treeObject.getDouble(JSON_TREE_DIAM);
diamLL = treeObject.getDouble(JSON_TREE_DIAMDEG);
minDiam = min(minDiam, diamLL);
maxDiam = max(maxDiam, diamLL);
}
if (treeObject.has(JSON_TREE_ID_MATCHED)) {
matchedCount++;
hasMatch = true;
}
if (!hasDiam) {
fpCount++;
} else {
if (!hasMatch) {
fnCount++;
}
}
JSONObject treeObjectTransfer = new JSONObject();
treesArrayTransfer.put(index++, treeObjectTransfer);
treeObjectTransfer.put(JSON_TREE_ID, treeId);
treeObjectTransfer.put(JSON_TREE_LAT, treeObject.getDouble(JSON_TREE_LAT));
treeObjectTransfer.put(JSON_TREE_LON, treeObject.getDouble(JSON_TREE_LON));
treeObjectTransfer.put(JSON_TREE_HEIGHT, treeObject.getDouble(JSON_TREE_HEIGHT));
if (hasDiam) {
treeObjectTransfer.put(JSON_TREE_DIAMDEG, diamLL);
treeObjectTransfer.put(JSON_TREE_DIAM, diam);
}
if (hasMatch) {
treeObjectTransfer.put(JSON_TREE_ID_MATCHED, treeObject.getString(JSON_TREE_ID_MATCHED));
for( String dir : JSON_DIRECTIONS ) {
double progressiveMatched = treeObject.getDouble(JSON_TREE_PROGRESSIVE_MATCHED + dir);
treeObjectTransfer.put(JSON_TREE_PROGRESSIVE_MATCHED + dir, progressiveMatched);
}
treeObjectTransfer.put(JSON_TREE_HEIGHT_MATCHED, treeObject.getDouble(JSON_TREE_HEIGHT_MATCHED));
}
}
plotInfoSB.append("<br/><b>Matching:</b><br/>\n");
plotInfoSB.append("true positives = " + matchedCount + "<br/>");
plotInfoSB.append("false negatives = " + fnCount + "<br/>");
plotInfoSB.append("false positives = " + fpCount + "<br/>");
| String text = "<font color=\"" + StageUtils.TEXTCOLOR + "\">" + plotInfoSB.toString() + "</font>"; | 1 |
bodar/yatspec | test/com/googlecode/yatspec/rendering/html/HtmlResultRendererTest.java | [
"public class ContentAtUrl implements Content {\n private final URL url;\n\n public ContentAtUrl(URL url) {\n this.url = url;\n }\n\n @Override\n public String toString() {\n InputStream inputStream = null;\n try {\n inputStream = url.openStream();\n return ... | import com.googlecode.totallylazy.Strings;
import com.googlecode.yatspec.rendering.ContentAtUrl;
import com.googlecode.yatspec.rendering.Renderer;
import com.googlecode.yatspec.state.Scenario;
import com.googlecode.yatspec.state.TestResult;
import com.googlecode.yatspec.state.givenwhenthen.TestState;
import org.junit.Test;
import java.nio.file.Paths;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.nullValue; | package com.googlecode.yatspec.rendering.html;
public class HtmlResultRendererTest {
public static final String CUSTOM_RENDERED_TEXT = "some crazy and likely random string that wouldn't appear in the html";
@Test
public void providesLinksToResultOutputRelativeToOutputDirectory() throws Exception {
assertThat(
HtmlResultRenderer.htmlResultRelativePath(this.getClass()),
is(Paths.get("com/googlecode/yatspec/rendering/html/HtmlResultRendererTest.html").toString()));
}
@Test
public void loadsTemplateOffClassPath() throws Exception {
TestResult result = new TestResult(this.getClass());
String html = new HtmlResultRenderer().render(result);
assertThat(html, is(not(nullValue())));
}
@Test
public void supportsCustomRenderingOfScenarioLogs() throws Exception {
TestResult result = aTestResultWithCustomRenderTypeAddedToScenarioLogs();
String html = new HtmlResultRenderer().
withCustomRenderer(RenderedType.class, new DefaultReturningRenderer(CUSTOM_RENDERED_TEXT)).
render(result);
assertThat(html, containsString(CUSTOM_RENDERED_TEXT));
}
@Test
public void supportsCustomHeaderContent() throws Exception {
TestResult result = new TestResult(getClass());
String html = new HtmlResultRenderer(). | withCustomHeaderContent(new ContentAtUrl(getClass().getResource("CustomHeaderContent.html"))). | 0 |
yyxhdy/ManyEAs | src/jmetal/encodings/solutionType/IntRealSolutionType.java | [
"public abstract class Problem implements Serializable {\n\n\t/**\n\t * Defines the default precision of binary-coded variables\n\t */\n\tprivate final static int DEFAULT_PRECISSION = 16;\n\n\t/**\n\t * Stores the number of variables of the problem\n\t */\n\tprotected int numberOfVariables_;\n\n\t/**\n\t * Stores t... | import jmetal.core.Problem;
import jmetal.core.SolutionType;
import jmetal.core.Variable;
import jmetal.encodings.variable.Int;
import jmetal.encodings.variable.Real; | // IntRealSolutionType.java
//
// Author:
// Antonio J. Nebro <antonio@lcc.uma.es>
// Juan J. Durillo <durillo@lcc.uma.es>
//
// Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo
//
// This program 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.
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jmetal.encodings.solutionType;
/**
* Class representing a solution type including two variables: an integer
* and a real.
*/
public class IntRealSolutionType extends SolutionType {
private final int intVariables_ ;
private final int realVariables_ ;
/**
* Constructor
* @param problem Problem to solve
* @param intVariables Number of integer variables
* @param realVariables Number of real variables
*/ | public IntRealSolutionType(Problem problem, int intVariables, int realVariables) { | 0 |
DaiDongLiang/DSC | src/main/java/net/floodlightcontroller/core/internal/Controller.java | [
"public class ControllerId {\n private final short nodeId;\n\n private ControllerId(short nodeId) {\n if(nodeId == ClusterConfig.NODE_ID_UNCONFIGURED)\n throw new IllegalArgumentException(\"nodeId is unconfigured\");\n\n this.nodeId = nodeId;\n }\n\n public short getNodeId() {\n... | import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;
import net.dsc.cluster.HAListenerTypeMarker;
import net.dsc.cluster.HARole;
import net.dsc.cluster.IClusterService;
import net.dsc.cluster.RoleInfo;
import net.dsc.cluster.model.ControllerModel;
import net.dsc.hazelcast.IHazelcastService;
import net.dsc.hazelcast.listener.IHAListener;
import net.floodlightcontroller.core.ControllerId;
import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IInfoProvider;
import net.floodlightcontroller.core.IListener.Command;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.IOFSwitchListener;
import net.floodlightcontroller.core.IShutdownService;
import net.floodlightcontroller.core.LogicalOFMessageCategory;
import net.floodlightcontroller.core.PortChangeType;
import net.floodlightcontroller.core.annotations.LogMessageDoc;
import net.floodlightcontroller.core.annotations.LogMessageDocs;
import net.floodlightcontroller.core.module.FloodlightModuleException;
import net.floodlightcontroller.core.module.FloodlightModuleLoader;
import net.floodlightcontroller.core.util.ListenerDispatcher;
import net.floodlightcontroller.core.web.CoreWebRoutable;
import net.floodlightcontroller.debugcounter.IDebugCounterService;
import net.floodlightcontroller.debugevent.IDebugEventService;
import net.floodlightcontroller.notification.INotificationManager;
import net.floodlightcontroller.notification.NotificationManagerFactory;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.perfmon.IPktInProcessingTimeService;
import net.floodlightcontroller.restserver.IRestApiService;
import net.floodlightcontroller.storage.IResultSet;
import net.floodlightcontroller.storage.IStorageSourceListener;
import net.floodlightcontroller.storage.IStorageSourceService;
import net.floodlightcontroller.storage.StorageException;
import net.floodlightcontroller.threadpool.IThreadPoolService;
import net.floodlightcontroller.util.LoadMonitor;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;
import org.projectfloodlight.openflow.protocol.OFMessage;
import org.projectfloodlight.openflow.protocol.OFPacketIn;
import org.projectfloodlight.openflow.protocol.OFPortDesc;
import org.projectfloodlight.openflow.protocol.OFType;
import org.projectfloodlight.openflow.types.DatapathId;
import org.sdnplatform.sync.ISyncService;
import org.sdnplatform.sync.ISyncService.Scope;
import org.sdnplatform.sync.error.SyncException;
import org.sdnplatform.sync.internal.config.ClusterConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; | void setRestApiService(IRestApiService restApi) {
this.restApiService = restApi;
}
void setThreadPoolService(IThreadPoolService tp) {
this.threadPoolService = tp;
}
IThreadPoolService getThreadPoolService() {
return this.threadPoolService;
}
public void setSwitchService(IOFSwitchService switchService) {
this.switchService = switchService;
}
public IOFSwitchService getSwitchService() {
return this.switchService;
}
@Override
public int getWorkerThreads() {
return this.workerThreads;
}
@Override
public HARole getRole() {
return notifiedRole;
}
@Override
public RoleInfo getRoleInfo() {
return roleManager.getRoleInfo();
}
@Override
public void setRole(HARole role, String changeDescription) {
roleManager.setRole(role, changeDescription);
}
// ****************
// Message handlers
// ****************
// Handler for SwitchPortsChanged was here (notifyPortChanged). Handled in OFSwitchManager
//处理交换机端口变化
/**
* flcontext_cache - Keep a thread local stack of contexts
* FloodlightContext缓存,持有一个本地线程上下文栈
*/
protected static final ThreadLocal<Stack<FloodlightContext>> flcontext_cache =
new ThreadLocal <Stack<FloodlightContext>> () {
@Override
protected Stack<FloodlightContext> initialValue() {
return new Stack<FloodlightContext>();
}
};
/**
* flcontext_alloc - pop a context off the stack, if required create a new one
* 从栈顶弹出一个上下文,如果有必要会创建一个新的
* @return FloodlightContext
*/
protected static FloodlightContext flcontext_alloc() {
FloodlightContext flcontext = null;
if (flcontext_cache.get().empty()) {
flcontext = new FloodlightContext();
}
else {
flcontext = flcontext_cache.get().pop();
}
return flcontext;
}
/**
* flcontext_free - Free the context to the current thread
* 在当前线程释放上下文
* @param flcontext
*/
protected void flcontext_free(FloodlightContext flcontext) {
flcontext.getStorage().clear();
flcontext_cache.get().push(flcontext);
}
/**
*
* Handle and dispatch a message to IOFMessageListeners.
* 处理,调度一个消息给IOFMessageListeners
* We only dispatch messages to listeners if the controller's role is MASTER.
* 我们只给是MASTER角色的控制器角度消息
* @param sw The switch sending the message 发送消息的交换机
* @param m The message the switch sent 消息
* @param flContext The floodlight context to use for this message. If
* null, a new context will be allocated.
* 使用这个消息的上下文,如果不存在将会被创建。
* @throws IOException
*
* FIXME: this method and the ChannelHandler disagree on which messages
* should be dispatched and which shouldn't
* 这个方法和ChannelHandler在哪个消息应该被调度上有分歧
*/
@LogMessageDocs({
@LogMessageDoc(level="ERROR",
message="Ignoring PacketIn (Xid = {xid}) because the data" +
" field is empty.",
explanation="The switch sent an improperly-formatted PacketIn" +
" message",
recommendation=LogMessageDoc.CHECK_SWITCH),
@LogMessageDoc(level="WARN",
message="Unhandled OF Message: {} from {}",
explanation="The switch sent a message not handled by " +
"the controller")
})
@SuppressFBWarnings(value="SF_SWITCH_NO_DEFAULT",
justification="False positive -- has default")
@Override | public void handleMessage(IOFSwitch sw, OFMessage m, | 2 |
tomdw/java-modules-context-boot | integration-tests/src/main/java/module-info.java | [
"@Configuration\n@Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class})\npublic class IntegrationTestConfiguration {\n\n}",
"public interface FailingSpeakerService {\n\n\tString getSpeakerNameButThrowsRuntimeException();\n\n\tString getSpeakerNameButThrowsCheckedExc... | import io.github.tomdw.java.modules.context.boot.api.ModuleContext;
import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration;
import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService;
import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService;
import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService;
import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; |
@ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class)
module io.github.tomdw.java.modules.spring.integration.tests {
requires io.github.tomdw.java.modules.context.boot;
requires io.github.tomdw.java.modules.spring.samples.basicapplication.application;
requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker;
uses SpeakerService; | uses MultipleSpeakerService; | 2 |
onesocialweb/osw-openfire-plugin | src/java/org/onesocialweb/openfire/handler/MessageEventInterceptor.java | [
"@SuppressWarnings(\"serial\")\npublic class AccessDeniedException extends Exception {\n\n\tpublic AccessDeniedException(String message) {\n\t\tsuper(message);\n\t}\n\t\n}",
"@SuppressWarnings(\"serial\")\npublic class InvalidRelationException extends Exception {\n\n\tpublic InvalidRelationException(String messag... | import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.activity.InvalidActivityException;
import org.dom4j.Element;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.interceptor.PacketInterceptor;
import org.jivesoftware.openfire.interceptor.PacketRejectedException;
import org.jivesoftware.openfire.session.ClientSession;
import org.jivesoftware.openfire.session.Session;
import org.jivesoftware.util.Log;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.model.relation.Relation;
import org.onesocialweb.openfire.exception.AccessDeniedException;
import org.onesocialweb.openfire.exception.InvalidRelationException;
import org.onesocialweb.openfire.handler.activity.PEPActivityHandler;
import org.onesocialweb.openfire.manager.ActivityManager;
import org.onesocialweb.openfire.manager.RelationManager;
import org.onesocialweb.openfire.model.activity.PersistentActivityDomReader;
import org.onesocialweb.openfire.model.relation.PersistentRelationDomReader;
import org.onesocialweb.xml.dom.ActivityDomReader;
import org.onesocialweb.xml.dom.RelationDomReader;
import org.onesocialweb.xml.dom4j.ElementAdapter;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet; | /*
* Copyright 2010 Vodafone Group Services Ltd.
*
* 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.onesocialweb.openfire.handler;
public class MessageEventInterceptor implements PacketInterceptor {
private final XMPPServer server;
public MessageEventInterceptor() {
server = XMPPServer.getInstance();
}
@SuppressWarnings( { "deprecation", "unchecked" })
public void interceptPacket(Packet packet, Session session,
boolean incoming, boolean processed) throws PacketRejectedException {
// We only care for incoming Messages has not yet been processed
if (incoming && !processed && packet instanceof Message) {
final Message message = (Message) packet;
final JID fromJID = message.getFrom();
final JID toJID = message.getTo();
// We are only interested by message to bareJID (we don't touch the one sent to fullJID)
if (!toJID.toBareJID().equalsIgnoreCase(toJID.toString())) {
return;
}
// We only care for messaes to local users
if (!server.isLocal(toJID)
|| !server.getUserManager().isRegisteredUser(toJID)) {
return;
}
// We only bother about pubsub events
Element eventElement = message.getChildElement("event",
"http://jabber.org/protocol/pubsub#event");
if (eventElement == null) {
return;
}
// That contains items
Element itemsElement = eventElement.element("items");
if (itemsElement == null || itemsElement.attribute("node") == null)
return;
// Relating to the microblogging node
if (itemsElement.attribute("node").getValue().equals(
PEPActivityHandler.NODE)) {
Log.debug("Processing an activity event from " + fromJID
+ " to " + toJID);
final ActivityDomReader reader = new PersistentActivityDomReader();
List<Element> items=(List<Element>) itemsElement.elements("item");
if ((items!=null) && (items.size()!=0)){
for (Element itemElement :items) {
ActivityEntry activity = reader
.readEntry(new ElementAdapter(itemElement
.element("entry")));
try {
ActivityManager.getInstance().handleMessage(
fromJID.toBareJID(), toJID.toBareJID(),
activity);
} catch (InvalidActivityException e) {
throw new PacketRejectedException();
} catch (AccessDeniedException e) {
throw new PacketRejectedException();
}
}
} else if (itemsElement.element("retract")!=null)
{
Element retractElement = itemsElement.element("retract");
String activityId=reader.readActivityId(new ElementAdapter(retractElement));
ActivityManager.getInstance().deleteMessage(activityId);
}
Set<JID> recipientFullJIDs = getFullJIDs(toJID
.toBareJID());
Iterator<JID> it = recipientFullJIDs.iterator();
Message extendedMessage = message.createCopy();
while (it.hasNext()) {
String fullJid = it.next().toString();
extendedMessage.setTo(fullJid);
server.getMessageRouter().route(extendedMessage);
}
throw new PacketRejectedException();
}
// or a relation event
else if (itemsElement.attribute("node").getValue().equals(
RelationManager.NODE)) { | final RelationDomReader reader = new PersistentRelationDomReader(); | 6 |
sorinMD/MCTS | src/main/java/mcts/seeder/pdf/CatanTypePDFSeedTrigger.java | [
"public class GameFactory {\n\tpublic static final int TICTACTOE = 0;\n\tpublic static final int CATAN = 1;\n\t\n\tprivate GameConfig gameConfig;\n\tprivate Belief belief;\n\t\n\tpublic GameFactory(GameConfig gameConfig, Belief belief) {\n\t\tthis.gameConfig = gameConfig;\n\t\tthis.belief = belief;\n\t}\n\t\n\tpubl... | import java.util.ArrayList;
import java.util.Map;
import com.google.common.util.concurrent.AtomicDoubleArray;
import mcts.game.GameFactory;
import mcts.game.catan.Catan;
import mcts.game.catan.CatanConfig;
import mcts.game.catan.GameStateConstants;
import mcts.game.catan.typepdf.ActionTypePdf;
import mcts.game.catan.typepdf.UniformActionTypePdf;
import mcts.seeder.SeedTrigger;
import mcts.tree.node.StandardNode;
import mcts.tree.node.TreeNode; | package mcts.seeder.pdf;
/**
* This uses the typed pdf to seed in the tree without launching new threads.
*
* @author sorinMD
*
*/
public class CatanTypePDFSeedTrigger extends SeedTrigger implements GameStateConstants{
public ActionTypePdf pdf = new UniformActionTypePdf();
public CatanTypePDFSeedTrigger() {
// TODO Auto-generated constructor stub
}
@Override
public void addNode(TreeNode node, GameFactory factory) {
//no need to start a new thread just for this. Also no need to track what was already evaluated as this should be pretty quick
int task = getTaskIDFromState(node);
if(task == -1)
return;
Catan game = (Catan) factory.getGame(node.getState());
ArrayList<Integer> types = game.listNormalActionTypes();
Map<Integer,Double> dist = pdf.getDist(types);
//trades are A_TRADE in rollouts, but could be A_OFFER in tree, so handle this aspect here | if(((CatanConfig)factory.getConfig()).NEGOTIATIONS) { | 2 |
rolandkrueger/user-microservice | service/src/test/java/info/rolandkrueger/userservice/service/AuthenticationListenerTest.java | [
"@SpringBootApplication\n@PropertySource(\"userservice.properties\")\npublic class UserMicroserviceApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(\n new Object[]{\n UserMicroserviceApplication.class,\n Develop... | import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.api.model.UserApiData;
import info.rolandkrueger.userservice.api.service.AuthenticationListener;
import info.rolandkrueger.userservice.api.service.StaticEndpointProvider;
import info.rolandkrueger.userservice.testsupport.AbstractRestControllerTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue; | package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@WebIntegrationTest(randomPort = true)
public class AuthenticationListenerTest extends AbstractRestControllerTest {
private AuthenticationListener listener;
@Value("${local.server.port}")
private int port;
@Before
public void setUp() {
setPort(port);
deleteAllUsers();
deleteAllAuthorities();
listener = new AuthenticationListener(new StaticEndpointProvider("http://localhost:" + port));
registerUser("alice", "passw0rd", "alice@example.com");
}
@Test
public void testAuthenticationSuccess() { | UserApiData user = new UserApiData(); | 1 |
mutualmobile/Barricade | app/src/androidTest/java/com/mutualmobile/barricade/sample/BarricadeActivityTest.java | [
"public class Barricade {\n static final String TAG = \"Barricade\";\n private static final String ROOT_DIRECTORY = \"barricade\";\n private static final long DEFAULT_DELAY = 150;\n private static Barricade instance;\n\n private IBarricadeConfig barricadeConfig;\n private AssetFileManager fileManager;\n priv... | import androidx.test.InstrumentationRegistry;
import androidx.test.espresso.Espresso;
import androidx.test.espresso.contrib.RecyclerViewActions;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import com.mutualmobile.barricade.Barricade;
import com.mutualmobile.barricade.BarricadeConfig;
import com.mutualmobile.barricade.activity.BarricadeActivity;
import com.mutualmobile.barricade.response.BarricadeResponse;
import com.mutualmobile.barricade.response.BarricadeResponseSet;
import com.mutualmobile.barricade.utils.AndroidAssetFileManager;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static com.mutualmobile.barricade.sample.utils.RecyclerViewMatcher.withRecyclerView; | package com.mutualmobile.barricade.sample;
/**
* Contains Espresso tests for the Barricade Activity UI. We verify the response and it's corresponding response sets in the UI. Functionality of
* delay and reset is verified as well
*/
@RunWith(AndroidJUnit4.class) @LargeTest public class BarricadeActivityTest {
@Rule public ActivityTestRule<BarricadeActivity> activityTestRule = new ActivityTestRule<>(BarricadeActivity.class);
private static Barricade barricade;
@BeforeClass public static void setup() {
barricade = new Barricade.Builder(BarricadeConfig.getInstance(), new AndroidAssetFileManager(InstrumentationRegistry.getTargetContext())).
install();
}
@Test public void verifyEndpoints() {
int count = 0;
for (String endpoint : barricade.getConfig().keySet()) {
onView(withRecyclerView(com.mutualmobile.barricade.R.id.endpoint_rv).atPosition(count)).check(matches(hasDescendant(withText(endpoint))));
count++;
}
}
@Test public void verifyResponsesForEndpoints() {
int endpointCount = 0; | Map<String, BarricadeResponseSet> hashMap = barricade.getConfig(); | 3 |
turn/sorcerer | src/main/java/com/turn/sorcerer/pipeline/executable/impl/PipelineFactory.java | [
"public class SorcererInjector {\n\tprivate static final Logger logger =\n\t\t\tLoggerFactory.getLogger(SorcererInjector.class);\n\n\t// We use Guice as the underlying binder\n\tprivate Injector INJECTOR;\n\n\t/**\n\t * Singleton pattern. A single instance of Sorcerer runs per JVM.\n\t */\n\tprivate static Sorcerer... | import com.turn.sorcerer.injector.SorcererInjector;
import com.turn.sorcerer.pipeline.Pipeline;
import com.turn.sorcerer.pipeline.executable.ExecutablePipeline;
import com.turn.sorcerer.pipeline.impl.CronPipeline;
import com.turn.sorcerer.pipeline.impl.DefaultPipeline;
import com.turn.sorcerer.pipeline.type.PipelineType;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.pipeline.executable.impl;
/**
* Class Description Here
*
* @author tshiou
*/
public class PipelineFactory {
private static final Logger logger =
LoggerFactory.getLogger(PipelineFactory.class);
private static PipelineFactory INSTANCE = new PipelineFactory();
public static PipelineFactory get() {
return INSTANCE;
}
private Table<String, Integer, ExecutablePipeline> pipelineInstances = HashBasedTable.create();
private PipelineFactory() {
}
public Pipeline getPipeline(PipelineType type) {
if (type.getCronString() != null && type.getCronString().length() > 0) {
return new CronPipeline(type.getCronString());
}
if (SorcererInjector.get().bindingExists(type)) {
return SorcererInjector.get().getInstance(type);
}
| return new DefaultPipeline(type); | 4 |
Modbder/ThaumicBases | java/tb/init/TBTiles.java | [
"public class TileAuraLinker extends TileEntity implements IWandable,ITickable{\n\t\n\tpublic Coord3D linkCoord;\n\tpublic int syncTimer;\n\tpublic int instability;\n\tObject beam;\n\t@Override\n\tpublic void update() {\n\t\t\n\t\tif(syncTimer <= 0)\n\t\t{\n\t\t\tsyncTimer = 100;\n\t\t\tNBTTagCompound tg = new NBTT... | import net.minecraftforge.fml.common.registry.GameRegistry;
import tb.common.tile.TileAuraLinker;
import tb.common.tile.TileBraizer;
import tb.common.tile.TileCampfire;
import tb.common.tile.TileNodeManipulator;
import tb.common.tile.TileOverchanter; | package tb.init;
public class TBTiles {
public static void setup()
{
GameRegistry.registerTileEntity(TileOverchanter.class, "tb.overchanter");
GameRegistry.registerTileEntity(TileCampfire.class, "tb.campfire"); | GameRegistry.registerTileEntity(TileBraizer.class, "tb.brazier"); | 1 |
tavianator/sangria | sangria-listbinder/src/main/java/com/tavianator/sangria/listbinder/ListBinder.java | [
"public abstract class PotentialAnnotation {\n /**\n * A visitor interface to examine a {@link PotentialAnnotation}'s annotation, if it exists.\n *\n * @param <T> The type to return.\n * @author Tavian Barnes (tavianator@tavianator.com)\n * @version 1.1\n * @since 1.1\n */\n public... | import java.lang.annotation.Annotation;
import java.util.*;
import javax.inject.Inject;
import javax.inject.Provider;
import com.google.common.base.Function;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ListMultimap;
import com.google.inject.AbstractModule;
import com.google.inject.Binder;
import com.google.inject.CreationException;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.spi.Message;
import com.google.inject.util.Types;
import com.tavianator.sangria.core.PotentialAnnotation;
import com.tavianator.sangria.core.PrettyTypes;
import com.tavianator.sangria.core.Priority;
import com.tavianator.sangria.core.TypeLiterals;
import com.tavianator.sangria.core.UniqueAnnotations; | /****************************************************************************
* Sangria *
* Copyright (C) 2014 Tavian Barnes <tavianator@tavianator.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.tavianator.sangria.listbinder;
/**
* A multi-binder with guaranteed order.
*
* <p>
* {@link ListBinder} is much like {@link Multibinder}, except it provides a guaranteed iteration order, and binds a
* {@link List} instead of a {@link Set}. For example:
* </p>
*
* <pre>
* ListBinder<String> listBinder = ListBinder.build(binder(), String.class)
* .withDefaultPriority();
* listBinder.addBinding().toInstance("a");
* listBinder.addBinding().toInstance("b");
* </pre>
*
* <p>
* This will create a binding for a {@code List<String>}, which contains {@code "a"} followed by {@code "b"}. It also
* creates a binding for {@code List<Provider<String>>} — this may be useful in more advanced cases to allow list
* elements to be lazily loaded.
* </p>
*
* <p>To add an annotation to the list binding, simply write this:</p>
*
* <pre>
* ListBinder<String> listBinder = ListBinder.build(binder(), String.class)
* .annotatedWith(Names.named("name"))
* .withDefaultPriority();
* </pre>
*
* <p>
* and the created binding will be {@code @Named("name") List<String>} instead.
* </p>
*
* <p>
* For large lists, it may be helpful to split up their specification across different modules. This is accomplished by
* specifying <em>priorities</em> for the {@link ListBinder}s when they are created. For example:
* </p>
*
* <pre>
* // In some module
* ListBinder<String> listBinder1 = ListBinder.build(binder(), String.class)
* .withPriority(0);
* listBinder1.addBinding().toInstance("a");
* listBinder1.addBinding().toInstance("b");
*
* // ... some other module
* ListBinder<String> listBinder2 = ListBinder.build(binder(), String.class)
* .withPriority(1);
* listBinder2.addBinding().toInstance("c");
* listBinder2.addBinding().toInstance("d");
* </pre>
*
* <p>
* The generated list will contain {@code "a"}, {@code "b"}, {@code "c"}, {@code "d"}, in order. This happens because
* the first {@link ListBinder} had a smaller priority, so its entries come first. For more information about the
* priority system, see {@link Priority}.
* </p>
*
* @param <T> The type of the list element.
* @author Tavian Barnes (tavianator@tavianator.com)
* @version 1.1
* @since 1.1
*/
public class ListBinder<T> {
private static final Class<?>[] SKIPPED_SOURCES = {
ListBinder.class,
BuilderImpl.class,
};
private final Binder binder;
private final Multibinder<ListElement<T>> multibinder;
private final Multibinder<ListBinderErrors<T>> errorMultibinder;
private final TypeLiteral<T> entryType;
private final Key<List<T>> listKey;
private final Key<List<Provider<T>>> listOfProvidersKey;
private final Key<Set<ListElement<T>>> setKey;
private final Key<Set<ListBinderErrors<T>>> errorSetKey;
private final PotentialAnnotation potentialAnnotation; | private final Priority initialPriority; | 2 |
MX-Futhark/hook-any-text | src/main/java/hextostring/convert/EncodingAgnosticConverter.java | [
"public class DebuggableDecodingAttempt {\n\n\tprivate DebuggableLineList attempt;\n\tprivate Charset encoding;\n\tprivate EvaluationResult encodingEvaluationResult;\n\tprivate boolean validEncoding = false;\n\n\tpublic DebuggableDecodingAttempt(DebuggableLineList attempt,\n\t\tCharset encoding) {\n\n\t\tthis.attem... | import hextostring.debug.DebuggableDecodingAttempt;
import hextostring.debug.DebuggableDecodingAttemptList;
import hextostring.debug.DebuggableLineList;
import hextostring.debug.DebuggableStrings;
import hextostring.evaluate.EvaluationResult;
import hextostring.evaluate.EvaluatorFactory;
import hextostring.evaluate.encoding.EncodingEvaluator;
import hextostring.replacement.Replacements;
import hextostring.utils.Charsets; | package hextostring.convert;
/**
* Converter choosing the right encoding by itself.
*
* @author Maxime PIA
*/
public class EncodingAgnosticConverter implements Converter {
private AbstractConverter[] converters = {
(AbstractConverter)
ConverterFactory.getConverterInstance(Charsets.SHIFT_JIS, null),
(AbstractConverter)
ConverterFactory.getConverterInstance(Charsets.UTF16_BE, null),
(AbstractConverter)
ConverterFactory.getConverterInstance(Charsets.UTF16_LE, null),
(AbstractConverter)
ConverterFactory.getConverterInstance(Charsets.UTF8, null)
};
private EncodingEvaluator encodingEvaluator =
EvaluatorFactory.getEncodingEvaluatorInstance();
@Override
public DebuggableStrings convert(String hex) {
boolean encodingFound = false;
int maxValidity = 0;
DebuggableDecodingAttemptList allAttempts =
new DebuggableDecodingAttemptList();
DebuggableDecodingAttempt validAttempt = null;
for (AbstractConverter c : converters) {
DebuggableLineList lines = c.convert(hex);
DebuggableDecodingAttempt currentAttempt =
new DebuggableDecodingAttempt(lines, c.getCharset());
| EvaluationResult encodingEvaluationResult = | 4 |
mokies/ratelimitj | ratelimitj-aerospike/src/test/java/es/moki/aerospike/request/AerospikeSlidingWindowRequestRateLimiterPerformanceTest.java | [
"public class AerospikeClientFactory {\n\n public static AerospikeClient getAerospikeClient() {\n\n Policy readPolicy = new Policy();\n readPolicy.maxRetries = 1;\n readPolicy.readModeAP = ReadModeAP.ONE;\n readPolicy.replica = Replica.MASTER_PROLES;\n readPolicy.sleepBetweenRetries = 5;\n readPo... | import com.aerospike.client.AerospikeClient;
import es.moki.aerospike.extensions.AerospikeClientFactory;
import es.moki.ratelimitj.aerospike.request.AerospikeContext;
import es.moki.ratelimitj.aerospike.request.AerospikeSlidingWindowRateLimiter;
import es.moki.ratelimitj.core.limiter.request.RequestLimitRule;
import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter;
import es.moki.ratelimitj.core.time.TimeSupplier;
import es.moki.ratelimitj.test.limiter.request.AbstractSyncRequestRateLimiterPerformanceTest;
import java.util.Set;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; | package es.moki.aerospike.request;
public class AerospikeSlidingWindowRequestRateLimiterPerformanceTest extends AbstractSyncRequestRateLimiterPerformanceTest {
private static AerospikeContext aerospikeContext;
@AfterAll
static void afterAll() {
aerospikeContext.aerospikeClient.close();
}
@BeforeAll
static void beforeAll() { | AerospikeClient aerospikeClient = AerospikeClientFactory.getAerospikeClient(); | 0 |
larusba/neo4j-jdbc | neo4j-jdbc-http/src/main/java/org/neo4j/jdbc/http/HttpNeo4jConnection.java | [
"public class CypherExecutor {\n\n\t/**\n\t * URL of the transaction endpoint.\n\t */\n\tfinal String transactionUrl;\n\n\t/**\n\t * If we are in https or not.\n\t */\n\tprivate Boolean secure;\n\n\t/**\n\t * Autocommit transaction.\n\t * Must be null at creation time.\n\t * Initiation of this property is made by i... | import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.neo4j.jdbc.*;
import org.neo4j.jdbc.http.driver.CypherExecutor;
import org.neo4j.jdbc.http.driver.Neo4jResponse;
import org.neo4j.jdbc.http.driver.Neo4jStatement;
import org.neo4j.jdbc.impl.Neo4jConnectionImpl;
import org.neo4j.jdbc.utils.ExceptionBuilder;
import org.neo4j.jdbc.utils.Neo4jJdbcRuntimeException;
import org.neo4j.jdbc.utils.TimeLimitedCodeBlock;
import java.sql.PreparedStatement;
import java.sql.SQLException; | /*
* Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it]
* <p>
* This file is part of the "LARUS Integration Framework for Neo4j".
* <p>
* The "LARUS Integration Framework for Neo4j" is licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* <p>
* Created on 15/4/2016
*/
package org.neo4j.jdbc.http;
public class HttpNeo4jConnection extends Neo4jConnectionImpl implements Loggable {
CypherExecutor executor;
private boolean isClosed = false;
private boolean debug = false;
private int debugLevel;
/**
* Default constructor.
*
* @param host Hostname of the Neo4j instance.
* @param port HTTP port of the Neo4j instance.
* @param secure Secure
* @param properties Properties of the url connection.
* @param url Url
* @throws SQLException sqlexption
*/
public HttpNeo4jConnection(String host, Integer port, Boolean secure, Properties properties, String url) throws SQLException {
super(properties, url, Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT);
this.executor = new CypherExecutor(host, port, secure, properties);
}
/**
* Execute a cypher query.
*
* @param queries List of cypher queries
* @param parameters Parameter of the cypher queries (match by index)
* @param stats Do we need to include stats ?
* @return ...
* @throws SQLException sqlexception
*/
public Neo4jResponse executeQueries(final List<String> queries, List<Map<String, Object>> parameters, Boolean stats) throws SQLException {
checkClosed();
if(queries.size() != parameters.size()) {
throw new SQLException("Query and parameter list haven't the same cardinality");
}
| List<Neo4jStatement> neo4jStatements = new ArrayList<>(); | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.