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 |
|---|---|---|---|---|---|---|
apache/geronimo-gshell | gshell-core/src/main/java/org/apache/geronimo/gshell/builtins/ExitCommand.java | [
"public abstract class CommandSupport\n implements Command\n{\n protected Log log;\n\n private String name;\n\n private CommandContext context;\n\n protected CommandSupport(final String name) {\n setName(name);\n }\n\n /**\n * Sub-class <b>must</b> call {@link #setName(String)}.\n ... | import org.apache.commons.cli.CommandLine;
import org.apache.geronimo.gshell.command.CommandSupport;
import org.apache.geronimo.gshell.command.MessageSource;
import org.apache.geronimo.gshell.command.CommandException;
import org.apache.geronimo.gshell.console.IO;
import org.apache.geronimo.gshell.ExitNotification;
import org.apache.geronimo.gshell.util.Arguments; | /*
* 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.geronimo.gshell.builtins;
/**
* Exit the current shell.
*
* @version $Rev$ $Date$
*/
public class ExitCommand
extends CommandSupport
{
private int exitCode = 0;
public ExitCommand() {
super("exit");
}
protected String getUsage() {
return super.getUsage() + " [code]";
}
protected boolean processCommandLine(final CommandLine line) throws CommandException {
assert line != null;
String[] args = line.getArgs();
IO io = getIO();
MessageSource messages = getMessageSource();
if (args.length > 1) {
io.err.println(messages.getMessage("info.unexpected_args", Arguments.asString(args)));
io.err.println();
return true;
}
if (args.length == 1) {
exitCode = Integer.parseInt(args[0]);
}
return false;
}
protected Object doExecute(Object[] args) throws Exception {
assert args != null;
log.info("Exiting w/code: " + exitCode);
//
// DO NOT Call System.exit() !!!
//
| throw new ExitNotification(exitCode); | 4 |
mercyblitz/confucius-commons | confucius-commons-lang/src/main/java/org/confucius/commons/lang/ClassUtils.java | [
"public interface Constants {\n\n /**\n * Dot : \".\"\n */\n String DOT = \".\";\n\n /**\n * Class : \"class\"\n */\n String CLASS = \"class\";\n\n /**\n * And : \"&\"\n */\n String AND = \"&\";\n\n /**\n * Equal : \"=\"\n */\n String EQUAL = \"=\";\n}",
"pu... | import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.confucius.commons.lang.constants.Constants;
import org.confucius.commons.lang.constants.FileSuffixConstants;
import org.confucius.commons.lang.constants.PathConstants;
import org.confucius.commons.lang.filter.ClassFileJarEntryFilter;
import org.confucius.commons.lang.io.FileUtils;
import org.confucius.commons.lang.io.scanner.SimpleFileScanner;
import org.confucius.commons.lang.io.scanner.SimpleJarEntryScanner;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; | /**
* Find class path under specified class name
*
* @param type
* class
* @return class path
*/
@Nullable
public static String findClassPath(Class<?> type) {
return findClassPath(type.getName());
}
/**
* Find class path under specified class name
*
* @param className
* class name
* @return class path
*/
@Nullable
public static String findClassPath(String className) {
return classNameToClassPathsMap.get(className);
}
/**
* Gets class name {@link Set} under specified class path
*
* @param classPath
* class path
* @param recursive
* is recursive on sub directories
* @return non-null {@link Set}
*/
@Nonnull
public static Set<String> getClassNamesInClassPath(String classPath, boolean recursive) {
Set<String> classNames = classPathToClassNamesMap.get(classPath);
if (CollectionUtils.isEmpty(classNames)) {
classNames = findClassNamesInClassPath(classPath, recursive);
}
return classNames;
}
/**
* Gets class name {@link Set} under specified package
*
* @param onePackage
* one package
* @return non-null {@link Set}
*/
@Nonnull
public static Set<String> getClassNamesInPackage(Package onePackage) {
return getClassNamesInPackage(onePackage.getName());
}
/**
* Gets class name {@link Set} under specified package name
*
* @param packageName
* package name
* @return non-null {@link Set}
*/
@Nonnull
public static Set<String> getClassNamesInPackage(String packageName) {
Set<String> classNames = packageNameToClassNamesMap.get(packageName);
return classNames == null ? Collections.<String>emptySet() : classNames;
}
protected static Set<String> findClassNamesInDirectory(File classesDirectory, boolean recursive) {
Set<String> classNames = Sets.newLinkedHashSet();
SimpleFileScanner simpleFileScanner = SimpleFileScanner.INSTANCE;
Set<File> classFiles = simpleFileScanner.scan(classesDirectory, recursive, new SuffixFileFilter(FileSuffixConstants.CLASS));
for (File classFile : classFiles) {
String className = resolveClassName(classesDirectory, classFile);
classNames.add(className);
}
return classNames;
}
protected static Set<String> findClassNamesInJarFile(File jarFile, boolean recursive) {
if (!jarFile.exists()) {
return Collections.emptySet();
}
Set<String> classNames = Sets.newLinkedHashSet();
SimpleJarEntryScanner simpleJarEntryScanner = SimpleJarEntryScanner.INSTANCE;
try {
JarFile jarFile_ = new JarFile(jarFile);
Set<JarEntry> jarEntries = simpleJarEntryScanner.scan(jarFile_, recursive, ClassFileJarEntryFilter.INSTANCE);
for (JarEntry jarEntry : jarEntries) {
String jarEntryName = jarEntry.getName();
String className = resolveClassName(jarEntryName);
if (StringUtils.isNotBlank(className)) {
classNames.add(className);
}
}
} catch (Exception e) {
}
return classNames;
}
protected static String resolveClassName(File classesDirectory, File classFile) {
String classFileRelativePath = FileUtils.resolveRelativePath(classesDirectory, classFile);
return resolveClassName(classFileRelativePath);
}
/**
* Resolve resource name to class name
*
* @param resourceName
* resource name
* @return class name
*/
public static String resolveClassName(String resourceName) { | String className = StringUtils.replace(resourceName, PathConstants.SLASH, Constants.DOT); | 2 |
TechzoneMC/NPCLib | nms-v1_8_R1/src/main/java/net/techcable/npclib/nms/versions/v1_8_R1/NMS.java | [
"public interface HumanNPC extends LivingNPC {\r\n\r\n /**\r\n * Return this npc's skin\r\n * <p/>\r\n * A value of null represents a steve skin\r\n *\r\n * @return this npc's skin\r\n */\r\n public UUID getSkin();\r\n\r\n /**\r\n * Set the npc's skin\r\n * <p/>\r\n * A ... | import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.mojang.authlib.GameProfile;
import net.minecraft.server.v1_8_R1.EntityLiving;
import net.minecraft.server.v1_8_R1.EntityPlayer;
import net.minecraft.server.v1_8_R1.MinecraftServer;
import net.minecraft.server.v1_8_R1.Packet;
import net.minecraft.server.v1_8_R1.WorldServer;
import net.techcable.npclib.HumanNPC;
import net.techcable.npclib.LivingNPC;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.IHumanNPCHook;
import net.techcable.npclib.nms.ILivingNPCHook;
import net.techcable.npclib.nms.versions.v1_8_R1.LivingNPCHook.LivingHookable;
import net.techcable.npclib.nms.versions.v1_8_R1.entity.EntityNPCPlayer;
import net.techcable.npclib.utils.NPCLog;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_8_R1.CraftServer;
import org.bukkit.craftbukkit.v1_8_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_8_R1.entity.CraftLivingEntity;
import org.bukkit.craftbukkit.v1_8_R1.entity.CraftPlayer;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; | package net.techcable.npclib.nms.versions.v1_8_R1;
public class NMS implements net.techcable.npclib.nms.NMS {
private static NMS instance;
public NMS() {
if (instance == null) instance = this;
}
public static NMS getInstance() {
return instance;
}
@Override
public IHumanNPCHook spawnHumanNPC(Location toSpawn, HumanNPC npc) {
return new HumanNPCHook(npc, toSpawn);
}
@Override
public void onJoin(Player joined, Collection<? extends NPC> npcs) {
for (NPC npc : npcs) {
if (!(npc instanceof HumanNPC)) continue;
HumanNPCHook hook = getHook((HumanNPC) npc);
if (hook == null) continue;
hook.onJoin(joined);
}
}
// UTILS
public static final String NO_CRAFTBUKKIT_MSG = "Non-CraftBukkit implementations are unsupported";
public static EntityPlayer getHandle(Player player) {
if (!(player instanceof CraftPlayer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
return ((CraftPlayer) player).getHandle();
}
public static EntityLiving getHandle(LivingEntity player) {
if (!(player instanceof CraftLivingEntity)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
return ((CraftLivingEntity) player).getHandle();
}
public static MinecraftServer getServer() {
Server server = Bukkit.getServer();
if (!(server instanceof CraftServer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
return ((CraftServer) server).getServer();
}
public static WorldServer getHandle(World world) {
if (!(world instanceof CraftWorld)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
return ((CraftWorld) world).getHandle();
}
public static HumanNPCHook getHook(HumanNPC npc) {
EntityPlayer player = getHandle(npc.getEntity());
if (player instanceof EntityNPCPlayer) return null;
return ((EntityNPCPlayer) player).getHook();
}
public static LivingNPCHook getHook(LivingNPC npc) {
if (npc instanceof HumanNPC) return getHook((HumanNPC) npc);
EntityLiving entity = getHandle(npc.getEntity());
if (entity instanceof LivingHookable) return ((LivingHookable) entity).getHook();
return null;
}
public static void sendToAll(Packet packet) {
for (Player p : Bukkit.getOnlinePlayers()) {
getHandle(p).playerConnection.sendPacket(packet);
}
}
private static final LoadingCache<UUID, GameProfile> properties = CacheBuilder.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build(new CacheLoader<UUID, GameProfile>() {
@Override
public GameProfile load(UUID uuid) throws Exception {
return MinecraftServer.getServer().aB().fillProfileProperties(new GameProfile(uuid, null), true);
}
});
public static void setSkin(GameProfile profile, UUID skinId) {
GameProfile skinProfile;
if (Bukkit.getPlayer(skinId) != null) {
skinProfile = getHandle(Bukkit.getPlayer(skinId)).getProfile();
} else {
skinProfile = properties.getUnchecked(skinId);
}
if (skinProfile.getProperties().containsKey("textures")) {
profile.getProperties().removeAll("textures");
profile.getProperties().putAll("textures", skinProfile.getProperties().get("textures"));
} else { | NPCLog.debug("Skin with uuid not found: " + skinId); | 7 |
idega/com.idega.block.datareport | src/java/com/idega/block/datareport/business/JasperReportBusinessBean.java | [
"public class DesignBox {\n\t\n\tpublic static final String REPORT_HEADLINE_KEY = \"ReportTitle\";\n\t\n\tprivate JasperDesign design;\n\t\n\tprivate Map parameterMap;\n\n\t/**\n\t * @return Returns the design.\n\t */\n\tpublic JasperDesign getDesign() {\n\t\treturn this.design;\n\t}\n\n\t/**\n\t * @param design Th... | import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ejb.CreateException;
import javax.ejb.RemoveException;
import net.sf.jasperreports.engine.JRBand;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import com.idega.block.dataquery.data.QueryResult;
import com.idega.block.dataquery.data.QueryResultField;
import com.idega.block.dataquery.data.sql.DirectSQLStatement;
import com.idega.block.dataquery.data.sql.InputDescription;
import com.idega.block.dataquery.data.sql.SQLQuery;
import com.idega.block.dataquery.data.xml.QueryFieldPart;
import com.idega.block.datareport.data.DesignBox;
import com.idega.block.datareport.presentation.ReportOverviewWindowPlugin;
import com.idega.block.datareport.util.ReportDescription;
import com.idega.block.datareport.util.ReportableCollection;
import com.idega.block.datareport.util.ReportableField;
import com.idega.business.IBOLookup;
import com.idega.business.IBOLookupException;
import com.idega.business.IBOServiceBean;
import com.idega.business.InputHandler;
import com.idega.core.file.data.ICFile;
import com.idega.core.file.data.ICFileHome;
import com.idega.data.IDOLookup;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWCacheManager;
import com.idega.idegaweb.IWMainApplication;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.IWContext;
import com.idega.presentation.PresentationObject;
import com.idega.repository.data.RefactorClassRegistry;
import com.idega.user.business.UserGroupPlugInBusiness;
import com.idega.user.data.Group;
import com.idega.user.data.User;
import com.idega.util.FileUtil;
import com.idega.util.StringHandler; | package com.idega.block.datareport.business;
/**
* <p>Title: idegaWeb</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: idega Software</p>
* @author <a href="thomas@idega.is">Thomas Hilbig</a>
* @version 1.0
* Created on Jun 10, 2003
*/
public class JasperReportBusinessBean extends IBOServiceBean implements JasperReportBusiness,UserGroupPlugInBusiness {
private static String REPORT_FOLDER = "reports";
private static String HTML_FILE_EXTENSION = "html";
private static String XML_FILE_EXTENSION = "xml";
private static String PDF_FILE_EXTENSION = "pdf";
private static String EXCEL_FILE_EXTENSION = "xls";
private static String REPORT_COLUMN_PARAMETER_NAME = "Column_";
private static char DOT = '.';
public JasperPrint getReport(JRDataSource dataSource, Map parameterMap, JasperDesign design) throws JRException {
//System.out.println("JASPERREPORT: "+parameterMap.toString());
JasperReport report = JasperManager.compileReport(design);
return JasperFillManager.fillReport(report, parameterMap, dataSource);
}
private void synchronizeAndReset(QueryResult dataSource, DesignBox designBox) {
synchronizeResultAndDesign(dataSource, designBox);
// henceforth we treat the QueryResult as a JRDataSource,
// therefore we reset the QueryResult to prepare it
dataSource.resetDataSource(); // resets only the DataSource functionality (sets the pointer to the first row)
}
public JasperPrint printSynchronizedReport(QueryResult dataSource, DesignBox designBox) {
synchronizeAndReset(dataSource, designBox);
JasperPrint print = null;
try {
Map map = designBox.getParameterMap();
JasperDesign design = designBox.getDesign();
print = getReport(dataSource, map, design);
}
catch (JRException ex) {
logError("[ReportBusiness]: Jasper print could not be generated.");
log(ex);
return null;
}
return print;
}
public String getHtmlReport(JasperPrint print, String nameOfReport) {
// prepare path
long folderIdentifier = System.currentTimeMillis();
String path = getRealPathToReportFile(nameOfReport, HTML_FILE_EXTENSION,folderIdentifier);
try {
JasperExportManager.exportReportToHtmlFile(print, path);
/* Not needed since jasper 0.5 if you use utf-8
* UNLESS APACHE ALWAYS OUTPUTS ISO AS THE ENCODING
*/
JRHtmlExporter exporter = new JRHtmlExporter();
//to handle icelandic in html
//saw this in the JRHTMLExport of jasperreports
String enc = getIWMainApplication().getSettings().getCharacterEncoding();
if (enc == null) {
enc = "UTF-8";
}
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING,enc);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, path);
exporter.exportReport();
}
catch (JRException ex) {
logError("[ReportBusiness]: Jasper print could not be generated.");
log(ex);
return null;
}
return getURIToReport(nameOfReport, HTML_FILE_EXTENSION,folderIdentifier);
}
public String getXmlReport(JasperPrint print, String nameOfReport) {
// prepare path
long folderIdentifier = System.currentTimeMillis();
String path = getRealPathToReportFile(nameOfReport, XML_FILE_EXTENSION,folderIdentifier);
try {
JasperExportManager.exportReportToXmlFile(print, path, false);
}
catch (JRException ex) {
logError("[ReportBusiness]: Jasper print could not be generated.");
log(ex);
return null;
}
return getURIToReport(nameOfReport, XML_FILE_EXTENSION,folderIdentifier);
}
public String getPdfReport(JasperPrint print, String nameOfReport) {
// prepare path
long folderIdentifier = System.currentTimeMillis();
String path = getRealPathToReportFile(nameOfReport, PDF_FILE_EXTENSION,folderIdentifier);
try {
JasperExportManager.exportReportToPdfFile(print, path);
}
catch (JRException ex) {
logError("[ReportBusiness]: Jasper print could not be generated.");
log(ex);
return null;
}
return getURIToReport(nameOfReport, PDF_FILE_EXTENSION,folderIdentifier);
}
public String getExcelReport(JasperPrint print, String nameOfReport) {
// prepare path
long folderIdentifier = System.currentTimeMillis();
String path = getRealPathToReportFile(nameOfReport, EXCEL_FILE_EXTENSION,folderIdentifier);
// see samples of the jasper download package
try {
JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, path);
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
exporter.exportReport();
}
catch (JRException ex) {
logError("[ReportBusiness]: Jasper print could not be generated.");
log(ex);
return null;
}
return getURIToReport(nameOfReport, EXCEL_FILE_EXTENSION,folderIdentifier);
}
public String getSynchronizedSimpleExcelReport(QueryResult dataSource, DesignBox designBox, String nameOfReport) {
synchronizeAndReset(dataSource, designBox);
Map designerMap = designBox.getParameterMap();
ReportDescription reportDescription = new ReportDescription();
Iterator iterator = designBox.getDesign().getFieldsList().iterator();
int columnNumber = 1;
while (iterator.hasNext()) {
JRField jrField = (JRField) iterator.next();
String designFieldId = jrField.getName(); | ReportableField reportField = new ReportableField(designFieldId, String.class); | 4 |
tabulapdf/tabula-web-java | src/main/java/technology/tabula/tabula_web/routes/ExtractDataRoute.java | [
"public class CoordSpec implements Comparable<CoordSpec> {\n\tpublic Integer page;\n\tpublic String extraction_method;\n\tpublic String selection_id;\n\tpublic float x1;\n\tpublic float x2;\n\tpublic float y1;\n\tpublic float y2;\n\tpublic float width;\n\tpublic float height;\n\tpublic int spec_index;\n\t\n\tpublic... | import java.io.ByteArrayOutputStream;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import spark.Request;
import spark.Response;
import spark.Route;
import technology.tabula.Cell;
import technology.tabula.RectangularTextContainer;
import technology.tabula.TextChunk;
import technology.tabula.json.TextChunkSerializer;
import technology.tabula.tabula_web.extractor.CoordSpec;
import technology.tabula.tabula_web.extractor.Extractor;
import technology.tabula.tabula_web.extractor.TableWithSpecIndex;
import technology.tabula.tabula_web.extractor.TableWithSpecIndexSerializer;
import technology.tabula.tabula_web.workspace.WorkspaceDAO;
import technology.tabula.writers.CSVWriter;
import technology.tabula.writers.TSVWriter; | package technology.tabula.tabula_web.routes;
public class ExtractDataRoute implements Route {
static class TableSerializerExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
@Override
public boolean shouldSkipField(FieldAttributes fa) {
return !fa.hasModifier(Modifier.PUBLIC);
}
}
private WorkspaceDAO workspaceDAO;
public ExtractDataRoute(WorkspaceDAO workspaceDAO) {
this.workspaceDAO = workspaceDAO;
}
@Override
public Object handle(Request request, Response response) throws Exception {
String requestedCoords = request.queryParams("coords");
Type targetClassType = new TypeToken<ArrayList<CoordSpec>>() {
}.getType();
ArrayList<CoordSpec> specs = new Gson().fromJson(requestedCoords, targetClassType);
// sort extraction specs by page number, then vertical position and then horizontal position
Collections.sort(specs);
int i = 0;
for (CoordSpec spec : specs) {
spec.spec_index = i++;
}
| List<TableWithSpecIndex> tables = Extractor.extractTables(this.workspaceDAO.getDocumentPath(request.params(":file_id")), specs); | 2 |
Anchormen/sql4es | src/main/java/nl/anchormen/sql4es/ESUpdateState.java | [
"public class BasicQueryState implements QueryState {\n\n\tprivate Heading heading;\n\tprivate Properties props;\n\tprivate String sql;\n\tprivate SQLException exception = null;\n\tprivate HashMap<String, Object> kvStore = new HashMap<String, Object>();\n\tprivate List<QuerySource> relations = new ArrayList<QuerySo... | import java.sql.Array;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.facebook.presto.sql.tree.*;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesResponse;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.facebook.presto.sql.parser.SqlParser;
import nl.anchormen.sql4es.model.BasicQueryState;
import nl.anchormen.sql4es.model.Column;
import nl.anchormen.sql4es.model.Heading;
import nl.anchormen.sql4es.model.QuerySource;
import nl.anchormen.sql4es.model.Utils;
import nl.anchormen.sql4es.parse.sql.RelationParser;
import nl.anchormen.sql4es.parse.sql.SelectParser;
import nl.anchormen.sql4es.parse.sql.UpdateParser;
import nl.anchormen.sql4es.parse.sql.WhereParser; | package nl.anchormen.sql4es;
/**
* Responsible for execution of update statements (CREATE, INSERT, DELETE).
* @author cversloot
*
*/
public class ESUpdateState {
private final UpdateParser updateParser = new UpdateParser();
private Client client;
private Properties props;
private List<String> bulkList = new ArrayList<String>();
private ESQueryState queryState;
private Statement statement;
private Pattern updateRegex = Pattern.compile("UPDATE\\s+(\\w+)\\.?(\\w+)?\\s+SET\\s+(.+)\\s+WHERE\\s+(.+)", Pattern.CASE_INSENSITIVE);
public ESUpdateState(Client client, Statement statement) throws SQLException{
this.client = client;
this.props = statement.getConnection().getClientInfo();
this.statement = statement;
this.queryState = new ESQueryState(client, statement);
}
/**
* Parses the given name to extract the type and optionally the index in format (index.)type.
* The case sensitive name is extracted from the sql using the provided prefix and suffix.
* @param name
* @param sql
* @param prefix
* @param suffix
* @param defaultIndex
* @return array {index, type} where index may be the default provided
*/
private String[] getIndexAndType(String name, String sql, String prefix, String suffix, String defaultIndex){ | String target = Heading.findOriginal(sql.trim()+";", name, prefix, suffix); | 2 |
Aleksey-Terzi/MerchantsTFC | src/com/aleksey/merchants/Helpers/WarehouseManager.java | [
"public class WarehouseBookInfo\n{\n public int X;\n public int Y;\n public int Z;\n public int Key;\n \n public static WarehouseBookInfo readFromNBT(NBTTagCompound nbt)\n {\n if(nbt == null)\n return null;\n \n WarehouseBookInfo info = new WarehouseBookInfo();\n... | import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import com.aleksey.merchants.Core.WarehouseBookInfo;
import com.aleksey.merchants.TileEntities.TileEntityWarehouse;
import com.aleksey.merchants.WarehouseContainers.BarrelContainer;
import com.aleksey.merchants.WarehouseContainers.ChestContainer;
import com.aleksey.merchants.WarehouseContainers.IngotPileContainer;
import com.aleksey.merchants.WarehouseContainers.LogPileContainer;
import com.aleksey.merchants.WarehouseContainers.ToolRackContainer;
import com.aleksey.merchants.api.IWarehouseContainer;
import com.aleksey.merchants.api.ItemTileEntity;
import com.aleksey.merchants.api.Point;
import com.aleksey.merchants.api.WarehouseContainerList;
import com.bioxx.tfc.Items.Pottery.ItemPotterySmallVessel;
import com.bioxx.tfc.api.Interfaces.IFood; | package com.aleksey.merchants.Helpers;
public class WarehouseManager
{
private static final int _searchContainerRadius = 3;
private static final int _searchWarehouseDistance = 10;
private ArrayList<Point> _containerLocations;
private Hashtable<String, Integer> _quantities;
private ItemStack _goodItemStack;
private ItemStack _payItemStack;
private ArrayList<ItemTileEntity> _goodList;
private ArrayList<ItemTileEntity> _payList;
public static void init()
{
WarehouseContainerList.addContainer(new ChestContainer());
WarehouseContainerList.addContainer(new LogPileContainer());
WarehouseContainerList.addContainer(new IngotPileContainer());
WarehouseContainerList.addContainer(new ToolRackContainer());
WarehouseContainerList.addContainer(new BarrelContainer());
}
public WarehouseManager()
{
_containerLocations = new ArrayList<Point>();
_quantities = new Hashtable<String, Integer>();
}
public int getContainers()
{
return _containerLocations.size();
}
public int getQuantity(ItemStack itemStack)
{
String itemKey = ItemHelper.getItemKey(itemStack);
return _quantities.containsKey(itemKey) ? _quantities.get(itemKey): 0;
}
public void confirmTrade(World world)
{
confirmTradeGoods(world);
String goodKey = ItemHelper.getItemKey(_goodItemStack);
_quantities.put(goodKey, _quantities.get(goodKey) - ItemHelper.getItemStackQuantity(_goodItemStack));
_goodList = null;
confirmTradePays(world);
String payKey = ItemHelper.getItemKey(_payItemStack);
int currentQuantity = _quantities.containsKey(payKey) ? _quantities.get(payKey): 0;
_quantities.put(payKey, currentQuantity + ItemHelper.getItemStackQuantity(_payItemStack));
_payList = null;
}
private void confirmTradeGoods(World world)
{
for(int i = 0; i < _goodList.size(); i++)
{
ItemTileEntity goodTileEntity = _goodList.get(i);
goodTileEntity.Container.confirmTradeGoods(world, goodTileEntity, _goodItemStack);
world.markBlockForUpdate(goodTileEntity.TileEntity.xCoord, goodTileEntity.TileEntity.yCoord, goodTileEntity.TileEntity.zCoord);
}
}
private void confirmTradePays(World world)
{
for(int i = 0; i < _payList.size(); i++)
{
ItemTileEntity payTileEntity = _payList.get(i);
payTileEntity.Container.confirmTradePays(world, payTileEntity, _payItemStack, _containerLocations);
world.markBlockForUpdate(payTileEntity.TileEntity.xCoord, payTileEntity.TileEntity.yCoord, payTileEntity.TileEntity.zCoord);
}
}
public PrepareTradeResult prepareTrade(ItemStack goodStack, ItemStack payStack, WarehouseBookInfo info, World world)
{
int goodQuantity = ItemHelper.getItemStackQuantity(goodStack);
int payQuantity = ItemHelper.getItemStackQuantity(payStack);
if(goodQuantity == 0 || getQuantity(goodStack) < goodQuantity)
return PrepareTradeResult.NoGoods;
_goodList = new ArrayList<ItemTileEntity>();
_payList = new ArrayList<ItemTileEntity>();
if(payStack.getItem() instanceof IFood)
{
for(int i = 0; i < _containerLocations.size() && payQuantity > 0; i++)
{
Point p = _containerLocations.get(i);
TileEntity tileEntity = world.getTileEntity(p.X, p.Y, p.Z);
IWarehouseContainer container = WarehouseContainerList.getContainer(tileEntity);
if(container != null)
payQuantity -= container.searchFreeSpaceInSmallVessels(tileEntity, payStack, payQuantity, _payList);
}
}
int extendLimitY = info.Y + _searchContainerRadius;
for(int i = 0; i < _containerLocations.size() && (goodQuantity > 0 || payQuantity > 0); i++)
{
Point p = _containerLocations.get(i);
TileEntity tileEntity = world.getTileEntity(p.X, p.Y, p.Z);
IWarehouseContainer container = WarehouseContainerList.getContainer(tileEntity);
if(container == null)
continue;
if(goodQuantity > 0)
goodQuantity -= container.searchItems(tileEntity, goodStack, goodQuantity, _goodList);
if(payQuantity > 0)
payQuantity -= container.searchFreeSpace(world, tileEntity, payStack, payQuantity, extendLimitY, _payList);
}
_goodItemStack = goodStack.copy();
_payItemStack = payStack.copy();
if(goodQuantity == 0 && payQuantity == 0)
return PrepareTradeResult.Success;
return goodQuantity > 0 ? PrepareTradeResult.NoGoods: PrepareTradeResult.NoPays;
}
public boolean existWarehouse(int stallX, int stallY, int stallZ, WarehouseBookInfo info, World world)
{
double distance = Math.sqrt(Math.pow(info.X - stallX, 2) + Math.pow(info.Y - stallY, 2) + Math.pow(info.Z - stallZ, 2));
if(distance > _searchWarehouseDistance)
return false;
TileEntity tileEntity = world.getTileEntity(info.X, info.Y, info.Z);
| return tileEntity instanceof TileEntityWarehouse && ((TileEntityWarehouse)tileEntity).getKey() == info.Key; | 1 |
pakoito/SongkickInterview | app/src/main/java/com/pacoworks/dereference/screens/songkicklist/SongkickListPresenter.java | [
"public abstract class ZimplBasePresenter<T extends IUi, U extends ZimpleBaseState> {\n private final Class<U> stateClass;\n\n private final List<Subscription> pauseSubscriptions = new ArrayList<>();\n\n private final List<Subscription> destroySubscriptions = new ArrayList<>();\n\n @Inject\n @Getter(... | import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import timber.log.Timber;
import com.github.pwittchen.reactivenetwork.library.ConnectivityStatus;
import com.pacoworks.dereference.BuildConfig;
import com.pacoworks.dereference.dependencies.skeleton.ZimplBasePresenter;
import com.pacoworks.dereference.model.Artist;
import com.pacoworks.dereference.model.SearchResult;
import com.pacoworks.dereference.network.EmptyResultException;
import com.pacoworks.dereference.network.SongkickApi;
import com.pacoworks.dereference.reactive.RxActions;
import com.pacoworks.dereference.reactive.RxLog;
import com.pacoworks.dereference.reactive.RxTuples;
import com.pacoworks.dereference.reactive.tuples.Tuple; | /*
* Copyright (c) pakoito 2015
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pacoworks.dereference.screens.songkicklist;
public class SongkickListPresenter extends ZimplBasePresenter<ISongkickListUI, SongkickListState> {
public static final int INPUT_DEBOUNCE_POLICY = 1;
public static final int CONNECTIVITY_DEBOUNCE_POLICY = 1;
public static final int MIN_SEARCH_POLICY = 2;
private static final int TIMEOUT_POLICY = 60;
private static final long SECOND_IN_NANOS = 1000000000l;
private static final long STALE_SECONDS = 60 * SECOND_IN_NANOS;
@Inject
Observable<ConnectivityStatus> connectivity;
@Inject
SongkickApi songkickApi;
public SongkickListPresenter() {
super(SongkickListState.class);
}
@Override
protected SongkickListState createNewState() {
return new SongkickListState();
}
@Override
public void create() {
}
@Override
public void resume() {
bindUntilPause(observeConnectivity(connectivity),
refreshData(songkickApi, TIMEOUT_POLICY, BuildConfig.API_KEY), handleClicks());
}
private Subscription observeConnectivity(Observable<ConnectivityStatus> connectivity) {
return connectivity.map(ConnectivityStatus.isEqualTo(ConnectivityStatus.OFFLINE))
.subscribe(getUi().showOfflineOverlay());
}
private Subscription refreshData(final SongkickApi songkickApi, final int timeoutPolicy,
final String apiKey) {
return Observable
.combineLatest(getProcessedConnectivityObservable(), getDebouncedSearchBoxInputs(),
RxTuples.<ConnectivityStatus, String> singleToTuple())
.observeOn(AndroidSchedulers.mainThread()).doOnNext(getUi().showLoading()) | .flatMap(new Func1<Tuple<ConnectivityStatus, String>, Observable<List<Artist>>>() { | 1 |
Nilhcem/devoxxfr-2016 | app/src/main/java/com/nilhcem/devoxxfr/ui/schedule/pager/SchedulePagerFragment.java | [
"@DebugLog\npublic class DevoxxApp extends Application {\n\n private AppComponent component;\n\n public static DevoxxApp get(Context context) {\n return (DevoxxApp) context.getApplicationContext();\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n AndroidThreeTen... | import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import com.hannesdorfmann.fragmentargs.annotation.Arg;
import com.hannesdorfmann.fragmentargs.annotation.FragmentWithArgs;
import com.nilhcem.devoxxfr.DevoxxApp;
import com.nilhcem.devoxxfr.R;
import com.nilhcem.devoxxfr.data.app.DataProvider;
import com.nilhcem.devoxxfr.data.app.model.Schedule;
import com.nilhcem.devoxxfr.ui.BaseFragment;
import com.nilhcem.devoxxfr.ui.drawer.DrawerActivity;
import javax.inject.Inject;
import butterknife.Bind; | package com.nilhcem.devoxxfr.ui.schedule.pager;
@FragmentWithArgs
public class SchedulePagerFragment extends BaseFragment<SchedulePagerPresenter> implements SchedulePagerView {
@Arg boolean allSessions;
| @Inject DataProvider dataProvider; | 1 |
common-workflow-language/cwlviewer | src/main/java/org/commonwl/view/cwl/CWLService.java | [
"public class DockerService {\n\n // URL validation for docker pull id\n private static final String DOCKERHUB_ID_REGEX = \"^([0-9a-z]{4,30})(?:\\\\/([a-zA-Z0-9_-]+))?(?:\\\\:[a-zA-Z0-9_-]+)?$\";\n private static final Pattern dockerhubPattern = Pattern.compile(DOCKERHUB_ID_REGEX);\n\n /**\n * Get a... | import static org.apache.commons.io.FileUtils.readFileToString;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.jena.iri.IRI;
import org.apache.jena.iri.IRIFactory;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.riot.RiotException;
import org.commonwl.view.docker.DockerService;
import org.commonwl.view.git.GitDetails;
import org.commonwl.view.graphviz.ModelDotWriter;
import org.commonwl.view.graphviz.RDFDotWriter;
import org.commonwl.view.workflow.Workflow;
import org.commonwl.view.workflow.WorkflowNotFoundException;
import org.commonwl.view.workflow.WorkflowOverview;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import org.yaml.snakeyaml.constructor.SafeConstructor; | /*
* 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.commonwl.view.cwl;
/**
* Provides CWL parsing for workflows to gather an overview
* for display and visualisation
*/
@Service
public class CWLService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final IRIFactory iriFactory = IRIFactory.iriImplementation();
// Autowired properties/services
private final RDFService rdfService;
private final CWLTool cwlTool;
private final int singleFileSizeLimit;
// CWL specific strings
private final String DOC_GRAPH = "$graph";
private final String CLASS = "class";
private final String WORKFLOW = "Workflow";
private final String COMMANDLINETOOL = "CommandLineTool";
private final String EXPRESSIONTOOL = "ExpressionTool";
private final String STEPS = "steps";
private final String INPUTS = "inputs";
private final String IN = "in";
private final String OUTPUTS = "outputs";
private final String OUT = "out";
private final String ID = "id";
private final String TYPE = "type";
private final String LABEL = "label";
private final String DEFAULT = "default";
private final String OUTPUT_SOURCE = "outputSource";
private final String SOURCE = "source";
private final String DOC = "doc";
private final String DESCRIPTION = "description";
private final String ARRAY = "array";
private final String ARRAY_ITEMS = "items";
private final String LOCATION = "location";
private final String RUN = "run";
/**
* Constructor for the Common Workflow Language service
* @param rdfService A service for handling RDF queries
* @param cwlTool Handles cwltool integration
* @param singleFileSizeLimit The file size limit for single files
*/
@Autowired
public CWLService(RDFService rdfService,
CWLTool cwlTool,
@Value("${singleFileSizeLimit}") int singleFileSizeLimit) {
this.rdfService = rdfService;
this.cwlTool = cwlTool;
this.singleFileSizeLimit = singleFileSizeLimit;
}
/**
* Gets whether a file is packed using schema salad
* @param workflowFile The file to be parsed
* @return Whether the file is packed
*/
public boolean isPacked(File workflowFile) throws IOException {
if (workflowFile.length() > singleFileSizeLimit) {
return false;
}
String fileContent = readFileToString(workflowFile);
return fileContent.contains("$graph");
}
/**
* Gets a list of workflows from a packed CWL file
* @param packedFile The packed CWL file
* @return The list of workflow overviews
*/ | public List<WorkflowOverview> getWorkflowOverviewsFromPacked(File packedFile) throws IOException { | 6 |
psycopaths/jconstraints | src/test/java/gov/nasa/jpf/constraints/expressions/functions/math/MathFunctionsTest.java | [
"public abstract class Expression<E> extends AbstractPrintable {\n \n \n public static final int QUOTE_IDENTIFIERS = 1;\n public static final int INCLUDE_VARIABLE_TYPE = 2;\n public static final int INCLUDE_BOUND_DECL_TYPE = 4;\n public static final int SIMPLE_PROP_OPERATORS = 8;\n \n public static final in... | import gov.nasa.jpf.constraints.api.Expression;
import gov.nasa.jpf.constraints.api.Valuation;
import gov.nasa.jpf.constraints.api.Variable;
import gov.nasa.jpf.constraints.expressions.NumericCompound;
import gov.nasa.jpf.constraints.expressions.NumericOperator;
import gov.nasa.jpf.constraints.expressions.functions.Function;
import gov.nasa.jpf.constraints.expressions.functions.FunctionExpression;
import gov.nasa.jpf.constraints.expressions.functions.math.MathFunctions;
import gov.nasa.jpf.constraints.types.BuiltinTypes;
import java.lang.reflect.Method;
import java.util.Random;
import org.testng.Assert;
import org.testng.annotations.Test; | /*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform 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 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 gov.nasa.jpf.constraints.expressions.functions.math;
@Test
public class MathFunctionsTest {
private static final Random random = new Random();
| private static final Variable<Double> VAR_X = Variable.create(BuiltinTypes.DOUBLE, "x"); | 8 |
jimdowling/nat-traverser | stun/stun-client/src/test/java/se/sics/gvod/stun/client/StunClientTest.java | [
"public class VodConfig extends BaseCommandLineConfig {\n\n private static final Logger logger = LoggerFactory.getLogger(VodConfig.class);\n public static boolean GUI = true;\n public static boolean CLOUD_HELPER = false;\n public static boolean OPEN_IP = false;\n public static final String TORRENT_FI... | import java.io.IOException;
import se.sics.gvod.config.StunServerConfiguration;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.sics.gvod.address.Address;
import se.sics.gvod.common.Self;
import se.sics.gvod.common.SelfNoParents;
import se.sics.gvod.common.util.ToVodAddr;
import se.sics.gvod.config.StunClientConfiguration;
import se.sics.gvod.config.VodConfig;
import se.sics.gvod.nat.common.PortInit;
import se.sics.gvod.nat.common.PortReservoirComp;
import se.sics.gvod.nat.emu.DistributedNatGatewayEmulator;
import se.sics.gvod.nat.emu.IpIntPair;
import se.sics.gvod.nat.emu.events.DistributedNatGatewayEmulatorInit;
import se.sics.gvod.net.VodAddress;
import se.sics.gvod.net.Nat;
import se.sics.gvod.net.VodNetwork;
import se.sics.gvod.net.NatNetworkControl;
import se.sics.gvod.net.msgs.DirectMsg;
import se.sics.gvod.stun.client.events.GetNatTypeRequest;
import se.sics.gvod.stun.client.events.GetNatTypeResponse;
import se.sics.gvod.stun.client.events.GetNatTypeResponseRuleExpirationTime;
import se.sics.gvod.stun.client.events.StunClientInit;
import se.sics.gvod.stun.client.simulator.NetworkSimulator;
import se.sics.gvod.stun.client.simulator.NetworkSimulatorInit;
import se.sics.gvod.stun.server.StunServer;
import se.sics.gvod.stun.server.events.StunServerInit;
import se.sics.kompics.ChannelFilter;
import se.sics.kompics.Component;
import se.sics.kompics.ComponentDefinition;
import se.sics.kompics.Handler;
import se.sics.kompics.Kompics;
import se.sics.kompics.Start;
import se.sics.gvod.timer.ScheduleTimeout;
import se.sics.gvod.timer.Timeout;
import se.sics.gvod.timer.Timer;
import se.sics.gvod.timer.java.JavaTimer;
import se.sics.kompics.Init; | package se.sics.gvod.stun.client;
/**
* Unit test for simple App.
*/
public class StunClientTest {
private static final Logger logger = LoggerFactory.getLogger(StunClientTest.class);
private static Semaphore semaphore = new Semaphore(0);
int testNumber = 0;
boolean res = true;
public static class StunClientComponentTester extends ComponentDefinition {
private static final Logger logger = LoggerFactory.getLogger(StunClientComponentTester.class);
private Component stunClientComp;
private List<Component> serverS1Components = new ArrayList<Component>();
private List<Component> serverS2Components = new ArrayList<Component>();
private Component natComp;
private Component timer, networkSimulator;
private Component portReservoir_For_A, portReservoir_For_B;
public static Nat nat;
public static int ruleLifeTime;
public static StunClientTest testObj = null;
private Address stunClientAddress;
int clientPort;
static int clientID = 0;
InetAddress natIP = null;
int natID;
private List<Address> serverS1Addresses = new ArrayList<Address>();
private List<Address> serverS2Addresses = new ArrayList<Address>();
int serverS1Port;
int serverS1ChangePort = 3479;
int serverS2Port;
int serverS2ChangePort = 3479;
public static int numberOfPairServers = 2;
public static int numberOfSingleServers = 1;
public StunClientComponentTester() {
doCreateAndConnect();
subscribe(handleStart, control); | subscribe(handleMsgTimeout, timer.getPositive(Timer.class)); | 4 |
tsauvine/omr | src/omr/gui/calibration/SheetCalibrationEditor.java | [
"public class RegistrationMarker extends Observable {\n public enum RegistrationMarkerEvent {\n MARKER_CHANGED\n }\n \n private int x; // Middlepoint of the marker (center of the image) \n private int y;\n private int imageWidth; // Width of the marker image\n private in... | import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Observable;
import omr.RegistrationMarker;
import omr.Project;
import omr.QuestionGroup;
import omr.Sheet;
import omr.SheetStructure;
import omr.gui.SheetEditor; | package omr.gui.calibration;
/**
* Shows the sheet with question groups. Filled, unfilled and uncertain bubbles are rendered differently.
* User can override answers by clicking bubbles.
*/
public class SheetCalibrationEditor extends SheetEditor implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
private Project project; // The model, never null.
//private Tool currentTool;
public SheetCalibrationEditor() {
super();
addMouseMotionListener(this);
addMouseListener(this);
}
public void setProject(Project project) {
this.project = project;
}
protected BufferedImage getSheetBuffer() throws OutOfMemoryError, IOException {
if (this.sheet == null) {
return null;
}
return sheet.getAlignedBuffer(zoomLevel);
}
protected void paintComponent(Graphics g) {
// Draw sheet
super.paintComponent(g);
if (sheet == null) {
return;
}
double zoom = getZoomLevel();
| SheetStructure structure = project.getSheetStructure(); | 4 |
wuman/AndroidImageLoader | samples/src/main/java/com/wuman/androidimageloader/samples/FlickrInterestingnessFragment.java | [
"public final class ImageLoader {\n\n private static final String LOG_TAG = ImageLoader.class.getSimpleName();\n\n private static final int APP_VERSION = 1;\n\n /**\n * The default cache size (in bytes).\n */\n // 25% of available memory, up to a maximum of 16MB\n public static final long DEF... | import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import com.wuman.androidimageloader.ImageLoader;
import com.wuman.androidimageloader.samples.FlickrUtil.FlickrInterestingnessAdapter;
import com.wuman.androidimageloader.samples.provider.SamplesContract.InterestingPhotos;
import com.wuman.androidimageloader.samples.ui.DebugView;
import com.wuman.androidimageloader.samples.ui.ListDecorator;
import com.wuman.androidimageloader.samples.ui.ListScrollListener;
import com.wuman.androidimageloader.samples.ui.Loadable;
import com.wuman.androidimageloader.samples.ui.StatusViewManager; | package com.wuman.androidimageloader.samples;
public class FlickrInterestingnessFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor>, View.OnClickListener {
private DebugView mDebugView;
private FlickrInterestingnessAdapter mAdapter; | private Loadable mPhotos; | 6 |
lijunyandev/MeetMusic | app/src/main/java/com/lijunyan/blackmusic/fragment/SingleFragment.java | [
"public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>\n implements SectionIndexer{\n\n private static final String TAG = RecyclerViewAdapter.class.getName();\n private List<MusicInfo> musicInfoList;\n private Context context;\n private DBManager dbManager;... | import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.lijunyan.blackmusic.R;
import com.lijunyan.blackmusic.adapter.RecyclerViewAdapter;
import com.lijunyan.blackmusic.database.DBManager;
import com.lijunyan.blackmusic.entity.MusicInfo;
import com.lijunyan.blackmusic.receiver.PlayerManagerReceiver;
import com.lijunyan.blackmusic.service.MusicPlayerService;
import com.lijunyan.blackmusic.util.Constant;
import com.lijunyan.blackmusic.util.MyMusicUtil;
import com.lijunyan.blackmusic.view.MusicPopMenuWindow;
import com.lijunyan.blackmusic.view.SideBar;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | recyclerViewAdapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
@Override
public void onOpenMenuClick(int position) {
MusicInfo musicInfo = musicInfoList.get(position);
showPopFormBottom(musicInfo);
}
@Override
public void onDeleteMenuClick(View swipeView, int position) {
MusicInfo musicInfo = musicInfoList.get(position);
deleteOperate(swipeView,position,context);
}
@Override
public void onContentClick(int position) {
MyMusicUtil.setShared(Constant.KEY_LIST,Constant.LIST_ALLMUSIC);
}
});
// 当点击外部空白处时,关闭正在展开的侧滑菜单
recyclerView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
SwipeMenuLayout viewCache = SwipeMenuLayout.getViewCache();
if (null != viewCache) {
viewCache.smoothClose();
}
}
return false;
}
});
playModeRl = (RelativeLayout)view.findViewById(R.id.local_music_playmode_rl);
playModeIv = (ImageView)view.findViewById(R.id.local_music_playmode_iv);
playModeTv = (TextView)view.findViewById(R.id.local_music_playmode_tv);
initDefaultPlayModeView();
// 顺序 --> 随机-- > 单曲
playModeRl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int playMode = MyMusicUtil.getIntShared(Constant.KEY_MODE);
switch (playMode){
case Constant.PLAYMODE_SEQUENCE:
playModeTv.setText(Constant.PLAYMODE_RANDOM_TEXT);
MyMusicUtil.setShared(Constant.KEY_MODE,Constant.PLAYMODE_RANDOM);
break;
case Constant.PLAYMODE_RANDOM:
playModeTv.setText(Constant.PLAYMODE_SINGLE_REPEAT_TEXT);
MyMusicUtil.setShared(Constant.KEY_MODE,Constant.PLAYMODE_SINGLE_REPEAT);
break;
case Constant.PLAYMODE_SINGLE_REPEAT:
playModeTv.setText(Constant.PLAYMODE_SEQUENCE_TEXT);
MyMusicUtil.setShared(Constant.KEY_MODE,Constant.PLAYMODE_SEQUENCE);
break;
}
initPlayMode();
}
});
sideBarPreTv = (TextView) view.findViewById(R.id.local_music_siderbar_pre_tv);
sideBar = (SideBar)view.findViewById(R.id.local_music_siderbar);
sideBar.setTextView(sideBarPreTv);
sideBar.setOnListener(new SideBar.OnTouchingLetterChangedListener() {
@Override
public void onTouchingLetterChanged(String letter) {
Log.i(TAG, "onTouchingLetterChanged: letter = "+letter);
//该字母首次出现的位置
int position = recyclerViewAdapter.getPositionForSection(letter.charAt(0));
if(position != -1){
recyclerView.smoothScrollToPosition(position);
}
}
});
return view;
}
private void initDefaultPlayModeView(){
int playMode = MyMusicUtil.getIntShared(Constant.KEY_MODE);
switch (playMode){
case Constant.PLAYMODE_SEQUENCE:
playModeTv.setText(Constant.PLAYMODE_SEQUENCE_TEXT);
break;
case Constant.PLAYMODE_RANDOM:
playModeTv.setText(Constant.PLAYMODE_RANDOM_TEXT);
break;
case Constant.PLAYMODE_SINGLE_REPEAT:
playModeTv.setText(Constant.PLAYMODE_SINGLE_REPEAT_TEXT);
break;
}
initPlayMode();
}
private void initPlayMode() {
int playMode = MyMusicUtil.getIntShared(Constant.KEY_MODE);
if (playMode == -1) {
playMode = 0;
}
playModeIv.setImageLevel(playMode);
}
public void updateView(){
musicInfoList = dbManager.getAllMusicFromMusicTable();
Collections.sort(musicInfoList);
recyclerViewAdapter.updateMusicInfoList(musicInfoList);
Log.d(TAG, "updateView: musicInfoList.size() = "+musicInfoList.size());
if (musicInfoList.size() == 0){
sideBar.setVisibility(View.GONE);
playModeRl.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
}else {
sideBar.setVisibility(View.VISIBLE);
playModeRl.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.VISIBLE);
}
initDefaultPlayModeView();
}
public void showPopFormBottom(MusicInfo musicInfo) { | MusicPopMenuWindow menuPopupWindow = new MusicPopMenuWindow(getActivity(),musicInfo,view,Constant.ACTIVITY_LOCAL); | 7 |
wpilibsuite/EclipsePlugins | edu.wpi.first.wpilib.plugins.cpp/src/main/java/edu/wpi/first/wpilib/plugins/cpp/wizards/examples/ExampleCPPWizard.java | [
"public class WPILibCore extends AbstractUIPlugin {\n\n\t// The plug-in ID\n\tpublic static final String PLUGIN_ID = \"edu.wpi.first.wpilib.plugins.core\"; //$NON-NLS-1$\n\n\t// The shared instance\n\tprivate static WPILibCore plugin;\n\n\t/**\n\t * The constructor\n\t */\n\tpublic WPILibCore() {\n\t}\n\n\t/*\n\t *... | import java.net.URL;
import java.util.List;
import java.util.Properties;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.wizard.IWizardPage;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
import edu.wpi.first.wpilib.plugins.core.wizards.ExampleWizard;
import edu.wpi.first.wpilib.plugins.core.wizards.IExampleProject;
import edu.wpi.first.wpilib.plugins.core.wizards.IExampleProject.ExportFile;
import edu.wpi.first.wpilib.plugins.core.wizards.INewProjectInfo;
import edu.wpi.first.wpilib.plugins.core.wizards.NewProjectMainPage;
import edu.wpi.first.wpilib.plugins.core.wizards.ProjectCreationUtils;
import edu.wpi.first.wpilib.plugins.cpp.WPILibCPPPlugin;
import edu.wpi.first.wpilib.plugins.cpp.wizards.newproject.WPIRobotCPPProjectCreator; | package edu.wpi.first.wpilib.plugins.cpp.wizards.examples;
public class ExampleCPPWizard extends ExampleWizard {
private NewProjectMainPage detailsPage;
/**
* Constructor for SampleNewWizard.
*/
public ExampleCPPWizard() {
super();
setNeedsProgressMonitor(true);
}
@Override
protected void doFinish(IExampleProject ex, String teamNumber) throws CoreException {
Properties props = WPILibCore.getDefault().getProjectProperties(null);
props.setProperty("team-number", teamNumber);
WPILibCore.getDefault().saveGlobalProperties(props);
final String projectName = detailsPage.getProjectName(); | ProjectCreationUtils.createProject(new WPIRobotCPPProjectCreator(projectName, ex, detailsPage.getWorld())); | 6 |
mattcasters/pentaho-pdi-dataset | src/main/java/org/pentaho/di/dataset/spoon/xtpoint/ShowUnitTestMenuExtensionPoint.java | [
"@MetaStoreElementType(\n name = \"Kettle Transformation Unit Test\",\n description = \"This describes a golden data unit test for a transformation with defined input data sets\" )\npublic class TransUnitTest {\n\n private String name;\n\n @MetaStoreAttribute( key = \"description\" )\n private String descripti... | import org.apache.commons.lang.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.extension.ExtensionPoint;
import org.pentaho.di.core.extension.ExtensionPointInterface;
import org.pentaho.di.core.gui.AreaOwner;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.dataset.TransUnitTest;
import org.pentaho.di.dataset.TransUnitTestSetLocation;
import org.pentaho.di.dataset.spoon.DataSetHelper;
import org.pentaho.di.dataset.spoon.dialog.TransUnitTestSetLocationDialog;
import org.pentaho.di.dataset.util.DataSetConst;
import org.pentaho.di.dataset.util.FactoriesHierarchy;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.spoon.trans.TransGraphExtension;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Pentaho : http://www.pentaho.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 org.pentaho.di.dataset.spoon.xtpoint;
@ExtensionPoint(
id = "ShowUnitTestMenuExtensionPoint",
description = "Quick unit test menu",
extensionPointId = "TransGraphMouseDown" )
public class ShowUnitTestMenuExtensionPoint implements ExtensionPointInterface {
private static Class<?> PKG = ShowUnitTestMenuExtensionPoint.class; // for i18n purposes, needed by Translator2!!
@Override
public void callExtensionPoint( LogChannelInterface log, Object object ) throws KettleException {
if ( !( object instanceof TransGraphExtension ) ) {
return;
}
TransGraphExtension tge = (TransGraphExtension) object;
final TransMeta transMeta = tge.getTransGraph().getTransMeta(); | final TransUnitTest unitTest = DataSetHelper.getCurrentUnitTest( transMeta ); | 0 |
WojciechZankowski/iextrading4j-hist | iextrading4j-hist-test/src/test/java/pl/zankowski/iextrading4j/hist/test/segment/DEEPSegmentTest.java | [
"public enum IEXMessageType implements IEXByteEnum {\n\n QUOTE_UPDATE((byte) 0x51),\n TRADE_REPORT((byte) 0x54),\n TRADE_BREAK((byte) 0x42),\n SYSTEM_EVENT((byte) 0x53),\n SECURITY_DIRECTORY((byte) 0x44),\n TRADING_STATUS((byte) 0x48),\n OPERATIONAL_HALT_STATUS((byte) 0x4f),\n SHORT_SALE_PRI... | import org.junit.jupiter.api.Test;
import pl.zankowski.iextrading4j.hist.api.IEXMessageType;
import pl.zankowski.iextrading4j.hist.api.field.IEXPrice;
import pl.zankowski.iextrading4j.hist.api.message.IEXMessage;
import pl.zankowski.iextrading4j.hist.api.message.IEXMessageHeader;
import pl.zankowski.iextrading4j.hist.api.message.IEXMessageProtocol;
import pl.zankowski.iextrading4j.hist.api.message.trading.IEXTradeMessage;
import pl.zankowski.iextrading4j.hist.deep.IEXDEEPMessageBlock;
import pl.zankowski.iextrading4j.hist.test.ExtendedUnitTestBase;
import java.io.IOException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; | package pl.zankowski.iextrading4j.hist.test.segment;
class DEEPSegmentTest extends ExtendedUnitTestBase {
@Test
void testDeepSegment() throws IOException {
final byte[] packet = loadPacket("DEEPSegment.dump");
| final IEXDEEPMessageBlock segment = IEXDEEPMessageBlock.createIEXSegment(packet); | 6 |
CommonsLab/CommonsLab | app/src/main/java/com/commonslab/commonslab/Fragments/AudioFragment.java | [
"public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, EasyPermissions.PermissionCallbacks {\n\n public static final String SEEKBAR_UPDATE_BROADCAST = \"org.wikimedia.commons.wikimedia.SEEKBAR_UPDATE_BROADCAST\";\n public static final String CONTRIBUTI... | import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.commonslab.commonslab.Activities.MainActivity;
import com.commonslab.commonslab.R;
import com.commonslab.commonslab.Utils.RecyclerViewAdapters.AudioRecyclerViewAdapter;
import com.commonslab.commonslab.Utils.RecyclerViewClick.RecyclerViewItemClickInterface;
import com.commonslab.commonslab.Utils.RecyclerViewClick.RecyclerViewTouchListener;
import com.commonslab.commonslab.Utils.SharedPreferencesUtils.StorageUtil;
import java.lang.reflect.Type;
import java.util.ArrayList;
import apiwrapper.commons.wikimedia.org.Models.Contribution; | package com.commonslab.commonslab.Fragments;
public class AudioFragment extends Fragment {
public static final String Broadcast_PLAY_NEW_AUDIO = "org.wikimedia.commons.wikimedia.PlayNewAudio";
private static final String AUDIO_LIST = "org.wikimedia.commons.wikimedia.AUDIO_LIST";
private static final String LAST_VISIBLE_AUDIO = "org.wikimedia.commons.wikimedia.LAST_VISIBLE_AUDIO";
private AudioRecyclerViewAdapter adapter;
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private ArrayList<Contribution> contributionsList;
private SharedPreferences preferences;
public AudioFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
contributionsList = new ArrayList<>();
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_audio, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
contributionsList = loadContributionsList();
initRecyclerView();
//After the RecyclerView is initialized notify the adapter to display the previous available data
adapter.notifyDataSetChanged();
int position = savedInstanceState.getInt(LAST_VISIBLE_AUDIO);
recyclerView.scrollToPosition(position);
}
if (savedInstanceState == null) {
initRecyclerView();
if (new StorageUtil(getActivity()).usersContributionsAvailable() && contributionsList.size() == 0) {
//must reload data from cache
loadContributions();
}
}
}
private void initRecyclerView() {
adapter = new AudioRecyclerViewAdapter(contributionsList, getActivity());
recyclerView = (RecyclerView) getActivity().findViewById(R.id.recyclerviewAudios);
recyclerView.setAdapter(adapter);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
// Item touch Listener | recyclerView.addOnItemTouchListener(new RecyclerViewTouchListener(getActivity(), recyclerView, new RecyclerViewItemClickInterface() { | 3 |
googleapis/java-trace | google-cloud-trace/src/test/java/com/google/cloud/trace/v1/TraceServiceClientTest.java | [
"public static class ListTracesPagedResponse\n extends AbstractPagedListResponse<\n ListTracesRequest,\n ListTracesResponse,\n Trace,\n ListTracesPage,\n ListTracesFixedSizeCollection> {\n\n public static ApiFuture<ListTracesPagedResponse> createAsync(\n PageContext<ListT... | import static com.google.cloud.trace.v1.TraceServiceClient.ListTracesPagedResponse;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.testing.LocalChannelProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.common.collect.Lists;
import com.google.devtools.cloudtrace.v1.GetTraceRequest;
import com.google.devtools.cloudtrace.v1.ListTracesRequest;
import com.google.devtools.cloudtrace.v1.ListTracesResponse;
import com.google.devtools.cloudtrace.v1.PatchTracesRequest;
import com.google.devtools.cloudtrace.v1.Trace;
import com.google.devtools.cloudtrace.v1.TraceSpan;
import com.google.devtools.cloudtrace.v1.Traces;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Empty;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.annotation.Generated;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.trace.v1;
@Generated("by gapic-generator-java")
public class TraceServiceClientTest {
private static MockServiceHelper mockServiceHelper;
private static MockTraceService mockTraceService;
private LocalChannelProvider channelProvider;
private TraceServiceClient client;
@BeforeClass
public static void startStaticServer() {
mockTraceService = new MockTraceService();
mockServiceHelper =
new MockServiceHelper(
UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList(mockTraceService));
mockServiceHelper.start();
}
@AfterClass
public static void stopServer() {
mockServiceHelper.stop();
}
@Before
public void setUp() throws IOException {
mockServiceHelper.reset();
channelProvider = mockServiceHelper.createChannelProvider();
TraceServiceSettings settings =
TraceServiceSettings.newBuilder()
.setTransportChannelProvider(channelProvider)
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = TraceServiceClient.create(settings);
}
@After
public void tearDown() throws Exception {
client.close();
}
@Test
public void listTracesTest() throws Exception {
Trace responsesElement = Trace.newBuilder().build();
ListTracesResponse expectedResponse =
ListTracesResponse.newBuilder()
.setNextPageToken("")
.addAllTraces(Arrays.asList(responsesElement))
.build();
mockTraceService.addResponse(expectedResponse);
String projectId = "projectId-894832108";
ListTracesPagedResponse pagedListResponse = client.listTraces(projectId);
List<Trace> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getTracesList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockTraceService.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListTracesRequest actualRequest = ((ListTracesRequest) actualRequests.get(0));
Assert.assertEquals(projectId, actualRequest.getProjectId());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listTracesExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockTraceService.addException(exception);
try {
String projectId = "projectId-894832108";
client.listTraces(projectId);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getTraceTest() throws Exception {
Trace expectedResponse =
Trace.newBuilder()
.setProjectId("projectId-894832108")
.setTraceId("traceId-1067401920") | .addAllSpans(new ArrayList<TraceSpan>()) | 6 |
copygirl/WearableBackpacks | src/main/java/net/mcft/copy/backpacks/client/gui/config/BaseEntryList.java | [
"@SideOnly(Side.CLIENT)\npublic enum Direction {\n\t\n\tHORIZONTAL,\n\tVERTICAL;\n\t\n\tpublic Direction perpendicular()\n\t\t{ return (this == HORIZONTAL) ? VERTICAL : HORIZONTAL; }\n\t\n}",
"@SideOnly(Side.CLIENT)\npublic class GuiContainer extends GuiElementBase {\n\t\n\tprotected List<GuiElementBase> children... | import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.mcft.copy.backpacks.client.gui.Direction;
import net.mcft.copy.backpacks.client.gui.GuiContainer;
import net.mcft.copy.backpacks.client.gui.GuiElementBase;
import net.mcft.copy.backpacks.client.gui.GuiLayout;
import net.mcft.copy.backpacks.client.gui.config.IConfigEntry;
import net.mcft.copy.backpacks.client.gui.control.GuiButton;
import net.mcft.copy.backpacks.config.Status;
import net.mcft.copy.backpacks.config.Status.Severity; | package net.mcft.copy.backpacks.client.gui.config;
@SideOnly(Side.CLIENT)
public abstract class BaseEntryList<T> extends GuiLayout implements IConfigEntry {
protected final List<T> defaultValue;
protected final List<T> previousValue;
public final GuiLayout layoutList;
public final GuiButton buttonAdd;
public BaseEntryList(int width, List<T> defaultValue, List<T> previousValue) {
super(Direction.VERTICAL);
setCenteredHorizontal(width);
this.defaultValue = defaultValue;
this.previousValue = previousValue;
layoutList = new GuiLayout(Direction.VERTICAL);
layoutList.setFillHorizontal();
buttonAdd = new GuiButton(0, DEFAULT_ENTRY_HEIGHT, TextFormatting.GREEN + "+");
buttonAdd.setFill();
buttonAdd.setAction(this::addButtonPressed);
addFixed(layoutList);
addFixed(buttonAdd);
setValue(previousValue);
}
protected abstract Entry<T> createListEntry();
protected void addButtonPressed() { addEntry(); }
public void addEntry(T value)
{ addEntry().setValue(value); }
public Entry<T> addEntry() {
Entry<T> entry = createListEntry();
layoutList.addFixed(entry);
return entry;
}
public Stream<Entry<T>> getEntries() {
return layoutList.getChildren().stream()
.filter(Entry.class::isInstance)
.map(Entry.class::cast);
}
public Stream<T> getValueAsStream()
{ return getEntries().map(Entry::getValue); }
public List<T> getValue()
{ return getValueAsStream().collect(Collectors.toList()); }
public void setValue(List<T> value) {
layoutList.clear();
value.forEach(this::addEntry);
}
public abstract static class Entry<T> extends GuiLayout {
public final MoveButton buttonMove;
public final GuiButton buttonRemove;
public Entry(BaseEntryList<T> owningList) {
super(Direction.HORIZONTAL);
setFillHorizontal();
buttonMove = new MoveButton();
buttonRemove = new GuiButton(DEFAULT_ENTRY_HEIGHT, DEFAULT_ENTRY_HEIGHT, TextFormatting.RED + "x");
buttonRemove.setAction(() -> owningList.layoutList.remove(this));
}
public abstract T getValue();
public abstract void setValue(T value);
public abstract List<Status> getStatus();
@Override
public void draw(int mouseX, int mouseY, float partialTicks) {
GlStateManager.pushMatrix();
GlStateManager.translate(0, buttonMove.renderYOffset, 0);
Severity severity = Status.getSeverity(getStatus());
enableBlendAlphaStuffs();
drawColoredRectARGB(-4, -1, getWidth() + 8, getHeight() + 2, severity.backgroundColor);
disableBlendAlphaStuffs();
super.draw(mouseX, mouseY, partialTicks);
GlStateManager.popMatrix();
}
public class MoveButton extends GuiButton {
public static final int WIDTH = 12;
protected int yOffset = 0;
protected float renderYOffset = 0.0F;
public MoveButton() {
super(WIDTH, DEFAULT_ENTRY_HEIGHT - 2, "=");
setCenteredVertical();
}
@Override
public boolean canDrag() { return true; }
@Override
@SuppressWarnings("unchecked")
public void onDragged(int mouseX, int mouseY, int deltaX, int deltaY, int startX, int startY) {
GuiContainer parent = Entry.this.getParent(); | List<GuiElementBase> elements = parent.getChildren(); | 2 |
jhy/jsoup | src/test/java/org/jsoup/integration/ParseTest.java | [
"public class Jsoup {\n private Jsoup() {}\n\n /**\n Parse HTML into a Document. The parser will make a sensible, balanced document tree out of any HTML.\n\n @param html HTML to parse\n @param baseUri The URL where the HTML was retrieved from. Used to resolve relative URLs to absolute URLs, tha... | import org.jsoup.Jsoup;
import org.jsoup.helper.DataUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.ParseErrorList;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.zip.GZIPInputStream;
import static org.junit.jupiter.api.Assertions.*; | package org.jsoup.integration;
/**
* Integration test: parses from real-world example HTML.
*
* @author Jonathan Hedley, jonathan@hedley.net
*/
public class ParseTest {
@Test
public void testSmhBizArticle() throws IOException {
File in = getFile("/htmltests/smh-biz-article-1.html.gz");
Document doc = Jsoup.parse(in, "UTF-8",
"http://www.smh.com.au/business/the-boards-next-fear-the-female-quota-20100106-lteq.html");
assertEquals("The board’s next fear: the female quota",
doc.title()); // note that the apos in the source is a literal ’ (8217), not escaped or '
assertEquals("en", doc.select("html").attr("xml:lang"));
Elements articleBody = doc.select(".articleBody > *");
assertEquals(17, articleBody.size());
// todo: more tests!
}
@Test
public void testNewsHomepage() throws IOException {
File in = getFile("/htmltests/news-com-au-home.html.gz");
Document doc = Jsoup.parse(in, "UTF-8", "http://www.news.com.au/");
assertEquals("News.com.au | News from Australia and around the world online | NewsComAu", doc.title());
assertEquals("Brace yourself for Metro meltdown", doc.select(".id1225817868581 h4").text().trim());
| Element a = doc.select("a[href=/entertainment/horoscopes]").first(); | 3 |
ozwolf-software/raml-mock-server | src/main/java/net/ozwolf/mockserver/raml/internal/validator/body/ResponseBodyValidator.java | [
"public class NoValidActionException extends RamlMockServerException {\n private final static String MESSAGE = \"Expectation [ %s %s ] has no valid matching action specification.\";\n\n public NoValidActionException(ApiExpectation expectation) {\n super(String.format(MESSAGE, expectation.getMethod(), e... | import net.ozwolf.mockserver.raml.exception.NoValidActionException;
import net.ozwolf.mockserver.raml.internal.domain.ApiExpectation;
import net.ozwolf.mockserver.raml.internal.domain.BodySpecification;
import net.ozwolf.mockserver.raml.internal.domain.ValidationErrors;
import net.ozwolf.mockserver.raml.internal.validator.Validator;
import org.apache.commons.lang.StringUtils;
import org.raml.model.MimeType;
import org.raml.model.Response;
import javax.ws.rs.core.MediaType;
import java.util.Map;
import java.util.Optional; | package net.ozwolf.mockserver.raml.internal.validator.body;
public class ResponseBodyValidator implements Validator {
private final ApiExpectation expectation;
public ResponseBodyValidator(ApiExpectation expectation) {
this.expectation = expectation;
}
@Override | public ValidationErrors validate() { | 3 |
cloudsoft/brooklyn-tosca | brooklyn-tosca-transformer/src/main/java/io/cloudsoft/tosca/a4c/brooklyn/plan/ToscaTypePlanTransformer.java | [
"public interface AlienPlatformFactory {\n\n ToscaPlatform newPlatform(ManagementContext mgmt) throws Exception;\n \n public static class Default implements AlienPlatformFactory {\n @Override\n public ToscaPlatform newPlatform(ManagementContext mgmt) throws Exception {\n Applicatio... | import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.brooklyn.api.entity.Application;
import org.apache.brooklyn.api.entity.EntitySpec;
import org.apache.brooklyn.api.internal.AbstractBrooklynObjectSpec;
import org.apache.brooklyn.api.mgmt.ManagementContext;
import org.apache.brooklyn.api.typereg.RegisteredType;
import org.apache.brooklyn.api.typereg.RegisteredTypeLoadingContext;
import org.apache.brooklyn.config.ConfigKey;
import org.apache.brooklyn.core.BrooklynFeatureEnablement;
import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
import org.apache.brooklyn.core.config.ConfigKeys;
import org.apache.brooklyn.core.mgmt.classloading.JavaBrooklynClassLoadingContext;
import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
import org.apache.brooklyn.core.typereg.AbstractFormatSpecificTypeImplementationPlan;
import org.apache.brooklyn.core.typereg.AbstractTypePlanTransformer;
import org.apache.brooklyn.core.typereg.BasicTypeImplementationPlan;
import org.apache.brooklyn.core.typereg.RegisteredTypes;
import org.apache.brooklyn.core.typereg.UnsupportedTypePlanException;
import org.apache.brooklyn.entity.stock.BasicApplication;
import org.apache.brooklyn.util.exceptions.Exceptions;
import org.apache.brooklyn.util.guava.Maybe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import io.cloudsoft.tosca.a4c.brooklyn.AlienPlatformFactory;
import io.cloudsoft.tosca.a4c.brooklyn.ApplicationSpecsBuilder;
import io.cloudsoft.tosca.a4c.brooklyn.ToscaApplication;
import io.cloudsoft.tosca.a4c.brooklyn.ToscaParser;
import io.cloudsoft.tosca.a4c.platform.Alien4CloudToscaPlatform;
import io.cloudsoft.tosca.a4c.platform.ToscaPlatform; | package io.cloudsoft.tosca.a4c.brooklyn.plan;
public class ToscaTypePlanTransformer extends AbstractTypePlanTransformer {
private static final Logger log = LoggerFactory.getLogger(ToscaTypePlanTransformer.class);
public static final ConfigKey<Alien4CloudToscaPlatform> TOSCA_ALIEN_PLATFORM = ConfigKeys.builder(Alien4CloudToscaPlatform.class)
.name("tosca.a4c.platform")
.build();
@VisibleForTesting
public static final String FEATURE_TOSCA_ENABLED = BrooklynFeatureEnablement.FEATURE_PROPERTY_PREFIX + ".tosca";
private static final AtomicBoolean hasLoggedDisabled = new AtomicBoolean(false);
private static final ConfigKey<String> TOSCA_ID = ConfigKeys.newStringConfigKey("tosca.id");
private static final ConfigKey<String> TOSCA_DELEGATE_ID = ConfigKeys.newStringConfigKey("tosca.delegate.id");
private static final ConfigKey<String> TOSCA_DEPLOYMENT_ID = ConfigKeys.newStringConfigKey("tosca.deployment.id");
private ManagementContext mgmt;
private ToscaPlatform platform;
private AlienPlatformFactory platformFactory;
private final AtomicBoolean alienInitialised = new AtomicBoolean();
public static final String FORMAT = "brooklyn-tosca";
// TODO support these -- more specific parsers (whereas this one autodetects between the first two and doesn't support the last one)
// public static final String FORMAT_SERVICE_TEMPLATE_YAML = "tosca-service-template-yaml";
// public static final String FORMAT_CSAR_LINK = "brooklyn-tosca-csar-link";
// public static final String FORMAT_CSAR_ZIP = "tosca-csar-zip";
public ToscaTypePlanTransformer() {
super(FORMAT, "OASIS TOSCA / Brooklyn", "The Apache Brooklyn implementation of the OASIS TOSCA blueprint plan format and extensions");
}
@Override
public synchronized void setManagementContext(ManagementContext managementContext) {
if (!isEnabled()) {
if (hasLoggedDisabled.compareAndSet(false, true)) {
log.info("Not loading brooklyn-tosca platform: feature disabled");
}
return;
}
if (this.mgmt != null && this.mgmt != managementContext) {
throw new IllegalStateException("Cannot switch mgmt context");
} else if (this.mgmt == null) {
this.mgmt = managementContext;
initialiseAlien();
}
}
private void initialiseAlien() {
try {
platform = mgmt.getConfig().getConfig(TOSCA_ALIEN_PLATFORM);
log.info("Initializing Alien4Cloud TOSCA for "+this+": "+platform);
if (platform == null) {
Alien4CloudToscaPlatform.grantAdminAuth();
if (platformFactory==null) platformFactory = new AlienPlatformFactory.Default();
platform = platformFactory.newPlatform(mgmt);
((LocalManagementContext) mgmt).getBrooklynProperties().put(TOSCA_ALIEN_PLATFORM, platform);
log.info("Initialized Alien4Cloud TOSCA for "+this+": "+platform);
}
alienInitialised.set(true);
} catch (Exception e) {
log.error("Failure initializing Alien4Cloud TOSCA for "+this+" (rethrowing): "+e);
throw Exceptions.propagate(e);
}
}
public EntitySpec<? extends Application> createApplicationSpecFromTopologyId(String id) {
return createApplicationSpec(platform.getToscaApplication(id));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected EntitySpec<? extends Application> createApplicationSpec(ToscaApplication toscaApplication) {
EntitySpec<BasicApplication> rootSpec = EntitySpec.create(BasicApplication.class)
.displayName(toscaApplication.getName())
.configure(TOSCA_ID, toscaApplication.getId())
.configure(TOSCA_DELEGATE_ID, toscaApplication.getDelegateId())
.configure(TOSCA_DEPLOYMENT_ID, toscaApplication.getDeploymentId());
@SuppressWarnings("deprecation") | ApplicationSpecsBuilder specsBuilder = platform.getBean(ApplicationSpecsBuilder.class); | 1 |
authlete/java-oauth-server | src/main/java/com/authlete/jaxrs/server/ad/AuthenticationDevice.java | [
"public class ServerConfig\n{\n /**\n * Properties.\n */\n private static final ServerProperties sProperties = new ServerProperties();\n\n\n /**\n * Property keys.\n */\n private static final String AUTHLETE_AD_BASE_URL_KEY = \"authlete.ad.base_url\";\n private sta... | import com.authlete.jaxrs.server.ad.dto.SyncAuthenticationRequest;
import com.authlete.jaxrs.server.ad.dto.SyncAuthenticationResponse;
import static org.glassfish.jersey.client.ClientProperties.CONNECT_TIMEOUT;
import static org.glassfish.jersey.client.ClientProperties.READ_TIMEOUT;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import org.glassfish.jersey.client.ClientConfig;
import com.authlete.jaxrs.server.ServerConfig;
import com.authlete.jaxrs.server.ad.dto.AsyncAuthenticationRequest;
import com.authlete.jaxrs.server.ad.dto.AsyncAuthenticationResponse;
import com.authlete.jaxrs.server.ad.dto.PollAuthenticationRequest;
import com.authlete.jaxrs.server.ad.dto.PollAuthenticationResponse;
import com.authlete.jaxrs.server.ad.dto.PollAuthenticationResultRequest;
import com.authlete.jaxrs.server.ad.dto.PollAuthenticationResultResponse; | /*
* Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.ad;
/**
* A class to communicate with <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim">
* Authlete CIBA authentication device simulator API</a>.
*
* @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication
* device simulator</a>
*
* @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim">Authlete CIBA authentication device simulator API</a>
*
* @author Hideki Ikeda
*/
public class AuthenticationDevice
{
/**
* The limit values for end-user authentication/authorization timeout defined
* by <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim">Authlete
* CIBA authentication device simulator API</a>.
*/
public static final int AUTH_TIMEOUT_MIN = 5;
public static final int AUTH_TIMEOUT_MAX = 60;
/**
* Authlete CIBA authentication simulator API endpoints.
*/
private static final String SYNC_ENDPOINT_PATH = "/api/authenticate/sync";
private static final String ASYNC_ENDPOINT_PATH = "/api/authenticate/async";
private static final String POLL_ENDPOINT_PATH = "/api/authenticate/poll";
private static final String POLL_RESULT_ENDPOINT_PATH = "/api/authenticate/result";
/**
* Parameters required to communicate with the authentication device simulator.
*/
private static final String sBaseUrl = ServerConfig.getAuthleteAdBaseUrl();
private static final String sWorkspace = ServerConfig.getAuthleteAdWorkspace();
private static final int sSyncConnectTimeout = ServerConfig.getAuthleteAdSyncConnectTimeout();
private static final int sSyncAdditionalReadTimeout = ServerConfig.getAuthleteAdSyncAdditionalReadTimeout();
private static final int sAsyncConnectTimeout = ServerConfig.getAuthleteAdAsyncConnectTimeout();
private static final int sAsyncReadTimeout = ServerConfig.getAuthleteAdAsyncReadTimeout();
private static final int sPollConnectTimeout = ServerConfig.getAuthleteAdPollConnectTimeout();
private static final int sPollReadTimeout = ServerConfig.getAuthleteAdPollReadTimeout();
private static final int sPollResultConnectTimeout = ServerConfig.getAuthleteAdPollResultConnectTimeout();
private static final int sPollResultReadTimeout = ServerConfig.getAuthleteAdPollResultReadTimeout();
private static Client createClient(int readTimeout, int connectTimeout)
{
// Client configuration.
ClientConfig config = new ClientConfig();
// Read timeout.
config.property(READ_TIMEOUT, readTimeout);
// Connect timeout.
config.property(CONNECT_TIMEOUT, connectTimeout);
// The client that synchronously communicates with the authentication device simulator.
return ClientBuilder.newClient(config);
}
/**
* Send a request to the authentication device simulator for end-user authentication
* and authorization in synchronous mode.
*
* @param subject
* The subject of the end-user to be authenticated and asked to authorize
* the client application.
*
* @param message
* A message to be shown to the end-user on the authentication device.
*
* @param authTimeout
* The value of timeout in seconds for the end-user authentication/authorization
* on the authentication device.
*
* @param actionizeToken
* A token that is used with the actionize endpoint ({@code /api/atuhenticate/actionize})
* to automate authentication device responses.
*
* @return
* A response from the authentication device.
*/ | public static SyncAuthenticationResponse sync(String subject, String message, | 8 |
winterDroid/android-drawable-importer-intellij-plugin | src/main/java/de/mprengemann/intellij/plugin/androidicons/controllers/iconimporter/IIconsImporterController.java | [
"public interface IController<T> {\n void addObserver(T observer);\n\n void removeObserver(T observer);\n\n void tearDown();\n}",
"public interface IIconPackController {\n\n String getId();\n\n List<ImageAsset> getAssets(String category);\n\n List<ImageAsset> getAssets(List<String> categories);\... | import com.intellij.openapi.project.Project;
import de.mprengemann.intellij.plugin.androidicons.controllers.IController;
import de.mprengemann.intellij.plugin.androidicons.controllers.icons.IIconPackController;
import de.mprengemann.intellij.plugin.androidicons.images.RefactoringTask;
import de.mprengemann.intellij.plugin.androidicons.model.Format;
import de.mprengemann.intellij.plugin.androidicons.model.ImageAsset;
import de.mprengemann.intellij.plugin.androidicons.model.Resolution;
import java.io.File;
import java.util.List;
import java.util.Set; | package de.mprengemann.intellij.plugin.androidicons.controllers.iconimporter;
public interface IIconsImporterController extends IController<IconsImporterObserver>{
void setExportRoot(String exportRoot);
void setSelectedIconPack(String iconPack);
void setSelectedCategory(String category);
| void setSelectedAsset(ImageAsset asset); | 4 |
koen-serneels/HomeAutomation | src/main/java/be/error/rpi/heating/HeatingInfoPollerJobSchedulerFactory.java | [
"public static RunConfig getInstance() {\n\tif (runConfig == null) {\n\t\tthrow new IllegalStateException(\"Initialize first\");\n\t}\n\treturn runConfig;\n}",
"public static String JOB_CONFIG_KEY = \"jobconfig\";",
"public interface EbusCommand<R> {\n\n\tString[] getEbusCommands();\n\n\tR convertResult(List<St... | import static be.error.rpi.config.RunConfig.getInstance;
import static be.error.rpi.heating.jobs.HeatingInfoPollerJob.JOB_CONFIG_KEY;
import static org.apache.commons.lang3.time.DateUtils.addSeconds;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import java.util.Date;
import java.util.Map;
import org.quartz.CronExpression;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tuwien.auto.calimero.GroupAddress;
import be.error.rpi.ebus.EbusCommand;
import be.error.rpi.heating.jobs.HeatingInfoPollerJob;
import be.error.rpi.heating.jobs.JobConfig; | /*-
* #%L
* Home Automation
* %%
* Copyright (C) 2016 - 2017 Koen Serneels
* %%
* 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.
* #L%
*/
package be.error.rpi.heating;
public class HeatingInfoPollerJobSchedulerFactory {
private static final Logger logger = LoggerFactory.getLogger("heating");
private final EbusDeviceAddress ebusDeviceAddress;
private final Map<EbusCommand<?>, GroupAddress> map;
public HeatingInfoPollerJobSchedulerFactory(EbusDeviceAddress ebusDeviceAddress, Map<EbusCommand<?>, GroupAddress> map) throws Exception {
this.map = map;
this.ebusDeviceAddress = ebusDeviceAddress;
logger.debug("Scheduling HeatingInfoPollerJob");
getInstance().getScheduler().scheduleJob(getJob(HeatingInfoPollerJob.class, ebusDeviceAddress, map),
newTrigger().withSchedule(cronSchedule(new CronExpression("0 0/2 * * * ?"))).startNow().build());
}
public void triggerNow() throws SchedulerException {
getInstance().getScheduler().scheduleJob(getJob(HeatingInfoPollerJob.class, ebusDeviceAddress, map),
newTrigger().startAt(addSeconds(new Date(), 5)).withSchedule(simpleSchedule().withRepeatCount(0)).build());
}
private JobDetail getJob(Class<? extends Job> job, EbusDeviceAddress ebusDeviceAddress, Map<EbusCommand<?>, GroupAddress> map) {
JobDetail jobDetail = newJob(job).build();
JobConfig jobConfig = new JobConfig(ebusDeviceAddress, map); | jobDetail.getJobDataMap().put(JOB_CONFIG_KEY, jobConfig); | 1 |
52North/Supervisor | core/src/main/java/org/n52/supervisor/resources/Checks.java | [
"@Singleton\npublic class CheckerResolver {\n\n private static Logger log = LoggerFactory.getLogger(CheckerResolver.class);\n\n\t@Inject\n\tprivate Set<RunnerFactory> factories;\n \n public CheckRunner getRunner(final Check check) {\n log.debug(\"Resolving check: {}\", check);\n // String che... | import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.n52.supervisor.CheckerResolver;
import org.n52.supervisor.api.Check;
import org.n52.supervisor.api.CheckRunner;
import org.n52.supervisor.db.CheckDatabase;
import org.n52.supervisor.db.ResultDatabase;
import org.n52.supervisor.tasks.ManualChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.servlet.SessionScoped; | /**
* Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH
*
* 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.n52.supervisor.resources;
/**
*
* @author Daniel Nüst
*
*/
@Path("/api/v1/checks")
@SessionScoped
public class Checks {
private static Logger log = LoggerFactory.getLogger(Checks.class);
private final ExecutorService manualExecutor;
private final CheckDatabase checkDatabase;
private final ResultDatabase resultDatabase;
private final CheckerResolver checkResolver;
@Inject
public Checks(final CheckDatabase cd, final ResultDatabase rd, final CheckerResolver cr) {
checkDatabase = cd;
resultDatabase = rd;
checkResolver = cr;
// create thread pool for manually started checks
manualExecutor = Executors.newSingleThreadExecutor();
log.info("NEW {}", this);
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getCheck(@PathParam("id") final String id) {
log.debug("Requesting checker with id {}", id);
final Check check = checkDatabase.getCheck(id);
if (check != null) {
return Response.ok().entity(check).build();
}
return Response.status(Status.NOT_FOUND).entity("{\"error\": \"entitiy for id not found:" + id + "\" } ").build();
}
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response getChecks(@Context final UriInfo uriInfo) throws JSONException {
final List<Check> checks = checkDatabase.getAllChecks();
// GenericEntity<List<Check>> entity = new GenericEntity<List<Check>>(Lists.newArrayList(checks)) {};
final JSONObject result = new JSONObject();
final JSONArray jsonChecks = new JSONArray();
result.put("checks", jsonChecks);
for (final Check check : checks) {
final JSONObject jsonCheck = new JSONObject();
jsonCheck.put("id", check.getIdentifier());
URI path = uriInfo.getBaseUriBuilder().path(Checks.class).path(check.getIdentifier()).build();
jsonCheck.put("uri", path);
path = uriInfo.getBaseUriBuilder().path(Checks.class).path(check.getIdentifier() + "/results").build();
jsonCheck.put("results",path);
jsonChecks.put(jsonCheck);
}
return Response.ok(result).build();
// return Response.ok(entity).build();
}
@GET
@Path("/{id}/results")
@Produces(MediaType.APPLICATION_JSON)
public Response getChecksResults(
@Context final UriInfo uriInfo,
@PathParam("id") final String id) {
final UriBuilder redirect = uriInfo.getBaseUriBuilder().path(Results.class).queryParam("checkId", id);
return Response.seeOther(redirect.build()).build();
}
@PUT
@Path("/run")
@Produces(MediaType.TEXT_PLAIN)
public Response runChecksNow(
@QueryParam("notify") @DefaultValue("true") final boolean notify,
@QueryParam("all") @DefaultValue("false") final boolean runAll,
@QueryParam("ids") final String ids,
@Context final UriInfo uri) {
log.debug("Running processes: notify = {}, all = {}, ids = {}", notify, runAll, ids);
log.debug(uri.toString());
if (runAll && ids != null) {
log.warn("Both ids and 'all' specified.");
}
ManualChecker manualChecker = null;
if (runAll) { | final Collection<CheckRunner> checkers = new ArrayList<>(); | 2 |
bibryam/semat | fixture/src/main/java/com/ofbizian/semat/fixture/scenarios/DemoFixture.java | [
"public enum AlphaType {\n OPPORTUNITY,\n STAKEHOLDERS,\n REQUIREMENTS,\n SOFTWARE_SYSTEM,\n WORK,\n TEAM,\n WAY_OF_WORKING;\n}",
"@javax.jdo.annotations.PersistenceCapable(\n identityType= IdentityType.DATASTORE,\n schema = \"simple\"\n)\n@DomainObject\npublic class Item extend... | import java.util.Set;
import com.google.common.collect.Sets;
import com.ofbizian.semat.dom.domain.AlphaType;
import com.ofbizian.semat.dom.domain.Item;
import com.ofbizian.semat.dom.domain.Project;
import com.ofbizian.semat.dom.domain.ProjectRepository;
import com.ofbizian.semat.dom.domain.State;
import com.ofbizian.semat.fixture.dom.ItemCreate;
import com.ofbizian.semat.fixture.dom.ProjectCreate;
import com.ofbizian.semat.fixture.dom.ProjectTearDown;
import com.ofbizian.semat.fixture.dom.StateCreate; | package com.ofbizian.semat.fixture.scenarios;
public class DemoFixture extends AbstractFixtureScript {
public DemoFixture() {
withDiscoverability(Discoverability.DISCOVERABLE);
}
private Set<Project> projects = Sets.newLinkedHashSet();
@Override
protected void doExecute(ExecutionContext ec) {
ec.executeChild(this, new ProjectTearDown());
createProject(ec, "SOE", "Standard Operating Environment", "This is a demo SOE project");
createProject(ec, "ESB", "Enterprise Service Bus", "This is a demo ESB project");
}
private void createProject(ExecutionContext ec, String code, String name, String description) { | ProjectCreate projectCreate = new ProjectCreate(); | 6 |
indvd00m/java-ascii-render | ascii-render/src/test/java/com/indvd00m/ascii/render/tests/TestContext.java | [
"public class Render implements IRender {\n\n\tprotected boolean pseudoCanvas;\n\n\t@Override\n\tpublic IContextBuilder newBuilder() {\n\t\treturn ContextBuilder.newBuilder();\n\t}\n\n\t@Override\n\tpublic ICanvas render(IContext context) {\n\t\tfinal ICanvas canvas;\n\t\tif (pseudoCanvas) {\n\t\t\tcanvas = new Pse... | import com.indvd00m.ascii.render.Render;
import com.indvd00m.ascii.render.api.IContext;
import com.indvd00m.ascii.render.api.IContextBuilder;
import com.indvd00m.ascii.render.api.IElement;
import com.indvd00m.ascii.render.api.IRender;
import com.indvd00m.ascii.render.elements.Dot;
import com.indvd00m.ascii.render.elements.Rectangle;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package com.indvd00m.ascii.render.tests;
/**
* @author indvd00m (gotoindvdum[at]gmail[dot]com)
* @since 1.2.0
*/
public class TestContext {
@Test
public void test01() { | IRender render = new Render(); | 0 |
SmasSive/DaggerWorkshopGDG | app/src/main/java/com/smassive/daggerworkshopgdg/app/injector/component/ApplicationComponent.java | [
"@Module\npublic class ApplicationModule {\n\n private final AndroidApplication application;\n\n public ApplicationModule(AndroidApplication application) {\n this.application = application;\n }\n\n // provide dependencies\n @Provides\n @Singleton\n Context provideContext() {\n ret... | import com.smassive.daggerworkshopgdg.app.injector.module.ApplicationModule;
import com.smassive.daggerworkshopgdg.app.navigation.Navigator;
import com.smassive.daggerworkshopgdg.app.view.activity.BaseActivity;
import com.smassive.daggerworkshopgdg.domain.executor.PostExecutionThread;
import com.smassive.daggerworkshopgdg.domain.executor.ThreadExecutor;
import com.smassive.daggerworkshopgdg.domain.repository.ComicsRepository;
import javax.inject.Singleton;
import dagger.Component; | /**
* Copyright (C) 2016 Sergi Castillo Open Source Project
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.smassive.daggerworkshopgdg.app.injector.component;
@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
// where should I inject the dependencies?
void inject(BaseActivity baseActivity);
Navigator getNavigator();
ThreadExecutor getThreadExecutor();
PostExecutionThread getPostExecutionThread();
| ComicsRepository getComicsRepository(); | 5 |
GuntherDW/TweakcraftUtils | src/com/guntherdw/bukkit/tweakcraft/Commands/CommandHandler.java | [
"public class CommandException extends Exception {\n public CommandException(String e) {\n super(e);\n }\n}",
"public class CommandSenderException extends Exception {\n public CommandSenderException(String e) {\n super(e);\n }\n}",
"public class CommandUsageException extends Exception ... | import com.guntherdw.bukkit.tweakcraft.Commands.Commands.*;
import com.guntherdw.bukkit.tweakcraft.Exceptions.CommandException;
import com.guntherdw.bukkit.tweakcraft.Exceptions.CommandSenderException;
import com.guntherdw.bukkit.tweakcraft.Exceptions.CommandUsageException;
import com.guntherdw.bukkit.tweakcraft.Exceptions.PermissionsException;
import com.guntherdw.bukkit.tweakcraft.Packages.LocalPlayer;
import com.guntherdw.bukkit.tweakcraft.TweakcraftUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.SimplePluginManager;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*; | /*
* Copyright (c) 2011 GuntherDW
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.guntherdw.bukkit.tweakcraft.Commands;
/**
* @author GuntherDW
*/
public class CommandHandler {
private Map<String, iCommand> commandMap = new HashMap<String, iCommand>();
private Map<String, Method> newCommandMap = new HashMap<String, Method>();
private Map<String, Method> aliasCommandMap = new HashMap<String, Method>();
private Map<String, List<String>> commandAliases = new HashMap<String, List<String>>();
private Map<Method, Object> instanceMap = new HashMap<Method, Object>();
/** Command Classes **/
public AdminCommands adminCommands = null;
public ChatCommands chatCommands = null;
public DebugCommands debugCommands = null;
public EssentialsCommands essentialsCommands = null;
public GeneralCommands generalCommands = null;
public TeleportationCommands teleportationCommands = null;
public WeatherCommands weatherCommands = null;
/** Bukkit Command Injection stuff **/
private SimplePluginManager simplePluginManager = null;
private SimpleCommandMap simpleCommandMap = null;
private Constructor<PluginCommand> pluginCommandConstructor = null;
private TweakcraftUtils plugin;
private Object getMethodInstance(Method method) {
if (instanceMap.containsKey(method))
return instanceMap.get(method);
return null;
}
public CommandHandler(TweakcraftUtils instance) {
this.plugin = instance;
commandMap.clear();
newCommandMap.clear();
adminCommands = new AdminCommands(instance);
chatCommands = new ChatCommands(instance);
debugCommands = new DebugCommands(instance);
essentialsCommands = new EssentialsCommands(instance);
generalCommands = new GeneralCommands(instance);
teleportationCommands = new TeleportationCommands(instance);
weatherCommands = new WeatherCommands(instance);
addCommandClass(adminCommands, false);
addCommandClass(chatCommands, false);
addCommandClass(debugCommands, false);
addCommandClass(essentialsCommands, false);
addCommandClass(generalCommands, false);
addCommandClass(teleportationCommands, false);
addCommandClass(weatherCommands, false);
}
public void addCommandClass(Object instance) {
this.addCommandClass(instance, true);
}
public void addCommandClass(Object instance, boolean injectIntoBukkit) {
for (Method m : instance.getClass().getDeclaredMethods()) {
if (m.getAnnotation(aCommand.class) != null)
injectCommand(m, instance, injectIntoBukkit);
}
}
public void injectCommand(Method method, Object instance, boolean injectIntoBukkit) {
aCommand annotation = method.getAnnotation(aCommand.class);
String[] aliases = annotation.aliases();
if (aliases.length > 0) {
String commandName = aliases[0];
String[] commandAliases_array = new String[aliases.length-1];
if(aliases.length > 1)
System.arraycopy(aliases, 1, commandAliases_array, 0, aliases.length-1);
if (newCommandMap.containsKey(commandName)) {
plugin.getLogger().warning("Duplicate command found!");
plugin.getLogger().warning("Method : " + method.getName() + "!");
plugin.getLogger().warning("Command : " + commandName + "!");
return;
}
List<String> al = new ArrayList<String>();
newCommandMap.put(commandName, method);
for(String alias : commandAliases_array) {
al.add(alias);
aliasCommandMap.put(alias, method);
}
this.commandAliases.put(commandName, al);
instanceMap.put(method, instance);
if(injectIntoBukkit) {
// plugin.getLogger().info("Injecting "+commandName+" into Bukkit!");
this.injectIntoBukkit(commandName, aliases, method, instance, annotation);
}
}
}
public void getBukkitCommandMap() {
try {
Object plmgr = plugin.getServer().getPluginManager();
if (plmgr instanceof SimplePluginManager) {
SimplePluginManager pluginmanager = (SimplePluginManager) plmgr;
Field f = SimplePluginManager.class.getDeclaredField("commandMap");
f.setAccessible(true);
SimpleCommandMap simpleCommandMap = (SimpleCommandMap) f.get(pluginmanager);
Constructor<PluginCommand> con = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
con.setAccessible(true);
this.simplePluginManager = pluginmanager;
this.simpleCommandMap = simpleCommandMap;
this.pluginCommandConstructor = con;
}
} catch (Exception e) {
plugin.getLogger().warning("Exception caught while getting the CommandMap, plugin command injection will NOT work!");
e.printStackTrace();
}
}
public void injectIntoBukkit(String command, String[] aliases, Method commandMethod, Object classInstance, aCommand annotation) {
if(this.simplePluginManager == null)
this.getBukkitCommandMap();
try {
if (this.simplePluginManager != null) {
PluginCommand cmd = pluginCommandConstructor.newInstance(command, this.plugin);
cmd.setAliases(Arrays.asList(aliases));
cmd.setPermission("tweakcraftutils."+annotation.permissionBase());
cmd.setDescription(annotation.description());
cmd.setUsage(annotation.usage());
cmd.setExecutor(plugin);
this.simpleCommandMap.register("tweakcraftutils", cmd);
}
} catch (Exception e) {
plugin.getLogger().warning("Exception caught while injecting '" + command + "' into Bukkit!");
e.printStackTrace();
}
}
public List<String> getAliases(String command) {
return commandAliases.get(command);
}
public void addHelpTopics() {
for(Map.Entry<String, Method> entry : newCommandMap.entrySet()) {
String commandName = entry.getKey();
Method m = entry.getValue();
aCommand annotation = m.getAnnotation(aCommand.class);
if(annotation == null)
continue;
PluginCommand pcmd = plugin.getCommand(commandName);
if(pcmd!=null && !annotation.permissionBase().equals(""))
pcmd.setPermission("tweakcraftutils."+annotation.permissionBase());
}
}
@SuppressWarnings("unchecked")
public void checkCommands() {
if (plugin.getConfigHandler().enableDebug) { /* Show commands with no command attached */
PluginDescriptionFile pdFile = plugin.getDescription();
Map<String, Map<String, Object>> pluginCommands = pdFile.getCommands();
Set<String> cmds = pluginCommands.keySet();
for (String c : cmds) {
if (!this.newCommandMap.containsKey(c) && !this.aliasCommandMap.containsKey(c))
plugin.getLogger().warning("WARNING: Unmapped command : " + c);
}
}
}
public TweakcraftUtils getPlugin() {
return plugin;
}
public Map<String, Method> getCommandMap() {
return newCommandMap;
}
public boolean isInjected(String commandName) {
return plugin.getCommand(commandName) != null;
/* for(Map.Entry<String, Method> entry : getCommandMap().entrySet()) {
if(plugin.getCommand())
} */
}
public Method getCommand(String command) {
if (newCommandMap.containsKey(command)) {
return newCommandMap.get(command);
} else if (aliasCommandMap.containsKey(command)) {
return aliasCommandMap.get(command);
} else {
return null;
}
}
public Object getCommandInstance(Method command) {
if (instanceMap.containsKey(command)) {
return instanceMap.get(command);
} else {
return null;
}
}
public boolean executeCommand(CommandSender sender, String name, String[] args) {
String mess = "";
if (args.length > 1) {
for (String m : args)
mess += m + " ";
mess = mess.substring(0, mess.length() - 1);
} else if (args.length == 1) {
mess = args[0];
}
// Method
if (newCommandMap.containsKey(name) || aliasCommandMap.containsKey(name)) {
try {
if (!runMethod(sender, name, args)) {
sender.sendMessage("This command did not go as intended!");
}
/* if (sender instanceof Player) {
final LocalPlayer lp = plugin.wrapPlayer((Player)sender);
plugin.getLogger().info((lp.isInvisible()?"[INVIS] ":"") + sender.getName() + " issued: /" + name + " " + mess);
} else */
if(!(sender instanceof Player))
plugin.getLogger().info("CONSOLE issued: /" + name + " " + mess);
return true;
} /*catch (CommandNotFoundException e) {
sender.sendMessage("TweakcraftUtils error, command not found!");
}*/ catch (PermissionsException e) {
sender.sendMessage(ChatColor.RED + "You do not have the correct permissions for this command or usage!");
if (sender instanceof Player) {
final LocalPlayer lp = plugin.wrapPlayer((Player)sender);
plugin.getLogger().info((lp.isInvisible()?"[INVIS] ":"") + ((Player) sender).getName() + " tried: /" + name + " " + mess);
}
} catch (CommandUsageException e) {
sender.sendMessage(ChatColor.YELLOW + e.getMessage()); | } catch (CommandSenderException e) { | 1 |
centralperf/centralperf | src/main/java/org/centralperf/service/RunStatisticsService.java | [
"@Entity\npublic class Run {\n\n\t@Id\n\t@GeneratedValue\n\tprivate Long id;\n\n\t@NotNull\n\t@Size(min = 1, max = 33)\n\tprivate String label;\n\n\t@ManyToOne\n\tprivate ScriptVersion scriptVersion;\n\t\n\tprivate boolean launched = false;\n\t\n\tprivate boolean running = false;\n\t\n\tprivate Date startDate;\n\t\... | import java.util.Iterator;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.centralperf.model.dao.Run;
import org.centralperf.model.graph.ErrorRateGraph;
import org.centralperf.model.graph.ResponseSizeGraph;
import org.centralperf.model.graph.ResponseTimeGraph;
import org.centralperf.model.graph.RunStats;
import org.centralperf.model.graph.SummaryGraph;
import org.centralperf.repository.RunRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.service;
/**
* This class is singleton service to collect run data and graphs.<br>
* A cache mechanism with time eviction is used to avoid database overload if too many refresh
* are asked by users.
* @since 1.0
*/
@Service
public class RunStatisticsService {
@Resource
private RunRepository runRepository;
@PersistenceContext
private EntityManager em;
@Value("${centralperf.report.cache.delay-seconds}")
private Long cacheRefreshDelay;
@Value("${centralperf.report.scaling.level1-seconds}")
private Long limitOfFisrtScaling;
@Value("${centralperf.report.scaling.level2-seconds}")
private Long limitOfSecondScaling;
//Cache can't be load on object construction as refresh delay is not yet set | private LoadingCache<Long, SummaryGraph> summaryGraphCache; | 5 |
neowu/core-ng-demo-project | demo-service/src/main/java/app/demo/customer/service/CustomerService.java | [
"public class CreateCustomerRequest {\n @NotNull\n @NotBlank\n @Property(name = \"email\")\n public String email;\n\n @NotNull\n @NotBlank\n @Property(name = \"first_name\")\n public String firstName;\n\n @NotBlank\n @Property(name = \"last_name\")\n public String lastName;\n}",
"... | import app.demo.api.customer.CreateCustomerRequest;
import app.demo.api.customer.CustomerView;
import app.demo.api.customer.SearchCustomerRequest;
import app.demo.api.customer.SearchCustomerResponse;
import app.demo.api.customer.UpdateCustomerRequest;
import app.demo.customer.domain.Customer;
import app.demo.customer.domain.CustomerStatus;
import core.framework.db.Query;
import core.framework.db.Repository;
import core.framework.inject.Inject;
import core.framework.util.Strings;
import core.framework.web.exception.ConflictException;
import core.framework.web.exception.NotFoundException;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.stream.Collectors; | package app.demo.customer.service;
public class CustomerService {
@Inject
Repository<Customer> customerRepository;
public CustomerView get(Long id) {
Customer customer = customerRepository.get(id).orElseThrow(() -> new NotFoundException("customer not found, id=" + id));
return view(customer);
}
public CustomerView create(CreateCustomerRequest request) {
Optional<Customer> existingCustomer = customerRepository.selectOne("email = ?", request.email);
if (existingCustomer.isPresent()) {
throw new ConflictException("customer already exists, email=" + request.email);
}
Customer customer = new Customer();
customer.status = CustomerStatus.ACTIVE;
customer.email = request.email;
customer.firstName = request.firstName;
customer.lastName = request.lastName;
customer.updatedTime = LocalDateTime.now();
customer.id = customerRepository.insert(customer).orElseThrow();
return view(customer);
}
public CustomerView update(Long id, UpdateCustomerRequest request) {
Customer customer = customerRepository.get(id).orElseThrow(() -> new NotFoundException("customer not found, id=" + id));
customer.updatedTime = LocalDateTime.now();
customer.firstName = request.firstName;
if (request.lastName != null) {
customer.lastName = request.lastName;
}
customerRepository.partialUpdate(customer);
return view(customer);
}
| public SearchCustomerResponse search(SearchCustomerRequest request) { | 3 |
paolodongilli/SASAbus | src/it/sasabz/android/sasabus/classes/dialogs/SelectDialog.java | [
"public class MapSelectActivity extends MapActivity {\r\n\t\r\n\tprivate String from = \"\";\r\n\t\r\n\tprivate String to = \"\";\r\n\t\r\n\t/**\r\n\t * sets the text from the textview from to the string from\r\n\t * @param from is the string to set\r\n\t */\r\n\tpublic void setFrom(String from)\r\n\t{\r\n\t\tthis.... | import it.sasabz.android.sasabus.MapSelectActivity;
import it.sasabz.android.sasabus.R;
import it.sasabz.android.sasabus.R.string;
import it.sasabz.android.sasabus.classes.adapter.MyXMLConnectionAdapter;
import it.sasabz.android.sasabus.classes.dbobjects.Palina;
import it.sasabz.android.sasabus.classes.hafas.XMLConnection;
import it.sasabz.android.sasabus.classes.hafas.XMLJourney;
import it.sasabz.android.sasabus.fragments.OrarioFragment;
import it.sasabz.android.sasabus.fragments.WayFragment;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Vector;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
| /**
*
* ConnectionDialog.java
*
*
* Copyright (C) 2012 Markus Windegger
*
* This file is part of SasaBus.
* SasaBus 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.
*
* SasaBus 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 SasaBus. If not, see <http://www.gnu.org/licenses/>.
*
*/
package it.sasabz.android.sasabus.classes.dialogs;
public class SelectDialog extends Dialog{
private MapSelectActivity activity = null;
| private Palina palina = null;
| 2 |
zozoh/zdoc | java/test/org/nutz/zdoc/impl/AbstractScannerTest.java | [
"public class ZDocBaseTest {\n\n protected Parser parser;\n\n protected AmFactory NewAmFactory(String name) {\n return new AmFactory(\"org/nutz/zdoc/am/\" + name + \".js\");\n }\n\n protected Parsing ING(String str) {\n return new Parsing(Lang.inr(str));\n }\n\n protected Parsing ING... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.nutz.zdoc.ZDocBaseTest;
import org.nutz.zdoc.Parsing;
import org.nutz.zdoc.ZBlock;
import org.nutz.zdoc.ZLine;
import org.nutz.zdoc.ZLineType; | package org.nutz.zdoc.impl;
public class AbstractScannerTest extends ZDocBaseTest {
protected AbstractScanner scanner;
protected void _C(Parsing ing,
int bIndex,
ZLineType expectBlockType,
int lIndex,
String expectText,
int expectIndent,
ZLineType expectLineType) {
this._C(ing,
bIndex,
expectBlockType,
lIndex,
expectText,
expectIndent,
expectLineType,
(char) 0);
}
protected void _C(Parsing ing,
int bIndex,
ZLineType expectBlockType,
int lIndex,
String expectText,
int expectIndent,
ZLineType expectLineType,
char expectIType) { | ZBlock bl = ing.blocks.get(bIndex); | 2 |
TheTorbinWren/OresPlus | src/main/java/tw/oresplus/core/OreEventHandler.java | [
"@Mod(modid = References.MOD_ID, name = References.MOD_NAME, version = References.MOD_VERSION, dependencies=\"required-after:Forge@10.13.0.1180;after:TConstruct\")\npublic class OresPlus {\n\t\n\t@SidedProxy(clientSide=\"tw.oresplus.client.ClientProxy\", serverSide=\"tw.oresplus.core.ServerProxy\") \n\tpublic stati... | import java.util.ArrayList;
import tw.oresplus.OresPlus;
import tw.oresplus.blocks.BlockManager;
import tw.oresplus.worldgen.IOreGenerator;
import tw.oresplus.worldgen.OreGenType;
import tw.oresplus.worldgen.OreGenerators;
import tw.oresplus.worldgen.OreGeneratorsEnd;
import tw.oresplus.worldgen.OreGeneratorsNether;
import tw.oresplus.worldgen.WorldGenCore;
import tw.oresplus.worldgen.WorldGenOre;
import cpw.mods.fml.common.event.FMLMissingMappingsEvent;
import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage;
import cpw.mods.fml.common.eventhandler.Event.Result;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraftforge.event.terraingen.OreGenEvent.GenerateMinable;
import net.minecraftforge.event.world.ChunkDataEvent;
import net.minecraftforge.event.world.WorldEvent; | package tw.oresplus.core;
public class OreEventHandler {
@SubscribeEvent
public void chunkLoad(ChunkDataEvent.Load event) {
NBTTagCompound oresPlusRegen = event.getData().getCompoundTag("OresPlus");
if (oresPlusRegen.hasNoTags()) { // regen info not found, checking for old regen key
oresPlusRegen.setString("ores", event.getData().getString("OresPlus:regenKey"));
}
NBTTagCompound oreRegenArray = oresPlusRegen.getCompoundTag("oreRegenArray");
int dimId = event.world.provider.dimensionId;
ArrayList<WorldGenOre> oreGenArray = WorldGenCore.oreGenerators.get(dimId);
if (oreGenArray != null) {
for (WorldGenOre oreGen : oreGenArray) {
String oreRegenKey = oreRegenArray.getString(oreGen.getOreName());
if (oreRegenKey.equals("")) {
oreRegenKey = oresPlusRegen.getString("ores");
}
if (oreGen.doRegen && !oreGen.regenKey.equals(oreRegenKey)) {
ArrayList<ChunkCoordIntPair> chunks = oreGen.regenList.get(Integer.valueOf(dimId));
if (chunks == null)
chunks = new ArrayList();
chunks.add(event.getChunk().getChunkCoordIntPair());
oreGen.regenList.put(dimId, chunks);
}
}
}
if (!OresPlus.regenKeyOil.equals("DISABLED") && !oresPlusRegen.getString("oil").equals(OresPlus.regenKeyOil)) {
int dim = event.world.provider.dimensionId;
ArrayList chunks = TickHandler.oilRegenList.get(Integer.valueOf(dim));
if (chunks == null)
chunks = new ArrayList();
chunks.add(event.getChunk().getChunkCoordIntPair());
TickHandler.oilRegenList.put(Integer.valueOf(dim), chunks);
}
if (!OresPlus.regenKeyRubberTree.equals("DISABLED") && !oresPlusRegen.getString("rubberTree").equals(OresPlus.regenKeyRubberTree)) {
int dim = event.world.provider.dimensionId;
ArrayList chunks = TickHandler.rubberTreeRegenList.get(Integer.valueOf(dim));
if (chunks == null)
chunks = new ArrayList();
chunks.add(event.getChunk().getChunkCoordIntPair());
TickHandler.rubberTreeRegenList.put(Integer.valueOf(dim), chunks);
}
if (!OresPlus.regenKeyBeehives.equals("DISABLED") && !oresPlusRegen.getString("beehives").equals(OresPlus.regenKeyBeehives)) {
int dim = event.world.provider.dimensionId;
ArrayList chunks = TickHandler.beehiveRegenList.get(Integer.valueOf(dim));
if (chunks == null)
chunks = new ArrayList();
chunks.add(event.getChunk().getChunkCoordIntPair());
TickHandler.beehiveRegenList.put(Integer.valueOf(dim), chunks);
}
}
@SubscribeEvent
public void chunkSave(ChunkDataEvent.Save event) {
NBTTagCompound oresPlusRegen = new NBTTagCompound();
int dimId = event.world.provider.dimensionId;
NBTTagCompound oreRegenArray = new NBTTagCompound();
ArrayList<WorldGenOre> oreGenArray = WorldGenCore.oreGenerators.get(dimId);
if (oreGenArray != null) {
for (WorldGenOre oreGen : oreGenArray) {
oreRegenArray.setString(oreGen.getOreName(), oreGen.regenKey);
}
}
oresPlusRegen.setTag("oreRegenArray", oreRegenArray);
oresPlusRegen.setString("ores", OresPlus.regenKeyOre);
oresPlusRegen.setString("oil", OresPlus.regenKeyOil);
oresPlusRegen.setString("rubberTree", OresPlus.regenKeyRubberTree);
oresPlusRegen.setString("beehives", OresPlus.regenKeyBeehives);
event.getData().setTag("OresPlus", oresPlusRegen);
}
@SubscribeEvent
public void worldLoad(WorldEvent.Load event) {
OresPlus.log.info("Loading ore generators for dimension id " + event.world.provider.dimensionId);
int dim = event.world.provider.dimensionId;
if (WorldGenCore.oreGenerators.get(dim) != null) {
OresPlus.log.debug("Skipping load, dimension already loaded");
return;
}
ArrayList<WorldGenOre> oreGenList = new ArrayList();
IOreGenerator[] sources;
switch (dim) {
case -1: | sources = OreGeneratorsNether.values(); | 6 |
google/android-classyshark | ClassySharkWS/src/com/google/classyshark/silverghost/translator/dex/DexInfoTranslator.java | [
"public interface TokensMapper {\n\n TokensMapper readMappings(File file);\n\n Map<String,String> getReverseClasses();\n}",
"public class DexlibLoader {\n public static DexFile loadDexFile(File binaryArchiveFile) throws Exception {\n DexBackedDexFile newDexFile = DexFileFactory.loadDexFile(binaryA... | import com.google.classyshark.silverghost.TokensMapper;
import com.google.classyshark.silverghost.contentreader.dex.DexlibLoader;
import com.google.classyshark.silverghost.translator.Translator;
import com.google.classyshark.silverghost.translator.jar.JarInfoTranslator;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.jf.dexlib2.dexbacked.DexBackedDexFile;
import org.jf.dexlib2.iface.DexFile;
import static com.google.classyshark.silverghost.translator.apk.dashboard.ApkDashboard.getClassesWithNativeMethodsPerDexIndex;
import static com.google.classyshark.silverghost.translator.java.dex.MultidexReader.extractClassesDex; | /*
* Copyright 2015 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.classyshark.silverghost.translator.dex;
/**
* Translator for the classes.dex entry
*/
public class
DexInfoTranslator implements Translator {
private File apkFile;
private String dexFileName;
private int index;
private List<ELEMENT> elements = new ArrayList<>();
public DexInfoTranslator(String dexFileName, File apkFile) {
this.apkFile = apkFile;
this.dexFileName = dexFileName;
}
@Override
public String getClassName() {
return dexFileName;
}
@Override
public void addMapper(TokensMapper reverseMappings) {
}
@Override
public void apply() {
try {
elements.clear();
| File classesDex = extractClassesDex(dexFileName, apkFile, this); | 5 |
OpenWatch/OpenWatch-Android | app/OpenWatch/src/org/ale/openwatch/OWMissionViewActivity.java | [
"public class Constants {\n\n public static final String SUPPORT_EMAIL = \"team@openwatch.net\";\n public static final String GOOGLE_STORE_URL = \"https://play.google.com/store/apps/details?id=org.ale.openwatch\";\n public static final String APPLE_STORE_URL = \"https://itunes.apple.com/us/app/openwatch-so... | import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.ale.openwatch.constants.Constants;
import org.ale.openwatch.http.OWServiceRequests;
import org.ale.openwatch.model.OWMission;
import org.ale.openwatch.model.OWServerObject;
import org.ale.openwatch.share.Share;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.util.Date; | package org.ale.openwatch;
/**
* Created by davidbrodsky on 6/10/13.
*/
public class OWMissionViewActivity extends SherlockActivity implements OWObjectBackedEntity {
private static final String TAG = "OWMissionViewActivity";
int model_id = -1;
int server_id = -1;
private static int owphoto_id = -1;
private static int owphoto_parent_id = -1;
String missionTag;
String lastBounty; // only animate bounty view if value changes
Context c;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mission_view);
c = getApplicationContext();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
OWUtils.setReadingFontOnChildren((ViewGroup) findViewById(R.id.relativeLayout));
this.getSupportActionBar().setTitle("");
processMissionFromIntent(getIntent());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_mission_view, menu);
return true;
}
public void camcorderButtonClick(View v){
Intent i = new Intent(this, RecorderActivity.class);
i.putExtra(Constants.OBLIGATORY_TAG, missionTag);
startActivity(i);
}
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data){
Log.i("OWMissionViewActivity-onActivityResult","got it");
if(data == null)
Log.i("OWMissionViewActivity-onActivityResult", "data null");
if(requestCode == Constants.CAMERA_ACTION_CODE && resultCode == RESULT_OK){
Intent i = new Intent(this, OWPhotoReviewActivity.class);
i.putExtra("owphoto_id", owphoto_id);
i.putExtra(Constants.INTERNAL_DB_ID, owphoto_parent_id); // server object id
// TODO: Bundle tag to add
Log.i("OWMissionViewActivity-onActivityResult", String.format("bundling owphoto_id: %d, owserverobject_id: %d",owphoto_id, owphoto_parent_id));
startActivity(i);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.tab_share:
if(server_id > 0){
OWServerObject object = OWServerObject.objects(getApplicationContext(), OWServerObject.class).get(model_id); | Share.showShareDialogWithInfo(this, getString(R.string.share_mission), object.getTitle(getApplicationContext()), OWUtils.urlForOWServerObject(object, getApplicationContext())); | 4 |
Nilhcem/devfestnantes-2016 | app/src/test/java/com/nilhcem/devfestnantes/data/database/DbMapperTest.java | [
"@Singleton\npublic class LocalDateTimeAdapter {\n\n private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm\", Locale.US);\n\n @Inject\n public LocalDateTimeAdapter() {\n }\n\n @ToJson\n public String toText(LocalDateTime dateTime) {\n return dateTime.for... | import android.os.Build;
import com.nilhcem.devfestnantes.BuildConfig;
import com.nilhcem.devfestnantes.core.moshi.LocalDateTimeAdapter;
import com.nilhcem.devfestnantes.data.app.AppMapper;
import com.nilhcem.devfestnantes.data.app.model.Room;
import com.nilhcem.devfestnantes.data.app.model.Session;
import com.nilhcem.devfestnantes.data.app.model.Speaker;
import com.squareup.moshi.Moshi;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.threeten.bp.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.truth.Truth.assertThat;
import static java.util.Collections.singletonList;
import static org.mockito.Mockito.when; | package com.nilhcem.devfestnantes.data.database;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
public class DbMapperTest {
private DbMapper dbMapper;
private final Moshi moshi = new Moshi.Builder().build();
private final AppMapper appMapper = new AppMapper();
private final LocalDateTime now = LocalDateTime.now();
| @Mock LocalDateTimeAdapter adapter; | 0 |
cthbleachbit/TransitRailMod | src/main/java/tk/cth451/transitrailmod/TransitRailMod.java | [
"public class ModBlocks {\n\tpublic static Block closed_platform_top;\n\tpublic static Block closed_platform_door_block;\n\tpublic static Block closed_platform_panel_block;\n\tpublic static Block platform_gate_block;\n\tpublic static Block platform_panel_block;\n\tpublic static Block logo_block;\n\tpublic static Bl... | import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import tk.cth451.transitrailmod.init.ModBlocks;
import tk.cth451.transitrailmod.init.ModGuiHandler;
import tk.cth451.transitrailmod.init.ModItems;
import tk.cth451.transitrailmod.init.ModRecipe;
import tk.cth451.transitrailmod.init.ModTileEntities;
import tk.cth451.transitrailmod.proxy.CommonProxy; | package tk.cth451.transitrailmod;
@Mod(modid = References.MOD_ID, version = References.VERSION, name = References.VERSION)
public class TransitRailMod
{
@Instance(References.MOD_ID)
public static TransitRailMod instance;
@SidedProxy(clientSide = References.CLIENT_PROXY_CLASS, serverSide = References.SERVER_PROXY_CLASS)
public static CommonProxy proxy;
public static final TransitRailTab tabTransitRail = new TransitRailTab("tabTransitRail");
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
ModBlocks.init();
ModBlocks.register();
ModItems.init();
ModItems.register();
ModTileEntities.register();
}
@EventHandler
public void init(FMLInitializationEvent event)
{ | ModRecipe.addItemsRecipe(); | 3 |
fralalonde/iostream | src/main/java/ca/rbon/iostream/IO.java | [
"public interface BytesBiChannel<T> extends Filter<BytesBiChannel<T>>, CharIn<T>, ByteIn<T>, CharOut<T>, ByteOut<T> {\n\n}",
"public interface BytesInChannel<T> extends Filter<BytesInChannel<T>>, CharIn<T>, ByteIn<T> {\n}",
"public interface BytesOutChannel<T> extends Filter<BytesOutChannel<T>>, CharOut<T>, Byt... | import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
import ca.rbon.iostream.channel.BytesBiChannel;
import ca.rbon.iostream.channel.BytesInChannel;
import ca.rbon.iostream.channel.BytesOutChannel;
import ca.rbon.iostream.channel.CharBiChannel;
import ca.rbon.iostream.channel.CharOutChannel;
import ca.rbon.iostream.channel.part.ByteOut;
import ca.rbon.iostream.resource.*;
import ca.rbon.iostream.wrap.InputStreamOf;
import lombok.RequiredArgsConstructor; | package ca.rbon.iostream;
/**
* <p>
* IoStream is the root object for IO streams builder methods. Creating an IO
* stream involves selecting a resource such as {@link #file(String)} and a
* channel such as {@link ByteOut#dataOutputStream()}.
* </p>
*/
public class IO {
private static final String DEFAULT_TEMP_FILE_PREFIX = "IoStream";
/**
* <p>
* Stream to or from a file.
* </p>
*
* @param name Name of the file to use
* @return An input or output picker
*/
public static BytesBiChannel<File> file(String name) {
return file(new File(name));
}
/**
* <p>
* Stream to or from a file.
* </p>
*
* @param file File to use
* @return An input or output picker
*/
@SuppressWarnings("unchecked")
public static BytesBiChannel<File> file(File file) {
return proxy(new FileResource(file, false), BytesBiChannel.class);
}
/**
* <p>
* Write to a file.
* </p>
*
* @param name Name of file to write to.
* @param append True to append to an existing file. False to overwrite an
* existing file. If file doesn't exist it is just created.
* @return An output picker
*/ | public static BytesOutChannel<File> file(String name, boolean append) { | 2 |
teivah/TIBreview | src/test/java/com/tibco/exchange/tibreview/processor/resourcerule/CProcessorJNDITest.java | [
"public class TIBResource {\n\tprivate String filePath;\n\tprivate String type;\n\t\n\tprivate static final String REQUEST_GET_TYPE = \"/jndi:namedResource/@type\";\n\t\n\tpublic TIBResource(String filePath) throws Exception {\n\t\tthis.filePath = filePath;\n\t\tthis.type = Util.xpathEval(filePath, Constants.RESOUR... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.tibco.exchange.tibreview.common.TIBResource;
import com.tibco.exchange.tibreview.engine.Context;
import com.tibco.exchange.tibreview.model.pmd.Violation;
import com.tibco.exchange.tibreview.model.rules.Configuration;
import com.tibco.exchange.tibreview.model.rules.Resource;
import com.tibco.exchange.tibreview.model.rules.Tibrules;
import com.tibco.exchange.tibreview.parser.RulesParser;
| package com.tibco.exchange.tibreview.processor.resourcerule;
public class CProcessorJNDITest {
private static final Logger LOGGER = Logger.getLogger(CProcessorJNDITest.class);
@Test
public void testCProcessorJNDITest() {
TIBResource fileresource;
try {
fileresource = new TIBResource("src/test/resources/FileResources/JNDIConfiguration.jndiConfigResource");
fileresource.toString();
LOGGER.info(fileresource.toString());
assertTrue(fileresource.toString().equals("TIBResource [filePath=src/test/resources/FileResources/JNDIConfiguration.jndiConfigResource, type=jms:JNDIConnection]"));
Tibrules tibrules= RulesParser.getInstance().parseFile("src/test/resources/FileResources/xml/JNDIConnectionResource.xml");
Resource resource = tibrules.getResource();
LOGGER.info(resource.getRule().size());
assertEquals(resource.getRule().size(),1);
ConfigurationProcessor a = new ConfigurationProcessor();
Configuration Configuracion = resource.getRule().get(0).getConfiguration();
| List<Violation> b = a.process(new Context(), fileresource, resource.getRule().get(0), Configuracion);
| 1 |
esmasui/deb-kitkat-storage-access-framework | KitKatStorageProject/KitKatStorage/src/main/java/com/uphyca/kitkat/storage/internal/impl/LiveSdkDocumentsColumnMapper.java | [
"public interface DocumentsColumnMapper<T> {\n\n /**\n * @see DocumentsContract.Document#COLUMN_DOCUMENT_ID\n * <p>\n * Type: STRING\n * @param source\n */\n String mapDocumentId(T source);\n\n /**\n * @see DocumentsContract.Document#COLUMN_MIME_TYPE\n * <p>\n ... | import com.uphyca.kitkat.storage.skydrive.SkyDrivePhoto;
import com.uphyca.kitkat.storage.skydrive.SkyDriveVideo;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import android.provider.DocumentsContract;
import com.uphyca.kitkat.storage.internal.DocumentsColumnMapper;
import com.uphyca.kitkat.storage.internal.MimeTypeResolver;
import com.uphyca.kitkat.storage.skydrive.SkyDriveAlbum;
import com.uphyca.kitkat.storage.skydrive.SkyDriveAudio;
import com.uphyca.kitkat.storage.skydrive.SkyDriveFile;
import com.uphyca.kitkat.storage.skydrive.SkyDriveFolder;
import com.uphyca.kitkat.storage.skydrive.SkyDriveObject; | /*
* Copyright (C) 2013 uPhyca Inc. http://www.uphyca.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.uphyca.kitkat.storage.internal.impl;
/**
* LiveSDK for Androidを使った実装。
*
* @see <a href="https://github.com/liveservices/LiveSDK-for-Android/">LiveSDK for Android</a>
* @author masui@uphyca.com
*/
public class LiveSdkDocumentsColumnMapper implements DocumentsColumnMapper<SkyDriveObject> {
private final MimeTypeResolver mMimeTypeResolver;
private final DateFormat mDateFormat;
{
mDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZ");
mDateFormat.setTimeZone(TimeZone.getDefault());
}
public LiveSdkDocumentsColumnMapper(MimeTypeResolver mimeTypeResolver) {
mMimeTypeResolver = mimeTypeResolver;
}
@Override
public String mapDocumentId(SkyDriveObject source) {
return source.getId();
}
@Override
public String mapMimeType(SkyDriveObject source) {
return thatObjectIsDirectory(source) ? DocumentsContract.Document.MIME_TYPE_DIR : mMimeTypeResolver.resolveMimeTypeFromName(source.getName());
}
@Override
public String mapDisplayName(SkyDriveObject source) {
return source.getName();
}
@Override
public String mapSummary(SkyDriveObject source) {
return source.getDescription();
}
@Override
public Long mapLastModified(SkyDriveObject source) {
try {
return mDateFormat.parse(source.getUpdatedTime())
.getTime();
} catch (ParseException ignore) {
}
return null;
}
@Override
public Integer mapIcon(SkyDriveObject source) {
return null;
}
@Override
public Integer mapFlags(SkyDriveObject source) {
int flags = 0;
flags |= DocumentsContract.Document.FLAG_SUPPORTS_WRITE;
if (thatObjectIsDirectory(source)) {
flags |= DocumentsContract.Document.FLAG_DIR_SUPPORTS_CREATE;
} else {
flags |= DocumentsContract.Document.FLAG_SUPPORTS_WRITE;
}
flags |= DocumentsContract.Document.FLAG_SUPPORTS_DELETE;
String mimeType = mapMimeType(source);
if (mimeType.startsWith("image/")) {
flags |= DocumentsContract.Document.FLAG_SUPPORTS_THUMBNAIL;
}
return flags;
}
@Override
public Long mapSize(SkyDriveObject source) {
final long[] size = new long[1];
source.accept(new SkyDriveObject.Visitor() {
@Override
public void visit(SkyDriveAlbum album) {
}
@Override
public void visit(SkyDriveAudio audio) {
size[0] = audio.getSize();
}
@Override | public void visit(SkyDrivePhoto photo) { | 7 |
tommai78101/PokemonWalking | game/src/main/java/data/chunk/AreaChunk.java | [
"public abstract class Chunk {\n\tprotected byte[] name;\n\n\tpublic Chunk() {\n\t\tthis.name = null;\n\t}\n\n\tpublic String getDisplayName() {\n\t\treturn Arrays.toString(this.name);\n\t}\n\n\t/**\n\t * This reads the byte data from the RandomAccessFile and store the data into the chunk.\n\t * \n\t * @param raf\n... | import java.io.IOException;
import java.io.RandomAccessFile;
import abstracts.Chunk;
import level.Area;
import level.OverWorld;
import level.WorldConstants;
import main.Game; | package data.chunk;
/**
*
* @author tlee
*/
public class AreaChunk extends Chunk {
// Current area data
public static final byte[] AREA = "AREA".getBytes();
private int currentAreaID;
public AreaChunk() {
this.name = AreaChunk.AREA;
}
public int getCurrentAreaId() {
return this.currentAreaID;
}
@Override
public void read(Game game, RandomAccessFile raf) throws IOException {
int rafSize = raf.readShort();
for (byte b : AreaChunk.AREA) {
if (b != raf.readByte()) {
throw new IOException("Incorrect area chunk name.");
}
}
this.currentAreaID = raf.readInt();
OverWorld gameWorld = game.getWorld(); | Area area = WorldConstants.convertToArea(gameWorld.getAllAreas(), this.currentAreaID); | 1 |
maeln/LambdaHindleyMilner | src/test/java/types/TFunctionTest.java | [
"public class Variable extends Expression {\n\tprivate String name;\n\n\tpublic Variable(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\n\t@Override\n\tpublic Type infer(TypeInferenceEnv env) {\... | import ast.Variable;
import inference.Substitution;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
import static types.TFunction.function;
import static types.TVariable.variable;
import static types.TVariable.variables; | package types;
/**
* Created by valentin on 20/10/2016.
*/
public class TFunctionTest {
private static final String name = "TEST";
@Test
public void createFunction() throws Exception { | Type left = variable(name); | 3 |
krasa/MavenHelper | src/main/java/krasa/mavenhelper/MavenHelperApplicationService.java | [
"@SuppressWarnings(\"ComponentNotRegistered\")\npublic class MainMavenActionGroup extends ActionGroup implements DumbAware {\n\tstatic final Logger LOG = Logger.getInstance(MainMavenActionGroup.class);\n\n\tprivate Set<String> pluginGoalsSet = new HashSet<String>();\n\n\tpublic MainMavenActionGroup() {\n\t}\n\n\tpu... | import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import krasa.mavenhelper.action.MainMavenActionGroup;
import krasa.mavenhelper.action.RunGoalAction;
import krasa.mavenhelper.action.RunTestFileAction;
import krasa.mavenhelper.action.debug.DebugGoalAction;
import krasa.mavenhelper.action.debug.DebugTestFileAction;
import krasa.mavenhelper.action.debug.MainMavenDebugActionGroup;
import krasa.mavenhelper.icons.MyIcons;
import krasa.mavenhelper.model.ApplicationSettings;
import krasa.mavenhelper.model.Goal;
import org.apache.commons.lang.WordUtils;
import org.jetbrains.annotations.NotNull; | package krasa.mavenhelper;
@State(name = "MavenRunHelper", storages = {@Storage("mavenRunHelper.xml")})
public class MavenHelperApplicationService implements PersistentStateComponent<ApplicationSettings> {
static final Logger LOG = Logger.getInstance(MavenHelperApplicationService.class);
public static final String RUN_MAVEN = "Run Maven";
public static final String DEBUG_MAVEN = "Debug Maven";
private ApplicationSettings settings = new ApplicationSettings();
public void initShortcuts() {
addActionGroup(new MainMavenDebugActionGroup(DEBUG_MAVEN, MyIcons.ICON), DEBUG_MAVEN);
addActionGroup(new MainMavenActionGroup(RUN_MAVEN, MyIcons.RUN_MAVEN_ICON), RUN_MAVEN);
registerActions();
}
public void registerActions() {
ActionManager instance = ActionManager.getInstance();
for (Goal goal : settings.getAllGoals()) {
String actionId = getActionId(goal);
registerAction(instance, actionId, RunGoalAction.create(goal, MyIcons.PLUGIN_GOAL, false, null));
actionId = getDebugActionId(goal);
registerAction(instance, actionId, DebugGoalAction.createDebug(goal, MyIcons.PLUGIN_GOAL, false, null));
}
registerAction(instance, "krasa.MavenHelper.RunTestFileAction", new RunTestFileAction()); | registerAction(instance, "krasa.MavenHelper.DebugTestFileAction", new DebugTestFileAction()); | 4 |
CreativeCodingLab/PathwayMatrix | src/org/biopax/paxtools/pattern/miner/Dialog.java | [
"public class Match implements Cloneable\n{\n\t/**\n\t * Array of variables.\n\t */\n\tprivate BioPAXElement[] variables;\n\n\t/**\n\t * Constructor with size.\n\t * @param size array size\n\t */\n\tpublic Match(int size)\n\t{\n\t\tthis.variables = new BioPAXElement[size];\n\t}\n\n\t/**\n\t * Getter for the element... | import org.biopax.paxtools.io.SimpleIOHandler;
import org.biopax.paxtools.model.BioPAXElement;
import org.biopax.paxtools.model.Model;
import org.biopax.paxtools.pattern.Match;
import org.biopax.paxtools.pattern.Pattern;
import org.biopax.paxtools.pattern.Searcher;
import org.biopax.paxtools.pattern.util.Blacklist;
import org.biopax.paxtools.pattern.util.ProgressWatcher;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipInputStream;
import static javax.swing.JOptionPane.*; |
// Prepare progress bar
ProgressWatcher prg = new ProgressWatcher()
{
@Override
public void setTotalTicks(int total)
{
prgBar.setMaximum(total);
}
@Override
public void tick(int times)
{
prgBar.setValue(prgBar.getValue() + times);
}
};
prgBar.setVisible(true);
// Get the model file
File modFile;
if (pcRadio.isSelected())
{
if (getMaxMemory() < 4000)
{
showMessageDialog(this, "Maximum memory not large enough for handling\n" +
"Pathway Commons data. But will try anyway.\n" +
"Please consider running this application with the\n" +
"virtual machine parameter \"-Xmx5G\".");
}
modFile = new File(getPCFilename());
if (!modFile.exists())
{
prgLabel.setText("Downloading model");
if (!downloadPC(prg)){
eraseProgressBar();
showMessageDialog(this,
"Cannot download Pathway Commons data for some reason. Sorry.");
return;
}
assert modFile.exists();
}
}
else if (customFileRadio.isSelected())
{
modFile = new File("./level3/RNAP II Pre-transcription Events.owl");
}
else if (customURLRadio.isSelected())
{
String url = urlField.getText().trim();
prgLabel.setText("Downloading model");
if (url.endsWith(".gz")) downloadCompressed(prg, url, "temp.owl", true);
else if (url.endsWith(".zip")) downloadCompressed(prg, url, "temp.owl", false);
else downloadPlain(url, "temp.owl");
modFile = new File("temp.owl");
if (!modFile.exists())
{
showMessageDialog(this,
"Cannot download the model at the given URL.");
eraseProgressBar();
return;
}
}
else
{
throw new RuntimeException("Code should not be able to reach here!");
}
// Get the output file
File outFile = new File("output.txt");
try
{
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
writer.write("x");
writer.close();
//outFile.delete();
}
catch (IOException e){
e.printStackTrace();
eraseProgressBar();
showMessageDialog(this, "Cannot write to file: " + outFile.getPath());
return;
}
// Load model
prgLabel.setText("Loading the model");
prgBar.setIndeterminate(true);
prgBar.setStringPainted(false);
SimpleIOHandler io = new SimpleIOHandler();
Model model;
try
{
model = io.convertFromOWL(new FileInputStream(modFile));
prgBar.setIndeterminate(false);
prgBar.setStringPainted(true);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
eraseProgressBar();
showMessageDialog(this, "File not found: " + modFile.getPath());
return;
}
// Search
// patternCombo.setSelectedIndex(21);
Miner min = (Miner) patternCombo.getSelectedItem();
System.out.println("patternCombo.getSelectedItem() = "+patternCombo.getSelectedItem());
Pattern p = min.getPattern();
prgLabel.setText("Searching the pattern");
prgBar.setValue(0); | Map<BioPAXElement,List<Match>> matches = Searcher.search(model, p, prg); | 2 |
kinnla/eniac | src/eniac/menu/MenuHandler.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 eniac.menu.action.EAction;
import eniac.util.EProperties;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import javax.swing.AbstractButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import eniac.Manager;
import eniac.io.IOUtil;
import eniac.io.XMLUtil; | /*******************************************************************************
* 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 25.03.2004
*/
package eniac.menu;
/**
* @author zoppke
*/
public class MenuHandler extends DefaultHandler {
// constant tag and attribute names for parsing the menu xml file
private enum Tag {
MENU, GROUP, ACTION, NAME, MENUBAR, TOOLBAR, SEPARATOR, KEY, SID;
}
// Enum representing the parsing state (FSM)
private enum ParsingState {
DEFAULT, TOOLBAR, MENUBAR;
}
// =============================== fields //================================
private Hashtable<String, EAction> _actionDefaults = null;
private JMenu _currentMenu = null;
private JToolBar _toolBar = null;
private JMenuBar _menuBar = null;
private ParsingState _parsingState = ParsingState.DEFAULT;
private Hashtable<String, EAction> _actions = new Hashtable<>();
// ============================ lifecycle //================================
public MenuHandler(Hashtable<String, EAction> actionDefaults) {
_actionDefaults = actionDefaults;
}
public void init() {
// parse menu and toolbar from xml
String path = EProperties.getInstance().getProperty("MENU_FILE");
InputStream in = Manager.class.getClassLoader().getResourceAsStream(path);
try { | IOUtil.parse(in, this); | 1 |
unbroken-dome/gradle-gitversion-plugin | src/main/java/org/unbrokendome/gradle/plugins/gitversion/internal/DefaultVersioningRulesBuilder.java | [
"public interface Rule {\n\n boolean apply(RuleEvaluationContext evaluationContext);\n}",
"public interface VersioningRules {\n\n @Nonnull\n SemVersion evaluate(Project project, GitRepository gitRepository);\n\n @Nonnull\n static VersioningRulesBuilder builder() {\n return new DefaultVersion... | import com.google.common.collect.Iterables;
import org.unbrokendome.gradle.plugins.gitversion.core.Rule;
import org.unbrokendome.gradle.plugins.gitversion.core.VersioningRules;
import org.unbrokendome.gradle.plugins.gitversion.core.VersioningRulesBuilder;
import org.unbrokendome.gradle.plugins.gitversion.internal.DefaultVersioningRules;
import org.unbrokendome.gradle.plugins.gitversion.version.SemVersion;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull; | package org.unbrokendome.gradle.plugins.gitversion.internal;
public class DefaultVersioningRulesBuilder implements VersioningRulesBuilder {
private static final SemVersion DEFAULT_BASE_VERSION = SemVersion.create(0, 1, 0);
private SemVersion baseVersion = DEFAULT_BASE_VERSION;
private List<Rule> beforeRules = new ArrayList<>(1);
private List<Rule> rules = new ArrayList<>(5);
private List<Rule> afterRules = new ArrayList<>(1);
@Nonnull
@Override
public VersioningRulesBuilder setBaseVersion(SemVersion baseVersion) {
this.baseVersion = SemVersion.immutableCopyOf(baseVersion);
return this;
}
@Nonnull
@Override
public VersioningRulesBuilder addBeforeRule(Rule rule) {
beforeRules.add(rule);
return this;
}
@Nonnull
@Override
public VersioningRulesBuilder addRule(Rule rule) {
rules.add(rule);
return this;
}
@Nonnull
@Override
public VersioningRulesBuilder addAfterRule(Rule rule) {
afterRules.add(rule);
return this;
}
@Nonnull
@Override | public VersioningRules build() { | 1 |
mstojcevich/Radix | core/src/sx/lambda/voxel/net/mc/client/handlers/ChunkDataHandler.java | [
"public class RadixClient extends ApplicationAdapter {\n\n // TODO CLEANUP the render loop is VERY undocumented and things happen all over the place, clean that up\n\n public static final String GAME_TITLE = \"VoxelTest\";\n private static RadixClient theGame;\n\n private SettingsManager settingsManager... | import com.badlogic.gdx.Gdx;
import org.spacehq.mc.protocol.data.game.chunk.Chunk;
import org.spacehq.mc.protocol.data.game.world.block.BlockState;
import org.spacehq.mc.protocol.packet.ingame.server.world.ServerChunkDataPacket;
import sx.lambda.voxel.RadixClient;
import sx.lambda.voxel.api.BuiltInBlockIds;
import sx.lambda.voxel.api.RadixAPI;
import sx.lambda.voxel.util.Vec3i;
import sx.lambda.voxel.world.biome.Biome;
import sx.lambda.voxel.world.chunk.BlockStorage;
import sx.lambda.voxel.world.chunk.FlatBlockStorage; | package sx.lambda.voxel.net.mc.client.handlers;
public class ChunkDataHandler implements PacketHandler<ServerChunkDataPacket> {
private final RadixClient game;
public ChunkDataHandler(RadixClient game) {
this.game = game;
}
@Override
public void handle(ServerChunkDataPacket scdp) {
if(scdp.getColumn().getChunks().length == 0) {
RadixClient.getInstance().getWorld().rmChunk(RadixClient.getInstance().getWorld().getChunk(scdp.getColumn().getX(), scdp.getColumn().getZ()));
}
int biomeID = 0;
if(scdp.getColumn().getBiomeData() != null) {
biomeID = scdp.getColumn().getBiomeData()[0];
}
Biome biome = RadixAPI.instance.getBiomeByID(biomeID);
if(biome == null)
biome = RadixAPI.instance.getBiomeByID(biomeID-128);
if(biome == null)
biome = RadixAPI.instance.getBiomeByID(0);
int cx = scdp.getColumn().getX()*16;
int cz = scdp.getColumn().getZ()*16;
sx.lambda.voxel.world.chunk.Chunk ck = (sx.lambda.voxel.world.chunk.Chunk)game.getWorld().getChunk(cx, cz);
boolean hadChunk = ck != null;
if(!hadChunk) {
ck = new sx.lambda.voxel.world.chunk.Chunk(game.getWorld(), new Vec3i(cx, 0, cz), biome, false);
}
FlatBlockStorage[] blockStorages = ck.getBlockStorage();
int yIndex = 0;
int highestPoint = 0;
for(Chunk c : scdp.getColumn().getChunks()) {
if(c == null) {
yIndex++;
continue;
}
FlatBlockStorage storage = blockStorages[yIndex];
if(storage == null) {
storage = blockStorages[yIndex] = new FlatBlockStorage(16, 16, 16);
}
for(int y = 0; y < 16; y++) {
for(int z = 0; z < 16; z++) {
for(int x = 0; x < 16; x++) {
BlockState blk = c.getBlocks().get(x, y, z);
int id = blk.getId();
if(id == 0)
continue;
int meta = blk.getData();
boolean exists = RadixAPI.instance.getBlock(id) != null;
if(!exists) {
try {
storage.setId(x, y, z, BuiltInBlockIds.UNKNOWN_ID); | } catch (BlockStorage.CoordinatesOutOfBoundsException e) { | 5 |
dvanherbergen/robotframework-formslibrary | src/main/java/org/robotframework/formslibrary/keyword/TableKeywords.java | [
"public class FormsLibraryException extends RuntimeException {\n\n private static final long serialVersionUID = 1L;\n\n public static final boolean ROBOT_SUPPRESS_NAME = true;\n\n public FormsLibraryException(String message) {\n super(message);\n }\n\n public FormsLibraryException(Throwable t)... | import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import org.robotframework.formslibrary.FormsLibraryException;
import org.robotframework.formslibrary.chooser.ByNameChooser;
import org.robotframework.formslibrary.context.ContextChangeMonitor;
import org.robotframework.formslibrary.operator.ContextOperator;
import org.robotframework.formslibrary.operator.TableOperator;
import org.robotframework.formslibrary.operator.TextFieldOperatorFactory;
import org.robotframework.formslibrary.operator.VerticalScrollBarOperator;
import org.robotframework.formslibrary.util.ComponentType;
import org.robotframework.javalib.annotation.ArgumentNames;
import org.robotframework.javalib.annotation.RobotKeyword;
import org.robotframework.javalib.annotation.RobotKeywords;
| package org.robotframework.formslibrary.keyword;
@RobotKeywords
public class TableKeywords {
@RobotKeyword("Select a row in a result table by content.\n\n" + "Example:\n" + "| Select Row | _market_ | _gas_ | \n")
@ArgumentNames({ "*columnvalues" })
public void selectRow(String... columnValues) {
new TableOperator().selectRow(columnValues);
}
@RobotKeyword("Double Click on a row in a result table by content.\n\n" + "Example:\n" + "| Double Click Row Row | _market_ | _gas_ | \n")
@ArgumentNames({ "*columnvalues" })
public void doubleClickRow(String... columnValues) {
new TableOperator().doubleClickRow(columnValues);
}
@RobotKeyword("Select a row in a result table by content. If the row is not visible, the down button in the scrollbar will be pressed up to 50 times in an attempt to try and locate the row. Specify the index (occurrence) of the scrollbar which should be used for scrolling."
+ "Example:\n" + "| Scroll To Row | _scrollbarIndex_ | _market_ | _gas_ | \n")
@ArgumentNames({ "scrollbarIndex", "*columnvalues" })
public void scrollToRow(int scrollBarIndex, String... columnValues) {
VerticalScrollBarOperator scrollOperator = new VerticalScrollBarOperator(scrollBarIndex - 1);
TableOperator tableOperator = new TableOperator();
for (int i = 0; i < 50; i++) {
if (tableOperator.rowExists(columnValues)) {
tableOperator.selectRow(columnValues);
return;
} else {
scrollOperator.scrollDown(1);
}
}
throw new FormsLibraryException("Row could not be found within the first 50 records.");
}
@RobotKeyword("Set a field value in a table row." + " The row is identified by values\n\n" + "Example:\n"
+ "| Set Row Field | _field name_ | _field value_ | _first col value_ | _second col value_ | \n")
@ArgumentNames({ "identifier", "value", "*columnvalues" })
public void setRowField(String identifier, String value, String... columnValues) {
new TableOperator().setRowField(identifier, value, columnValues);
}
@RobotKeyword("Set a field value in a table row."
+ " The column is identified by it's name, the row is identified by the index, index starts at 1\n\n" + "Example:\n"
+ "| Set Field At Index | _column name_ | _row index_ | _value_ | \n" + "| Set Field At Index | _ naam _ || _ 2 _ | _value_ | \n")
@ArgumentNames({ "columnName", "rowIndex", "columnValue" })
public void setFieldAtIndex(String columnName, int rowIndex, String columnValue) {
new TableOperator().setFieldAtIndex(columnName, rowIndex, columnValue);
}
@RobotKeyword("Get a text field value in a table row." + " The field is identified by name. The row is identified by values\n\n" + "Example:\n"
+ "| Get Row Field | _field name_ || _first col value_ | _second col value_ | \n")
@ArgumentNames({ "identifier", "*columnvalues" })
public String getRowField(String identifier, String... columnValues) {
return new TableOperator().getRowField(identifier, columnValues);
}
@RobotKeyword("Select a checkbox in a table row. The first checkbox in a row is identified using index 1, the second one as 2, etc."
+ " The row is identified by values\n\n" + "Example:\n"
+ "| Select Row Checkbox | _checkbox index_ | _first col value_ | _second col value_ | \n")
@ArgumentNames({ "index", "*columnvalues" })
public void selectRowCheckbox(int index, String... columnValues) {
new TableOperator().selectRowCheckbox(index, columnValues);
}
@RobotKeyword("Deselect a checkbox in a table row. The first checkbox in a row is identified using index 1, the second one as 2, etc."
+ " The row is identified by values\n\n" + "Example:\n"
+ "| Select Row Checkbox | _checkbox index_ | _first col value_ | _second col value_ | \n")
@ArgumentNames({ "index", "*columnvalues" })
public void deselectRowCheckbox(int index, String... columnValues) {
new TableOperator().deselectRowCheckbox(index, columnValues);
}
@RobotKeyword("Get the state (true/false) of a checkbox in a table row. The first checkbox in a row is identified using index 1, the second one as 2, etc."
+ " The row is identified by values\n\n" + "Example:\n"
+ "| ${value}= | Get Row Checkbox | _checkbox index_ | _first col value_ | _second col value_ | \n")
@ArgumentNames({ "index", "*columnvalues" })
public boolean getRowCheckbox(int index, String... columnValues) {
return new TableOperator().getRowCheckboxState(index, columnValues);
}
@RobotKeyword("Click on a button in a table row. The first button in a row is identified using index 1, the second one as 2, etc."
+ " The row is identified by values\n\n" + "Example:\n"
+ "| Select Row Button | _button index_ | _first col value_ | _second col value_ | \n")
@ArgumentNames({ "index", "*columnvalues" })
public void selectRowButton(int index, String... columnValues) {
ContextChangeMonitor monitor = new ContextChangeMonitor();
monitor.start();
new TableOperator().selectRowButton(index, columnValues);
monitor.stop();
}
// @formatter:off
@RobotKeyword("Get all values for certain columns in a table. Returns an array[row][column]. \n"+
"\n Example usage:\n" +
"| @{table}= | Get Table Fields | _col1_ | _col3_ | \n" +
"| Log Many | @{Table} | | | \n" +
"| Log | ${Table[3][1]} | | | \n" )
// @formatter:on
@ArgumentNames({ "*columnnames" })
public List<List<String>> getTableFields(String[] identifiers) {
List<List<String>> result = new ArrayList<List<String>>();
for (int i = 0; i < identifiers.length; i++) {
List<Component> columnFields = new ContextOperator()
.findTableFields(new ByNameChooser(identifiers[i], ComponentType.ALL_TEXTFIELD_TYPES));
if (i == 0) {
// first column, so we need to create the rows
for (Component c : columnFields) {
| String value = TextFieldOperatorFactory.getOperator(c).getValue();
| 5 |
intellimate/Izou | src/main/java/org/intellimate/izou/system/context/Output.java | [
"@AddonAccessible\npublic interface EventModel<X extends EventModel> extends Identifiable {\n /**\n * The type of the Event.\n * It describes the Type of the Event.\n * @return A String containing an ID\n */\n String getType();\n\n /**\n * Returns the source of the event, e.g. the objec... | import org.intellimate.izou.events.EventModel;
import org.intellimate.izou.identification.Identifiable;
import org.intellimate.izou.identification.Identification;
import org.intellimate.izou.identification.IllegalIDException;
import org.intellimate.izou.output.OutputControllerModel;
import org.intellimate.izou.output.OutputExtensionModel;
import org.intellimate.izou.output.OutputPluginModel;
import ro.fortsoft.pf4j.AddonAccessible;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture; | package org.intellimate.izou.system.context;
/**
* @author Leander Kurscheidt
* @version 1.0
*/
@AddonAccessible
public interface Output {
/**
* adds output extension to desired outputPlugin
*
* adds output extension to desired outputPlugin, so that the output-plugin can start and stop the outputExtension
* task as needed. The outputExtension is specific to the output-plugin
*
* @param outputExtension the outputExtension to be added
* @throws IllegalIDException not yet implemented
*/
void addOutputExtension(OutputExtensionModel outputExtension) throws IllegalIDException;
/**
* removes the output-extension of id: extensionId from outputPluginList
*
* @param outputExtension the OutputExtension to remove
*/
void removeOutputExtension(OutputExtensionModel outputExtension);
/**
* adds outputPlugin to outputPluginList, starts a new thread for the outputPlugin, and stores the future object in a HashMap
* @param outputPlugin OutputPlugin to add
* @throws IllegalIDException not yet implemented
*/
void addOutputPlugin(OutputPluginModel outputPlugin) throws IllegalIDException;
/**
* removes the OutputPlugin and stops the thread
* @param outputPlugin the outputPlugin to remove
*/
void removeOutputPlugin(OutputPluginModel outputPlugin);
/**
* Adds a new {@link OutputControllerModel} to Izou.
*
* @param outputController The OutputController to add to Izou.
*/ | void addOutputController(OutputControllerModel outputController); | 4 |
utapyngo/owl2vcs | src/main/java/owl2vcs/analysis/EntityCollector.java | [
"public class AddPrefixData extends PrefixChangeData {\r\n\r\n private static final long serialVersionUID = 2801228470061214801L;\r\n\r\n public AddPrefixData(String prefixName, String prefix) {\r\n super(prefixName, prefix);\r\n }\r\n\r\n @Override\r\n public <R, E extends Exception> R accept... | import java.util.Collection;
import java.util.Set;
import org.semanticweb.owlapi.change.AddAxiomData;
import org.semanticweb.owlapi.change.AddImportData;
import org.semanticweb.owlapi.change.AddOntologyAnnotationData;
import org.semanticweb.owlapi.change.RemoveAxiomData;
import org.semanticweb.owlapi.change.RemoveImportData;
import org.semanticweb.owlapi.change.RemoveOntologyAnnotationData;
import org.semanticweb.owlapi.change.SetOntologyIDData;
import org.semanticweb.owlapi.model.OWLAnonymousIndividual;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.util.OWLEntityCollector;
import owl2vcs.changes.AddPrefixData;
import owl2vcs.changes.ModifyPrefixData;
import owl2vcs.changes.RemovePrefixData;
import owl2vcs.changes.RenamePrefixData;
import owl2vcs.changes.SetOntologyFormatData;
import owl2vcs.changeset.CustomOntologyChangeDataVisitor;
| package owl2vcs.analysis;
public class EntityCollector extends OWLEntityCollector implements
CustomOntologyChangeDataVisitor<Object, EntityCollectorException> {
public EntityCollector(final Set<OWLEntity> toReturn,
final Collection<OWLAnonymousIndividual> anonsToReturn) {
super(toReturn, anonsToReturn);
}
@Override
public Object visit(AddAxiomData data) {
data.getAxiom().accept(this);
return null;
}
@Override
public Object visit(RemoveAxiomData data) {
data.getAxiom().accept(this);
return null;
}
@Override
public Object visit(AddOntologyAnnotationData data) {
// We don't need to count annotation properties and datatypes as entities
return null;
}
@Override
public Object visit(RemoveOntologyAnnotationData data) {
// We don't need to count annotation properties and datatypes as entities
return null;
}
@Override
public Object visit(SetOntologyIDData data) {
return null;
}
@Override
public Object visit(AddImportData data) {
return null;
}
@Override
public Object visit(RemoveImportData data) {
return null;
}
@Override
| public Object visit(SetOntologyFormatData data) {
| 4 |
cqyijifu/OpenFalcon-SuitAgent | src/main/java/com/yiji/falcon/agent/plugins/plugin/zk/ZookeeperPlugin.java | [
"public enum CounterType {\n /**\n * 用户上传什么样的值,就原封不动的存储\n */\n GAUGE,\n /**\n * 指标在存储和展现的时候,会被计算为speed,即(当前值 - 上次值)/ 时间间隔\n */\n COUNTER\n}",
"@Data\npublic class FalconReportObject implements Cloneable{\n\n /**\n * 标明Metric的主体(属主),比如metric是cpu_idle,那么Endpoint就表示这是哪台机器的cpu_idle... | import com.yiji.falcon.agent.falcon.CounterType;
import com.yiji.falcon.agent.falcon.FalconReportObject;
import com.yiji.falcon.agent.falcon.MetricsType;
import com.yiji.falcon.agent.jmx.vo.JMXMetricsValueInfo;
import com.yiji.falcon.agent.jmx.vo.JMXObjectNameInfo;
import com.yiji.falcon.agent.plugins.JMXPlugin;
import com.yiji.falcon.agent.plugins.metrics.MetricsCommon;
import com.yiji.falcon.agent.plugins.util.PluginActivateType;
import com.yiji.falcon.agent.util.CommandUtilForUnix;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map; | /*
* www.yiji.com Inc.
* Copyright (c) 2016 All Rights Reserved
*/
package com.yiji.falcon.agent.plugins.plugin.zk;
/*
* 修订记录:
* guqiu@yiji.com 2016-06-27 15:41 创建
*/
/**
* @author guqiu@yiji.com
*/
@Slf4j
public class ZookeeperPlugin implements JMXPlugin {
private String basePropertiesKey;
private String jmxServerName;
private int step;
private PluginActivateType pluginActivateType;
private static String lastAgentSignName = "";
/**
* 自定义的监控属性的监控值基础配置名
*
* @return 若无配置文件, 可返回null
*/
@Override
public String basePropertiesKey() {
return basePropertiesKey;
}
/**
* 该插件所要监控的服务在JMX连接中的displayName识别名
* 若有该插件监控的相同类型服务,但是displayName不一样,可用逗号(,)进行分隔,进行统一监控
*
* @return
*/
@Override
public String jmxServerName() {
return jmxServerName;
}
/**
* 该插件监控的服务标记名称,目的是为能够在操作系统中准确定位该插件监控的是哪个具体服务
* 如该服务运行的端口号等
* 若不需要指定则可返回null
*
* @param jmxMetricsValueInfo 该服务连接的jmx对象
* @param pid 该服务当前运行的进程id
* @return
*/
@Override
public String agentSignName(JMXMetricsValueInfo jmxMetricsValueInfo, int pid) {
try {
lastAgentSignName = String.valueOf(ZKConfig.getClientPort(pid));
return lastAgentSignName;
} catch (IOException e) {
log.error("获取zookeeper clientPort 信息失败 ,返回最后的AgentSignName:{}",lastAgentSignName);
return lastAgentSignName;
}
}
/**
* 插件监控的服务正常运行时的內建监控报告
* 若有些特殊的监控值无法用配置文件进行配置监控,可利用此方法进行硬编码形式进行获取
* 注:此方法只有在监控对象可用时,才会调用,并加入到监控值报告中,一并上传
*
* @param metricsValueInfo 当前的JMXMetricsValueInfo信息
* @return
*/
@Override
public Collection<FalconReportObject> inbuiltReportObjectsForValid(JMXMetricsValueInfo metricsValueInfo) {
boolean isLeader = false;
String name = metricsValueInfo.getJmxConnectionInfo().getName();
List<FalconReportObject> result = new ArrayList<>();
for (JMXObjectNameInfo objectNameInfo : metricsValueInfo.getJmxObjectNameInfoList()) {
if(objectNameInfo.toString().contains("Leader")){
//若ObjectName中包含有 Leader 则该zk为Leader角色
isLeader = true;
}
}
result.add(generatorIsLeaderReport(metricsValueInfo.getTimestamp(),isLeader,name));
return result;
}
private FalconReportObject generatorIsLeaderReport(long timestamp,boolean isLeader,String name){
FalconReportObject falconReportObject = new FalconReportObject();
MetricsCommon.setReportCommonValue(falconReportObject,step);
falconReportObject.setCounterType(CounterType.GAUGE);
falconReportObject.setMetric(MetricsCommon.getMetricsName("isZookeeperLeader"));
falconReportObject.setValue(isLeader ? "1" : "0");
falconReportObject.setTimestamp(timestamp); | falconReportObject.appendTags(MetricsCommon.getTags(name,this,serverName(), MetricsType.JMX_OBJECT_IN_BUILD)); | 2 |
sqrlserverjava/sqrl-server-base | src/main/java/com/github/sqrlserverjava/backchannel/nut/SqrlNutToken1SingleBlockFormat.java | [
"@XmlRootElement\npublic class SqrlConfig {\n\t// @formatter:off\n\t/* *********************************************************************************************/\n\t/* *************************************** REQUIRED ********************************************/\n\t/* *******************************************... | import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
import javax.crypto.Cipher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sqrlserverjava.SqrlConfig;
import com.github.sqrlserverjava.SqrlConfigOperations;
import com.github.sqrlserverjava.backchannel.SqrlTifFlag;
import com.github.sqrlserverjava.exception.SqrlClientRequestProcessingException;
import com.github.sqrlserverjava.exception.SqrlException;
import com.github.sqrlserverjava.exception.SqrlInvalidRequestException;
import com.github.sqrlserverjava.util.SqrlConfigHelper;
import com.github.sqrlserverjava.util.SqrlUtil; | package com.github.sqrlserverjava.backchannel.nut;
/**
* "Nut" token format matching the size (but not the data layout) of the format suggested by the SQRL spec. This is not
* the preferred format but is retained in case clients have issues processing our preferred format, which is larger in
* size
*
* This token format is deprecated for the following reasons:
* <li/>1. Requires server side state (that is, database entries) when displaying the login page
* <li/>2. This token is encrypted but is <b>not</b> signed
* <li/>3. Can only store part of an IPv6 address, which makes IP mismatch debugging difficult
*
* @author Dave Badia
* @deprecated SqrlNutTokenEmbedded is preferred
*/
@Deprecated
public class SqrlNutToken1SingleBlockFormat extends SqrlNutToken0 {
private static final Logger logger = LoggerFactory.getLogger(SqrlNutToken1SingleBlockFormat.class);
private static final int IPV6_TO_PACK_BYTES = 4;
static final int FORMAT_ID = 1;
private final int inetInt;
private final long issuedTimestamp;
private final int randomInt;
/**
* The encrypted nut in base64url format as it appeared in the query string
*/
private final String base64UrlEncryptedNut;
/**
*
* @param timestamp
* The time at which the Nut was created, typically {@link System#currentTimeMillis()}. Note that the
* data in the Nut is only stored with second granularity
* @param randomInt
* @throws SqrlException
*
* @deprecated SqrlNutTokenEmbedded is preferred
*/
@Deprecated | SqrlNutToken1SingleBlockFormat(final InetAddress browserIp, final SqrlConfigOperations configOps, | 1 |
Stratio/stratio-connector-cassandra | cassandra-connector/src/main/java/com/stratio/connector/cassandra/engine/CassandraStorageEngine.java | [
"public final class CassandraExecutor {\n\n /**\n * The {@link com.stratio.connector.cassandra.utils.Utils}.\n */\n private static Utils utils = new Utils();\n\n /**\n * Private class constructor as all methods are static.\n */\n private CassandraExecutor() {\n }\n\n /**\n * Ex... | import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.datastax.driver.core.Session;
import com.stratio.connector.cassandra.CassandraExecutor;
import com.stratio.connector.cassandra.statements.DeleteStatement;
import com.stratio.connector.cassandra.statements.InsertIntoStatement;
import com.stratio.connector.cassandra.statements.TruncateStatement;
import com.stratio.connector.cassandra.statements.UpdateTableStatement;
import com.stratio.connector.cassandra.utils.ColumnInsertCassandra;
import com.stratio.crossdata.common.connector.IStorageEngine;
import com.stratio.crossdata.common.data.ClusterName;
import com.stratio.crossdata.common.data.ColumnName;
import com.stratio.crossdata.common.data.Row;
import com.stratio.crossdata.common.data.TableName;
import com.stratio.crossdata.common.exceptions.ConnectorException;
import com.stratio.crossdata.common.exceptions.ExecutionException;
import com.stratio.crossdata.common.logicalplan.Filter;
import com.stratio.crossdata.common.metadata.ColumnMetadata;
import com.stratio.crossdata.common.metadata.TableMetadata;
import com.stratio.crossdata.common.statements.structures.Relation; | /*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.stratio.connector.cassandra.engine;
/**
* Class CassandraStorageEngine: Allow to make insert queries with the connector.
*/
public class CassandraStorageEngine implements IStorageEngine {
private Map<String, Session> sessions;
/**
* Basic Constructor.
*
* @param sessions Map with the sessions
*/
public CassandraStorageEngine(Map<String, Session> sessions) {
this.sessions = sessions;
}
/**
* Insert method to a table.
*
* @param targetCluster The target cluster.
* @param targetTable The target table.
* @param row The inserted row.
* @throws ConnectorException
*/
@Override
public void insert(ClusterName targetCluster,
com.stratio.crossdata.common.metadata.TableMetadata targetTable, Row row, boolean ifNotExists)
throws ConnectorException {
Session session = sessions.get(targetCluster.getName());
String query = insertBlock(row, targetTable, ifNotExists);
CassandraExecutor.execute(query, session);
}
/**
* Multiple insertion in a table.
*
* @param targetCluster The target cluster.
* @param targetTable The target table.
* @param rows Collection of rows to insert.
* @throws ConnectorException
*/
@Override
public void insert(ClusterName targetCluster, TableMetadata targetTable, Collection<Row> rows, boolean ifNotExists)
throws ConnectorException {
Session session = sessions.get(targetCluster.getName());
StringBuilder sb= new StringBuilder();
sb.append("BEGIN BATCH ");
for (Row row : rows) {
String query = insertBlock(row, targetTable, ifNotExists);
sb.append(query).append(" ");
}
sb.append("APPLY BATCH");
CassandraExecutor.execute(sb.toString(), session);
}
private String insertBlock(Row row, TableMetadata targetTable, boolean ifNotExists) throws ExecutionException {
Set<String> keys = row.getCells().keySet();
Map<ColumnName, ColumnMetadata> columnsWithMetadata = targetTable.getColumns(); | Map<String, ColumnInsertCassandra> columnsMetadata = new HashMap<>(); | 5 |
pmarques/SocketIO-Server | SocketIO-Netty/src/test/java/eu/k2c/socket/io/ci/usecases/UC16Handler.java | [
"public abstract class AbstractHandler extends AbstractSocketIOHandler {\n\t@Override\n\tpublic boolean validate(String URI) {\n\t\t// This isn't belongs to socketIO Spec AFAIK\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void onConnect(final SocketIOOutbound outbound, final SocketIOSessionEventRegister eventReg... | import eu.k2c.socket.io.server.api.DisconnectReason;
import eu.k2c.socket.io.server.api.SocketIONSHandler;
import eu.k2c.socket.io.server.api.SocketIOOutbound;
import eu.k2c.socket.io.server.api.SocketIOSessionEventRegister;
import eu.k2c.socket.io.server.api.SocketIOSessionNSRegister;
import eu.k2c.socket.io.server.exceptions.SocketIOException;
import java.io.UnsupportedEncodingException;
import org.apache.log4j.Logger;
import eu.k2c.socket.io.ci.AbstractHandler; | /**
* Copyright (C) 2011 K2C @ Patrick Marques <patrickfmarques@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Except as contained in this notice, the name(s) of the above copyright holders
* shall not be used in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization.
*/
package eu.k2c.socket.io.ci.usecases;
public class UC16Handler extends AbstractHandler {
private static final Logger LOGGER = Logger.getLogger(UC17Handler.class);
private static String text;
static {
final byte [] b2 = {(byte) 0xC3, (byte) 0xB1}; // \uC3B1
try {
text = new String(b2, "UTF8");
} catch (UnsupportedEncodingException e) {
LOGGER.fatal(e);
}
}
@Override
public void onConnect(final SocketIOOutbound outbound, final SocketIOSessionEventRegister eventRegister, | final SocketIOSessionNSRegister NSRegister) { | 5 |
aarddict/android | src/aarddict/android/DictionaryService.java | [
"public final class Article implements Serializable {\n\n public UUID dictionaryUUID;\n public String volumeId;\n public String title;\n public String section;\n public long pointer;\n private String redirect;\n public String text;\n public String redirectedFromTitle;\n\n ... | import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import aarddict.Article;
import aarddict.ArticleNotFound;
import aarddict.Entry;
import aarddict.Library;
import aarddict.Metadata;
import aarddict.RedirectTooManyLevels;
import aarddict.Volume;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Binder;
import android.os.FileObserver;
import android.os.IBinder;
import android.util.Log; | Intent notifyOpened = new Intent(OPENED_DICT);
notifyOpened.putExtra("title", d.getDisplayTitle());
notifyOpened.putExtra("count", files.size());
notifyOpened.putExtra("i", i);
sendBroadcast(notifyOpened);
Thread.yield();
}
catch (Exception e) {
Log.e(TAG, "Failed to open " + file, e);
boolean displayErrorMessage = !(e instanceof java.io.FileNotFoundException);
Intent notifyFailed = new Intent(DICT_OPEN_FAILED);
notifyFailed.putExtra("file", file.getAbsolutePath());
notifyFailed.putExtra("count", files.size());
notifyFailed.putExtra("reason", e.getMessage());
notifyFailed.putExtra("displayErrorMessage", displayErrorMessage);
notifyFailed.putExtra("i", i);
sendBroadcast(notifyFailed);
Thread.yield();
errors.put(file, e);
}
}
sendBroadcast(new Intent(OPEN_FINISHED));
Thread.yield();
return errors;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
for (Volume d : library) {
try {
d.close();
}
catch (IOException e) {
Log.e(TAG, "Failed to close " + d, e);
}
}
library.clear();
for (DeleteObserver observer : deleteObservers.values()) {
observer.stopWatching();
}
Log.i(TAG, "destroyed");
}
public List<File> discover() {
sendBroadcast(new Intent(DISCOVERY_STARTED));
Thread.yield();
File scanRoot = new File ("/");
List<File> result = new ArrayList<File>();
result.addAll(scanDir(scanRoot));
Intent intent = new Intent(DISCOVERY_FINISHED);
intent.putExtra("count", result.size());
sendBroadcast(intent);
Thread.yield();
return result;
}
private List<File> scanDir(File dir) {
String absolutePath = dir.getAbsolutePath();
if (excludedScanDirs.contains(absolutePath)) {
Log.d(TAG, String.format("%s is excluded", absolutePath));
return Collections.emptyList();
}
boolean symlink = false;
try {
symlink = isSymlink(dir);
} catch (IOException e) {
Log.e(TAG,
String.format("Failed to check if %s is symlink",
dir.getAbsolutePath()));
}
if (symlink) {
Log.d(TAG, String.format("%s is a symlink", absolutePath));
return Collections.emptyList();
}
if (dir.isHidden()) {
Log.d(TAG, String.format("%s is hidden", absolutePath));
return Collections.emptyList();
}
Log.d(TAG, "Scanning " + absolutePath);
List<File> candidates = new ArrayList<File>();
File[] files = dir.listFiles(fileFilter);
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
candidates.addAll(scanDir(file));
} else {
if (!file.isHidden() && file.isFile()) {
candidates.add(file);
}
}
}
}
return candidates;
}
static boolean isSymlink(File file) throws IOException {
File fileInCanonicalDir = null;
if (file.getParent() == null) {
fileInCanonicalDir = file;
} else {
File canonicalDir = file.getParentFile().getCanonicalFile();
fileInCanonicalDir = new File(canonicalDir, file.getName());
}
if (fileInCanonicalDir.getCanonicalFile().equals(
fileInCanonicalDir.getAbsoluteFile())) {
return false;
} else {
return true;
}
}
public void setPreferred(String volumeId) {
library.makeFirst(volumeId);
}
| public Iterator<Entry> lookup(CharSequence word) { | 2 |
moonlight-stream/moonlight-pc | src/com/limelight/gui/GamepadConfigFrame.java | [
"public class Device {\n\tprivate int id;\n\tprivate int numButtons;\n\tprivate int numAxes;\n\t\n\tpublic Device(int deviceID, int numButtons, int numAxes) {\n\t\tthis.id = deviceID;\n\t\tthis.numButtons = numButtons;\n\t\tthis.numAxes = numAxes;\n\t}\n\t\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\t\n\tpublic ... | import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import com.limelight.LimeLog;
import com.limelight.input.Device;
import com.limelight.input.DeviceListener;
import com.limelight.input.gamepad.GamepadComponent;
import com.limelight.input.gamepad.GamepadListener;
import com.limelight.input.gamepad.GamepadMapping;
import com.limelight.input.gamepad.GamepadMapping.Mapping;
import com.limelight.input.gamepad.SourceComponent.Direction;
import com.limelight.input.gamepad.SourceComponent;
import com.limelight.settings.GamepadSettingsManager; | package com.limelight.gui;
/**
* A frame used to configure the gamepad mappings.
* @author Diego Waxemberg
*/
public class GamepadConfigFrame extends JFrame {
private static final long serialVersionUID = 1L;
private boolean configChanged = false;
private MappingThread mappingThread;
private GamepadMapping config;
private HashMap<Box, Mapping> componentMap;
/**
* Constructs a new config frame. The frame is initially invisible and will <br>
* be made visible after all components are built by calling <code>build()</code>
*/
public GamepadConfigFrame() {
super("Gamepad Settings");
LimeLog.info("Creating Settings Frame");
this.setSize(850, 550);
this.setResizable(false);
this.setAlwaysOnTop(true);
config = GamepadSettingsManager.getSettings();
}
/**
* Builds all components of the config frame and sets the frame visible.
*/
public void build() {
componentMap = new HashMap<Box, Mapping>();
GridLayout layout = new GridLayout(GamepadComponent.values().length/2 + 1, 2);
layout.setHgap(60);
layout.setVgap(3);
JPanel mainPanel = new JPanel(layout);
GamepadComponent[] components = GamepadComponent.values();
for (int i = 0; i < components.length; i++) {
Mapping mapping = config.get(components[i]);
if (mapping == null) {
mapping = config.new Mapping(components[i], false, false);
}
Box componentBox = createComponentBox(mapping);
mainPanel.add(componentBox);
}
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
this.setLayout(new BorderLayout());
this.getContentPane().add(mainPanel, "Center");
this.getContentPane().add(Box.createVerticalStrut(20), "North");
this.getContentPane().add(Box.createVerticalStrut(20), "South");
this.getContentPane().add(Box.createHorizontalStrut(20), "East");
this.getContentPane().add(Box.createHorizontalStrut(20), "West");
this.addWindowListener(createWindowListener());
this.setVisible(true);
}
/*
* Creates the box that holds the button and checkboxes
*/
private Box createComponentBox(Mapping mapping) {
Box componentBox = Box.createHorizontalBox();
JButton mapButton = new JButton();
JCheckBox invertBox = new GamepadCheckBox("Invert", GamepadCheckBox.Type.INVERT);
JCheckBox triggerBox = new GamepadCheckBox("Trigger", GamepadCheckBox.Type.TRIGGER);
Dimension buttonSize = new Dimension(110, 24);
mapButton.setMaximumSize(buttonSize);
mapButton.setMinimumSize(buttonSize);
mapButton.setPreferredSize(buttonSize);
mapButton.addActionListener(createMapListener());
setButtonText(mapButton, config.getMapping(mapping.padComp));
invertBox.setSelected(mapping.invert);
invertBox.addActionListener(createCheckboxListener());
invertBox.setName(mapping.padComp.name());
triggerBox.setSelected(mapping.trigger);
triggerBox.addActionListener(createCheckboxListener());
triggerBox.setName(mapping.padComp.name());
triggerBox.setToolTipText("If this component should act as a trigger. (one-way axis)");
componentBox.add(Box.createHorizontalStrut(5));
componentBox.add(mapping.padComp.getLabel());
componentBox.add(Box.createHorizontalGlue());
componentBox.add(mapButton);
componentBox.add(invertBox);
componentBox.add(triggerBox);
componentBox.add(Box.createHorizontalStrut(5));
componentBox.setBorder(new LineBorder(Color.GRAY, 1, true));
componentMap.put(componentBox, mapping);
return componentBox;
}
/*
* Creates the listener for the checkbox
*/
private ActionListener createCheckboxListener() {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
JCheckBox clicked = (JCheckBox)e.getSource();
GamepadComponent padComp = GamepadComponent.valueOf(clicked.getName());
Mapping currentMapping = config.get(padComp);
if (currentMapping == null) {
//this makes more semantic sense to me than using !=
clicked.setSelected(!(clicked.isSelected()));
} else {
((GamepadCheckBox)clicked).setValue(currentMapping, clicked.isSelected());
configChanged = true;
}
}
};
}
/*
* Creates the listener for the window.
* It will save configs on exit and restart controller threads
*/
private WindowListener createWindowListener() {
return new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (mappingThread != null && mappingThread.isAlive()) {
mappingThread.interrupt();
}
if (configChanged) {
updateConfigs();
}
dispose();
}
};
}
/*
* Creates the listener for the map button
*/
private ActionListener createMapListener() {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
Box toMap = (Box)((JButton)e.getSource()).getParent();
| if (GamepadListener.getInstance().deviceCount() == 0) { | 3 |
DarrenMowat/PicSync | src/com/darrenmowat/gdcu/service/UploadThread.java | [
"public class GDCU extends Application {\n\n\tpublic static final boolean DEVEL_BUILD = true;\n\n\tpublic static final String APP_NAME = \"PicSync Beta\";\n\n\tpublic static int VERSION;\n\tpublic static String VERSION_STRING;\n\tpublic static final String BUILD_TYPE = DEVEL_BUILD ? \"Development Build\" : \"Beta B... | import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import org.json.JSONException;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import com.darrenmowat.gdcu.GDCU;
import com.darrenmowat.gdcu.R;
import com.darrenmowat.gdcu.data.Database;
import com.darrenmowat.gdcu.data.Preferences;
import com.darrenmowat.gdcu.drive.DriveApi;
import com.darrenmowat.gdcu.utils.MD5Utils;
import com.flurry.android.FlurryAgent;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.api.services.drive.model.File; | package com.darrenmowat.gdcu.service;
public class UploadThread extends Thread {
private DriveApi drive;
private Database database;
private String email;
private UploadService service;
public boolean uploading = false;
private boolean shouldRequery = false;
private boolean shouldStop = false;
public UploadThread(UploadService service, String email) {
this.service = service;
this.email = email;
}
@Override
public void run() {
try {
uploading = true;
// Connect to the database
database = new Database(service);
database.connect();
try { | email = Preferences.getEmail(service); | 2 |
mgilangjanuar/GoSCELE | app/src/main/java/com/mgilangjanuar/dev/goscele/modules/forum/list/provider/ForumListProvider.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 org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
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 ForumListProvider extends BaseProvider {
private String url;
private ForumListListener listener;
public ForumListProvider(String url, ForumListListener listener) {
this.url = url;
this.listener = listener;
}
@Override
public void run() {
execute("#region-main");
}
@Override
public Map<String, String> cookies() {
return CookieModel.getCookiesMap();
}
@Override
public String url() {
return url;
}
@Override
protected void onPostExecute(List<Elements> elementses) {
super.onPostExecute(elementses);
try {
List<ForumModel> models = new ArrayList<>();
Elements elements = elementses.get(0);
String title = elements.select("div[role=main] > h2").text();
listener.onGetTitle(title);
for (Element e: elements.select(".discussion")) {
String url = e.select(".topic.starter a").attr("href");
ForumModel model = new ForumModel().find().where("url = ?", url).executeSingle();
if (model != null) model.delete();
model = new ForumModel();
model.listUrl = this.url;
model.forumTitle = title;
model.url = url;
model.title = e.select(".topic.starter").text();
model.author = e.select(".author").text();
model.repliesNumber = e.select(".replies").text();
model.lastUpdate = e.select(".lastpost a").get(1).text();
model.save();
models.add(model);
} | listener.onRetrieve(new ForumListRecyclerViewAdapter(models)); | 2 |
spotify/hdfs2cass | src/main/java/com/spotify/hdfs2cass/LegacyHdfs2Cass.java | [
"public class CassandraParams implements Serializable {\n private static final Logger logger = LoggerFactory.getLogger(CassandraParams.class);\n\n public static final String SCRUB_CASSANDRACLUSTER_PARTITIONER_CONFIG = \"scrub.cassandracluster.com.spotify.cassandra.thrift.partitioner\";\n public static final Stri... | import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.spotify.hdfs2cass.cassandra.utils.CassandraParams;
import com.spotify.hdfs2cass.crunch.cql.CQLRecord;
import com.spotify.hdfs2cass.crunch.cql.CQLTarget;
import com.spotify.hdfs2cass.crunch.thrift.ThriftRecord;
import com.spotify.hdfs2cass.crunch.thrift.ThriftTarget;
import org.apache.crunch.PCollection;
import org.apache.crunch.Pipeline;
import org.apache.crunch.PipelineResult;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.io.From;
import org.apache.crunch.types.avro.Avros;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.BasicConfigurator;
import java.io.Serializable;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.List; | /*
* Copyright 2014 Spotify AB. All rights reserved.
*
* The contents of this file are 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.spotify.hdfs2cass;
/**
* Crunch job used to import files with legacy-formatted data into Cassandra Thrift or CQL table.
* <p>
* See {@link com.spotify.hdfs2cass.LegacyInputFormat} for format definition.
* </p><p>
* How to use command line:
* TODO(zvo): add example usage
* </p><p>
* TODO(zvo): add example URIS
* </p><p>
* </p>
*/
public class LegacyHdfs2Cass extends Configured implements Tool, Serializable {
@Parameter(names = "--input", required = true)
protected List<String> input;
@Parameter(names = "--output", required = true)
protected String output;
public static void main(String[] args) throws Exception {
// Logging for local runs
BasicConfigurator.configure();
ToolRunner.run(new Configuration(), new LegacyHdfs2Cass(), args);
}
@Override
public int run(String[] args) throws Exception {
new JCommander(this, args);
URI outputUri = URI.create(output);
// Our crunch job is a MapReduce job
Pipeline pipeline = new MRPipeline(LegacyHdfs2Cass.class, getConf());
// Parse & fetch info about target Cassandra cluster | CassandraParams params = CassandraParams.parse(outputUri); | 0 |
xushaomin/apple-ums-server | apple-ums-server-storage/apple-ums-server-storage-db/src/main/java/com/appleframework/ums/server/storage/service/impl/ClientUsingLogServiceImpl.java | [
"public class ClientUsingLogEntity implements Serializable {\r\n\t\r\n private Integer id;\r\n\r\n private String sessionId;\r\n\r\n private Date startMillis;\r\n\r\n private Date endMillis;\r\n\r\n private Integer duration;\r\n\r\n private String activities;\r\n\r\n private String appkey;\r\n\... | import javax.annotation.Resource;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Service;
import com.appleframework.ums.server.core.entity.ClientUsingLogEntity;
import com.appleframework.ums.server.core.model.UsingLog;
import com.appleframework.ums.server.storage.dao.ClientUsingLogDao;
import com.appleframework.ums.server.storage.service.ClientUsingLogService;
import com.appleframework.ums.server.storage.utils.Contants;
| package com.appleframework.ums.server.storage.service.impl;
@Service("clientUsingLogService")
public class ClientUsingLogServiceImpl implements ClientUsingLogService {
@Resource
private ClientUsingLogDao clientUsingLogDao;
public void save(UsingLog log) {
try {
| ClientUsingLogEntity record = new ClientUsingLogEntity();
| 0 |
zetbaitsu/CodePolitan | app/src/main/java/id/zelory/codepolitan/controller/ReadLaterController.java | [
"public abstract class BenihController<P extends BenihController.Presenter>\n{\n protected P presenter;\n\n public BenihController(P presenter)\n {\n this.presenter = presenter;\n Timber.tag(getClass().getSimpleName());\n }\n\n public abstract void saveState(Bundle bundle);\n\n publi... | import rx.Observable;
import timber.log.Timber;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import id.zelory.benih.controller.BenihController;
import id.zelory.benih.util.BenihBus;
import id.zelory.benih.util.BenihScheduler;
import id.zelory.benih.util.BenihUtils;
import id.zelory.codepolitan.controller.event.ErrorEvent;
import id.zelory.codepolitan.controller.event.ReadLaterEvent;
import id.zelory.codepolitan.data.model.Article;
import id.zelory.codepolitan.data.api.CodePolitanApi;
import id.zelory.codepolitan.data.database.DataBaseHelper; | /*
* Copyright (c) 2015 Zelory.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package id.zelory.codepolitan.controller;
/**
* Created on : August 18, 2015
* Author : zetbaitsu
* Name : Zetra
* Email : zetra@mail.ugm.ac.id
* GitHub : https://github.com/zetbaitsu
* LinkedIn : https://id.linkedin.com/in/zetbaitsu
*/
public class ReadLaterController extends BenihController<ReadLaterController.Presenter>
{
private List<Article> articles;
private Article article;
public ReadLaterController(Presenter presenter)
{
super(presenter);
BenihBus.pluck()
.receive()
.subscribe(o -> {
if (o instanceof ReadLaterEvent)
{
onReadLaterEvent((ReadLaterEvent) o);
}
}, throwable -> Timber.e(throwable.getMessage()));
}
public void setArticle(Article article)
{
this.article = article;
}
private void onReadLaterEvent(ReadLaterEvent readLaterEvent)
{
if (article != null && article.getId() == readLaterEvent.getArticle().getId())
{
if (readLaterEvent.getArticle().isReadLater() && !article.isReadLater())
{
article.setReadLater(true);
presenter.onReadLater(article);
} else if (!readLaterEvent.getArticle().isReadLater() && article.isReadLater())
{
article.setReadLater(false);
presenter.onUnReadLater(article);
}
}
}
public void loadReadLaterArticles()
{
presenter.showLoading();
DataBaseHelper.pluck()
.getReadLaterArticles()
.compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))
.subscribe(articles -> {
int size = articles.size();
for (int i = 0; i < size; i++)
{
articles.get(i).setBookmarked(DataBaseHelper.pluck().isBookmarked(articles.get(i).getId()));
articles.get(i).setReadLater(DataBaseHelper.pluck().isReadLater(articles.get(i).getId())); | articles.get(i).setBig(BenihUtils.randInt(0, 8) == 5); | 2 |
wuyan345/onlineShop | src/main/java/com/shop/controller/portal/UserController.java | [
"public class Const {\n\n\tpublic static final String HTTP_IMAGE_PREFIX = \"http://img.zxshopdemo.com/\";\n\t\n\tpublic static final int SUCCESS = 0;\n\tpublic static final int FAILED = 1;\n\t\n\tpublic static final int NORMAL_USER = 1;\n\tpublic static final int MANAGER = 0;\n\t\n\tpublic static final String CURRE... | import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.shop.common.Const;
import com.shop.common.LoginCheck;
import com.shop.common.Message;
import com.shop.pojo.User;
import com.shop.service.IUserService; | package com.shop.controller.portal;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired | private IUserService iUserService; | 4 |
kcthota/JSONQuery | src/main/java/com/kcthota/JSONQuery/Query.java | [
"@SuppressWarnings(\"serial\")\npublic class MissingNodeException extends RuntimeException {\n\n\tpublic MissingNodeException(String message) {\n\t\tsuper(message);\n\t\t\n\t}\n}",
"@SuppressWarnings(\"serial\")\npublic class UnsupportedExprException extends RuntimeException {\n\n\tpublic UnsupportedExprException... | import java.util.Iterator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.kcthota.JSONQuery.exceptions.MissingNodeException;
import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
import com.kcthota.JSONQuery.expressions.ComparisonExpression;
import com.kcthota.JSONQuery.expressions.DoubleValueExpression;
import com.kcthota.JSONQuery.expressions.IntegerValueExpression;
import com.kcthota.JSONQuery.expressions.LongValueExpression;
import com.kcthota.JSONQuery.expressions.ValueExpression; | package com.kcthota.JSONQuery;
public class Query extends AbstractQuery {
private Integer top;
private Integer skip;
public Query(JsonNode node) {
super(node);
}
/**
* Number of objects in an ArrayNode to be returned from top
* @param value
* @return
*/
public Query top(Integer value) {
setTop(value);
return this;
}
/**
* Number of objects in an Arraynode to be skipped from top
* @param value
* @return
*/
public Query skip(Integer value) {
setSkip(value);
return this;
}
/**
* Verifies if the passed expression is true for the JsonNode
*
* @param expr
* Comparison expression to be evaluated
* @return returns if the expression is true for the JsonNode
*/
public boolean is(ComparisonExpression expr) {
try {
if (expr != null) {
return expr.evaluate(node);
}
} catch (MissingNodeException e) {
return false;
}
return false;
}
/**
* Gets the value for the property from the JsonNode
*
* @param property
* @return
*/
public JsonNode value(String property) {
return value(new ValueExpression(property));
}
/**
* Gets the value as per expression set from the JsonNode
*
* @param expression
* Value expression to be evaluated
* @return Returns the value for the passed expression
*/
public JsonNode value(ValueExpression expression) {
return expression.evaluate(node);
}
/**
* Returns the integer value as per expression set
*
* @param expression
* IntegerValueExpression to be evaluated
* @return Returns the integer value of the result of expression evaluated
*/
public int value(IntegerValueExpression expression) {
return expression.value(node);
}
/**
* Returns the long value as per expression set
*
* @param expression
* LongValueExpression to be evaluated
* @return Returns the long value of the result of expression evaluated
*/ | public long value(LongValueExpression expression) { | 5 |
logful/logful-api | src/main/java/com/getui/logful/server/parse/GraylogClientService.java | [
"public class GlobalReference {\n\n private static final int MAX_CAPACITY = 1000;\n private HashMap<String, Layout> layoutMap = new HashMap<>();\n\n private static class ClassHolder {\n static GlobalReference instance = new GlobalReference();\n }\n\n public static GlobalReference reference() {... | import com.getui.logful.server.GlobalReference;
import com.getui.logful.server.ServerProperties;
import com.getui.logful.server.entity.Layout;
import com.getui.logful.server.entity.LayoutItem;
import com.getui.logful.server.entity.LogMessage;
import com.getui.logful.server.mongod.LogMessageRepository;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import org.apache.commons.lang.StringUtils;
import org.graylog2.gelfclient.*;
import org.graylog2.gelfclient.transport.GelfTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean; | package com.getui.logful.server.parse;
@Component
public class GraylogClientService implements SenderInterface {
private static final Logger LOG = LoggerFactory.getLogger(GraylogClientService.class);
@Autowired
ServerProperties serverProperties;
@Autowired
LogMessageRepository logMessageRepository;
private AtomicBoolean connected = new AtomicBoolean(false);
private GelfTransport graylogTransport;
@PostConstruct
public void create() {
MongoOperations operations = logMessageRepository.getOperations();
try {
BasicDBObject index = new BasicDBObject("writeDate", 1);
BasicDBObject options = new BasicDBObject("expireAfterSeconds", serverProperties.expires());
DBCollection collection = operations.getCollection(operations.getCollectionName(LogMessage.class));
collection.createIndex(index, options);
} catch (Exception e) {
LOG.error("Exception", e);
}
String host = serverProperties.graylogHost();
int port = serverProperties.graylogPort();
if (StringUtils.isEmpty(host)) {
throw new IllegalArgumentException("Graylog host can not be null!");
}
if (port <= 0 || port >= 65536) {
throw new IllegalArgumentException("Graylog port Not valid!");
}
InetSocketAddress socketAddress = new InetSocketAddress(host, port);
GelfConfiguration config = new GelfConfiguration(socketAddress)
.transport(GelfTransports.TCP)
.queueSize(serverProperties.getGraylog().getQueueCapacity())
.connectTimeout(serverProperties.getGraylog().getConnectTimeout())
.reconnectDelay(serverProperties.getGraylog().getReconnectDelay())
.tcpNoDelay(true)
.sendBufferSize(serverProperties.getGraylog().getSendBufferSize());
graylogTransport = GelfTransports.create(config);
graylogTransport.setListener(new GelfTransportListener() {
@Override
public void connected() {
connected.set(true);
}
@Override
public void disconnected() {
connected.set(false);
}
@Override
public void retrySuccessful(LogMessage logMessage) {
if (logMessage.getId() != null && logMessage.getId().length() > 0) {
logMessage.setStatus(LogMessage.STATE_SUCCESSFUL);
logMessageRepository.save(logMessage);
}
}
@Override
public void failed(LogMessage logMessage) {
logMessageRepository.save(logMessage);
}
});
}
public boolean isConnected() {
return connected.get();
}
public void write(LogMessage logMessage) {
if (connected.get()) {
GelfMessage message = createMessage(logMessage);
if (message != null) {
try {
write(message);
} catch (InterruptedException e) {
logMessageRepository.save(logMessage);
LOG.error("Exception", e);
}
}
} else {
logMessageRepository.save(logMessage);
}
}
public void write(GelfMessage message) throws InterruptedException {
graylogTransport.send(message);
}
@Override
public void send(LogMessage logMessage) {
write(logMessage);
}
@Override
public void release() {
// Nothing.
}
public GelfMessage createMessage(LogMessage logMessage) {
boolean formatError = false;
GelfMessageBuilder builder = new GelfMessageBuilder(logMessage.getTag(), "127.0.0.1")
.level(GelfMessageLevel.INFO);
GelfMessage message = builder.message(logMessage.getMessage())
.timestamp(logMessage.getTimestamp() / 1000D)
.additionalField("_tag", logMessage.getTag())
.additionalField("_platform", logMessage.getPlatform())
.additionalField("_uid", logMessage.getUid())
.additionalField("_app_id", logMessage.getAppId())
.additionalField("_log_level", logMessage.getLevel())
.additionalField("_log_name", logMessage.getLoggerName())
.additionalField("_log_timestamp", logMessage.getTimestamp())
.build();
String attachment = logMessage.getAttachment();
if (StringUtils.isNotEmpty(attachment)) {
message.addAdditionalField("_attachment", attachment);
}
String alias = logMessage.getAlias();
if (StringUtils.isNotEmpty(alias)) {
message.addAdditionalField("_alias", alias);
}
String msg = logMessage.getMessage();
String template = logMessage.getMsgLayout();
| Layout layout = GlobalReference.getLayout(template); | 0 |
kevalpatel2106/smart-lens | app/src/androidTest/java/com/kevalpatel2106/smartlens/camera/CameraUtilsTest.java | [
"@SuppressWarnings(\"WeakerAccess\")\npublic final class CameraImageFormat {\n\n /**\n * Image format for .jpg/.jpeg.\n */\n public static final int FORMAT_JPEG = 849;\n /**\n * Image format for .png.\n */\n public static final int FORMAT_PNG = 545;\n /**\n * Image format for .png... | import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import android.app.Activity;
import android.graphics.Bitmap;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import com.kevalpatel2106.smartlens.camera.config.CameraImageFormat;
import com.kevalpatel2106.smartlens.camera.config.CameraRotation;
import com.kevalpatel2106.smartlens.testUtils.BaseTestClass;
import com.kevalpatel2106.smartlens.utils.FileUtils;
import com.kevalpatel2106.smartlens.utils.Utils;
import org.junit.Test;
import org.junit.runner.RunWith; | /*
* Copyright 2017 Keval Patel.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kevalpatel2106.smartlens.camera;
/**
* Created by Keval on 20-Jul-17.
*/
@RunWith(AndroidJUnit4.class)
public final class CameraUtilsTest extends BaseTestClass {
@Test
public void canInitiate() throws Exception {
try {
Class<?> c = Class.forName("CameraUtils");
Constructor constructor = c.getDeclaredConstructors()[0];
constructor.newInstance();
fail("Should have thrown Arithmetic exception");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
@Test
public void checkIfBitmapRotate() throws Exception {
//Generate mock bmp
int mockBmpWidth = 100;
int mockBmpHeight = 50;
Bitmap mockBmp = Bitmap.createBitmap(mockBmpWidth, mockBmpHeight, Bitmap.Config.RGB_565);
//Rotate by 90. | Bitmap rotatedBmp = CameraUtils.rotateBitmap(mockBmp, CameraRotation.ROTATION_90); | 1 |
zulip/zulip-android | app/src/main/java/com/zulip/android/activities/LoginActivity.java | [
"public class ZulipApp extends Application {\n private static final String API_KEY = \"api_key\";\n private static final String EMAIL = \"email\";\n private static final String USER_AGENT = \"ZulipAndroid\";\n private static final String DEFAULT_SERVER_URL = \"https://api.zulip.com/\";\n private stat... | import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.zulip.android.BuildConfig;
import com.zulip.android.R;
import com.zulip.android.ZulipApp;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.ZulipAsyncPushTask;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.response.ZulipBackendResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.ActivityTransitionAnim;
import com.zulip.android.util.AnimationHelper;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.Constants;
import com.zulip.android.util.ShowAppUpdateDialog;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Response; |
if (!isUrlValid(serverURL)) {
Toast.makeText(LoginActivity.this, R.string.invalid_url, Toast.LENGTH_SHORT).show();
commonProgressDialog.dismiss();
return;
}
Uri serverUri = Uri.parse(serverURL);
serverUri = serverUri.buildUpon().scheme(httpScheme).build();
// display server url with http scheme used
serverIn.setText(serverUri.toString().toLowerCase(Locale.US));
mServerEditText.setText(serverUri.toString().toLowerCase(Locale.US));
mServerEditText.setEnabled(false);
// if server url does not end with "api/" or if the path is empty, use "/api" as last segment in the path
List<String> paths = serverUri.getPathSegments();
if (paths.isEmpty() || !paths.get(paths.size() - 1).equals("api")) {
serverUri = serverUri.buildUpon().appendEncodedPath("api/").build();
}
((ZulipApp) getApplication()).setServerURL(serverUri.toString().toLowerCase(Locale.US));
// create new zulipServices object every time by setting it to null
getApp().setZulipServices(null);
getServices()
.getAuthBackends()
.enqueue(new DefaultCallback<ZulipBackendResponse>() {
@Override
public void onSuccess(Call<ZulipBackendResponse> call, Response<ZulipBackendResponse> response) {
View view = LoginActivity.this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
if (response.body().isPassword()) {
findViewById(R.id.passwordAuthLayout).setVisibility(View.VISIBLE);
}
if (response.body().isGoogle()) {
findViewById(R.id.google_sign_in_button).setVisibility(View.VISIBLE);
}
if (response.body().isDev()) {
findViewById(R.id.local_server_button).setVisibility(View.VISIBLE);
}
commonProgressDialog.dismiss();
showLoginFields();
}
@Override
public void onError(Call<ZulipBackendResponse> call, Response<ZulipBackendResponse> response) {
Toast.makeText(LoginActivity.this, R.string.toast_login_failed_fetching_backends, Toast.LENGTH_SHORT).show();
commonProgressDialog.dismiss();
}
@Override
public void onFailure(Call<ZulipBackendResponse> call, Throwable t) {
super.onFailure(call, t);
if (!isNetworkAvailable()) {
Toast.makeText(LoginActivity.this, R.string.toast_no_internet_connection, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, R.string.invalid_url, Toast.LENGTH_SHORT).show();
}
commonProgressDialog.dismiss();
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void showHTTPDialog(final String serverURL) {
new AlertDialog.Builder(this)
.setTitle(R.string.http_or_https)
.setMessage(((BuildConfig.DEBUG) ? R.string.http_message_debug : R.string.http_message))
.setPositiveButton(R.string.use_https, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showBackends("https", serverURL);
}
})
.setNeutralButton(R.string.use_http, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showBackends("http", serverURL);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
}).show();
}
private void handleSignInResult(final GoogleSignInResult result) {
Log.d("Login", "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
// if there's a problem with fetching the account, bail
if (account == null) {
commonProgressDialog.dismiss();
Toast.makeText(LoginActivity.this, R.string.google_app_login_failed, Toast.LENGTH_SHORT).show();
return;
}
getServices()
.login("google-oauth2-token", account.getIdToken()) | .enqueue(new DefaultCallback<LoginResponse>() { | 3 |
flanglet/kanzi | java/src/main/java/kanzi/entropy/BinaryEntropyDecoder.java | [
"public interface Predictor\n{\n // Update the probability model\n public void update(int bit);\n\n\n // Return the split value representing the probability of 1 in the [0..4095] range.\n // E.G. 410 represents roughly a probability of 10% for 1\n public int get();\n}",
"public interface EntropyDec... | import kanzi.Predictor;
import kanzi.EntropyDecoder;
import kanzi.InputBitStream;
import kanzi.Memory;
import kanzi.SliceByteArray; | /*
Copyright 2011-2021 Frederic Langlet
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 kanzi.entropy;
// This class is a generic implementation of a boolean entropy decoder
public class BinaryEntropyDecoder implements EntropyDecoder
{
private static final long TOP = 0x00FFFFFFFFFFFFFFL;
private static final long MASK_24_56 = 0x00FFFFFFFF000000L;
private static final long MASK_0_56 = 0x00FFFFFFFFFFFFFFL;
private static final long MASK_0_32 = 0x00000000FFFFFFFFL;
private static final int MAX_BLOCK_SIZE = 1 << 30;
private static final int MAX_CHUNK_SIZE = 1 << 26;
private final Predictor predictor;
private long low;
private long high;
private long current;
private final InputBitStream bitstream; | private SliceByteArray sba; | 4 |
mzule/AndroidWeekly | app/src/main/java/com/github/mzule/androidweekly/ui/activity/ArticleActivity.java | [
"public class FavoriteDao extends SQLiteOpenHelper {\n private static final String NAME = \"favorite\";\n private static final int VERSION = 1;\n private static final int INDEX_TITLE = 1;\n private static final int INDEX_BRIEF = 2;\n private static final int INDEX_LINK = 3;\n private static final ... | import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.github.mzule.androidweekly.R;
import com.github.mzule.androidweekly.dao.FavoriteDao;
import com.github.mzule.androidweekly.dao.TextZoomKeeper;
import com.github.mzule.androidweekly.entity.Article;
import com.github.mzule.androidweekly.ui.view.ProgressView;
import com.github.mzule.androidweekly.ui.view.TranslateView;
import com.github.mzule.layoutannotation.Layout;
import butterknife.Bind;
import butterknife.OnClick; | package com.github.mzule.androidweekly.ui.activity;
/**
* Created by CaoDongping on 3/24/16.
*/
@Layout(R.layout.activity_article)
public class ArticleActivity extends BaseActivity {
@Bind(R.id.webView)
WebView webView;
@Bind(R.id.progressView)
ProgressView progressView;
@Bind(R.id.drawerLayout)
DrawerLayout drawerLayout;
@Bind(R.id.favoriteButton)
View favoriteButton; | private Article article; | 2 |
lob/lob-java | src/main/java/com/lob/model/SelfMailer.java | [
"public class APIException extends LobException {\n\n private static final long serialVersionUID = 1L;\n\n @JsonCreator\n public APIException(@JsonProperty(\"error\") final Map<String, Object> error) {\n super((String)error.get(\"message\"), (Integer)error.get(\"status_code\"));\n }\n\n}",
"pub... | import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lob.exception.APIException;
import com.lob.exception.AuthenticationException;
import com.lob.exception.InvalidRequestException;
import com.lob.exception.ParsingException;
import com.lob.exception.RateLimitException;
import com.lob.net.APIResource;
import com.lob.net.LobResponse;
import com.lob.net.RequestOptions;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | ", description='" + description + '\'' +
", to=" + to +
", from=" + from +
", url='" + url + '\'' +
", outsideTemplateId='" + outsideTemplateId + '\'' +
", insideTemplateId='" + insideTemplateId + '\'' +
", outsideTemplateVersionId='" + outsideTemplateVersionId + '\'' +
", insideTemplateVersionId='" + insideTemplateVersionId + '\'' +
", carrier='" + carrier + '\'' +
", trackingEvents='" + trackingEvents + '\'' +
", thumbnails='" + thumbnails + '\'' +
", size='" + size + '\'' +
", mailType='" + mailType + '\'' +
", mergeVariables=" + mergeVariables +
", expectedDeliveryDate=" + expectedDeliveryDate +
", dateCreated=" + dateCreated +
", dateModified=" + dateModified +
", sendDate=" + sendDate +
", mailType='" + mailType + '\'' +
", metadata=" + metadata +
", deleted=" + deleted +
", billingGroupId='" + billingGroupId + '\'' +
", object=" + object +
'}';
}
public static final class RequestBuilder {
private Map<String, Object> params = new HashMap<String, Object>();
private boolean isMultipart = false;
private ObjectMapper objectMapper = new ObjectMapper();
public RequestBuilder() {
}
public RequestBuilder setDescription(String description) {
params.put("description", description);
return this;
}
public RequestBuilder setTo(String to) {
params.put("to", to);
return this;
}
public RequestBuilder setTo(Address.RequestBuilder to) {
params.put("to", to.build());
return this;
}
public RequestBuilder setFrom(String from) {
params.put("from", from);
return this;
}
public RequestBuilder setFrom(Address.RequestBuilder from) {
params.put("from", from.build());
return this;
}
public RequestBuilder setOutside(File outside) {
isMultipart = true;
params.put("outside", outside);
return this;
}
public RequestBuilder setOutside(String inside) {
params.put("outside", inside);
return this;
}
public RequestBuilder setInside(String inside) {
params.put("inside", inside);
return this;
}
public RequestBuilder setInside(File outside) {
isMultipart = true;
params.put("inside", outside);
return this;
}
public RequestBuilder setMergeVariables(Map mergeVariables) throws ParsingException {
try {
params.put("merge_variables", objectMapper.writeValueAsString(mergeVariables));
return this;
} catch (JsonProcessingException e) {
throw new ParsingException(e);
}
}
public RequestBuilder setSize(String size) {
params.put("size", size);
return this;
}
public RequestBuilder setMailType(String mailType) {
params.put("mail_type", mailType);
return this;
}
public RequestBuilder setSendDate(String sendDate) {
params.put("send_date", sendDate);
return this;
}
public RequestBuilder setSendDate(ZonedDateTime sendDate) {
params.put("send_date", sendDate);
return this;
}
public RequestBuilder setMetadata(Map<String, String> metadata) {
params.put("metadata", metadata);
return this;
}
public RequestBuilder setBillingGroupId(String billingGroupId) {
params.put("billing_group_id", billingGroupId);
return this;
}
| public LobResponse<SelfMailer> create() throws APIException, IOException, AuthenticationException, InvalidRequestException, RateLimitException { | 0 |
kihira/Tails | src/main/java/uk/kihira/tails/proxy/ClientProxy.java | [
"public class ClientEventHandler \n{\n private boolean sentPartInfoToServer = false;\n private boolean clearAllPartInfo = false;\n\n /*\n *** Tails Editor Button ***\n */\n @SubscribeEvent\n public void onScreenInitPost(GuiScreenEvent.InitGuiEvent.Post event) \n {\n if (event.getGui... | import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.PlayerRenderer;
import net.minecraftforge.common.MinecraftForge;
import uk.kihira.tails.client.ClientEventHandler;
import uk.kihira.tails.client.MountPoint;
import uk.kihira.tails.client.PartRenderer;
import uk.kihira.tails.client.render.LayerPart;
import uk.kihira.tails.common.LibraryManager;
import java.util.Map; | package uk.kihira.tails.proxy;
public class ClientProxy extends CommonProxy
{
public PartRenderer partRenderer;
@Override
public void preInit()
{
registerMessages();
registerHandlers();
this.libraryManager = new LibraryManager.ClientLibraryManager();
}
@Override
protected void registerHandlers()
{
ClientEventHandler eventHandler = new ClientEventHandler();
MinecraftForge.EVENT_BUS.register(eventHandler);
//super.registerHandlers();
}
@Override
public void onResourceManagerReload()
{
setupRenderers();
}
/**
* Sets up the various part renders on the player model.
* Renderers used depends upon legacy setting
*/
private void setupRenderers()
{
/* boolean legacyRenderer = Config.forceLegacyRendering.get();
if (legacyRenderer)
{
Tails.LOGGER.info("Legacy Renderer has been forced enabled");
}*/
// todo Fix smart moving compat
// else if (Loader.isModLoaded("SmartMoving"))
// {
// Tails.LOGGER.info("Legacy Renderer enabled automatically for mod compatibility");
// legacyRenderer = true;
// }
partRenderer = new PartRenderer();
Map<String, PlayerRenderer> skinMap = Minecraft.getInstance().getRenderManager().getSkinMap();
/* if (legacyRenderer)
{
MinecraftForge.EVENT_BUS.register(new FallbackRenderHandler());
// Default
PlayerModel<AbstractClientPlayerEntity> model = skinMap.get("default").getEntityModel();
model.bipedHead.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.HEAD));
model.bipedBody.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.CHEST));
model.bipedLeftArm.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.LEFT_ARM));
model.bipedRightArm.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.RIGHT_ARM));
model.bipedLeftLeg.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.LEFT_LEG));
model.bipedRightLeg.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.RIGHT_LEG));
// Slim
model = skinMap.get("slim").getEntityModel();
model.bipedHead.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.HEAD));
model.bipedBody.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.CHEST));
model.bipedLeftArm.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.LEFT_ARM));
model.bipedRightArm.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.RIGHT_ARM));
model.bipedLeftLeg.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.LEFT_LEG));
model.bipedRightLeg.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.RIGHT_LEG));
} else */
{
// Default
PlayerRenderer renderPlayer = skinMap.get("default"); | renderPlayer.addLayer(new LayerPart(renderPlayer, renderPlayer.getEntityModel().bipedHead, partRenderer, MountPoint.HEAD)); | 3 |
zznate/intravert-ug | src/test/java/io/teknek/intravert/action/impl/SessionTest.java | [
"public class ActionFactory {\n \n public static final String CREATE_SESSION = \"createsession\";\n public static final String LOAD_SESSION = \"loadsession\";\n public static final String SET_KEYSPACE = \"setkeyspace\";\n public static final String GET_KEYSPACE = \"getkeyspace\";\n public static final String ... | import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import io.teknek.intravert.action.ActionFactory;
import io.teknek.intravert.model.Constants;
import io.teknek.intravert.model.Operation;
import io.teknek.intravert.model.Request;
import io.teknek.intravert.model.Response;
import io.teknek.intravert.service.DefaultIntravertService;
import io.teknek.intravert.service.IntravertService;
import io.teknek.intravert.test.TestUtils;
import org.junit.Test;
import com.google.common.collect.ImmutableMap; | package io.teknek.intravert.action.impl;
public class SessionTest {
@Test
public void aTest(){
IntravertService service = new DefaultIntravertService();
String keyspaceName = "bla";
{ | Request request = new Request(); | 3 |
SW-Team/java-TelegramBot | src/milk/telegram/method/update/CaptionEditor.java | [
"public class TelegramBot extends Thread{\n\n public static final String BASE_URL = \"https://api.telegram.org/bot%s/%s\";\n\n private String token = \"\";\n\n private int lastId = 0;\n private int limit = 100;\n private int timeout = 1500;\n\n private User me;\n\n private Handler handler;\n\n ... | import milk.telegram.bot.TelegramBot;
import milk.telegram.type.Identifier;
import milk.telegram.type.Usernamed;
import milk.telegram.type.chat.Channel;
import milk.telegram.type.message.Message;
import milk.telegram.type.reply.ReplyMarkup;
import org.json.JSONObject; | package milk.telegram.method.update;
public class CaptionEditor extends Editor{
public CaptionEditor(TelegramBot bot){
super(bot);
}
public String getCaption(){
return this.optString("caption");
}
public String getChatId(){
return this.optString("chat_id");
}
public long getMessageId(){
return this.optLong("message_id");
}
public String getInlineId(){
return this.optString("inline_id");
}
public JSONObject getReplyMarkup(){
return this.optJSONObject("reply_markup");
}
public CaptionEditor setChatId(Object chat_id){
if(chat_id instanceof Identifier){
chat_id = chat_id instanceof Channel ? "@" + ((Usernamed) chat_id).getUsername() : ((Identifier) chat_id).getId();
}
if(chat_id instanceof String){
this.put("chat_id", chat_id);
}else if(chat_id instanceof Number){
this.put("chat_id", ((Number) chat_id).longValue() + "");
}
return this;
}
public CaptionEditor setMessageId(Object message_id){
if(message_id instanceof Message){
this.put("message_id", ((Message) message_id).getId());
this.put("chat_id", ((Message) message_id).getChat().getId() + "");
}else if(message_id instanceof Number){
this.put("message_id", ((Number) message_id).longValue());
}
return this;
}
| public CaptionEditor setReplyMarkup(ReplyMarkup reply_markup){ | 5 |
immopoly/android | src/org/immopoly/android/adapter/PortfolioFlatsAdapter.java | [
"public class ImageListDownloader {\n\tprivate static final String LOG_TAG = \"ImageDownloader\";\n\n\tprivate static final int HARD_CACHE_CAPACITY = 40;\n\tprivate static final int DELAY_BEFORE_PURGE = 30 * 1000; // in milliseconds\n\n\tprivate Bitmap loadingBitmap;\n\tprivate Bitmap fallbackBitmap;\n\tpriva... | import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.immopoly.android.R;
import org.immopoly.android.helper.ImageListDownloader;
import org.immopoly.android.helper.Settings;
import org.immopoly.android.model.Flat;
import org.immopoly.android.model.Flats;
import org.immopoly.android.widget.EllipsizingTextView; | /*
* This is the Android component of Immopoly
* http://immopoly.appspot.com
* Copyright (C) 2011 Tobias Sasse
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package org.immopoly.android.adapter;
/**
* ListAdapter for the portfolio list fragment
*
* @author bjoern
*
*/
public class PortfolioFlatsAdapter extends BaseAdapter {
private LayoutInflater inflater;
| private Flats mFlats; | 3 |
AstartesGuardian/WebDAV-Server | WebDAV-Server/src/webdav/server/virtual/entity/remote/webdav/RsWebDavHelper.java | [
"public class ExtendableByteBuffer\r\n{\r\n public ExtendableByteBuffer()\r\n { }\r\n \r\n protected int internalBufferSize = 1500;\r\n protected List<byte[]> content = new ArrayList<>();\r\n protected int totalLength = 0;\r\n \r\n \r\n \r\n public ExtendableByteBuffer setInternalBuffe... | import http.ExtendableByteBuffer;
import http.StringJoiner;
import http.server.exceptions.NotFoundException;
import http.server.message.HTTPRequest;
import http.server.message.HTTPResponse;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.Socket;
import java.util.stream.Stream;
| package webdav.server.virtual.entity.remote.webdav;
public class RsWebDavHelper
{
| public static ExtendableByteBuffer sendRequest(byte[] ip, int port, HTTPRequest.Builder requestBuilder) throws IOException
| 3 |
Doist/JobSchedulerCompat | library/src/main/java/com/doist/jobschedulercompat/scheduler/jobscheduler/JobSchedulerJobService.java | [
"public class JobParameters {\n private final int jobId;\n private final PersistableBundle extras;\n private final Bundle transientExtras;\n private final Network network;\n private final Uri[] triggeredContentUris;\n private final String[] triggeredContentAuthorities;\n private final boolean o... | import com.doist.jobschedulercompat.JobParameters;
import com.doist.jobschedulercompat.JobScheduler;
import com.doist.jobschedulercompat.JobService;
import com.doist.jobschedulercompat.PersistableBundle;
import com.doist.jobschedulercompat.job.JobStatus;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.util.SparseArray;
import androidx.annotation.RestrictTo; | package com.doist.jobschedulercompat.scheduler.jobscheduler;
/**
* Job service for all {@link android.app.job.JobScheduler}-based schedulers, such as {@link JobSchedulerSchedulerV21}.
*
* This service runs whenever {@link android.app.job.JobScheduler} starts it based on the current jobs and constraints.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@RestrictTo(RestrictTo.Scope.LIBRARY) | public class JobSchedulerJobService extends android.app.job.JobService implements JobService.Binder.Callback { | 2 |
PuffOpenSource/Puff-Android | app/src/main/java/sun/bob/leela/App.java | [
"public class AccountHelper {\n private static AccountHelper ourInstance;\n private Context context;\n private DaoMaster daoMaster;\n private DaoSession daoSession;\n private AccountDao accountDao;\n\n public static AccountHelper getInstance(Context context) {\n if (ourInstance == null) {\n... | import android.app.Application;
import sun.bob.leela.db.AccountHelper;
import sun.bob.leela.db.CategoryHelper;
import sun.bob.leela.db.TypeHelper;
import sun.bob.leela.utils.CategoryUtil;
import sun.bob.leela.utils.EnvUtil;
import sun.bob.leela.utils.ResUtil;
import sun.bob.leela.utils.UserDefault; | package sun.bob.leela;
/**
* Created by bob.sun on 16/3/19.
*/
public class App extends Application {
@Override
public void onCreate(){
super.onCreate();
AccountHelper.getInstance(getApplicationContext());
CategoryHelper categoryHelper = CategoryHelper.getInstance(getApplicationContext());
TypeHelper typeHelper = TypeHelper.getInstance(getApplicationContext());
if (categoryHelper.getAllCategory() == null || categoryHelper.getAllCategory().size() == 0) {
CategoryUtil.getInstance(getApplicationContext()).initBuiltInCategories();
}
if (typeHelper.getAllTypes() == null || typeHelper.getAllTypes().size() == 0) {
CategoryUtil.getInstance(getApplicationContext()).initBuiltInTypes();
}
ResUtil.getInstance(getApplicationContext());
CategoryUtil.getInstance(getApplicationContext()); | EnvUtil.getInstance(getApplicationContext()); | 4 |
mit-dig/punya | appinventor/appengine/src/com/google/appinventor/client/explorer/commands/AddFormCommand.java | [
"public static final OdeMessages MESSAGES = GWT.create(OdeMessages.class);",
"public class DesignToolbar extends Toolbar {\n\n /*\n * A Screen groups together the form editor and blocks editor for an\n * application screen. Name is the name of the screen (form) displayed\n * in the screens pull-down.\n *... | import static com.google.appinventor.client.Ode.MESSAGES;
import java.util.HashSet;
import java.util.Set;
import com.google.appinventor.client.DesignToolbar;
import com.google.appinventor.client.Ode;
import com.google.appinventor.client.OdeAsyncCallback;
import com.google.appinventor.client.editor.FileEditor;
import com.google.appinventor.client.editor.ProjectEditor;
import com.google.appinventor.client.explorer.project.Project;
import com.google.appinventor.client.widgets.LabeledTextBox;
import com.google.appinventor.client.youngandroid.TextValidators;
import com.google.appinventor.shared.rpc.project.ProjectNode;
import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidBlocksNode;
import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidFormNode;
import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidPackageNode;
import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidProjectNode;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel; | if (formName.startsWith(prefix)) {
try {
highIndex = Math.max(highIndex, Integer.parseInt(formName.substring(prefixLength)));
} catch (NumberFormatException e) {
continue;
}
}
}
}
String defaultFormName = prefix + (highIndex + 1);
newNameTextBox = new LabeledTextBox(MESSAGES.formNameLabel());
newNameTextBox.setText(defaultFormName);
newNameTextBox.getTextBox().addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
int keyCode = event.getNativeKeyCode();
if (keyCode == KeyCodes.KEY_ENTER) {
handleOkClick(projectRootNode);
} else if (keyCode == KeyCodes.KEY_ESCAPE) {
hide();
executionFailedOrCanceled();
}
}
});
contentPanel.add(newNameTextBox);
String cancelText = MESSAGES.cancelButton();
String okText = MESSAGES.okButton();
// Keeps track of the total number of screens.
int formCount = otherFormNames.size() + 1;
if (formCount > MAX_FORM_COUNT) {
HorizontalPanel errorPanel = new HorizontalPanel();
HTML tooManyScreensLabel = new HTML(MESSAGES.formCountErrorLabel());
errorPanel.add(tooManyScreensLabel);
errorPanel.setSize("100%", "24px");
contentPanel.add(errorPanel);
okText = MESSAGES.addScreenButton();
cancelText = MESSAGES.cancelScreenButton();
// okText = "Add";
// cancelText = "Don't Add";
}
Button cancelButton = new Button(cancelText);
cancelButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
executionFailedOrCanceled();
}
});
Button okButton = new Button(okText);
okButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
handleOkClick(projectRootNode);
}
});
HorizontalPanel buttonPanel = new HorizontalPanel();
buttonPanel.add(cancelButton);
buttonPanel.add(okButton);
buttonPanel.setSize("100%", "24px");
contentPanel.add(buttonPanel);
contentPanel.setSize("320px", "100%");
add(contentPanel);
}
private void handleOkClick(YoungAndroidProjectNode projectRootNode) {
String newFormName = newNameTextBox.getText();
if (validate(newFormName)) {
hide();
addFormAction(projectRootNode, newFormName);
} else {
newNameTextBox.setFocus(true);
}
}
private boolean validate(String newFormName) {
// Check that it meets the formatting requirements.
if (!TextValidators.isValidIdentifier(newFormName)) {
Window.alert(MESSAGES.malformedFormNameError());
return false;
}
// Check that it's unique.
if (otherFormNames.contains(newFormName)) {
Window.alert(MESSAGES.duplicateFormNameError());
return false;
}
return true;
}
/**
* Adds a new form to the project.
*
* @param formName the new form name
*/
protected void addFormAction(final YoungAndroidProjectNode projectRootNode,
final String formName) {
final Ode ode = Ode.getInstance();
final YoungAndroidPackageNode packageNode = projectRootNode.getPackageNode();
String qualifiedFormName = packageNode.getPackageName() + '.' + formName;
final String formFileId = YoungAndroidFormNode.getFormFileId(qualifiedFormName);
final String blocksFileId = YoungAndroidBlocksNode.getBlocklyFileId(qualifiedFormName);
OdeAsyncCallback<Long> callback = new OdeAsyncCallback<Long>(
// failure message
MESSAGES.addFormError()) {
@Override
public void onSuccess(Long modDate) {
final Ode ode = Ode.getInstance();
ode.updateModificationDate(projectRootNode.getProjectId(), modDate);
// Add the new form and blocks nodes to the project | final Project project = ode.getProjectManager().getProject(projectRootNode); | 4 |
ResearchStack/ResearchStack | backbone/src/main/java/org/researchstack/backbone/StorageAccess.java | [
"public interface EncryptionProvider {\n /**\n * Returns whether the user has created a pin code.\n *\n * @param context android context\n * @return boolean indicating whether the user has created a pin code\n */\n boolean hasPinCode(Context context);\n\n /**\n * Create a pin code f... | import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.MainThread;
import org.researchstack.backbone.storage.database.AppDatabase;
import org.researchstack.backbone.storage.file.EncryptionProvider;
import org.researchstack.backbone.storage.file.FileAccess;
import org.researchstack.backbone.storage.file.PinCodeConfig;
import org.researchstack.backbone.storage.file.StorageAccessException;
import org.researchstack.backbone.storage.file.StorageAccessListener;
import org.researchstack.backbone.ui.PinCodeActivity;
import org.researchstack.backbone.utils.UiThreadContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | package org.researchstack.backbone;
/**
* This class is responsible for providing access to the pin-protected file storage and database.
* Before calling {@link #getFileAccess()} or {@link #getAppDatabase()}, make sure to call {@link
* #register} and {@link #requestStorageAccess}. Once {@link StorageAccessListener#onDataReady()} is
* called, then you may call these methods and read/write your data.
* <p>
* If {@link StorageAccessListener#onDataAuth()} is called, then you must prompt the user for their
* pin and authenticate using {@link #authenticate}.
* <p>
* {@link org.researchstack.backbone.ui.PinCodeActivity} handles almost all of this for you,
* including presenting the pin code screen to the user. PinCodeActivity should be used, extended,
* or it's fuctionality copied to your application's own base Activity. Make sure to delay any data
* access until {@link PinCodeActivity#onDataReady()} has been called.
*/
public class StorageAccess {
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Assert Constants
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
private static final boolean CHECK_THREADS = false;
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Static Fields
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
private static StorageAccess instance = new StorageAccess();
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Fields
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
private FileAccess fileAccess;
private PinCodeConfig pinCodeConfig;
private AppDatabase appDatabase;
private EncryptionProvider encryptionProvider;
private Handler handler = new Handler(Looper.getMainLooper());
private List<StorageAccessListener> listeners = Collections.synchronizedList(new ArrayList<>());
private StorageAccess() {
}
/**
* Returns the singleton instance of this class.
*
* @return the singleton instance of this class
*/
public static StorageAccess getInstance() {
return instance;
}
/**
* Initializes the storage access singleton with the provided dependencies. It is best to call
* this method inside your {@link Application#onCreate()} method.
*
* @param pinCodeConfig an instance of the pin code configuration for your app
* @param encryptionProvider an encryption provider
* @param fileAccess an implementation of FileAccess
* @param appDatabase an implementation of AppDatabase
*/
public void init(PinCodeConfig pinCodeConfig, EncryptionProvider encryptionProvider, FileAccess fileAccess, AppDatabase appDatabase) {
this.pinCodeConfig = pinCodeConfig;
this.appDatabase = appDatabase;
this.fileAccess = fileAccess;
this.encryptionProvider = encryptionProvider;
}
/**
* Returns the FileAccess singleton for this application. Should only be called after {@link
* StorageAccessListener#onDataReady()}.
*
* @return the FileAccess singleton
*/
public FileAccess getFileAccess() {
return fileAccess;
}
/**
* Returns the AppDatabase singleton for this application. Should only be called after {@link
* StorageAccessListener#onDataReady()}.
*
* @return the AppDatabase singleton
*/
public AppDatabase getAppDatabase() {
return appDatabase;
}
/**
* Returns the pin code configuration for the app
*
* @return the pin code configuration
*/
public PinCodeConfig getPinCodeConfig() {
return pinCodeConfig;
}
/**
* Returns whether the user has created a pin code or not
*
* @param context android context
* @return a boolean indicating if the user has created a pin code
*/
public boolean hasPinCode(Context context) {
return encryptionProvider.hasPinCode(context);
}
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Storage Access request and notification
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
/**
* Checks and inits storage access. Once storage access is ready, registered listeners will be
* notified via the {@link StorageAccessListener}. This is true whether there is an auth flow or
* if the system is already prepared. The callback will happen on the main thread looper, after
* all scheduled events, which will include (in the standard case) onCreate/onStart/onResume,
* and the equivalent Fragment callbacks. This is to ensure one path, and reduce edge case race
* conditions.
*
* @param context Calling context. If you are calling from an Activity, its best to send it and
* not the application context, because we may want to start new activities, and
* the application context can only do so with a new task, which will possibly
* complicate the back stack. We won't do anything weird that causes memory
* leaks. Promise ;)
*/
@MainThread
public void requestStorageAccess(Context context) {
UiThreadContext.assertUiThread();
if (encryptionProvider.needsAuth(context, pinCodeConfig)) {
// just need to re-auth
notifySoftFail();
} else {
notifyReady();
}
}
/**
* Registers a listener. If you want to read/write data, you'll need to implement this to know
* when file access is ready.
*
* @param storageAccessListener
*/
@MainThread
public final void register(StorageAccessListener storageAccessListener) {
if (CHECK_THREADS) {
UiThreadContext.assertUiThread();
}
if (listeners.contains(storageAccessListener)) { | throw new StorageAccessException("Listener already registered"); | 3 |
Spedge/hangar | hangar-api/src/main/java/com/spedge/hangar/repo/python/api/PythonDownloadEndpoint.java | [
"public enum RepositoryType\n{\n RELEASE_JAVA(RepositoryLanguage.JAVA), \n SNAPSHOT_JAVA(RepositoryLanguage.JAVA), \n PROXY_JAVA(RepositoryLanguage.JAVA), \n PROXY_PYTHON(RepositoryLanguage.PYTHON),\n UNKNOWN(RepositoryLanguage.UNKNOWN);\n\n private RepositoryLanguage lang;\n\n RepositoryType(R... | import com.spedge.hangar.repo.RepositoryType;
import com.spedge.hangar.repo.python.PythonIndexKey;
import com.spedge.hangar.repo.python.PythonRepository;
import com.spedge.hangar.repo.python.PythonStorageTranslator;
import com.spedge.hangar.storage.IStorageTranslator;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.StreamingOutput; | package com.spedge.hangar.repo.python.api;
public class PythonDownloadEndpoint extends PythonRepository
{
private String[] proxies;
/**
* pip starts by requesting a list of all the versions for the artifact it wants
* and doesn't give an idea of what version it's looking for. So, we need to return
* this list - taken from Pypi but with our local artifact locations injected.
*
* @param artifact Name of the artifact pip is looking for.
* @return
*/
@GET
@Path("/simple/{artifact : .+}/")
public StreamingOutput getMetadata(@PathParam("artifact") String artifact)
{
return super.getMetadata(proxies, artifact.replace("/", ""));
}
/**
* When we return the list of artifacts, if we don't have it locally the next request
* will hit this URL. The base information parameters are required to get the artifact
* from Pypi - which we will then save to our local storage.
*
* @param base1
* @param base2
* @param baseMax
* @param artifact
* @return
*/
@GET
@Path("/packages/{base1 : .+}/{base2 : .+}/{baseMax : .+}/{artifact : .+}")
public StreamingOutput getRemotePackage(@PathParam("base1") String base1,
@PathParam("base2") String base2,
@PathParam("baseMax") String baseMax,
@PathParam("artifact") String artifact)
{
return super.getProxiedArtifact(proxies, "/packages/" + base1 + "/" + base2 + "/" + baseMax + "/", artifact);
}
/**
* If we've got the artifact locally, the artifact URL will point at this endpoint
* which is a much simpler format and easier to understand.
*
* @param artifact
* @param filename
* @return
*/
@GET
@Path("/local/{artifact : .+}/{filename : .+}")
public StreamingOutput getLocalPackage(@PathParam("artifact") String artifact,
@PathParam("filename") String filename)
{
PythonIndexKey pk = new PythonIndexKey(getType(), artifact, filename);
return super.getLocalArtifact(proxies, pk);
}
public String[] getProxy()
{
return proxies;
}
public void setProxy(String[] proxy)
{
this.proxies = proxy;
}
@Override
public RepositoryType getType()
{
return RepositoryType.PROXY_PYTHON;
}
@Override | public IStorageTranslator getStorageTranslator() | 4 |
neoremind/navi-pbrpc | src/main/java/com/baidu/beidou/navi/pbrpc/client/BlockingIOPooledPbrpcClient.java | [
"public class CallFuture<T> implements Future<T>, Callback<T> {\r\n\r\n /**\r\n * 内部回调用的栅栏\r\n */\r\n private final CountDownLatch latch = new CountDownLatch(1);\r\n\r\n /**\r\n * 调用返回结果\r\n */\r\n private T result = null;\r\n\r\n /**\r\n * 调用错误信息\r\n */\r\n private Throwab... | import io.netty.channel.ChannelFuture;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baidu.beidou.navi.pbrpc.client.callback.CallFuture;
import com.baidu.beidou.navi.pbrpc.codec.Codec;
import com.baidu.beidou.navi.pbrpc.codec.impl.ProtobufCodec;
import com.baidu.beidou.navi.pbrpc.exception.client.OperationNotSupportException;
import com.baidu.beidou.navi.pbrpc.exception.client.PbrpcException;
import com.baidu.beidou.navi.pbrpc.transport.PbrpcMsg;
import com.google.protobuf.GeneratedMessage; | package com.baidu.beidou.navi.pbrpc.client;
/**
* ClassName: BlockingIOPooledPbrpcClient <br/>
* Function: 使用连接池技术的blocking io客户端
*
* @author Zhang Xu
*/
public class BlockingIOPooledPbrpcClient implements PbrpcClient {
private static final Logger LOG = LoggerFactory.getLogger(BlockingIOPooledPbrpcClient.class);
/**
* socket连接池
*/
private BlockingIOPbrpcClientSocketPool socketPool;
/**
* 连接池配置
*/
private GenericObjectPool.Config pooledConfig;
/**
* 客户端配置
*/
private PbrpcClientConfiguration pbrpcClientConfiguration = new PbrpcClientConfiguration();
/**
* 远程服务IP
*/
private String ip;
/**
* 远程服务端口
*/
private int port;
/**
* 客户端连接超时,单位毫秒
*/
private int connTimeout;
/**
* 客户端调用超时,单位毫秒
*/
private int readTimeout;
/**
* 可配置,默认使用protobuf来做body的序列化
*/
private Codec codec = new ProtobufCodec();
/**
* header+body通讯协议方式的头解析构造器
*/
private HeaderResolver headerResolver = new NsHeaderResolver();
public BlockingIOPooledPbrpcClient() {
}
/**
* Creates a new instance of BlockingIOPooledPbrpcClient.
*
* @param pooledConfig
* 连接池配置
* @param clientConfig
* 客户端配置
* @param ip
* socket远程ip
* @param port
* socket远程端口
* @param connTimeout
* 客户端连接时间,单位为毫秒
* @param readTimeout
* 客户端调用的超时时间,单位为毫秒,超时则会抛出{@link com.baidu.beidou.navi.pbrpc.exception.TimeoutException}
*/
public BlockingIOPooledPbrpcClient(PooledConfiguration configuration,
PbrpcClientConfiguration clientConfig, String ip, int port, int connTimeout,
int readTimeout) {
this.pooledConfig = configuration.getPoolConfig();
this.ip = ip;
this.port = port;
this.connTimeout = connTimeout;
this.readTimeout = readTimeout;
this.pbrpcClientConfiguration = clientConfig;
socketPool = new BlockingIOPbrpcClientSocketPool(pooledConfig, pbrpcClientConfiguration,
ip, port, connTimeout, readTimeout, codec, headerResolver);
}
/**
* @see com.baidu.beidou.navi.pbrpc.client.PbrpcClient#asyncTransport(java.lang.Class,
* com.baidu.beidou.navi.pbrpc.transport.PbrpcMsg)
*/
@Override
public <T extends GeneratedMessage> CallFuture<T> asyncTransport(Class<T> responseClazz,
PbrpcMsg pbrpcMsg) {
throw new OperationNotSupportException();
}
/**
* @see com.baidu.beidou.navi.pbrpc.client.PbrpcClient#syncTransport(java.lang.Class,
* com.baidu.beidou.navi.pbrpc.transport.PbrpcMsg)
*/
@Override
public <T extends GeneratedMessage> T syncTransport(Class<T> responseClazz, PbrpcMsg pbrpcMsg) {
BlockingIOPbrpcClient client = socketPool.getResource();
try {
T res = client.syncTransport(responseClazz, pbrpcMsg);
return res;
} catch (Exception e) {
LOG.error("asyncTransport failed, " + e.getMessage(), e);
socketPool.returnBrokenResource(client); | throw new PbrpcException("Pbrpc invocation failed on " + getInfo() + ", " | 4 |
dotcool/coolreader | src/com/dotcool/view/BookOnlineActivity.java | [
"public class DbDataOperation\n{\n\t/**\n\t * 得到书籍的详细信息\n\t * @param resolver \n\t * @return 返回添加了数据的book对象\n\t */\n\tpublic static ArrayList<Book> getBookInfo(ContentResolver resolver)\n\t{\n\t\tArrayList<Book> bookList = new ArrayList<Book>();\n\t\tBook book;\n\t\t\n\t\tCursor cursor = resolver.query(Uri.parse(Db... | import java.util.HashMap;
import java.util.Map;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.dotcool.R;
import com.dotcool.bll.DbDataOperation;
import com.dotcool.bll.Downloader;
import com.dotcool.model.LoadInfo;
import com.dotcool.util.AppUtil;
import com.dotcool.util.BookUtil;
import com.dotcool.util.TimeUtil; | package com.dotcool.view;
public class BookOnlineActivity extends ListActivity
{
private ListView lvBookOnline;
private ContentResolver resolver;
ImageView ivbookCover ;
TextView tvbookName,tvbookDetail;
Button btnDownload;
private int threadcount;
//Begin-change by Gank
private int[] bookIconRes = new int[]{R.drawable.p39113,R.drawable.p39143,R.drawable.p39534,
R.drawable.p39726};
private String[] bookNames = new String[]{"深圳情人","本色","天使不在线","我的天使我的爱"};
private String[] bookDetails = new String[]{
"刘雪婷慵懒地靠在浅绿色布艺沙发上,修长笔直的双腿随意搁在圆皮脚凳上,哈欠连天地看着手机里连绵不断的贺年短信。",
"两个人,像田地中的两只鼹鼠,你觅食,我守窝,你守窝,我觅食,在一起互相温暖着,照料着,度过每一个白天和夜晚,每一个春夏秋冬。",
"辟辟啪啪,打上这最后一行字,文字已经把电脑的屏幕塞得满满的,再也没有任何缝隙。键盘敲打的声音突然停止,四周重新陷入一片寂静中。",
"在我安静的小屋里有着星点的光,那是我的烟。月光从窗口洒下,光影里有隐约飘散的烟雾。慢慢地腾升,绕着墙上的十字绣画袅袅而上。"};
private final static String URL = "";
private String[] bookUrls = new String[]{
"http://storezhang-upload.stor.sinaapp.com/fiction/txt/c76b0495-8e4e-4dde-b6d4-ece72c53c2d9.txt",
"http://storezhang-upload.stor.sinaapp.com/fiction/txt/aa371da1-7368-4f81-a036-0897a87e04a8.txt",
"http://storezhang-upload.stor.sinaapp.com/fiction/txt/21243553-5e6c-4f59-8e3b-b3eafebddfba.txt",
"http://storezhang-upload.stor.sinaapp.com/fiction/txt/8eae5c2d-3c0c-43d1-8728-82bed11babb7.txt"};
//End
private static final String SD_PATH = "/mnt/sdcard/DotcoolReader/";
// 存放各个下载器
private Map<String, Downloader> downloaders = new HashMap<String, Downloader>();
// 存放与下载器对应的进度条
private Map<String, ProgressBar> ProgressBars = new HashMap<String, ProgressBar>();
private LinearLayout layout;
private NotificationManager notificationManager;
private int notificationId = 1;
private int currentPosition;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
String url = (String) msg.obj;
int length = msg.arg1;
ProgressBar bar = ProgressBars.get(url);
if (bar != null) {
// 设置进度条按读取的length长度更新
bar.incrementProgressBy(length);
if (bar.getProgress() == bar.getMax()) {
notificationManager.cancel(notificationId);
btnDownload.setText("下载");
// 下载完成后清除进度条并将map中的数据清空
LinearLayout layout = (LinearLayout) bar.getParent();
layout.removeView(bar);
ProgressBars.remove(url);
downloaders.get(url).delete(url);
downloaders.get(url).reset();
downloaders.remove(url);
new AlertDialog.Builder(BookOnlineActivity.this).setTitle("提示").setMessage("下载完成,是否将《"+bookNames[currentPosition]+"》加入书架?")
.setPositiveButton("加入", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{ | if(BookUtil.isExist( DbDataOperation.getBookInfo(resolver), SD_PATH+bookNames[currentPosition]+".txt")==true) | 0 |
keeps/roda-in | src/main/java/org/roda/rodain/core/Constants.java | [
"public class BagitSipCreator extends SimpleSipCreator implements SIPObserver, ISipCreator {\n private static final Logger LOGGER = LoggerFactory.getLogger(BagitSipCreator.class.getName());\n private int countFilesOfZip;\n private int currentSIPsize = 0;\n private int currentSIPadded = 0;\n private int repProc... | import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.roda.rodain.core.creation.BagitSipCreator;
import org.roda.rodain.core.creation.EarkSip2Creator;
import org.roda.rodain.core.creation.EarkSipCreator;
import org.roda.rodain.core.creation.HungarianSipCreator;
import org.roda.rodain.core.creation.ShallowSipCreator;
import org.roda.rodain.core.schema.IPContentType;
import org.roda.rodain.core.schema.RepresentationContentType;
import com.fasterxml.jackson.annotation.JsonCreator; | public static final String I18N_MAIN_HIDE_IGNORED = "Main.hideIgnored";
public static final String I18N_MAIN_HIDE_MAPPED = "Main.hideMapped";
public static final String I18N_MAIN_IGNORE_ITEMS = "Main.ignoreItems";
public static final String I18N_MAIN_LANGUAGE = "Main.language";
public static final String I18N_MAIN_LOADCS = "Main.loadCS";
public static final String I18N_MAIN_NEW_VERSION_HEADER = "Main.newVersion.header";
public static final String I18N_MAIN_NO_UPDATES_CONTENT = "Main.noUpdates.content";
public static final String I18N_MAIN_NO_UPDATES_HEADER = "Main.noUpdates.header";
public static final String I18N_MAIN_OPEN_CONFIGURATION_FOLDER = "Main.openConfigurationFolder";
public static final String I18N_MAIN_QUIT = "Main.quit";
public static final String I18N_MAIN_RESET = "Main.reset";
public static final String I18N_MAIN_SHOW_FILES = "Main.showFiles";
public static final String I18N_MAIN_SHOW_HELP = "Main.showHelp";
public static final String I18N_MAIN_SHOW_IGNORED = "Main.showIgnored";
public static final String I18N_MAIN_SHOW_MAPPED = "Main.showMapped";
public static final String I18N_MAIN_UPDATE_LANG_CONTENT = "Main.updateLang.content";
public static final String I18N_MAIN_UPDATE_LANG_HEADER = "Main.updateLang.header";
public static final String I18N_MAIN_UPDATE_LANG_TITLE = "Main.updateLang.title";
public static final String I18N_MAIN_USE_JAVA8 = "Main.useJava8";
public static final String I18N_MAIN_VIEW = "Main.view";
public static final String I18N_METADATA_DIFF_FOLDER_DESCRIPTION = "metadata.diffFolder.description";
public static final String I18N_METADATA_DIFF_FOLDER_TITLE = "metadata.diffFolder.title";
public static final String I18N_METADATA_EMPTY_FILE_DESCRIPTION = "metadata.emptyFile.description";
public static final String I18N_METADATA_EMPTY_FILE_TITLE = "metadata.emptyFile.title";
public static final String I18N_METADATA_SAME_FOLDER_DESCRIPTION = "metadata.sameFolder.description";
public static final String I18N_METADATA_SAME_FOLDER_TITLE = "metadata.sameFolder.title";
public static final String I18N_METADATA_SINGLE_FILE_DESCRIPTION = "metadata.singleFile.description";
public static final String I18N_METADATA_SINGLE_FILE_TITLE = "metadata.singleFile.title";
public static final String I18N_METADATA_TEMPLATE_DESCRIPTION = "metadata.template.description";
public static final String I18N_METADATA_TEMPLATE_TITLE = "metadata.template.title";
public static final String I18N_RULECELL_CREATED_ITEM = "RuleCell.createdItem";
public static final String I18N_RULEMODALPANE_ASSOCIATION_METHOD = "RuleModalPane.associationMethod";
public static final String I18N_RULEMODALPANE_CHOOSE_DIRECTORY = "RuleModalPane.chooseDirectory";
public static final String I18N_RULEMODALPANE_CHOOSE_FILE = "RuleModalPane.chooseFile";
public static final String I18N_RULEMODALPANE_METADATA_METHOD = "RuleModalPane.metadataMethod";
public static final String I18N_RULEMODALPANE_METADATA_PATTERN = "RuleModalPane.metadataPattern";
public static final String I18N_RULEMODALPROCESSING_CREATED_PREVIEWS = "RuleModalProcessing.createdPreviews";
public static final String I18N_RULEMODALPROCESSING_CREATING_PREVIEW = "RuleModalProcessing.creatingPreview";
public static final String I18N_RULEMODALPROCESSING_PROCESSED_DIRS_FILES = "RuleModalProcessing.processedDirsFiles";
public static final String I18N_RULEMODALREMOVING_REMOVED_FORMAT = "RuleModalRemoving.removedFormat";
public static final String I18N_RULEMODALREMOVING_TITLE = "RuleModalRemoving.title";
public static final String I18N_SCHEMAPANE_ADD = "SchemaPane.add";
public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_CONTENT = "SchemaPane.confirmNewScheme.content";
public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_HEADER = "SchemaPane.confirmNewScheme.header";
public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_TITLE = "SchemaPane.confirmNewScheme.title";
public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_CONTENT = "SchemaPane.confirmRemove.content";
public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_HEADER = "SchemaPane.confirmRemove.header";
public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_TITLE = "SchemaPane.confirmRemove.title";
public static final String I18N_SCHEMAPANE_CREATE = "SchemaPane.create";
public static final String I18N_SCHEMAPANE_DRAG_HELP = "SchemaPane.dragHelp";
public static final String I18N_SCHEMAPANE_HELP_TITLE = "SchemaPane.help.title";
public static final String I18N_SCHEMAPANE_NEW_NODE = "SchemaPane.newNode";
public static final String I18N_SCHEMAPANE_OR = "SchemaPane.or";
public static final String I18N_SCHEMAPANE_REMOVE = "SchemaPane.remove";
public static final String I18N_SCHEMAPANE_TITLE = "SchemaPane.title";
public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_CONTENT = "SchemaPane.tooManySelected.content";
public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_HEADER = "SchemaPane.tooManySelected.header";
public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_TITLE = "SchemaPane.tooManySelected.title";
public static final String I18N_SIMPLE_SIP_CREATOR_COPYING_DATA = "SimpleSipCreator.copyingData";
public static final String I18N_SIMPLE_SIP_CREATOR_DOCUMENTATION = "SimpleSipCreator.documentation";
public static final String I18N_SIMPLE_SIP_CREATOR_INIT_ZIP = "SimpleSipCreator.initZIP";
public static final String I18N_SIMPLE_SIP_CREATOR_CREATING_STRUCTURE = "SimpleSipCreator.creatingStructure";
public static final String I18N_SIMPLE_SIP_CREATOR_COPYING_METADATA = "SimpleSipCreator.copyingMetadata";
public static final String I18N_SIMPLE_SIP_CREATOR_FINALIZING_SIP = "SimpleSipCreator.finalizingSip";
public static final String I18N_SOURCE_TREE_CELL_REMOVE = "SourceTreeCell.remove";
public static final String I18N_SOURCE_TREE_LOADING_TITLE = "SourceTreeLoading.title";
public static final String I18N_SOURCE_TREE_LOAD_MORE_TITLE = "SourceTreeLoadMore.title";
public static final String I18N_ADD = "add";
public static final String I18N_AND = "and";
public static final String I18N_APPLY = "apply";
public static final String I18N_ASSOCIATE = "associate";
public static final String I18N_BACK = "back";
public static final String I18N_CANCEL = "cancel";
public static final String I18N_CLEAR = "clear";
public static final String I18N_CLOSE = "close";
public static final String I18N_COLLAPSE = "collapse";
public static final String I18N_CONFIRM = "confirm";
public static final String I18N_CONTINUE = "continue";
public static final String I18N_CREATIONMODALPROCESSING_REPRESENTATION = "CreationModalProcessing.representation";
public static final String I18N_DATA = "data";
public static final String I18N_DIRECTORIES = "directories";
public static final String I18N_DIRECTORY = "directory";
public static final String I18N_DOCUMENTATION = "documentation";
public static final String I18N_DONE = "done";
public static final String I18N_ERROR_VALIDATING_METADATA = "errorValidatingMetadata";
public static final String I18N_EXPAND = "expand";
public static final String I18N_EXPORT = "export";
public static final String I18N_FILE = "file";
public static final String I18N_FILES = "files";
public static final String I18N_FOLDERS = "folders";
public static final String I18N_HELP = "help";
public static final String I18N_IGNORE = "ignore";
public static final String I18N_INVALID_METADATA = "invalidMetadata";
public static final String I18N_IP_CONTENT_TYPE = "IPContentType.";
public static final String I18N_ITEMS = "items";
public static final String I18N_LOAD = "load";
public static final String I18N_LOADINGPANE_CREATE_ASSOCIATION = "LoadingPane.createAssociation";
public static final String I18N_NAME = "name";
public static final String I18N_REMOVE = "remove";
public static final String I18N_REPRESENTATION_CONTENT_TYPE = "RepresentationContentType.";
public static final String I18N_RESTART = "restart";
public static final String I18N_ROOT = "root";
public static final String I18N_SELECTED = "selected";
public static final String I18N_SIP_NAME_STRATEGY = "sipNameStrategy.";
public static final String I18N_START = "start";
public static final String I18N_TYPE = "type";
public static final String I18N_VALID_METADATA = "validMetadata";
public static final String I18N_VERSION = "version";
public static final String I18N_RENAME_REPRESENTATION = "RenameModalProcessing.renameRepresentation";
public static final String I18N_RENAME = "rename";
public static final String I18N_RENAME_REPRESENTATION_ALREADY_EXISTS = "RenameModalProcessing.renameAlreadyExists";
public static final String CONF_K_REFERENCE_TRANSFORMER_LIST = "reference.transformer.list[]";
public static final String CONF_K_REFERENCE_TRANSFORMER = "reference.transformer.";
/*
* ENUMs
*/
// sip type
public enum SipType { | EARK(EarkSipCreator.getText(), EarkSipCreator.requiresMETSHeaderInfo(), EarkSipCreator.ipSpecificContentTypes(), | 2 |
oehf/ipf-oht-atna | auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/XDSAuditor.java | [
"public abstract class IHETransactionEventTypeCodes extends CodedValueType\n{\n\t/**\n\t * Create a new IHE Event Code using a specific code and value\n\t * \n\t * @param value Coded value for IHE event code\n\t * @param meaning Display name for IHE event code\n\t */\n\tprotected IHETransactionEventTypeCodes(String... | import org.openhealthtools.ihe.atna.auditor.codes.ihe.IHETransactionEventTypeCodes;
import org.openhealthtools.ihe.atna.auditor.codes.rfc3881.RFC3881EventCodes.RFC3881EventOutcomeCodes;
import org.openhealthtools.ihe.atna.auditor.events.ihe.QueryEvent;
import org.openhealthtools.ihe.atna.auditor.models.rfc3881.CodedValueType;
import org.openhealthtools.ihe.atna.auditor.utils.EventUtils;
import java.util.List; | /*******************************************************************************
* Copyright (c) 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.openhealthtools.ihe.atna.auditor;
/**
* Abstract implementation of an IHE Cross-Enterprise Document Sharing auditor.
* Constructs audit messages that comply with ATNA Audit requirements for
* various XDS and XCA actors. See actor implementations for more details.
*
* @author <a href="mailto:mattadav@us.ibm.com">Matthew Davis</a>
*
*/
public abstract class XDSAuditor extends IHEAuditor
{
/**
* Audits a QUERY event for IHE XDS transactions, notably
* XDS Registry Query and XDS Registry Stored Query transactions.
*
* @param systemIsSource Whether the system sending the message is the source active participant
* @param transaction IHE Transaction sending the message
* @param eventOutcome The event outcome indicator
* @param auditSourceId The Audit Source Identification
* @param auditSourceEnterpriseSiteId The Audit Source Enterprise Site Identification
* @param sourceUserId The Source Active Participant User ID (varies by transaction)
* @param sourceAltUserId The Source Active Participant Alternate User ID
* @param sourceUserName The Source Active Participant UserName
* @param sourceNetworkId The Source Active Participant Network ID
* @param humanRequestor The Human Requestor Active Participant User ID
* @param humanRequestorName The Human Requestor Active Participant name
* @param registryEndpointUri The endpoint of the registry actor in this transaction (sets destination active participant user id and network id)
* @param registryAltUserId The registry alternate user id (for registry actors)
* @param storedQueryUUID The UUID for the stored query (if transaction is Registry Stored Query)
* @param adhocQueryRequestPayload The payload of the adhoc query request element
* @param homeCommunityId The home community id of the transaction (if present)
* @param patientId The patient ID queried (if query pertained to a patient id)
* @param purposesOfUse purpose of use codes (may be taken from XUA token)
* @param userRoles roles of the human user (may be taken from XUA token)
*/
protected void auditQueryEvent(
boolean systemIsSource, // System Type | IHETransactionEventTypeCodes transaction, RFC3881EventOutcomeCodes eventOutcome, // Event | 1 |
HackMyChurch/aelf-dailyreadings | app/src/main/java/co/epitre/aelf_lectures/LecturesActivity.java | [
"public class SectionBibleFragment extends SectionFragmentBase {\n public static final String TAG = \"SectionBibleFragment\";\n\n public SectionBibleFragment(){\n // Required empty public constructor\n }\n\n /**\n * Global managers / resources\n */\n private boolean initialized = false... | import android.accounts.Account;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import androidx.annotation.NonNull;
import com.google.android.material.navigation.NavigationView;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.widget.FrameLayout;
import java.io.File;
import co.epitre.aelf_lectures.bible.SectionBibleFragment;
import co.epitre.aelf_lectures.components.MessageDialogFragment;
import co.epitre.aelf_lectures.lectures.SectionLecturesFragment;
import co.epitre.aelf_lectures.lectures.data.AelfDate;
import co.epitre.aelf_lectures.lectures.data.LecturesController.WHAT;
import co.epitre.aelf_lectures.settings.SettingsActivity;
import co.epitre.aelf_lectures.sync.SyncAdapter; | } else {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
toolbar.setPadding(0, 0, 0, 0);
}
// Apply settings
View decorView = window.getDecorView();
decorView.setSystemUiVisibility(uiOptions);
}
private void enterFullscreen() {
isFullScreen = true;
prepare_fullscreen();
}
private void exitFullscreen() {
isFullScreen = false;
prepare_fullscreen();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
// manage application's intrusiveness for different Android versions
super.onWindowFocusChanged(hasFocus);
// If we are gaining the focus, go fullscreen
if (hasFocus) {
isFullScreen = true;
prepare_fullscreen();
}
}
@Override
public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
// Force fullscreen to false and refresh screen
super.onMultiWindowModeChanged(isInMultiWindowMode);
isMultiWindow = isInMultiWindowMode;
prepare_fullscreen();
}
public boolean onAbout() {
MessageDialogFragment aboutDialog = new MessageDialogFragment(
getString(R.string.dialog_about_title),
getString(R.string.dialog_about_content)
);
aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
return true;
}
public boolean onWhatsNew() {
MessageDialogFragment aboutDialog = new MessageDialogFragment(
getString(R.string.dialog_whats_new_title),
getString(R.string.dialog_whats_new_content)
);
aboutDialog.show(getSupportFragmentManager(), "whatsNewDialog");
return true;
}
public boolean onSyncPref() {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
public boolean onSyncDo() {
SyncAdapter.triggerSync(this);
return true;
}
public boolean onToggleNightMode() {
// Toggle the value
nightMode = !nightMode;
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(SettingsActivity.KEY_PREF_DISP_NIGHT_MODE, nightMode);
editor.apply();
return true;
}
public boolean onApplyOptimalSyncSettings() {
SharedPreferences.Editor editor = settings.edit();
// Reset sync settings
editor.putString(SettingsActivity.KEY_PREF_SYNC_DUREE, "mois");
editor.putString(SettingsActivity.KEY_PREF_SYNC_LECTURES, "messe-offices");
editor.putBoolean(SettingsActivity.KEY_PREF_SYNC_WIFI_ONLY, false);
// Reset test settings
editor.putString(SettingsActivity.KEY_PREF_PARTICIPATE_SERVER, "");
editor.putBoolean(SettingsActivity.KEY_PREF_PARTICIPATE_BETA, false);
editor.putBoolean(SettingsActivity.KEY_PREF_PARTICIPATE_NOCACHE, false);
// Make sure sync is enabled on device
SyncAdapter.configureSync(this);
editor.apply();
onRefresh("applied-settings");
return true;
}
public boolean onRefresh(String reason) {
return getCurrentSectionFragment().onRefresh(reason);
}
@Override
/** Drawer menu callback */
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Schedule drawer close (this is async)
drawerLayout.closeDrawers();
// Fast path: if was already checked, do nothing more
if (item.isChecked()) {
return true;
}
// Mark item as checked / active
item.setChecked(true);
// Route menu item | WHAT what = WHAT.fromMenuId(item.getItemId()); | 4 |
PROSRESEARCHCENTER/junitcontest | src/benchmarktool/src/main/java/sbst/benchmark/TestSuite.java | [
"public class JaCoCoLauncher {\n\n\tprivate String temp_folder;\n\tprivate String targetClass;\n\tprivate List<String> testCases;\n\tprivate String testFolder;\n\n\tprivate LinkedList<String> required_libraries; // it has to contain the CP required to run the tests\n\n\tprivate List<File> jar_to_instrument;\n\tpriv... | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.tools.ant.DirectoryScanner;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import sbst.benchmark.coverage.JaCoCoLauncher;
import sbst.benchmark.coverage.JacocoResult;
import sbst.benchmark.coverage.TestExecutionTask;
import sbst.benchmark.pitest.MutationAnalysis;
import sbst.benchmark.pitest.MutationsEvaluator;
import sbst.benchmark.pitest.PITWrapper;
import sbst.benchmark.pitest.TestInfo; | }
private void cmdExec(String cmdLine, OutputStream outStr) throws Throwable {
PumpStreamHandler psh = new PumpStreamHandler(outStr);
CommandLine cl = CommandLine.parse(cmdLine);
DefaultExecutor exec = new DefaultExecutor();
exec.setStreamHandler(psh);
exec.execute(cl);
}
private void d4jTestArchiving(final File testCaseDir, final String archiveFileName) {
String commandLine = "tar -cjf " + archiveFileName + " -C " + testCaseDir.getAbsolutePath() + " .";
Main.debug("\n===\nDefects4J test cases archiving command line:\n\n" + commandLine + "\n\n");
try {
cmdExec(commandLine, Main.debugStr);
} catch (Throwable t) {
Main.info("Could not archive test cases!");
t.printStackTrace(Main.debugStr);
}
}
// metrics gathered through Jacoco:
// - coverage metrics
private void jacoco(String cut) {
Main.info("\n=== Run Jacoco for Coverage ===");
try {
//System.out.println("HERE >>>> "+ testCaseDir);
//System.out.println("HERE >>>> "+ testCaseDir.getParent());
//System.out.println("HERE >>>> "+ getTestCaseBinDir(testCaseDir));
//System.out.println("HERE >>>> "+ getTask().getClassPath());
//System.out.println("HERE >>>> "+ getExtraCP());
//System.out.println("HERE >>>> "+Main.JUNIT_DEP_JAR+" : "+Main.JUNIT_JAR);
JaCoCoLauncher launcher = new JaCoCoLauncher(this.getTestCaseBinDir(testCaseDir).getParent());
launcher.setTestFolder(getTestCaseBinDir(testCaseDir).getAbsolutePath());
List<String> testClasses = getCompiledTestClassNames();
launcher.setTestCase(testClasses);
launcher.setJarInstrument(getTask().getClassPath());
String cp = new Util.CPBuilder().and(Main.JUNIT_DEP_JAR).and(Main.JUNIT_JAR).and(getExtraCP()).build();
cp = cp.replaceAll("::", ":");
launcher.setClassPath(cp);
launcher.setTargetClass(cut);
launcher.runJaCoCo();
JacocoResult result = launcher.getResults();
result.printResults();
// Count number of failing tests (HOW MUCH REAL FAULTS ARE DETECTED?)
d4jFailTests = 0;
// coverage metrics
if (result != null) {
this.d4jLinesTotal = result.getLinesTotal();
this.d4jLinesCovered = result.getLinesCovered();
this.d4jConditionsTotal = result.getBranchesTotal();
this.d4jConditionsCovered = result.getBranchesCovered();
}
// keep track of the uncovered lines for mutation analysis
this.jacoco_result = result;
} catch (Throwable t) {
Main.info("Could not calculate coverage metrics!");
t.printStackTrace(Main.debugStr);
}
}
// metrics gathered through PIT:
// - mutation coverage
private void mutationAnalysis(String cut){
Main.info("\n=== Run PIT ===");
try {
Main.debug("Generate mutations via PIT");
String cp = new Util.CPBuilder().and(Main.JUNIT_JAR).and(Main.JUNIT_DEP_JAR).and(getTask().getClassPath())
.and(getExtraCP()).and(getTestCaseBinDir(testCaseDir).getAbsolutePath()).build();
List<String> testClasses = getTestSrcFiles(testCaseDir);
List<String> fixedTestClasses = new ArrayList<String>();
for (int index = 0; index < testClasses.size(); index++){
if (!testClasses.get(index).contains(DUMMY_JUNIT_CLASS)){
String element = testClasses.get(index);
element = element.replace("/", ".");
if (element.startsWith("testcases."))
element = element.replace("testcases.","");
element = element.substring(0, element.length()-5);//replace(".java","");
fixedTestClasses.add(element);
}
}
Main.debug(" Running tests against generated Mutants");
Main.debug("Running PITWrapper with the following data:");
Main.debug("> CP = "+cp);
Main.debug("> CUT = "+cut);
Main.debug("> Test cases = "+fixedTestClasses);
PITWrapper wrapper = new PITWrapper(cp, cut, fixedTestClasses);
// prepare the mutant evaluator
MutationsEvaluator evaluator = new MutationsEvaluator(cp, cut, fixedTestClasses, this.flakyTests);
// compute mutation coverage
evaluator.computeCoveredMutants(wrapper.getGeneratedMutants(), jacoco_result);
Main.debug("Run tests against the covered mutations (i.e., mutants infecting on covered lines according to Jacoco)");
String mutated = this.getTestCaseBinDir(testCaseDir).getParent()+"/mutated_code"; // temporary folder where to save the mutated SUT
// compute killed mutations
evaluator.runMutations(mutated, new Util.CPBuilder().and(getTask().getClassPath()).build());
// if timeout is reached, we create a file TIMEOUT.txt
if (evaluator.isTimeoutReached()){
File time_out = new File(this.getTestCaseDir().getAbsolutePath() + File.separator + "TIMEOUT.txt");
time_out.createNewFile();
}
// mutation analysis results | MutationAnalysis cov = evaluator.getMutationCoverage(); | 3 |
ZonCon/Ecommerce-Retronight-Android | app/src/main/java/com/megotechnologies/ecommerce_retronight/policy/FragmentPolicyItemDetails.java | [
"public class FragmentMeta extends Fragment{\n\n\tprotected View v;\n\tprotected MainActivity activity;\n\tprotected DbConnection dbC;\n\tprotected Boolean LOCATION_SELECTED = false;\n\tprotected Boolean IS_SIGNEDIN = false;\n\tprotected Boolean IS_CLICKED = false;\n\n\t@Override\n\tpublic void onCreate(Bundle save... | import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Contacts.Intents;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils.TruncateAt;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.megotechnologies.ecommerce_retronight.FragmentMeta;
import com.megotechnologies.ecommerce_retronight.MainActivity;
import com.megotechnologies.ecommerce_retronight.R;
import com.megotechnologies.ecommerce_retronight.interfaces.ZCFragmentLifecycle;
import com.megotechnologies.ecommerce_retronight.interfaces.ZCRunnable;
import com.megotechnologies.ecommerce_retronight.ZoomImageActivity;
import com.megotechnologies.ecommerce_retronight.utilities.ImageProcessingFunctions;
import com.megotechnologies.ecommerce_retronight.utilities.MLog;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap; | String _idItem = map.get(MainActivity.DB_COL_ID);
final String title = map.get(MainActivity.DB_COL_TITLE);
final String subtitle = map.get(MainActivity.DB_COL_SUB);
String content = map.get(MainActivity.DB_COL_CONTENT);
Long ts = Long.parseLong(map.get(MainActivity.DB_COL_TIMESTAMP));
//Date tsDate = new Date(ts);
//String timestamp = new SimpleDateFormat("dd/MM/yyyy hh:mma").format(tsDate);
// Get handles for pictures, urls, locations, contacts & attachments
map = new HashMap<String, String>();
map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_PICTURE);
map.put(MainActivity.DB_COL_FOREIGN_KEY, _idItem);
ArrayList<HashMap<String, String>> recordsPictures = null;
if (dbC.isOpen()) {
dbC.isAvailale();
recordsPictures = dbC.retrieveRecords(map);
}
map = new HashMap<String, String>();
map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_URL);
map.put(MainActivity.DB_COL_FOREIGN_KEY, _idItem);
ArrayList<HashMap<String, String>> recordsUrls = null;
if (dbC.isOpen()) {
dbC.isAvailale();
recordsUrls = dbC.retrieveRecords(map);
}
map = new HashMap<String, String>();
map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_ATTACHMENT);
map.put(MainActivity.DB_COL_FOREIGN_KEY, _idItem);
ArrayList<HashMap<String, String>> recordsAttachments = null;
if (dbC.isOpen()) {
dbC.isAvailale();
recordsAttachments = dbC.retrieveRecords(map);
}
map = new HashMap<String, String>();
map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_LOCATION);
map.put(MainActivity.DB_COL_FOREIGN_KEY, _idItem);
ArrayList<HashMap<String, String>> recordsLocations = null;
if (dbC.isOpen()) {
dbC.isAvailale();
recordsLocations = dbC.retrieveRecords(map);
}
map = new HashMap<String, String>();
map.put(MainActivity.DB_COL_TYPE, MainActivity.DB_RECORD_TYPE_CONTACT);
map.put(MainActivity.DB_COL_FOREIGN_KEY, _idItem);
ArrayList<HashMap<String, String>> recordsContacts = null;
if (dbC.isOpen()) {
dbC.isAvailale();
recordsContacts = dbC.retrieveRecords(map);
}
int imgHeight = ((MainActivity.SCREEN_WIDTH * 3) / 4);
int imgMargin = (MainActivity.SCREEN_WIDTH / 16);
int imgWidth = (activity.SCREEN_WIDTH - imgMargin * 2);
int headHeight = (int) ((activity.SCREEN_HEIGHT / 10));
TextView tvHead = new TextView(activity.context);
tvHead.setText(title);
RelativeLayout.LayoutParams paramsLLHead = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
tvHead.setLayoutParams(paramsLLHead);
tvHead.setTextColor(getResources().getColor(R.color.text_color));
tvHead.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (MainActivity.TEXT_SIZE_TITLE * 1.2));
tvHead.setPadding(imgMargin, imgMargin + headHeight / 10, imgMargin, 0);
tvHead.setEllipsize(TruncateAt.END);
tvHead.setGravity(Gravity.CENTER);
llContainer.addView(tvHead);
ImageView ivProduct = new ImageView(activity.context);
LinearLayout lProductC = new LinearLayout(activity.context);
LayoutParams paramsProductC = new LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
paramsProductC.setMargins(0, imgMargin, 0, 0);
lProductC.setLayoutParams(paramsProductC);
lProductC.setOrientation(LinearLayout.VERTICAL);
llContainer.addView(lProductC);
RelativeLayout rBorderC = new RelativeLayout(activity.context);
LayoutParams paramsBorderC = new LayoutParams(imgWidth, imgHeight);
paramsBorderC.setMargins(imgMargin, 0, imgMargin, 0);
rBorderC.setLayoutParams(paramsBorderC);
rBorderC.setBackgroundColor(getResources().getColor(R.color.white));
lProductC.addView(rBorderC);
RelativeLayout.LayoutParams paramsIvProduct = null;
paramsIvProduct = new RelativeLayout.LayoutParams(imgWidth - 2, imgHeight - 2);
paramsIvProduct.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
paramsIvProduct.setMargins(1, 1, 1, 1);
ivProduct.setLayoutParams(paramsIvProduct);
ivProduct.setId(IV_ID_PREFIX + i);
ivProduct.setScaleType(ScaleType.CENTER_CROP);
ivProduct.setImageDrawable(getResources().getDrawable(R.drawable.cover));
try {
ivProduct.setCropToPadding(true);
} catch (NoSuchMethodError e) {
}
rBorderC.addView(ivProduct);
TextView tvDesc = new TextView(activity.context);
tvDesc.setTextColor(getResources().getColor(R.color.text_color));
tvDesc.setTextSize(TypedValue.COMPLEX_UNIT_SP, (int) (MainActivity.TEXT_SIZE_TILE));
tvDesc.setText(subtitle);
tvDesc.setPadding(imgMargin, imgMargin, imgMargin, 0);
tvDesc.setLineSpacing(0.0f, 1.2f);
llContainer.addView(tvDesc);
String picture = "";
if (recordsPictures.size() > 0) {
map = recordsPictures.get(0);
picture = map.get(MainActivity.DB_COL_PATH_ORIG);
if (picture.length() > 0) {
| MLog.log("Picture = " + picture); | 7 |
difi/datahotel | src/main/java/no/difi/datahotel/logic/FieldBean.java | [
"public class Disk {\r\n\tpublic static Object read(Class<?> cls, File path) {\r\n\t\ttry {\r\n\t\t\tJAXBContext jc = JAXBContext.newInstance(cls);\r\n\t\t\tUnmarshaller u = jc.createUnmarshaller();\r\n\t\t\treturn u.unmarshal(new StreamSource(path), cls).getValue();\r\n\t\t} catch (JAXBException e) {\r\n\t\t\tLogg... | import no.difi.datahotel.model.*;
import no.difi.datahotel.util.Disk;
import no.difi.datahotel.util.Filesystem;
import no.difi.datahotel.util.MetadataLogger;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static no.difi.datahotel.util.Filesystem.FILE_DEFINITIONS;
import static no.difi.datahotel.util.Filesystem.FOLDER_SLAVE; | package no.difi.datahotel.logic;
@Component("field")
public class FieldBean {
private Map<String, List<Field>> fields = new HashMap<String, List<Field>>();
private Map<String, Definition> definitions = new HashMap<String, Definition>();
/**
* Holds the timestamp of the definitions file last read.
*/
private long defUpdated;
/**
* Updated definitions if an updated definitions file is available.
*/
public void updateDefinitions() { | File f = Filesystem.getFile(FOLDER_SLAVE, FILE_DEFINITIONS); | 1 |
hpdcj/PCJ | src/main/java/org/pcj/internal/message/splitgroup/SplitGroupStates.java | [
"public interface Group {\n\n /**\n * Gets identifier of current PCJ Thread in the group.\n * <p>\n * Identifiers are consecutive numbers that start with 0.\n *\n * @return current PCJ Thread identifier\n */\n int myId();\n\n /**\n * Gets total number of PCJ Thread in the group.... | import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.pcj.Group;
import org.pcj.PcjFuture;
import org.pcj.internal.InternalCommonGroup;
import org.pcj.internal.InternalGroup;
import org.pcj.internal.InternalPCJ;
import org.pcj.internal.NodeData;
import org.pcj.internal.PcjThread;
import org.pcj.internal.message.Message; | /*
* Copyright (c) 2011-2021, PCJ Library, Marek Nowicki
* All rights reserved.
*
* Licensed under New BSD License (3-clause license).
*
* See the file "LICENSE" for the full license governing this code.
*/
package org.pcj.internal.message.splitgroup;
/*
* @author Marek Nowicki (faramir@mat.umk.pl)
*/
public class SplitGroupStates {
private final ConcurrentMap<Integer, AtomicInteger> counterMap;
private final ConcurrentMap<Integer, State> stateMap;
public SplitGroupStates() {
counterMap = new ConcurrentHashMap<>();
stateMap = new ConcurrentHashMap<>();
}
public int getNextRound(int threadId) {
AtomicInteger roundCounter = counterMap.computeIfAbsent(threadId, key -> new AtomicInteger(0));
return roundCounter.incrementAndGet();
}
| public State getOrCreate(int round, InternalCommonGroup commonGroup) { | 1 |
idega/com.idega.block.category | src/java/com/idega/block/category/business/CategoryServiceBean.java | [
"public interface Category extends com.idega.core.data.ICTreeNode\n{\n\t/**\n\t * Gets the iD of the Category object\n\t *\n\t * @return The ID value\n\t */\n\tpublic int getID();\n\t/**\n\t * Gets the name of the Category object\n\t *\n\t * @return The name value\n\t */\n\tpublic String getName();\n\t/**\n... | import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import com.idega.block.category.data.Category;
import com.idega.block.category.data.ICCategory;
import com.idega.block.category.data.ICCategoryHome;
import com.idega.block.category.data.ICCategoryTranslation;
import com.idega.block.category.data.ICCategoryTranslationHome;
import com.idega.business.IBOServiceBean;
import com.idega.core.component.business.ICObjectBusiness;
import com.idega.core.component.data.ICObjectInstance;
import com.idega.core.component.data.ICObjectInstanceHome;
import com.idega.data.GenericEntity;
import com.idega.data.IDOLookup;
import com.idega.util.IWTimestamp; | package com.idega.block.category.business;
public class CategoryServiceBean extends IBOServiceBean implements CategoryService {
public boolean disconnectBlock(int instanceid) throws RemoteException {
Collection L =null;
try{
L = getCategoryHome().findAllByObjectInstance(instanceid);
}
catch(FinderException ex)
{throw new RemoteException(ex.getMessage());}
if (L != null && !L.isEmpty()) {
Iterator I = L.iterator();
while (I.hasNext()) { | ICCategory Cat = (ICCategory) I.next(); | 1 |
ddf/Minim | src/main/java/ddf/minim/javasound/JSAudioOutput.java | [
"public interface AudioListener\n{\n /**\n * Called by the audio object this AudioListener is attached to \n * when that object has new samples.\n * \n * @example Advanced/AddAndRemoveAudioListener\n * \n * @param samp \n * \ta float[] buffer of samples from a MONO sound stream\n * \n * @related ... | import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.Control;
import javax.sound.sampled.SourceDataLine;
import ddf.minim.AudioEffect;
import ddf.minim.AudioListener;
import ddf.minim.AudioSignal;
import ddf.minim.Minim;
import ddf.minim.MultiChannelBuffer;
import ddf.minim.spi.AudioOut;
import ddf.minim.spi.AudioStream; | /*
* Copyright (c) 2007 by Damien Di Fede <ddf@compartmental.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package ddf.minim.javasound;
@SuppressWarnings("deprecation")
final class JSAudioOutput extends Thread implements AudioOut
{
private AudioListener listener;
private AudioStream stream;
private AudioSignal signal;
private AudioEffect effect;
private SourceDataLine line;
private AudioFormat format;
private FloatSampleBuffer buffer;
private MultiChannelBuffer mcBuffer;
private int bufferSize;
private boolean finished;
private byte[] outBytes;
JSAudioOutput(SourceDataLine sdl, int bufferSize)
{
super();
this.bufferSize = bufferSize;
format = sdl.getFormat();
buffer = new FloatSampleBuffer(format.getChannels(), bufferSize, format.getSampleRate());
mcBuffer = new MultiChannelBuffer(bufferSize, format.getChannels());
outBytes = new byte[buffer.getByteArrayBufferSize(format)];
finished = false;
line = sdl;
}
public void run()
{
line.start();
while (!finished)
{
buffer.makeSilence();
if ( signal != null )
{
readSignal();
}
else if ( stream != null )
{
readStream();
} | if (line.getFormat().getChannels() == Minim.MONO) | 1 |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/core/provider/ClassSearchProvider.java | [
"public class BundleScanner {\n\n\tprivate final Bundle bundle;\n\n\tpublic BundleScanner(Bundle bundle) {\n\t\tthis.bundle = bundle;\n\t}\n\n\tpublic List<String> findClassNames() {\n\t\treturn findClassNames(null);\n\t}\n\n\tpublic List<String> findClassNames(String phrase) {\n\t\tList<String> classNames = Lists.... | import com.neva.felix.webconsole.plugins.search.core.BundleScanner;
import com.neva.felix.webconsole.plugins.search.core.SearchParams;
import com.neva.felix.webconsole.plugins.search.core.SearchResult;
import com.neva.felix.webconsole.plugins.search.rest.BundleDownloadServlet;
import com.neva.felix.webconsole.plugins.search.rest.ClassDecompileServlet;
import com.neva.felix.webconsole.plugins.search.utils.BundleUtils;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.neva.felix.webconsole.plugins.search.core.SearchUtils.composeDescription; | package com.neva.felix.webconsole.plugins.search.core.provider;
public class ClassSearchProvider extends AbstractSearchProvider {
public static final String LABEL = "Class";
private static final int RESULT_RANK = 500;
private static final Logger LOG = LoggerFactory.getLogger(ClassSearchProvider.class);
public ClassSearchProvider(BundleContext bundleContext) {
super(bundleContext);
}
@Override
@SuppressWarnings("unchecked") | public List<SearchResult> search(SearchParams params) { | 2 |
otale/tale | src/main/java/com/tale/controller/InstallController.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.Environment;
import com.blade.ioc.annotation.Inject;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.JSON;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.PostRoute;
import com.blade.mvc.http.Request;
import com.blade.mvc.ui.RestResponse;
import com.tale.bootstrap.TaleConst;
import com.tale.model.entity.Users;
import com.tale.model.params.InstallParam;
import com.tale.service.OptionsService;
import com.tale.service.SiteService;
import com.tale.utils.TaleUtils;
import com.tale.validators.CommonValidator;
import lombok.extern.slf4j.Slf4j;
import java.nio.file.Files;
import java.nio.file.Paths;
import static com.tale.bootstrap.TaleConst.CLASSPATH;
import static com.tale.bootstrap.TaleConst.OPTION_ALLOW_INSTALL; | package com.tale.controller;
@Slf4j
@Path("install")
public class InstallController extends BaseController {
@Inject
private SiteService siteService;
@Inject
private OptionsService optionsService;
/**
* 安装页
*/
@GetRoute
public String index(Request request) {
boolean existInstall = Files.exists(Paths.get(CLASSPATH + "install.lock"));
boolean allowReinstall = TaleConst.OPTIONS.getBoolean(OPTION_ALLOW_INSTALL, false);
request.attribute("is_install", !allowReinstall && existInstall);
return "install";
}
@PostRoute
@JSON | public RestResponse<?> doInstall(InstallParam installParam) { | 2 |
pktczwd/tcc-transaction | tcc-transaction-tutorial-sample/tcc-transaction-sample/tcc-transaction-order/src/main/java/org/pankai/tcctransaction/sample/order/service/PlaceOrderService.java | [
"public class CancellingException extends RuntimeException {\n public CancellingException(Throwable cause) {\n super(cause);\n }\n}",
"public class ConfirmingException extends RuntimeException {\n\n public ConfirmingException(Throwable cause) {\n super(cause);\n }\n}",
"public class Or... | import org.apache.commons.lang3.tuple.Pair;
import org.pankai.tcctransaction.CancellingException;
import org.pankai.tcctransaction.ConfirmingException;
import org.pankai.tcctransaction.sample.order.domain.entity.Order;
import org.pankai.tcctransaction.sample.order.domain.entity.Shop;
import org.pankai.tcctransaction.sample.order.domain.repository.ShopRepository;
import org.pankai.tcctransaction.sample.order.domain.service.OrderService;
import org.pankai.tcctransaction.sample.order.domain.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List; | package org.pankai.tcctransaction.sample.order.service;
/**
* Created by pktczwd on 2016/12/19.
*/
@Service
public class PlaceOrderService {
@Autowired
private ShopRepository shopRepository;
@Autowired
private PaymentService paymentService;
@Autowired
private OrderService orderService;
public String placeOrder(long payerUserId, long shopId, List<Pair<Long, Integer>> productQuantities, BigDecimal redPacketPayAmount) {
Shop shop = shopRepository.findById(shopId);
Order order = orderService.createOrder(payerUserId, shop.getOwnerUserId(), productQuantities);
try {
paymentService.makePayment(order, redPacketPayAmount, order.getTotalAmount().subtract(redPacketPayAmount));
} catch (ConfirmingException e) {
//exception throws with the tcc transaction status is CONFIRMING,
//when tcc transaction is confirming status,
// the tcc transaction recovery will try to confirm the whole transaction to ensure eventually consistent. | } catch (CancellingException e) { | 0 |
OpenSensing/funf-v4 | funf_v4/src/main/java/edu/mit/media/funf/pipeline/BasicPipeline.java | [
"public class FunfManager extends Service {\n\t\n\tpublic static final String \n\tACTION_KEEP_ALIVE = \"funf.keepalive\",\n\tACTION_INTERNAL = \"funf.internal\";\n\t\n\tprivate static final String \n\tPROBE_TYPE = \"funf/probe\",\n\tPIPELINE_TYPE = \"funf/pipeline\";\n\t\n\tprivate static final String \n\tDISABLED_... | import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import edu.mit.media.funf.FunfManager;
import edu.mit.media.funf.Schedule;
import edu.mit.media.funf.config.ConfigUpdater;
import edu.mit.media.funf.config.Configurable;
import edu.mit.media.funf.config.RuntimeTypeAdapterFactory;
import edu.mit.media.funf.json.IJsonObject;
import edu.mit.media.funf.probe.Probe.DataListener;
import edu.mit.media.funf.probe.builtin.ProbeKeys;
import edu.mit.media.funf.storage.DefaultArchive;
import edu.mit.media.funf.storage.FileArchive;
import edu.mit.media.funf.storage.NameValueDatabaseHelper;
import edu.mit.media.funf.storage.RemoteFileArchive;
import edu.mit.media.funf.storage.UploadService;
import edu.mit.media.funf.util.LogUtil;
import edu.mit.media.funf.util.StringUtil; | /**
*
* Funf: Open Sensing Framework Copyright (C) 2013 Alan Gardner
*
* This file is part of Funf.
*
* Funf 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.
*
* Funf 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 Funf. If not,
* see <http://www.gnu.org/licenses/>.
*
*/
package edu.mit.media.funf.pipeline;
public class BasicPipeline implements Pipeline, DataListener {
public static final String
ACTION_ARCHIVE = "archive",
ACTION_UPLOAD = "upload",
ACTION_UPDATE = "update";
protected final int ARCHIVE = 0, UPLOAD = 1, UPDATE = 2, DATA = 3;
@Configurable
protected String name = "default";
@Configurable
protected int version = 1;
@Configurable
protected FileArchive archive = null;
@Configurable
protected RemoteFileArchive upload = null;
@Configurable
protected ConfigUpdater update = null;
@Configurable
protected List<JsonElement> data = new ArrayList<JsonElement>();
@Configurable
protected Map<String, Schedule> schedules = new HashMap<String, Schedule>();
private UploadService uploader;
private boolean enabled;
private FunfManager manager;
private SQLiteOpenHelper databaseHelper = null;
private Looper looper;
private Handler handler;
private Handler.Callback callback = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
onBeforeRun(msg.what, (JsonObject)msg.obj);
switch (msg.what) {
case ARCHIVE:
if (archive != null) {
runArchive();
}
break;
case UPLOAD:
if (archive != null && upload != null && uploader != null) {
uploader.run(archive, upload);
}
break;
case UPDATE:
if (update != null) {
update.run(name, manager);
}
break;
case DATA:
String name = ((JsonObject)msg.obj).get("name").getAsString();
IJsonObject data = (IJsonObject)((JsonObject)msg.obj).get("value");
writeData(name, data);
break;
default:
break;
}
onAfterRun(msg.what, (JsonObject)msg.obj);
return false;
}
};
protected void reloadDbHelper(Context ctx) { | this.databaseHelper = new NameValueDatabaseHelper(ctx, StringUtil.simpleFilesafe(name), version); | 6 |
davidmoten/rxjava2-jdbc | rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/Database.java | [
"public final class FlowableSingleDeferUntilRequest<T> extends Flowable<T> {\n\n private final Single<T> single;\n\n public FlowableSingleDeferUntilRequest(Single<T> single) {\n this.single = single;\n }\n\n @Override\n protected void subscribeActual(Subscriber<? super T> s) {\n SingleS... | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.sql.DataSource;
import org.davidmoten.rx.internal.FlowableSingleDeferUntilRequest;
import org.davidmoten.rx.jdbc.exceptions.SQLRuntimeException;
import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool;
import org.davidmoten.rx.jdbc.pool.Pools;
import org.davidmoten.rx.jdbc.pool.internal.ConnectionProviderBlockingPool;
import org.davidmoten.rx.pool.Member;
import org.davidmoten.rx.pool.Pool;
import com.github.davidmoten.guavamini.Preconditions;
import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.reactivex.Single;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function; | package org.davidmoten.rx.jdbc;
public final class Database implements AutoCloseable {
private final Pool<Connection> pool;
private final Single<Connection> connection;
private final Action onClose;
private Database(@Nonnull Pool<Connection> pool, @Nonnull Action onClose) {
this.pool = pool;
this.connection = pool.member().map(x -> {
if (x.value() == null) {
throw new NullPointerException("connection is null!");
}
return x.value();
});
this.onClose = onClose;
}
public static NonBlockingConnectionPool.Builder<Database> nonBlocking() {
return new NonBlockingConnectionPool.Builder<Database>(pool -> Database.from(pool, () -> pool.close()));
}
public static Database from(@Nonnull String url, int maxPoolSize) {
Preconditions.checkNotNull(url, "url cannot be null");
Preconditions.checkArgument(maxPoolSize > 0, "maxPoolSize must be greater than 0");
NonBlockingConnectionPool pool = Pools.nonBlocking() //
.url(url) //
.maxPoolSize(maxPoolSize) //
.build();
return Database.from( //
pool, //
() -> {
pool.close();
});
}
public static Database from(@Nonnull Pool<Connection> pool) {
Preconditions.checkNotNull(pool, "pool canot be null");
return new Database(pool, () -> pool.close());
}
public static Database from(@Nonnull Pool<Connection> pool, Action closeAction) {
Preconditions.checkNotNull(pool, "pool canot be null");
return new Database(pool, closeAction);
}
public static Database fromBlocking(@Nonnull ConnectionProvider cp) {
return Database.from(new ConnectionProviderBlockingPool(cp));
}
public static Database fromBlocking(@Nonnull DataSource dataSource) {
return fromBlocking(Util.connectionProvider(dataSource));
}
public static Database test(int maxPoolSize) {
Preconditions.checkArgument(maxPoolSize > 0, "maxPoolSize must be greater than 0");
return Database.from( //
Pools.nonBlocking() //
.connectionProvider(testConnectionProvider()) //
.maxPoolSize(maxPoolSize) //
.build());
}
static ConnectionProvider testConnectionProvider() {
return testConnectionProvider(nextUrl());
}
/**
* Returns a new testing Apache Derby in-memory database with a connection pool
* of size 3.
*
* @return new testing Database instance
*/
public static Database test() {
return test(3);
}
private static void createTestDatabase(@Nonnull Connection c) {
try {
Sql //
.statements(Database.class.getResourceAsStream("/database-test.sql")) //
.stream() //
.forEach(x -> {
try (PreparedStatement s = c.prepareStatement(x)) {
s.execute();
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
});
c.commit();
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
private static ConnectionProvider testConnectionProvider(@Nonnull String url) {
return new ConnectionProvider() {
private final AtomicBoolean once = new AtomicBoolean();
private final CountDownLatch latch = new CountDownLatch(1);
@Override
public Connection get() {
try {
Connection c = DriverManager.getConnection(url);
if (once.compareAndSet(false, true)) {
createTestDatabase(c);
latch.countDown();
} else {
if (!latch.await(1, TimeUnit.MINUTES)) {
throw new SQLRuntimeException("waited 1 minute but test database was not created");
}
}
return c;
} catch (SQLException e) {
throw new SQLRuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
public void close() {
//
}
};
}
private static final AtomicInteger testDbNumber = new AtomicInteger();
private static String nextUrl() {
return "jdbc:derby:memory:derby" + testDbNumber.incrementAndGet() + ";create=true";
}
public Single<Connection> connection() {
return connection;
}
/**
* <p>
* Returns a flowable stream of checked out Connections from the pool. It's
* preferrable to use the {@code connection()} method and subscribe to a
* MemberSingle instead because the sometimes surprising request patterns of
* Flowable operators may mean that more Connections are checked out from the
* pool than are needed. For instance if you use
*
* <pre>
* Flowable<Connection> cons = Database.connection().repeat()
* </pre>
* <p>
* then you will checkout more (1 more) Connection with {@code repeat} than you
* requested because {@code repeat} subscribes one more time than dictated by
* the requests (buffers).
*
* @return stream of checked out connections from the pool. When you call
* {@code close()} on a connection it is returned to the pool
*/
public Flowable<Connection> connections() { | return new FlowableSingleDeferUntilRequest<Connection>(connection).repeat(); | 0 |
notem/Saber-Bot | src/main/java/ws/nmathe/saber/commands/general/SyncCommand.java | [
"public class Main\n{\n private static ShardManager shardManager;\n private static BotSettingsManager botSettingsManager = new BotSettingsManager();\n private static EntryManager entryManager = new EntryManager();\n private static ScheduleManager scheduleManager = new Sched... | import com.google.api.client.auth.oauth2.Credential;
import com.google.api.services.calendar.Calendar;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import ws.nmathe.saber.Main;
import ws.nmathe.saber.commands.Command;
import ws.nmathe.saber.commands.CommandInfo;
import ws.nmathe.saber.core.google.GoogleAuth;
import ws.nmathe.saber.utils.MessageUtilities;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Updates.set; | package ws.nmathe.saber.commands.general;
/**
* Sets a channel to sync to a google calendar address
*/
public class SyncCommand implements Command
{
@Override
public String name()
{
return "sync";
}
@Override
public CommandInfo info(String prefix)
{
String head = prefix + this.name();
String usage = "``" + head + "`` - sync a schedule to a google calendar";
CommandInfo info = new CommandInfo(usage, CommandInfo.CommandType.GOOGLE);
String cat1 = "- Usage\n" + head + " <channel> [import|export] [<calendar address>]";
String cont1 = "The sync command will replace all events in the specified channel" +
"with events imported from a public google calendar.\n" +
"The command imports the next 7 days of events into the channel;" +
" the channel will then automatically re-sync once every day." +
"\n\n" +
"If ``<calendar address>`` is not included, " +
"the address saved in the schedule's settings will be used." +
"\n\n" +
"For more information concerning Google Calendar setup, reference the " +
"online docs at https://nmathe.ws/bots/saber";
info.addUsageCategory(cat1, cont1);
info.addUsageExample(head+" #new_schedule g.rit.edu_g4elai703tm3p4iimp10g8heig@group.calendar.google.com");
info.addUsageExample(head+" #calendar import g.rit.edu_g4elai703tm3p4iimp10g8heig@group.calendar.google.com");
info.addUsageExample(head+" #calendar export 0a0jbiclczoiaai@group.calendar.google.com");
info.addUsageExample(head+" #new_schedule");
return info;
}
@Override
public String verify(String prefix, String[] args, MessageReceivedEvent event)
{
String head = prefix + this.name();
int index = 0;
// check arg length
if(args.length < 1)
{
return "That's not enough arguments!\n" +
"Use ``" + head + " <channel> [<calendar address>]``";
}
if(args.length > 3)
{
return "That's too many arguments!\n" +
"Use ``" + head + " <channel> [<import|export> <calendar_address>]``";
}
// validate the supplied channel
String cId = args[0].replaceAll("[^\\d]",""); | if(!Main.getScheduleManager().isSchedule(cId)) | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.