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
mmonkey/Destinations
src/main/java/com/github/mmonkey/destinations/commands/ListWarpsCommand.java
[ "@Entity\n@DynamicUpdate\n@Table(name = \"access\", uniqueConstraints = {\n @UniqueConstraint(columnNames = \"access_id\")\n})\npublic class AccessEntity implements Serializable {\n\n private static final long serialVersionUID = -6492016883124144444L;\n\n @Id\n @Column(name = \"access_id\", unique =...
import com.github.mmonkey.destinations.entities.AccessEntity; import com.github.mmonkey.destinations.entities.PlayerEntity; import com.github.mmonkey.destinations.entities.WarpEntity; import com.github.mmonkey.destinations.persistence.cache.PlayerCache; import com.github.mmonkey.destinations.utilities.FormatUtil; import com.github.mmonkey.destinations.utilities.MessagesUtil; import com.github.mmonkey.destinations.utilities.PlayerUtil; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.service.pagination.PaginationService; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextStyles; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList;
package com.github.mmonkey.destinations.commands; public class ListWarpsCommand implements CommandExecutor { public static final String[] ALIASES = {"warps", "listwarps"}; /** * Get the Command Specifications for this command * * @return CommandSpec */ public static CommandSpec getCommandSpec() { return CommandSpec.builder() .permission("destionations.warp.use") .description(Text.of("/warps or /listwarps")) .extendedDescription(Text.of("Displays a list of your warps.")) .executor(new ListWarpsCommand()) .build(); } @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { if (!(src instanceof Player)) { return CommandResult.empty(); } Player player = (Player) src;
PlayerEntity playerEntity = PlayerCache.instance.get(player);
3
edmocosta/queryfy
queryfy-core/src/test/java/org/evcode/queryfy/core/QueryStructureTest.java
[ "public enum OrderOperatorType implements Operator {\n ASC,\n DESC\n}", "public class QueryParser extends BaseParser<Object> {\n\n final ParserConfig config;\n\n public QueryParser() {\n this.config = ParserConfig.DEFAULT;\n }\n\n public QueryParser(ParserConfig config) {\n this.co...
import java.util.Collections; import java.util.List; import org.evcode.queryfy.core.operator.OrderOperatorType; import org.evcode.queryfy.core.parser.QueryParser; import org.evcode.queryfy.core.parser.ast.FilterNode; import org.evcode.queryfy.core.parser.ast.LimitNode; import org.evcode.queryfy.core.parser.ast.OrderNode; import org.evcode.queryfy.core.parser.ast.ProjectionNode; import org.evcode.queryfy.core.utils.ExpressionParserUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.parboiled.Parboiled; import org.parboiled.support.ValueStack; import java.util.Arrays;
/* * Copyright 2017 EVCode * * 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.evcode.queryfy.core; @RunWith(JUnit4.class) public class QueryStructureTest { @Test public void testQuery() { List<String> oneTwoThreeSelectors = Arrays.asList("one", "two", "three"); testQuery("select one, two, three where one = 1 order by one limit 1,1", oneTwoThreeSelectors, 1L,
Arrays.asList(new OrderNode.OrderSpecifier("one", OrderOperatorType.ASC)),
4
isel-leic-mpd/mpd-2017-i41d
aula34-weather-webapp/src/main/java/weather/app/WeatherWebApp.java
[ "public class HttpRequest implements IRequest {\n @Override\n public Iterable<String> getContent(String path) {\n List<String> res = new ArrayList<>();\n try (InputStream in = new URL(path).openStream()) {\n /*\n * Consumir o Inputstream e adicionar dados ao res\n ...
import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletHolder; import util.HttpRequest; import util.HttpServer; import weather.WeatherService; import weather.WeatherServiceCache; import weather.controllers.WeatherController; import weather.data.WeatherWebApi; import static java.lang.ClassLoader.getSystemResource;
/* * Copyright (c) 2017, Miguel Gamboa * * 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 weather.app; public class WeatherWebApp { public static void main(String[] args) throws Exception { try(HttpRequest http = new HttpRequest()) {
WeatherService service = new WeatherServiceCache(new WeatherWebApi(http));
2
Nanopublication/nanopub-java
src/main/java/org/nanopub/extra/server/FetchIndexFromDb.java
[ "public class MalformedNanopubException extends Exception {\n\n\tprivate static final long serialVersionUID = -1022546557206977739L;\n\n\tpublic MalformedNanopubException(String message) {\n\t\tsuper(message);\n\t}\n\n}", "public interface Nanopub {\n\n\t// URIs in the nanopub namespace:\n\tpublic static final IR...
import java.io.OutputStream; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFHandlerException; import org.nanopub.MalformedNanopubException; import org.nanopub.Nanopub; import org.nanopub.NanopubUtils; import org.nanopub.extra.index.IndexUtils; import org.nanopub.extra.index.NanopubIndex;
package org.nanopub.extra.server; public class FetchIndexFromDb extends FetchIndex { public static final int maxParallelRequestsPerServer = 5; private String indexUri; private NanopubDb db; private OutputStream out; private RDFFormat format; private boolean writeIndex, writeContent; private int nanopubCount; private FetchIndex.Listener listener; public FetchIndexFromDb(String indexUri, NanopubDb db, OutputStream out, RDFFormat format, boolean writeIndex, boolean writeContent) { this.indexUri = indexUri; this.db = db; this.out = out; this.format = format; this.writeIndex = writeIndex; this.writeContent = writeContent; nanopubCount = 0; } public void run() { try { getIndex(indexUri); } catch (RDFHandlerException | MalformedNanopubException ex) { throw new RuntimeException(ex); } } private void getIndex(String indexUri) throws RDFHandlerException, MalformedNanopubException { NanopubIndex npi = getIndex(indexUri, db); while (npi != null) { if (writeIndex) { writeNanopub(npi); } if (writeContent) { for (IRI elementUri : npi.getElements()) { writeNanopub(GetNanopub.get(elementUri.toString(), db)); } } for (IRI subIndexUri : npi.getSubIndexes()) { getIndex(subIndexUri.toString()); } if (npi.getAppendedIndex() != null) { npi = getIndex(npi.getAppendedIndex().toString(), db); } else { npi = null; } } } private static NanopubIndex getIndex(String indexUri, NanopubDb db) throws MalformedNanopubException { Nanopub np = GetNanopub.get(indexUri, db); if (!IndexUtils.isIndex(np)) { throw new RuntimeException("NOT AN INDEX: " + np.getUri()); } return IndexUtils.castToIndex(np); } private void writeNanopub(Nanopub np) throws RDFHandlerException { nanopubCount++; if (listener != null && nanopubCount % 100 == 0) { listener.progress(nanopubCount); }
NanopubUtils.writeToStream(np, out, format);
2
52North/geoar-app
src/main/java/org/n52/geoar/ar/view/ARFragment.java
[ "public class CheckList<T> extends ArrayList<T> {\r\n\r\n\tpublic interface OnCheckedChangedListener<T> {\r\n\t\tvoid onCheckedChanged(T item, boolean newState);\r\n\t}\r\n\r\n\tpublic interface OnItemChangedListener<T> {\r\n\t\tvoid onItemAdded(T item);\r\n\r\n\t\tvoid onItemRemoved(T item);\r\n\t}\r\n\r\n\tpublic...
import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockFragment; import java.util.HashMap; import java.util.Map; import org.n52.geoar.utils.GeoLocation; import org.n52.geoar.R; import org.n52.geoar.newdata.CheckList; import org.n52.geoar.newdata.DataSourceHolder; import org.n52.geoar.newdata.DataSourceInstanceHolder; import org.n52.geoar.newdata.PluginLoader; import org.n52.geoar.newdata.CheckList.OnCheckedChangedListener; import org.n52.geoar.tracking.location.LocationHandler; import org.n52.geoar.tracking.location.LocationHandler.OnLocationUpdateListener; import android.location.Location; import android.os.Bundle;
/** * Copyright 2012 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.geoar.ar.view; /** * * @author Arne de Wall * */ public class ARFragment extends SherlockFragment implements OnLocationUpdateListener {
private Map<DataSourceInstanceHolder, DataSourceVisualizationHandler> mVisualizationHandlerMap = new HashMap<DataSourceInstanceHolder, DataSourceVisualizationHandler>();
2
bingyulei007/bingexcel
excel/src/test/java/com/chinamobile/excel/ReadTest3.java
[ "public class AbstractFieldConvertor implements FieldValueConverter {\n\n\t@Override\n\tpublic boolean canConvert(Class<?> clz) {\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic OutValue toObject(Object source, ConverterHandler converterHandler) {\n\t\tif(source==null){\n\t\t\treturn null;\n\t\t}\n\t\treturn new...
import java.io.File; import java.lang.reflect.Type; import java.net.URISyntaxException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import com.bing.excel.annotation.BingConvertor; import com.bing.excel.annotation.CellConfig; import com.bing.excel.converter.AbstractFieldConvertor; import com.bing.excel.converter.base.BooleanFieldConverter; import com.bing.excel.core.BingExcel; import com.bing.excel.core.BingExcelBuilder; import com.bing.excel.core.handler.ConverterHandler; import com.bing.excel.core.impl.BingExcelImpl.SheetVo; import com.google.common.base.MoreObjects;
package com.chinamobile.excel; public class ReadTest3 { @Test public void readExcelTest() throws URISyntaxException { // InputStream in = Person.class.getResourceAsStream("/person.xlsx"); URL url = Salary.class.getResource("/salary.xlsx"); File f = new File(url.toURI()); BingExcel bing = BingExcelBuilder.toBuilder().builder(); try { SheetVo<Salary> vo = bing.readFile(f, Salary.class, 1); System.out.println(vo.getSheetIndex()); System.out.println(vo.getSheetName()); List<Salary> objectList = vo.getObjectList(); for (Salary salary : objectList) { System.out.println(salary); } } catch (Exception e) { e.printStackTrace(); } } enum Department { develop, personnel, product; } public static class Salary { @CellConfig(index = 1) private String employNum; @CellConfig(index = 0) private String id; //默认的boolean类型只支持"TRUE", "FALSE"字符的转换,但是它自带了传参数的构造方法,具体可以参考源码, @CellConfig(index = 8) @BingConvertor(value = BooleanFieldConverter.class, strings = { "1","0" }, booleans = { false }) private boolean allDay; @CellConfig(index=7) private Department department;//枚举类型 @CellConfig(index = 13) @BingConvertor(DateTestConverter.class) // 自定义转换器 private Date atypiaDate; @CellConfig(index = 14) private Date entryTime; // 其他变量可以这样定义。 private transient String test; public String toString() { return MoreObjects.toStringHelper(this.getClass()).omitNullValues() .add("id", id).add("employNum", employNum) .add("allDay", allDay) .add("atypiaDate", atypiaDate) .add("department", department) .add("entryTime", entryTime).toString(); } } public static class DateTestConverter extends AbstractFieldConvertor { @Override public boolean canConvert(Class<?> clz) { return clz.equals(Date.class); } @Override
public Object fromString(String cell, ConverterHandler converterHandler,Type type) {
4
rodolfodpk/myeslib
myeslib-jdbi/src/test/java/org/myeslib/jdbi/storage/JdbiUnitOfWorkJournalTest.java
[ "public interface Command extends Serializable {\n\t\n UUID getCommandId();\n\tLong getTargetVersion();\n\t\n}", "public interface Event extends Serializable {\n\t\n}", "@SuppressWarnings(\"serial\")\n@Value\npublic class UnitOfWork implements Comparable<UnitOfWork>, Serializable {\n\n final UUID id;\n\tf...
import static org.mockito.Mockito.verify; import java.util.Arrays; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.myeslib.core.Command; import org.myeslib.core.Event; import org.myeslib.core.data.UnitOfWork; import org.myeslib.example.SampleDomain.IncreaseInventory; import org.myeslib.example.SampleDomain.InventoryIncreased; import org.myeslib.util.jdbi.UnitOfWorkJournalDao;
package org.myeslib.jdbi.storage; @RunWith(MockitoJUnitRunner.class) public class JdbiUnitOfWorkJournalTest { @Mock UnitOfWorkJournalDao<UUID> dao; @Test public void insert() { JdbiUnitOfWorkJournal<UUID> writer = new JdbiUnitOfWorkJournal<>(dao); UUID id = UUID.randomUUID();
Command command1 = new IncreaseInventory(UUID.randomUUID(), id, 2, 0l);
0
skuzzle/restrict-imports-enforcer-rule
src/main/java/org/apache/maven/plugins/enforcer/RestrictImports.java
[ "public static void checkArgument(boolean condition) {\n checkArgument(condition, \"Unexpected argument\");\n}", "public final class AnalyzeResult {\n\n private final List<MatchedFile> srcMatches;\n private final List<MatchedFile> testMatches;\n private final Duration duration;\n private final int ...
import static de.skuzzle.enforcer.restrictimports.util.Preconditions.checkArgument; import java.io.File; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.apache.maven.enforcer.rule.api.EnforcerLevel; import org.apache.maven.enforcer.rule.api.EnforcerRule; import org.apache.maven.enforcer.rule.api.EnforcerRule2; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.project.MavenProject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.skuzzle.enforcer.restrictimports.analyze.AnalyzeResult; import de.skuzzle.enforcer.restrictimports.analyze.AnalyzerSettings; import de.skuzzle.enforcer.restrictimports.analyze.BannedImportDefinitionException; import de.skuzzle.enforcer.restrictimports.analyze.BannedImportGroup; import de.skuzzle.enforcer.restrictimports.analyze.BannedImportGroups; import de.skuzzle.enforcer.restrictimports.analyze.SourceTreeAnalyzer; import de.skuzzle.enforcer.restrictimports.formatting.MatchFormatter;
package org.apache.maven.plugins.enforcer; /** * Enforcer rule which restricts the usage of certain packages or classes within a Java * code base. */ public class RestrictImports extends BannedImportGroupDefinition implements EnforcerRule, EnforcerRule2 { private static final Logger LOGGER = LoggerFactory.getLogger(RestrictImports.class); private static final String SKIP_PROPERTY_NAME = "restrictimports.skip"; private static final String FAIL_BUILD_PROPERTY_NAME = "restrictimports.failBuild"; private static final String PARALLEL_ANALYSIS_PROPERTY_NAME = "restrictimports.parallel"; private final SourceTreeAnalyzer analyzer = SourceTreeAnalyzer.getInstance(); private final MatchFormatter matchFormatter = MatchFormatter.getInstance(); private List<BannedImportGroupDefinition> groups = new ArrayList<>(); private boolean includeCompileCode = true; private boolean includeTestCode = true; private File excludedSourceRoot = null; private List<File> excludedSourceRoots = new ArrayList<>(); private boolean failBuild = true; private boolean skip = false; private boolean parallel = false; @Override public EnforcerLevel getLevel() { return failBuild ? EnforcerLevel.ERROR : EnforcerLevel.WARN; } @Override public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { try { if (isSkip(helper)) { LOGGER.info("restrict-imports-enforcer rule is skipped"); return; } final MavenProject project = (MavenProject) helper.evaluate("${project}"); LOGGER.debug("Checking for banned imports"); final BannedImportGroups groups = createGroupsFromPluginConfiguration(); LOGGER.debug("Banned import groups:\n{}", groups);
final AnalyzerSettings analyzerSettings = createAnalyzerSettingsFromPluginConfiguration(helper, project);
2
danijel3/KaldiJava
src/main/java/pl/edu/pjwstk/kaldi/service/tasks/KeywordSpottingTask.java
[ "public class TextGrid extends Segmentation {\n\n\tpublic TextGrid() {\n\n\t}\n\n\tpublic TextGrid(Segmentation segmentation) {\n\t\tthis.tiers = segmentation.tiers;\n\t}\n\n\tprivate String readUntil(BufferedReader reader, String prefix) throws IOException, RuntimeException {\n\t\tString line;\n\t\twhile ((line = ...
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.security.MessageDigest; import java.util.Vector; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import org.w3c.dom.Element; import pl.edu.pjwstk.kaldi.files.TextGrid; import pl.edu.pjwstk.kaldi.programs.KaldiKWS; import pl.edu.pjwstk.kaldi.programs.KaldiUtils; import pl.edu.pjwstk.kaldi.programs.Transcriber; import pl.edu.pjwstk.kaldi.utils.FileUtils; import pl.edu.pjwstk.kaldi.utils.Log; import pl.edu.pjwstk.kaldi.utils.Settings;
package pl.edu.pjwstk.kaldi.service.tasks; public class KeywordSpottingTask extends Task { private File input_keywords; private File words_table; @Override public void run() { state = State.RUNNING; try { File lattice = new File(Settings.curr_task_dir, "aligned_lattice"); File lattice_int = new File(Settings.curr_task_dir, "kws_lattice.int"); File lattice_txt = new File(Settings.curr_task_dir, "kws_lattice.txt"); File kw_clean = new File(Settings.curr_task_dir, "kws_clean_words"); File lat_vocab = new File(Settings.curr_task_dir, "kws_lat_vocab"); File vocab = new File(Settings.curr_task_dir, "kws_vocab"); File dict = new File(Settings.curr_task_dir, "kws_dict"); File kws_out = new File(Settings.curr_task_dir, "kws.txt"); File tg_out = new File(Settings.curr_task_dir, "out.TextGrid"); if (!lattice.canRead()) { Log.error("Cannot read lattice for task: " + Settings.curr_task_dir); Log.error("Keyword spotting HAS to be run after decoding the file first!"); state = State.FAILED; return; } cleanKeywords(input_keywords, kw_clean, Settings.default_encoding);
KaldiUtils.lattice_copy("ark", lattice, "ark,t", lattice_int, true);
2
GeneFeng/CircView
src/cn/edu/whu/ui/ComparisonFrame.java
[ "public class CircRna implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * circRNA ID\n\t */\n\tprivate String circRnaID;\n\n\t/**\n\t * Chromosome name\n\t */\n\tprivate String chrom;\n\n\t/**\n\t * circRNA start point;\n\t */\n\tprivate long startPoint;\n\n\t/**\n\t * cir...
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.TreeMap; import java.util.Vector; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; import cn.edu.whu.CircRna; import cn.edu.whu.CircView; import cn.edu.whu.Gene; import cn.edu.whu.GeneTranscript; import cn.edu.whu.MainData; import cn.edu.whu.util.Constant; import cn.edu.whu.util.EvenOddRenderer;
} } unSelected.addElement(slct); jlUnSelected.removeAll(); jlSelected.removeAll(); jlUnSelected.setListData(unSelected); jlSelected.setListData(selected); } } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }); btCompare.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String species = (String) cbSpecies.getSelectedItem(); if (null == species || species.equals("")) { return; } fillTable(); } }); btReset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { unSelected.removeAllElements(); selected.removeAllElements(); jlUnSelected.setListData(unSelected); jlSelected.setListData(selected); tableData.removeAllElements(); model.setDataVector(tableData, colName); } }); btSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CsvSaveFileChooser saveFile = new CsvSaveFileChooser("Save as ..."); saveFile.setFileSelectionMode(JFileChooser.FILES_ONLY); saveFile.setMultiSelectionEnabled(false); int returnValue = saveFile.showSaveDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File fileOut = saveFile.getSelectedFile(); String type = "csv"; String fileName = fileOut.getAbsolutePath() + "." + type; try { BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); for (int i = 0; i < tbResult.getColumnCount(); i++) { out.write(tbResult.getColumnName(i) + "\t"); } out.newLine(); for (int i = 0; i < tbResult.getRowCount(); i++) { for (int j = 0; j < tbResult.getColumnCount(); j++) { out.write(tbResult.getValueAt(i, j).toString() + "\t"); } out.newLine(); } out.close(); JOptionPane.showMessageDialog(null, "Export Data Successfully!"); } catch (IOException e1) { CircView.log.warn(e1.getMessage()); } } } }); tbResult.addMouseMotionListener(new MouseAdapter() { public void mouseMoved(MouseEvent e) { int row = tbResult.rowAtPoint(e.getPoint()); int col = tbResult.columnAtPoint(e.getPoint()); if (row >= 0 && col >= 0) { Object value = tbResult.getValueAt(row, col); if (null != value && !value.equals("")) { tbResult.setToolTipText(value.toString()); } else { tbResult.setToolTipText(null); } } } }); for (String speciesName : MainData.getSpeciesData().keySet()) { cbSpecies.addItem(speciesName); } for (int i = 0; i <= Constant.BP_MATCH_TOLERATE; i++) { cbTolerate.addItem(i + ""); } } private void fillTable() { tableData.removeAllElements(); if (selected.size() > 0) { fillTableOr(); } model.setDataVector(tableData, colName); } private void fillTableOr() { int tolerate = Integer.parseInt((String) cbTolerate.getSelectedItem()); int num = 0; String species = (String) cbSpecies.getSelectedItem(); if ((null == species) || (species.equals(""))) { return; } TreeMap<String, Gene> genes = MainData.getSpeciesData().get(species); for (String geneName : genes.keySet()) { Gene gene = genes.get(geneName); TreeMap<String, GeneTranscript> geneTrans = gene.getGeneTranscripts(); for (String geneTransName : geneTrans.keySet()) { GeneTranscript gt = geneTrans.get(geneTransName);
TreeMap<String, CircRna> circRnas = gt.getCircRnas();
0
TheCookieLab/poloniex-api-java
src/test/java/com/cf/data/map/poloniex/PoloniexDataMapperTest.java
[ "public class PoloniexChartData {\n\n public final ZonedDateTime date;\n public final BigDecimal high;\n public final BigDecimal low;\n public final BigDecimal open;\n public final BigDecimal close;\n public final BigDecimal volume;\n public final BigDecimal quoteVolume;\n public final BigDe...
import com.cf.data.model.poloniex.PoloniexChartData; import com.cf.data.model.poloniex.PoloniexFeeInfo; import com.cf.data.model.poloniex.PoloniexOpenOrder; import com.cf.data.model.poloniex.PoloniexOrderResult; import com.cf.data.model.poloniex.PoloniexTradeHistory; import com.cf.data.model.poloniex.PoloniexOrderTrade; import java.math.BigDecimal; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test;
package com.cf.data.map.poloniex; /** * * @author David */ public class PoloniexDataMapperTest { private final PoloniexDataMapper mapper = new PoloniexDataMapper(); @Test public void mapValidPoloniexChartData() { String results = "[{\"date\":1512777600,\"high\":487.0422141,\"low\":436.6987279,\"open\":441.81031703,\"close\":461.04968807,\"volume\":29389672.275876,\"quoteVolume\":63412.76665555,\"weightedAverage\":463.46617291},{\"date\":1512864000,\"high\":461.05014912,\"low\":412.0088,\"open\":461.05014912,\"close\":428.95845809,\"volume\":15297660.06622,\"quoteVolume\":35159.74815454,\"weightedAverage\":435.09014908},{\"date\":1512950400,\"high\":463.39998999,\"low\":428.95845926,\"open\":430,\"close\":461.83896992,\"volume\":8204186.3775461,\"quoteVolume\":18163.96559478,\"weightedAverage\":451.67374573}]";
List<PoloniexChartData> chartDataList = mapper.mapChartData(results);
0
dmillett/prank
src/test/java/net/prank/example/ExampleScoreCard.java
[ "public class Indices\n implements Serializable {\n\n private static final long serialVersionUID = 42L;\n /** A collection of indices for any object that is subject to multiple sorts */\n private final List<Integer> _indices;\n\n public Indices(int originalIndex) {\n _indices = new ArrayList<>...
import net.prank.core.Indices; import net.prank.core.RequestOptions; import net.prank.core.Result; import net.prank.core.ScoreCard; import net.prank.core.ScoreData; import net.prank.core.ScoreSummary; import net.prank.core.Statistics; import java.math.BigDecimal;
package net.prank.example; /** * A very simple example of a setupScoring card. More complex examples should still be stateless for * thread safety. Typically, the higher the setupScoring, the better the result. * <p/> * The adjustments are just examples of how scoring might be adjusted to make some * setupScoring cards more/less important than other setupScoring cards. If machine learning (ML) * indicates that price is the most important factor for all customers (or individual), * then it should have "heavier" weighting and it's setupScoring should be adjusted (+) * <p/> * Examples: * Price: the lowest price has the highest setupScoring. * Shipping cost: how much to ship the item * Shipping time: how long it takes an item to ship * * * @author dmillett * * Copyright 2012 David Millett * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class ExampleScoreCard implements ScoreCard<ExampleObject> { private final String _name = "SolutionPriceScoreCard"; // Mutable state (single threaded only) -- D private final int _scoreAdjustment; private final int _positionAdjustment; private final double _averageAdjustment; private final double _standardDeviationAdjustment; public ExampleScoreCard() { _scoreAdjustment = 5; _positionAdjustment = 3; _averageAdjustment = 2; _standardDeviationAdjustment = 1.0; } public ExampleScoreCard(int scoreAdjustment, int positionAdjustment, double averageAdjustment, double standardDeviationAdjustment) { _scoreAdjustment = scoreAdjustment; _positionAdjustment = positionAdjustment; _averageAdjustment = averageAdjustment; _standardDeviationAdjustment = standardDeviationAdjustment; } public ScoreSummary score(ExampleObject scoringObject) { // Ignore the summary for now performScoring(scoringObject); return null; } @Override public ScoreSummary scoreWith(ExampleObject scoringObject, RequestOptions options) { return score(scoringObject); } @Override public void updateObjectsWithScore(ExampleObject scoringObject) { performScoring(scoringObject); } @Override public void updateObjectsWithScore(ExampleObject scoringObject, RequestOptions options) { performScoring(scoringObject); } private void performScoring(ExampleObject scoringObject) { int score = scoringObject.getAverageShippingTime() + _scoreAdjustment; int position = _positionAdjustment; double average = scoringObject.getShippingCost().doubleValue() + _averageAdjustment; double standardDeviation = _standardDeviationAdjustment; // Calculate stats with primitives for performance
ScoreData.Builder scoreBuilder = new ScoreData.Builder();
4
leobm/teavm-jquery
core/src/main/java/de/iterable/teavm/jquery/ajax/JQueryAjaxSettingsObject.java
[ "@JSFunctor\npublic interface AjaxBeforeSendHandler extends JSObject {\n void onBeforeSend(JQueryXHR jqXHR, JQueryAjaxSettingsObject settings);\n}", "@JSFunctor\npublic interface AjaxCompleteHandler extends JSObject {\n\t\n\tvoid onComplete(JQueryXHR jqXHR, String textStatus);\n\n}", "@JSFunctor\npublic inte...
import org.teavm.jso.JSBody; import org.teavm.jso.JSObject; import org.teavm.jso.JSProperty; import org.teavm.jso.core.JSArray; import org.teavm.jso.core.JSString; import de.iterable.teavm.jquery.ajax.handler.AjaxBeforeSendHandler; import de.iterable.teavm.jquery.ajax.handler.AjaxCompleteHandler; import de.iterable.teavm.jquery.ajax.handler.AjaxErrorHandler; import de.iterable.teavm.jquery.ajax.handler.AjaxFilterHandler; import de.iterable.teavm.jquery.ajax.handler.AjaxSuccessHandler; import de.iterable.teavm.jquery.ajax.handler.AjaxXhrFunctionHandler; import de.iterable.teavm.utils.functor.JSFunctor0; import de.iterable.teavm.utils.jso.JSDictonary;
/* * Copyright 2015 Jan-Felix Wittmann. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.iterable.teavm.jquery.ajax; /** * * @author Jan-Felix Wittmann */ public abstract class JQueryAjaxSettingsObject implements JSObject { private JQueryAjaxSettingsObject() { } @JSBody(params = {}, script = "return {}") public static native final JQueryAjaxSettingsObject create(); @JSProperty public abstract void setAccepts(JSDictonary obj); @JSProperty public abstract void setAsync(boolean isAsync); @JSProperty("beforeSend")
public abstract void setBeforeSendHandler(AjaxBeforeSendHandler handler);
0
curtisullerich/attendance
src/main/java/edu/iastate/music/marching/attendance/servlets/AuthServlet.java
[ "public class Lang {\n\n\tpublic static final String ERROR_MESSAGE_NO_DIRECTOR = \"There is no director registered. You cannot register for an account yet.\";\n\tpublic static final String ERROR_INVALID_PRIMARY_REGISTER_EMAIL= \"Not a valid email, try logging in with your student account\";\n\tpublic static final ...
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.Email; import edu.iastate.music.marching.attendance.Lang; import edu.iastate.music.marching.attendance.model.interact.AuthManager; import edu.iastate.music.marching.attendance.model.interact.DataTrain; import edu.iastate.music.marching.attendance.model.store.User; import edu.iastate.music.marching.attendance.util.GoogleAccountException; import edu.iastate.music.marching.attendance.util.PageBuilder; import edu.iastate.music.marching.attendance.util.Util; import edu.iastate.music.marching.attendance.util.ValidationUtil;
package edu.iastate.music.marching.attendance.servlets; public class AuthServlet extends AbstractBaseServlet { private enum Page { index, login, login_callback, logout, welcome, register, register_post, login_fail; } private static final long serialVersionUID = -4587683490944456397L; private static final String SERVLET_PATH = "auth"; public static final String URL_LOGOUT = pageToUrl(Page.logout, SERVLET_PATH); public static final String URL_LOGIN = pageToUrl(Page.login, SERVLET_PATH); private static final String URL_REGISTER = pageToUrl(Page.register, SERVLET_PATH); private static final Logger LOG = Logger.getLogger(AuthServlet.class .getName()); private static String getLoginCallback(HttpServletRequest request) { String url = pageToUrl(Page.login_callback, SERVLET_PATH); try {
if (null != request.getParameter(PageBuilder.PARAM_REDIRECT_URL))
5
xcsp3team/XCSP3-Java-Tools
src/main/java/org/xcsp/parser/entries/XVariables.java
[ "public static enum TypeVar {\n\tinteger, symbolic, real, stochastic, symbolic_stochastic, set, symbolic_set, undirected_graph, directed_graph, point, interval, region;\n\n\t/** Returns true if the constant corresponds to integer, symbolic, real or (symbolic) stochastic. */\n\tpublic boolean isBasic() {\n\t\treturn...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; import java.util.stream.Stream; import org.xcsp.common.IVar; import org.xcsp.common.IVar.Var; import org.xcsp.common.IVar.VarSymbolic; import org.xcsp.common.Types.TypeVar; import org.xcsp.common.Utilities; import org.xcsp.common.domains.Domains.Dom; import org.xcsp.common.domains.Domains.IDom; import org.xcsp.common.domains.Values.IntegerEntity; import org.xcsp.common.domains.Values.IntegerInterval; import org.xcsp.parser.XParser.TypePrimitive; import org.xcsp.parser.entries.ParsingEntry.VEntry;
/* * Copyright (c) 2016 XCSP3 Team (contact@xcsp.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.xcsp.parser.entries; /** * In this class, we find intern classes for managing variables and arrays of variables. * * @author Christophe Lecoutre */ public class XVariables { public static final String OTHERS = "others"; /** The class used to represent variables. */ public static abstract class XVar extends VEntry implements IVar { /** Builds a variable with the specified id, type and domain. */ public static final XVar build(String id, TypeVar type, IDom dom) { switch (type) { case integer: return new XVarInteger(id, type, dom); case symbolic: return new XVarSymbolic(id, type, dom); case stochastic: return new XVarStochastic(id, type, dom); case real: return new XVarReal(id, type, dom); case set: return new XVarSet(id, type, dom); default: throw new RuntimeException("Unimplemented case "); } } /** Builds a variable from an array with the specified id (combined with the specified indexes), type and domain. */ public static final XVar build(String idArray, TypeVar type, IDom dom, int[] indexes) { return build(idArray + "[" + Utilities.join(indexes, "][") + "]", type, dom); } /** The domain of the variable. It is null if the variable is qualitative. */ public final IDom dom; /** The degree of the variable. This is automatically computed after all constraints have been parsed. */ public int degree; /** Builds a variable with the specified id, type and domain. */ protected XVar(String id, TypeVar type, IDom dom) { super(id, type); this.dom = dom; } // /** Builds a variable from an array with the specified id (combined with the specified indexes), type and domain. */ // protected VVar(String idArray, TypeVar type, DDom dom, int[] indexes) { // this(idArray + "[" + XUtility.join(indexes, "][") + "]", type, dom); // } @Override public String id() { return id; } @Override public String toString() { return id; // + " :" + type + " of " + dom; } } /** The following classes are introduced, only for being able to have types for variables in the parser interface */ public static final class XVarInteger extends XVar implements Var { /** * Returns the size of the Cartesian product for the domains of the specified variables. Importantly, if this value does not fit within a * {@code long}, -1 is returned. */ public static long domainCartesianProductSize(XVarInteger[] scp) { long[] domSizes = Stream.of(scp).mapToLong(x -> IntegerEntity.nValues((IntegerEntity[]) ((Dom) x.dom).values)).toArray(); if (LongStream.of(domSizes).anyMatch(l -> l == -1L)) return -1L; long cnt = 1; try { for (long size : domSizes) cnt = Math.multiplyExact(cnt, size); } catch (ArithmeticException e) { return -1L; } return cnt; } public TypePrimitive whichPrimitive() { return TypePrimitive.whichPrimitiveFor(firstValue(), lastValue()); } /** Builds an integer variable with the specified id, type and domain. */ protected XVarInteger(String id, TypeVar type, IDom dom) { super(id, type, dom); } public long firstValue() { return ((Dom) dom).firstValue(); } public long lastValue() { return ((Dom) dom).lastValue(); } @Override public Object allValues() { return ((Dom) dom).allValues(); } public boolean isZeroOne() { return firstValue() == 0 && lastValue() == 1; } } public static final class XVarSymbolic extends XVar implements VarSymbolic { /** Builds a symbolic variable with the specified id, type and domain. */ protected XVarSymbolic(String id, TypeVar type, IDom dom) { super(id, type, dom); } } public static final class XVarStochastic extends XVar { /** Builds a stochastic variable with the specified id, type and domain. */ protected XVarStochastic(String id, TypeVar type, IDom dom) { super(id, type, dom); } } public static final class XVarReal extends XVar { /** Builds a real variable with the specified id, type and domain. */ protected XVarReal(String id, TypeVar type, IDom dom) { super(id, type, dom); } } public static final class XVarSet extends XVar { /** Builds a set variable with the specified id, type and domain. */ protected XVarSet(String id, TypeVar type, IDom dom) { super(id, type, dom); } } /** The class used to represent arrays of variables. */ public static final class XArray extends VEntry { /** The size of the array, as defined in XCSP3. */ public final int[] size; /** * The flat (one-dimensional) array composed of all variables contained in the (multi-dimensional) array. This way, we can easily deal with * arrays of any dimensions. */ public final XVar[] vars; /** Builds an array of variables with the specified id, type and size. */ public XArray(String id, TypeVar type, int[] size) { super(id, type); this.size = size; this.vars = new XVar[Arrays.stream(size).reduce(1, (s, t) -> s * t)]; } /** Builds a variable with the specified domain for each unoccupied cell of the flat array. */ private void buildVarsWith(IDom dom) { int[] indexes = new int[size.length]; for (int i = 0; i < vars.length; i++) { if (vars[i] == null) vars[i] = XVar.build(id, type, dom, indexes); for (int j = indexes.length - 1; j >= 0; j--) if (++indexes[j] == size[j]) indexes[j] = 0; else break; } } /** * Builds an array of variables with the specified id, type and size. All variables are directly defined with the specified domain. */ public XArray(String id, TypeVar type, int[] sizes, IDom dom) { this(id, type, sizes); buildVarsWith(dom); } /** Transforms a flat index into a multi-dimensional index. */ protected int[] indexesFor(int flatIndex) { int[] t = new int[size.length]; for (int i = t.length - 1; i > 0; i--) { t[i] = flatIndex % size[i]; flatIndex = flatIndex / size[i]; } t[0] = flatIndex; return t; } /** Transforms a multi-dimensional index into a flat index. */ private int flatIndexFor(int... indexes) { int sum = 0; for (int i = indexes.length - 1, nb = 1; i >= 0; i--) { sum += indexes[i] * nb; nb *= size[i]; } return sum; } /** Returns the variable at the position given by the multi-dimensional index. */ public XVar varAt(int... indexes) { return vars[flatIndexFor(indexes)]; } /** * Returns the domain of the variable at the position given by the multi-dimensional index. However, if this variable does not exist or if its * degree is 0, <code>null</code> is returned. */ public Dom domAt(int... indexes) { XVar x = vars[flatIndexFor(indexes)]; return x == null || x.degree == 0 ? null : (Dom) x.dom; } /** * Builds an array of IntegerEnity objects for representing the ranges of indexes that are computed with respect to the specified compact * form. */ public IntegerEntity[] buildIndexRanges(String compactForm) { IntegerEntity[] t = new IntegerEntity[size.length]; String suffix = compactForm.substring(compactForm.indexOf("[")); for (int i = 0; i < t.length; i++) { int pos = suffix.indexOf("]"); String tok = suffix.substring(1, pos);
t[i] = tok.length() == 0 ? new IntegerInterval(0, size[i] - 1) : IntegerEntity.parse(tok);
5
NICTA/nicta-ner
nicta-ner/src/main/java/org/t3as/ner/classifier/feature/ExistingCleanPhraseFeature.java
[ "public class Phrase {\n // TODO: getters and setters for these\n /** phrase text array */\n public final List<Token> phrase;\n /** corresponding name type */\n public EntityClass phraseType;\n /** the start position of the phase in a sentence */\n public final int phrasePosition;\n /** the ...
import java.util.List; import java.util.Set; import static org.t3as.ner.util.Strings.clean; import static org.t3as.ner.util.Strings.toEngLowerCase; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableSet; import org.t3as.ner.Phrase; import org.t3as.ner.util.IO; import org.t3as.ner.util.Strings; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.HashSet;
/* * #%L * NICTA t3as Named-Entity Recognition library * %% * Copyright (C) 2010 - 2014 NICTA * %% * 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/gpl-3.0.html>. * #L% */ package org.t3as.ner.classifier.feature; @Immutable public class ExistingCleanPhraseFeature extends Feature { private ImmutableCollection<String> phrases; public ExistingCleanPhraseFeature(final List<String> resources, final int weight) throws IOException { super(resources, weight); } @Override public double score(final Phrase p) { final int w = getWeight(); if (w == 0) return 0;
final String phrase = Strings.simplify(p.phraseString());
2
wutongke/AndroidSkinAnimator
skin-app/src/main/java/com/ximsfei/dynamicskindemo/widget/CustomCircleImageView.java
[ "public class SkinCompatResources {\n private static volatile SkinCompatResources sInstance;\n private final Context mAppContext;\n private Resources mResources;\n private String mSkinPkgName;\n private boolean isDefaultSkin;\n\n private SkinCompatResources(Context context) {\n mAppContext ...
import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.ColorRes; import android.support.annotation.DrawableRes; import android.util.AttributeSet; import com.ximsfei.dynamicskindemo.R; import skin.support.content.res.SkinCompatResources; import skin.support.widget.SkinCompatHelper; import skin.support.widget.SkinCompatImageHelper; import skin.support.widget.SkinCompatSupportable; import static skin.support.widget.SkinCompatHelper.INVALID_ID;
package com.ximsfei.dynamicskindemo.widget; /** * Created by ximsfei on 2017/1/17. */ public class CustomCircleImageView extends CircleImageView implements SkinCompatSupportable { private final SkinCompatImageHelper mImageHelper; private int mFillColorResId = INVALID_ID; private int mBorderColorResId = INVALID_ID; public CustomCircleImageView(Context context) { this(context, null); } public CustomCircleImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomCircleImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mImageHelper = new SkinCompatImageHelper(this); mImageHelper.loadFromAttributes(attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0); mBorderColorResId = a.getResourceId(R.styleable.CircleImageView_civ_border_color, INVALID_ID); mFillColorResId = a.getResourceId(R.styleable.CircleImageView_civ_fill_color, INVALID_ID); a.recycle(); applySkin(); } @Override public void setImageResource(@DrawableRes int resId) { super.setImageResource(resId); if (mImageHelper != null) { mImageHelper.applySkin(); } } @Override public void setBorderColorResource(@ColorRes int borderColorRes) { super.setBorderColorResource(borderColorRes); mBorderColorResId = borderColorRes; applySkin(); } @Override public void setFillColorResource(@ColorRes int fillColorRes) { super.setFillColorResource(fillColorRes); mFillColorResId = fillColorRes; applySkin(); } @Override public void applySkin() { if (mImageHelper != null) { mImageHelper.applySkin(); } mBorderColorResId = SkinCompatHelper.checkResourceId(mBorderColorResId); if (mBorderColorResId != INVALID_ID) {
int color = SkinCompatResources.getInstance().getColor(mBorderColorResId);
0
sumeetchhetri/gatf
alldep-jar/src/main/java/com/gatf/selenium/SeleniumTest.java
[ "public class AcceptanceTestContext {\r\n\r\n\tprivate Logger logger = Logger.getLogger(AcceptanceTestContext.class.getSimpleName());\r\n\t\r\n\tpublic final static String\r\n\t PROP_SOAP_ACTION_11 = \"SOAPAction\",\r\n\t PROP_SOAP_ACTION_12 = \"action=\",\r\n\t PROP_CONTENT_TYPE = \"Content-Type\",\r\n\t ...
import java.awt.AWTException; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Method; import java.net.URL; import java.nio.charset.Charset; import java.security.Security; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.OutputType; import org.openqa.selenium.Point; import org.openqa.selenium.Rectangle; import org.openqa.selenium.SearchContext; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriver.TargetLocator; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.logging.LogEntry; import org.openqa.selenium.logging.LogType; import org.openqa.selenium.logging.LoggingPreferences; import org.openqa.selenium.remote.Augmenter; import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import com.gatf.executor.core.AcceptanceTestContext; import com.gatf.executor.core.GatfExecutorConfig; import com.gatf.executor.core.WorkflowContextHandler; import com.gatf.executor.report.RuntimeReportUtil; import com.gatf.selenium.Command.GatfSelCodeParseError; import com.gatf.selenium.SeleniumTestSession.SeleniumResult; import com.google.common.io.Resources; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileDriver; import io.appium.java_client.MultiTouchAction; import io.appium.java_client.TouchAction; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.ios.IOSDriver; import io.selendroid.client.SelendroidDriver; import ru.yandex.qatools.ashot.AShot; import ru.yandex.qatools.ashot.Screenshot; import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
return null; } else { Map<String, String> _mt = ___cxt___.getWorkflowContextHandler().getGlobalSuiteAndTestLevelParameters(null, null, index); return _mt.get(key); } } protected Object getProviderDataValueO(String key, boolean isVar) { if(isVar) { return ___get_var__(key); } if(getSession().providerTestDataMap.containsKey(TOP_LEVEL_PROV_NAME) && getSession().providerTestDataMap.get(TOP_LEVEL_PROV_NAME).get(0).containsKey(key)) { return getSession().providerTestDataMap.get(TOP_LEVEL_PROV_NAME).get(0).get(key); } if(getSession().__provdetails__.size()>0) { ArrayList<String> keys = new ArrayList<String>(getSession().__provdetails__.keySet()); for (int i=keys.size()-1;i>=0;i--) { String pn = keys.get(i); Integer pp = getSession().__provdetails__.get(pn); List<Map<String, String>> _t = getAllProviderData(pn); if(_t!=null && _t.get(pp)!=null) { Map<String, String> _mt = ___cxt___.getWorkflowContextHandler().getGlobalSuiteAndTestLevelParameters(null, _t.get(pp), index); if(_mt.containsKey(key)) { return _mt.get(key); } } } return null; } else { Map<String, String> _mt = ___cxt___.getWorkflowContextHandler().getGlobalSuiteAndTestLevelParameters(null, null, index); return _mt.get(key); } } protected void ___add_var__(String name, Object val) { if(getSession().__vars__.containsKey(name)) { throw new RuntimeException("Variable " + name + " redefined"); } getSession().__vars__.put(name, val); } protected Object ___get_var__(String name) { if(!getSession().__vars__.containsKey(name)) { throw new RuntimeException("Variable " + name + " not defined"); } return getSession().__vars__.get(name); } protected void addSubTest(String browserName, String stname) { if(getSession().__result__.containsKey(browserName)) { if(!getSession().__result__.get(getSession().browserName).__cresult__.containsKey(stname)) { getSession().__result__.get(browserName).__cresult__.put(stname, null); } else { throw new RuntimeException("Duplicate subtest defined"); } } else { throw new RuntimeException("Invalid browser specified"); } } protected WebDriver get___d___() { if(getSession().___d___.size()==0)return null; return getSession().___d___.get(getSession().__wpos__); } protected void set___d___(WebDriver ___d___) { ___d___.manage().timeouts().pageLoadTimeout(100, TimeUnit.SECONDS); getSession().___d___.add(___d___); } protected class PrettyPrintingMap<K, V> { private Map<K, V> map; public PrettyPrintingMap(Map<K, V> map) { this.map = map; } public String toString() { StringBuilder sb = new StringBuilder(); Iterator<Entry<K, V>> iter = map.entrySet().iterator(); while (iter.hasNext()) { Entry<K, V> entry = iter.next(); sb.append(entry.getKey()); sb.append('=').append('"'); sb.append(entry.getValue()); sb.append('"'); if (iter.hasNext()) { sb.append(',').append(' '); } } return sb.toString(); } } private String getPn(String name) { String pn = name; if(index>0) { pn += index; } return pn; } protected void ___cxt___add_param__(String name, Object value) { ___cxt___.getWorkflowContextHandler().addSuiteLevelParameter(index, name, value==null?null:value.toString()); } protected void ___cxt___print_provider__(String name) { System.out.println(getAllProviderData(getPn(name))); } protected void ___cxt___print_provider__json(String name) { try {
System.out.println(WorkflowContextHandler.OM.writerWithDefaultPrettyPrinter().writeValueAsString(getAllProviderData(getPn(name))));
2
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/ui/activitiy/TagActivity.java
[ "public class Constants {\n public static final String AUTHOR = \"author\";\n public static final String TAG = \"tag\";\n public static final String ARTICLE_ID = \"article_id\";\n public static final String AUTHOR_ID = \"author_id\";\n public static final String TAG_ID = \"tag_id\";\n public stati...
import android.graphics.drawable.Drawable; import androidx.recyclerview.widget.LinearLayoutManager; import android.view.View; import butterknife.ButterKnife; import nich.work.aequorea.R; import nich.work.aequorea.common.Constants; import nich.work.aequorea.common.utils.DisplayUtils; import nich.work.aequorea.common.utils.ThemeHelper; import nich.work.aequorea.model.SimpleArticleListModel; import nich.work.aequorea.model.entity.Data; import nich.work.aequorea.presenter.TagPresenter; import nich.work.aequorea.ui.adapter.SimpleArticleListAdapter;
package nich.work.aequorea.ui.activitiy; public class TagActivity extends SimpleArticleListActivity { @Override protected int getContentViewId() { return R.layout.activity_tag; } @Override protected void initModel() { mModel = new SimpleArticleListModel(); mModel.setId((int) getIntent().getLongExtra(Constants.TAG_ID, 0)); mModel.setTitle(getIntent().getStringExtra(Constants.TAG)); } @Override protected void initView() { ButterKnife.bind(this); mToolbar.setNavigationIcon(R.drawable.icon_ab_back_material); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); mToolbar.setTitle(mModel.getTitle()); mCoordinatorLayout.setPadding(0, DisplayUtils.getStatusBarHeight(getResources()), 0, 0); mAdapter = new SimpleArticleListAdapter(this, null); mRecyclerView.setAdapter(mAdapter); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.addOnScrollListener(mScrollListener); setStatusBarStyle(); } @Override protected void initPresenter() { mPresenter = new TagPresenter(); mPresenter.attach(this); mPresenter.load(); } @Override public void onDataLoaded(Data a) { super.onDataLoaded(a); } @Override public void onThemeSwitch() { super.onThemeSwitch();
int primaryColor = ThemeHelper.getResourceColor(this, R.attr.colorPrimary);
2
beckchr/juel
modules/impl/src/main/java/de/odysseus/el/util/SimpleResolver.java
[ "public class ArrayELResolver extends ELResolver {\r\n\tprivate final boolean readOnly;\r\n\r\n\t/**\r\n\t * Creates a new read/write ArrayELResolver.\r\n\t */\r\n\tpublic ArrayELResolver() {\r\n\t\tthis(false);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a new ArrayELResolver whose read-only status is determined by the gi...
import java.beans.FeatureDescriptor; import java.util.Iterator; import javax.el.ArrayELResolver; import javax.el.BeanELResolver; import javax.el.CompositeELResolver; import javax.el.ELContext; import javax.el.ELResolver; import javax.el.ListELResolver; import javax.el.MapELResolver; import javax.el.ResourceBundleELResolver;
/* * Copyright 2006-2009 Odysseus 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 de.odysseus.el.util; /** * Simple resolver implementation. This resolver handles root properties (top-level identifiers). * Resolving "real" properties (<code>base != null</code>) is delegated to a resolver specified at * construction time. * * @author Christoph Beck */ public class SimpleResolver extends ELResolver { private static final ELResolver DEFAULT_RESOLVER_READ_ONLY = new CompositeELResolver() { { add(new ArrayELResolver(true)); add(new ListELResolver(true)); add(new MapELResolver(true));
add(new ResourceBundleELResolver());
6
ardeleanasm/quantum_computing
quantumapp/src/main/java/com/ars/algorithms/grover/GroversAlgorithm.java
[ "public class MeasurementPerformer {\r\n\tprivate Qubit resultQubit = null;\r\n\tprivate int length;\r\n\tprivate static final double Q_TOLERANCE = 0.1e-5;\r\n\r\n\tpublic MeasurementPerformer() {\r\n\r\n\t}\r\n\r\n\tpublic MeasurementPerformer configure(Qubit resultQubit) {\r\n\t\tthis.resultQubit = resultQubit;\r...
import com.ars.algorithms.MeasurementPerformer; import com.ars.algorithms.QuantumAlgorithms; import com.ars.gates.EGateTypes; import com.ars.gates.IGate; import com.ars.quantum.exception.RegisterOverflowException; import com.ars.quantum.utils.QRegisterOperations; import com.ars.quantum.utils.QuantumOperations; import com.ars.qubits.QRegister;
package com.ars.algorithms.grover; public class GroversAlgorithm extends QuantumAlgorithms { private static final int NO_OF_INPUT = 3; private IGate gateH; private IGate gateX; private IGate gateCNot; private IGate gateCPhaseShift; public GroversAlgorithm() { } @Override public void init() { gateH = gateFactory.getGate(EGateTypes.E_HadamardGate); gateX = gateFactory.getGate(EGateTypes.E_XGate); gateCNot = gateFactory.getGate(EGateTypes.E_CNotGate); gateCPhaseShift = gateFactory.getGate(EGateTypes.E_CPhaseShift); QRegister qRegister=new QRegister(NO_OF_INPUT+1);
QRegisterOperations qRegOps=QRegisterOperations.getInstance();
5
nchambers/probschemas
src/main/java/nate/probschemas/KeywordDetector.java
[ "public class IDFMap {\n// private HashMap<String,Integer> _wordToDocAppearances;\n// private HashMap<String,Integer> _wordToFrequencies;\n// private HashMap<String,Float> _wordToIDF;\n private Map<String,WordCounts> _wordToCounts;\n private int _numDocs = 0;\n private int _totalCorpusCount = 0;\n\n private ...
import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import edu.stanford.nlp.stats.ClassicCounter; import edu.stanford.nlp.stats.Counter; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.trees.TypedDependency; import nate.IDFMap; import nate.ProcessedData; import nate.util.Directory; import nate.util.TreeOperator; import nate.util.WordNet; import nate.util.Ling;
package nate.probschemas; /** * Code that reads a document(s) and gives you the top most important event words. * This should be used for IR to find similar documents based on these keywords. * * This code is used by --KeywordTokenizer-- to process all of Gigaword and provide a short list * of keywords to be used by the Lucene index for search. * * getKeywords() is the main function. * - this was used to convert Gigaword docs * - use this to reduce current docs, and then call IRDocuments with those words * */ public class KeywordDetector { public WordNet wordnet = null; public IDFMap idf; public KeywordDetector() { init(); } public KeywordDetector(String[] args) { init(); runit(args); } private void init() { wordnet = new WordNet(WordNet.findWordnetPath()); idf = new IDFMap(IDFMap.findIDFPath()); } public void runit(String[] args) { load(args[args.length-1]); } /** * Just a testing function. */ public void load(String dataDir) { String parsesFile = dataDir + File.separator + Directory.nearestFile("parse", dataDir); String depsFile = dataDir + File.separator + Directory.nearestFile("deps", dataDir); String eventsFile = dataDir + File.separator + Directory.nearestFile("events", dataDir); String nerFile = dataDir + File.separator + Directory.nearestFile("ner", dataDir); // Read the data files from disk. ProcessedData data = new ProcessedData(parsesFile, depsFile, eventsFile, nerFile); data.nextStory(); // Count all of the verbs. while( data.getParseStrings() != null ) { List<Tree> trees = TreeOperator.stringsToTrees(data.getParseStrings()); Counter<String> verbs = getKeywordCounts(trees, data.getDependencies()); System.out.println("DOC " + data.currentStory()); for( String key : verbs.keySet() ) if( idf.get("v-" + key) > 1.5 ) System.out.println("\t" + key + "\t" + verbs.getCount(key) + "\t" + idf.get("v-" + key)); else System.out.println("\t(skip) " + key + "\t" + verbs.getCount(key) + "\t" + idf.get("v-" + key)); verbs.clear(); data.nextStory(); } } public List<String> getKeywords(List<Tree> trees, List<List<TypedDependency>> deps) { List<String> verbs = new ArrayList<String>(); int sid = 0; if( trees.size() != deps.size() ) { System.out.println("ERROR: " + trees.size() + " trees but " + deps.size() + " deps in KeywordDetector.getKeywords()"); return null; } for( Tree tree : trees ) { // Look for particles.
Map<Integer,String> particles = Ling.particlesInSentence(deps.get(sid++));
4
TranquilMarmot/spaceout
src/com/bitwaffle/spaceguts/util/console/ConsoleCommands.java
[ "public class Audio {\n\t/** Used for deleting all sound sources on shutdown (see {@link SoundSource}'s constructor, each SoundSource gets added to this when it's created */\n\tprotected static ArrayList<SoundSource> soundSources = new ArrayList<SoundSource>();\n\t\n\t/** Factor to use for doppler effect */\n\tpriv...
import java.util.StringTokenizer; import javax.vecmath.Quat4f; import org.lwjgl.util.vector.Quaternion; import org.lwjgl.util.vector.Vector3f; import com.bitwaffle.spaceguts.audio.Audio; import com.bitwaffle.spaceguts.entities.DynamicEntity; import com.bitwaffle.spaceguts.entities.Entities; import com.bitwaffle.spaceguts.entities.Entity; import com.bitwaffle.spaceguts.entities.Light; import com.bitwaffle.spaceguts.util.QuaternionHelper; import com.bitwaffle.spaceout.Runner; import com.bulletphysics.linearmath.DefaultMotionState; import com.bulletphysics.linearmath.Transform;
package com.bitwaffle.spaceguts.util.console; /** * All the possible console commands. These are called by the console by their name, * so name a command however you want it to be referenced to in-game. * Each command constructor takes in a command class that implements the inner Command interface. * Many commands can use the same command class. * Commands can also take other commands in their constructors, which allows multiple commands to call the * same Command class without needing to instantiate it. * @author TranquilMarmot * */ public enum ConsoleCommands { help(new HelpCommand()), list(new ListCommand()), xyz(new PositionCommand()), pos(xyz), position(xyz), clear(new ClearCommand()), speed(new SpeedCommand()), numentities(new NumberCommand()), beer(new BeerCommand()), camera(new CameraCommand()), quit(new QuitCommand()), q(quit), exit(quit), diamonds(new HowManyDiamonds()), warp(new WarpCommand()), mute(new MuteCommand()), volume(new VolumeCommand()), vol(volume); protected Command function; /** * Create a console command with a new function * @param function Function to use for this command */ private ConsoleCommands(Command function){ this.function = function; } /** * Create a console command that uses a function that another command already uses * @param command Command to get function from */ private ConsoleCommands(ConsoleCommands command){ function = command.function; } /** * Issues a command * @param toker StringTokenizer at the first arg for the command (calling toker.nextToken() will return the command's args[1]- the command itself is at args[0]) */ public void issue(StringTokenizer toker){ function.issue(toker); } /** * Prints out help for the command */ public void help(){ function.help(); } } /** * Every command class should implement this and override the issue() function to carry out a command * @author TranquilMarmot */ interface Command{ /** * This should issue the command for the class implementing this interface * @param toker This will contain the rest of the command, excluding the command itself, separated by spaces */ public void issue(StringTokenizer toker); /** * This should print out any help info about the command to the console */ public void help(); } /** * */ class HelpCommand implements Command{ @Override public void issue(StringTokenizer toker){ if(toker.hasMoreElements()){ String commStr = toker.nextToken(); try{ ConsoleCommands command = ConsoleCommands.valueOf(commStr); System.out.println("HELP for " + command + ":"); command.help(); } catch(IllegalArgumentException e){ System.out.println("Command not found! (" + commStr + ")"); } } else{ System.out.println("AVAILABLE COMMANDS:"); System.out.println("(use /help COMMAND or /COMMAND help for more details)"); for(ConsoleCommands command : ConsoleCommands.values()) System.out.println(command.name()); } } @Override public void help(){ System.out.println("Usage: /help command (leave command blank to get a list of commands)"); } } /** * Clear the console */ class ClearCommand implements Command{ @Override public void issue(StringTokenizer toker) { Console.console.clear(); } @Override public void help(){ System.out.println("Clears the console"); } } /** * Change the speed of the player */ class SpeedCommand implements Command{ @Override public void issue(StringTokenizer toker) { if(!toker.hasMoreTokens()){ this.help(); return; } String speedCommand = toker.nextToken().toLowerCase(); if(speedCommand.equals("top")){ if(toker.hasMoreTokens()){ Float speedChange = Float.parseFloat(toker.nextToken());
System.out.printf("Changing player top speed from %f to %f\n", Entities.player.ship.getTopSpeed(), speedChange);
2
dbuschman7/mongoFS
src/main/java/me/lightspeed7/mongofs/MongoFile.java
[ "public class MongoFileUrl {\n\n public static final String PROTOCOL = \"mongofile\";\n\n private URL url;\n\n // factories and helpers\n public static final MongoFileUrl construct(final ObjectId id, final String fileName, final String mediaType, final StorageFormat format)\n throws Malformed...
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.zip.GZIPInputStream; import me.lightspeed7.mongofs.url.MongoFileUrl; import me.lightspeed7.mongofs.url.Parser; import me.lightspeed7.mongofs.url.StorageFormat; import me.lightspeed7.mongofs.util.BytesCopier; import org.bson.types.ObjectId; import org.mongodb.Document; import org.mongodb.MongoException; import com.mongodb.BasicDBObject;
package me.lightspeed7.mongofs; /** * Object to hold the state of the file's metatdata. To persist this outside of MongoFS, use the getURL() and persist that. * * @author David Buschman * */ public class MongoFile implements InputFile { private final Document surrogate; private final MongoFileStore store; private StorageFormat format; /** * Construct a MongoFile object for reading data * * @param store * @param o */ /* package */MongoFile(final MongoFileStore store, final Document surrogate) { this.store = store; this.surrogate = surrogate; this.format = fetchFormat(surrogate); } private StorageFormat fetchFormat(final Document surrogate) { String format = surrogate.getString(MongoFileConstants.format); if (format == null) { format = surrogate.getString(MongoFileConstants.compressionFormat); } if (format == null) { return StorageFormat.GRIDFS; } return StorageFormat.find(format); } /** * Construct a MongoFile object for writing data * * @param collection * @param url */ /* package */MongoFile(final MongoFileStore store, final MongoFileUrl url, final long chunkSize) { this.store = store; this.format = url.getFormat(); surrogate = new Document(); surrogate.put(MongoFileConstants._id.toString(), url.getMongoFileId()); surrogate.put(MongoFileConstants.uploadDate.toString(), new Date()); surrogate.put(MongoFileConstants.chunkSize.toString(), chunkSize); surrogate.put(MongoFileConstants.filename.toString(), url.getFilePath()); surrogate.put(MongoFileConstants.contentType.toString(), url.getMediaType()); if (url.getFormat() != null) { surrogate.put(MongoFileConstants.format.toString(), url.getFormat().getCode()); } } // // logic methods // ////////////////// private String getBucketName() { return store.getFilesCollection().getName().split("\\.")[0]; } /** * Saves the file entry meta data to the files collection * * @throws MongoException */ public void save() { store.getFilesCollection().save(surrogate); } /** * Verifies that the MD5 matches between the database and the local file. This should be called after transferring a file. * * @throws MongoException */ public void validate() { MongoFileConstants md5key = MongoFileConstants.md5; String md5 = getString(md5key); if (md5 == null) { throw new MongoException("no md5 stored"); } Document cmd = new Document("filemd5", get(MongoFileConstants._id)); cmd.put("root", getBucketName()); Document res = store.getFilesCollection().getDatabase().executeCommand(cmd).getResponse(); if (res != null && res.containsKey(md5key.toString())) { String m = res.get(md5key.toString()).toString(); if (m.equals(md5)) { return; } throw new MongoException("md5 differ. mine [" + md5 + "] theirs [" + m + "]"); } // no md5 from the server throw new MongoException("no md5 returned from server: " + res); } public MongoFileUrl getURL() throws MalformedURLException { // compression and encrypted read from stored format
URL url = Parser.construct(getId(), getFilename(), getContentType(), this.format);
1
konachan700/JNekoImageDB
src/main/java/ui/dialogs/windows/MainWindow.java
[ "public interface UseServices {\n\tInitService initService = new InitService();\n\n\tdefault <T> T getService(Class<T> clazz) {\n\t\tif (initService.getServices() == null || !initService.getServices().containsKey(clazz)) {\n\t\t\tthrow new IllegalStateException(\"Class \\\"\" + clazz + \"\\\" not found in list of s...
import javafx.event.ActionEvent; import javafx.scene.layout.VBox; import proto.UseServices; import ui.StyleParser; import ui.annotation.style.CssStyle; import ui.annotation.style.HasStyledElements; import ui.dialogs.activities.engine.ActivityHolder; import ui.dialogs.activities.MainActivity; import ui.dialogs.activities.TagsEditorActivity; import ui.dialogs.activities.engine.EditorActivity; import ui.dialogs.windows.engine.DefaultWindow; import ui.elements.PanelButton; import ui.elements.entity.GlobalConfigUiEntity;
package ui.dialogs.windows; @HasStyledElements public class MainWindow extends DefaultWindow implements UseServices { private final ActivityHolder activityHolder = this.getActivityHolder(); private final MainActivity mainActivity = new MainActivity(activityHolder); private final GlobalConfigUiEntity uiEntity = new GlobalConfigUiEntity();
private final EditorActivity editorActivity = new EditorActivity(activityHolder, uiEntity, (a,b) -> {
5
thom-nic/openfire-jboss-clustering
src/main/java/com/enernoc/rnd/openfire/cluster/session/ClusteredClientSession.java
[ "public class ClientSessionTask extends RemoteSessionTask {\r\n private JID address;\r\n\r\n public ClientSessionTask() {\r\n super();\r\n }\r\n\r\n public ClientSessionTask(JID address, Operation operation) {\r\n super(operation);\r\n this.address = address;\r\n }\r\n\r\n pro...
import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.dom4j.Element; import org.dom4j.tree.DefaultElement; import org.jivesoftware.openfire.SessionManager; import org.jivesoftware.openfire.privacy.PrivacyList; import org.jivesoftware.openfire.privacy.PrivacyListManager; import org.jivesoftware.openfire.session.ClientSession; import org.jivesoftware.openfire.session.ClientSessionInfo; import org.jivesoftware.openfire.session.Session; import org.jivesoftware.openfire.user.UserNotFoundException; import org.jivesoftware.util.cache.Cache; import org.jivesoftware.util.cache.ClusterTask; import org.jivesoftware.util.cache.ExternalizableUtil; import org.xmpp.packet.JID; import org.xmpp.packet.Packet; import org.xmpp.packet.Presence; import com.enernoc.rnd.openfire.cluster.session.task.ClientSessionTask; import com.enernoc.rnd.openfire.cluster.session.task.DeliverRawTextTask; import com.enernoc.rnd.openfire.cluster.session.task.RemoteSessionTask; import com.enernoc.rnd.openfire.cluster.session.task.RemoteSessionTask.Operation; import com.enernoc.rnd.openfire.cluster.task.ProcessPacketTask;
/** * 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.enernoc.rnd.openfire.cluster.session; /** * This class acts as a remote proxy to send requests to a remote client session. * @author tnichols */ public class ClusteredClientSession extends ClusterSession implements ClientSession { private long initialized = -1; public ClusteredClientSession() {} public ClusteredClientSession( JID jid, byte[] nodeID ) { super( jid, nodeID ); } @Override void doCopy( Session s ) { ClientSession cs = (ClientSession)s; this.initialized = cs.isInitialized() ? 1 : 0; } @Override void doReadExternal( ExternalizableUtil ext, ObjectInput in ) throws IOException, ClassNotFoundException { this.initialized = ext.readLong(in); } @Override void doWriteExternal( ExternalizableUtil ext, ObjectOutput out ) throws IOException { ext.writeLong(out, this.initialized ); } public boolean canFloodOfflineMessages() { // Code copied from LocalClientSession to avoid remote calls if(isOfflineFloodStopped()) { return false; } String username = getAddress().getNode(); for (ClientSession session : SessionManager.getInstance().getSessions(username)) { if (session.isOfflineFloodStopped()) { return false; } } return true; } public PrivacyList getActiveList() { Cache<String, ClientSessionInfo> cache = SessionManager.getInstance().getSessionInfoCache(); ClientSessionInfo sessionInfo = cache.get(getAddress().toString()); if (sessionInfo != null && sessionInfo.getActiveList() != null) { return PrivacyListManager.getInstance().getPrivacyList(address.getNode(), sessionInfo.getActiveList()); } return null; } public PrivacyList getDefaultList() { Cache<String, ClientSessionInfo> cache = SessionManager.getInstance().getSessionInfoCache(); ClientSessionInfo sessionInfo = cache.get(getAddress().toString()); if (sessionInfo != null && sessionInfo.getDefaultList() != null) { return PrivacyListManager.getInstance().getPrivacyList(address.getNode(), sessionInfo.getDefaultList()); } return null; } public Presence getPresence() { Cache<String,ClientSessionInfo> cache = SessionManager.getInstance().getSessionInfoCache(); ClientSessionInfo sessionInfo = cache.get(getAddress().toString()); if (sessionInfo != null) { return sessionInfo.getPresence(); } return null; } public String getUsername() throws UserNotFoundException { return address.getNode(); } public boolean isAnonymousUser() { return SessionManager.getInstance().isAnonymousRoute(getAddress()); } public boolean isInitialized() { if (initialized == -1) { Presence presence = getPresence(); if (presence != null && presence.isAvailable()) { // Optimization to avoid making a remote call initialized = 1; } else {
ClusterTask task = getRemoteSessionTask(RemoteSessionTask.Operation.isInitialized);
3
SpongeBobSun/Prodigal
app/src/main/java/bob/sun/bender/view/WheelView.java
[ "public interface OnTickListener {\n public void onNextTick();\n public void onPreviousTick();\n public SelectionDetail getCurrentSelection();\n}", "public class Theme {\n\n static private Theme defaultTheme;\n\n class Icons {\n @SerializedName(\"next\")\n public String icNext;\n ...
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.PointF; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Region; import android.graphics.Shader; import android.os.Build; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import bob.sun.bender.BuildConfig; import bob.sun.bender.R; import bob.sun.bender.controller.OnButtonListener; import bob.sun.bender.controller.OnTickListener; import bob.sun.bender.theme.Theme; import bob.sun.bender.theme.ThemeManager; import bob.sun.bender.utils.AppConstants; import bob.sun.bender.utils.VibrateUtil;
package bob.sun.bender.view; /** * Created by bob.sun on 2015/4/23. */ public class WheelView extends View { private Point center; private Path viewBound; private int radiusOut,radiusIn; private Paint paintOut, paintIn, ripplePaint; private OnTickListener onTickListener; private float startDeg = Float.NaN; private OnButtonListener onButtonListener; private float buttonWidth, buttonHeight;
private Theme theme;
1
dkhmelenko/Varis-Android
app/src/main/java/com/khmelenko/lab/varis/repositories/RepositoriesPresenter.java
[ "public final class Constants {\n\n // denied constructor\n private Constants() {\n }\n\n /**\n * URL for open source projects\n */\n public static final String OPEN_SOURCE_TRAVIS_URL = \"https://api.travis-ci.org\";\n\n /**\n * URL for private projects\n */\n public static fina...
import com.khmelenko.lab.varis.common.Constants; import com.khmelenko.lab.varis.mvp.MvpPresenter; import com.khmelenko.lab.varis.network.response.Repo; import com.khmelenko.lab.varis.network.response.User; import com.khmelenko.lab.varis.network.retrofit.travis.TravisRestClient; import com.khmelenko.lab.varis.storage.AppSettings; import com.khmelenko.lab.varis.storage.CacheStorage; import com.khmelenko.lab.varis.util.StringUtils; import java.util.List; import javax.inject.Inject; import io.reactivex.SingleSource; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers;
package com.khmelenko.lab.varis.repositories; /** * Repositories presenter * * @author Dmytro Khmelenko (d.khmelenko@gmail.com) */ public class RepositoriesPresenter extends MvpPresenter<RepositoriesView> { private final TravisRestClient mTravisRestClient;
private final CacheStorage mCache;
5
mziccard/secureit
src/main/java/me/ziccard/secureit/async/upload/BluetoothPeriodicPositionUploaderTask.java
[ "public class SecureItPreferences {\n\t\n\tprivate SharedPreferences appSharedPrefs;\n private Editor prefsEditor;\n \n public static final String LOW = \"Low\";\n public static final String MEDIUM = \"Medium\";\n public static final String HIGH = \"High\";\n \n public static final String FRONT...
import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Date; import me.ziccard.secureit.SecureItPreferences; import me.ziccard.secureit.bluetooth.ObjectBluetoothSocket; import me.ziccard.secureit.config.Remote; import me.ziccard.secureit.messages.BluetoothMessage; import me.ziccard.secureit.messages.KeyRequest; import me.ziccard.secureit.messages.MessageBuilder; import me.ziccard.secureit.messages.MessageType; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast;
/* * Copyright (c) 2013-2015 Marco Ziccardi, Luca Bonato * Licensed under the MIT license. */ package me.ziccard.secureit.async.upload; public class BluetoothPeriodicPositionUploaderTask extends AsyncTask<Void, Void, Void> { private Context context; /** * Boolean true iff last thread iterations position has been sent */ private boolean dataSent = false; private SecureItPreferences prefs; /** * Adapter for bluetooth services */ private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); /** * Creates a BroadcastReceiver for ACTION_FOUND and ACTION_DISCOVERY_FINISHED */ private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { private ArrayList<BluetoothDevice> devices = new ArrayList<BluetoothDevice>(); @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); devices.add(device); Log.i("BluetoothPeriodicPositionUploaderTask", "Discovered "+device.getName()); CharSequence text = "Discovered "+device.getName(); int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); return; } // When ending the discovery if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { for (BluetoothDevice device : devices){ Log.i("DISCOVERY", "FINISHED"); try { BluetoothSocket tmp = null; tmp = device.createInsecureRfcommSocketToServiceRecord(Remote.BLUETOOTH_UUID); if (tmp != null) { Log.i("BluetoothPeriodicPositionUploaderTask", "Trying to connect to " + device.getName()); adapter.cancelDiscovery(); tmp.connect(); Log.i("BluetoothPeriodicPositionUploaderTask", "Connected to " + device.getName()); ObjectBluetoothSocket socket = new ObjectBluetoothSocket(tmp); MessageBuilder builder = new MessageBuilder(); builder.setPhoneId(phoneId); builder.setTimestamp(new Date()); //Sending hello message
BluetoothMessage message = builder.buildMessage(MessageType.HELLO);
6
Fedict/dcattools
scrapers/src/main/java/be/fedict/dcat/scrapers/wiv/HtmlWIV.java
[ "public class Cache {\n private static final Logger logger = LoggerFactory.getLogger(Cache.class);\n \n private DB db = null;\n private static final String CACHE = \"cache\";\n private static final String URLS = \"urls\";\n private static final String PAGES = \"pages\";\n\n /**\n * Stor...
import be.fedict.dcat.scrapers.Cache; import be.fedict.dcat.scrapers.Page; import be.fedict.dcat.helpers.Storage; import be.fedict.dcat.scrapers.Html; import be.fedict.dcat.vocab.MDR_LANG; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import javax.swing.text.html.HTML.Attribute; import org.jsoup.Jsoup; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.vocabulary.DCAT; import org.eclipse.rdf4j.model.vocabulary.DCTERMS; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.repository.RepositoryException;
/* * Copyright (c) 2020, FPS BOSA DG DT * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package be.fedict.dcat.scrapers.wiv; /** * Scraper WIV-ISP Covid data * * @see https://epistat.wiv-isp.be/covid/ * @author Bart Hanssens */ public class HtmlWIV extends Html { private final static String H_TITLE = "h2"; private final static String SECTION_P = "section#Covid p"; private final static String DIST_ROW = "table.table tbody tr"; private final static String HREFS = "a"; @Override protected List<URL> scrapeDatasetList() throws IOException { List<URL> urls = new ArrayList<>(); urls.add(getBase()); return urls; } /** * Generate DCAT distribution. * * @param store RDF store * @param dataset URI * @param access access URL of the dataset * @param row row element * @param lang language code * @throws MalformedURLException * @throws RepositoryException */ private void generateDist(Storage store, IRI dataset, URL access, Elements rows, String lang) throws MalformedURLException, RepositoryException { for (Element row: rows) { Elements cols = row.select("td"); String title = cols.get(0).ownText().trim(); Element link = cols.get(1).selectFirst(HREFS); String href = link.attr(Attribute.HREF.toString()); URL download = makeAbsURL(href); String ftype = link.text().trim(); URL u = makeDistURL(makeHashId(title) + "/" + ftype); IRI dist = store.getURI(u.toString()); logger.debug("Generating distribution {}", dist.toString()); store.add(dataset, DCAT.HAS_DISTRIBUTION, dist); store.add(dist, RDF.TYPE, DCAT.DISTRIBUTION); store.add(dist, DCTERMS.LANGUAGE, MDR_LANG.MAP.get(lang)); store.add(dist, DCTERMS.TITLE, title, lang); store.add(dist, DCAT.ACCESS_URL, access); store.add(dist, DCAT.DOWNLOAD_URL, download); store.add(dist, DCAT.MEDIA_TYPE, ftype.toLowerCase()); } } /** * Generate DCAT Dataset * * @param store RDF store * @param id dataset id * @param page * @throws MalformedURLException * @throws RepositoryException */ @Override protected void generateDataset(Storage store, String id, Map<String, Page> page) throws MalformedURLException, RepositoryException { String lang = getDefaultLang(); Page p = page.getOrDefault("", new Page()); String html = p.getContent(); URL u = p.getUrl(); Element content = Jsoup.parse(html).body(); IRI dataset = store.getURI(makeDatasetURL(makeHashId(id)).toString()); logger.debug("Generating dataset {}", dataset.toString()); Element h2 = content.select(H_TITLE).first(); if (h2 == null) { logger.warn("Empty title, skipping"); return; } String title = h2.text().trim(); Element div = content.select(SECTION_P).first(); String desc = (div != null) ? div.text() : title; store.add(dataset, RDF.TYPE, DCAT.DATASET); store.add(dataset, DCTERMS.LANGUAGE, MDR_LANG.MAP.get(lang)); store.add(dataset, DCTERMS.TITLE, title, lang); store.add(dataset, DCTERMS.DESCRIPTION, desc, lang); store.add(dataset, DCTERMS.IDENTIFIER, makeHashId(id)); store.add(dataset, DCAT.LANDING_PAGE, u); Elements dist = content.select(DIST_ROW); generateDist(store, dataset, u, dist, lang); } /** * Generate DCAT. * * @param cache * @param store * @throws RepositoryException * @throws MalformedURLException */ @Override
public void generateDcat(Cache cache, Storage store)
0
D-3/BS808
app/src/main/java/com/deew/bs808/MainActivity.java
[ "public class ClientConstants {\n\n public static final String PREF_FILE_NAME = \"client_preferences\";\n\n // Preference keys\n public static final String PREF_KEY_HOST = \"host\";\n public static final String PREF_KEY_PORT = \"port\";\n public static final String PREF_KEY_AUTH_CODE = \"auth_code\";...
import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.deew.jt808.ClientConstants; import com.deew.jt808.ClientStateCallback; import com.deew.jt808.JT808Client; import com.deew.jt808.msg.AuthenticateRequest; import com.deew.jt808.msg.LocationMessage; import com.deew.jt808.msg.RegisterReply; import com.deew.jt808.msg.RegisterRequest; import com.deew.jt808.msg.ServerGenericReply; import com.deew.jt808.util.LogUtils; import java.util.Timer; import java.util.TimerTask;
package com.deew.bs808; public class MainActivity extends AppCompatActivity implements ClientStateCallback, View.OnClickListener{ private static final String TAG = LogUtils.makeTag(MainActivity.class); private SharedPreferences mPrefs; private String mHost; private int mPort; private String mAuthCode; private JT808Client mJT808Client; private RegisterRequest.Builder mRegisterReqBuilder; private AuthenticateRequest.Builder mAuthReqBuilder; private LocationMessage.Builder mLocationMessageBuilder; private Timer mTimer; private Button mBtnRegister; private Button mBtnAuth; private Button mBtnLocation; private Button mBtnClose; private Button mBtnConnect; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtnRegister = (Button) findViewById(R.id.btn_regsiter); mBtnRegister.setOnClickListener(this); mBtnAuth = (Button) findViewById(R.id.btn_auth); mBtnAuth.setOnClickListener(this); mBtnLocation = (Button) findViewById(R.id.btn_location); mBtnLocation.setOnClickListener(this); mBtnClose = (Button) findViewById(R.id.btn_close); mBtnClose.setOnClickListener(this); mBtnConnect = (Button) findViewById(R.id.btn_connect); mBtnConnect.setOnClickListener(this); mPrefs = getSharedPreferences(ClientConstants.PREF_FILE_NAME, MODE_PRIVATE); mHost = mPrefs.getString(ClientConstants.PREF_KEY_HOST, ClientConstants.PREF_DEFAULT_HOST); mPort = mPrefs.getInt(ClientConstants.PREF_KEY_PORT, ClientConstants.PREF_DEFAULT_PORT); mAuthCode = mPrefs.getString(ClientConstants.PREF_KEY_AUTH_CODE, null); mRegisterReqBuilder = new RegisterRequest.Builder(); mLocationMessageBuilder = new LocationMessage.Builder(); mJT808Client = new JT808Client(); } @Override protected void onDestroy() { super.onDestroy(); mJT808Client.close(); mJT808Client = null; } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_regsiter: if(mJT808Client != null && mJT808Client.isConnected()){ registerClient(); } break; case R.id.btn_auth: if(mJT808Client != null && mJT808Client.isConnected()){ authenticate(mAuthCode); } break; case R.id.btn_location: if(mJT808Client != null && mJT808Client.isConnected()){ sendLocation(); } break; case R.id.btn_close: if (mJT808Client != null && mJT808Client.isConnected()){ mJT808Client.close(); } break; case R.id.btn_connect: if (mJT808Client != null){ connectToServer(mHost, mPort); } break; } } private void connectToServer(String host, int port){ mJT808Client.connect(host, port, this); } private void registerClient(){ RegisterRequest request = new RegisterRequest.Builder().build(); mJT808Client.registerClient(request); } private void authenticate(String authCode){ if(authCode == null){ Toast.makeText(this, "鉴权码为空", Toast.LENGTH_SHORT).show(); return; } mJT808Client.authenticate(mAuthCode); } @Override public void connectSuccess() { Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show(); if(mAuthCode == null){ registerClient(); }else{ authenticate(mAuthCode); } } @Override public void connectFail() { Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show(); } @Override public void connectionClosed() { Toast.makeText(this, "已关闭连接", Toast.LENGTH_SHORT).show(); } @Override
public void registerComplete(RegisterReply reply) {
5
Catalysts/cat-boot
cat-boot-report-pdf/src/main/java/cc/catalysts/boot/report/pdf/PdfReportBuilder.java
[ "public class PdfPageLayout {\n\n private float width;\n private float height;\n private float marginLeft;\n private float marginRight;\n private float marginTop;\n private float marginBottom;\n private float lineDistance;\n private float header;\n private float footer;\n private Posit...
import cc.catalysts.boot.report.pdf.config.PdfPageLayout; import cc.catalysts.boot.report.pdf.config.PdfTextStyle; import cc.catalysts.boot.report.pdf.elements.ReportElement; import cc.catalysts.boot.report.pdf.utils.PdfFontContext; import cc.catalysts.boot.report.pdf.utils.PositionOfStaticElements; import org.apache.pdfbox.pdmodel.PDDocument; import org.springframework.core.io.Resource; import java.io.IOException;
package cc.catalysts.boot.report.pdf; /** * @author Klaus Lehner */ public interface PdfReportBuilder { PdfReportBuilder addElement(ReportElement element); PdfReportBuilder addHeading(String heading); PdfReportBuilder addImage(Resource resource, float width, float height) throws IOException; PdfReportBuilder addImageWithMaxSize(Resource resource, float width, float height) throws IOException; PdfReportBuilder addLink(String text, String link); PdfReportBuilder addPadding(float padding); PdfReportBuilder addText(String text); PdfReportBuilder addText(String text, PdfTextStyle textConfig); PdfReportBuilder beginNewSection(String title, boolean startNewPage);
PdfReport buildReport(String fileName, PdfPageLayout pageConfig, Resource templateResource) throws IOException;
0
MinecraftForge/Srg2Source
src/test/java/net/minecraftforge/srg2source/test/SimpleTestBase.java
[ "public class RangeApplierBuilder {\n private PrintStream logStd = System.out;\n private PrintStream logErr = System.err;\n private List<InputSupplier> inputs = new ArrayList<>();\n private OutputSupplier output = null;\n private Consumer<RangeApplier> range = null;\n private List<Consumer<RangeAp...
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import org.junit.Assert; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import net.minecraftforge.srg2source.api.RangeApplierBuilder; import net.minecraftforge.srg2source.api.RangeExtractorBuilder; import net.minecraftforge.srg2source.api.SourceVersion; import net.minecraftforge.srg2source.apply.RangeApplier; import net.minecraftforge.srg2source.extract.RangeExtractor; import net.minecraftforge.srg2source.util.Util; import net.minecraftforge.srg2source.util.io.FolderSupplier;
/* * Srg2Source * Copyright (c) 2020. * * This library 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 version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.srg2source.test; public abstract class SimpleTestBase { private static final String FORGE_MAVEN = "https://maven.minecraftforge.net/"; protected abstract String getPrefix(); protected abstract List<String> getLibraries(); protected RangeExtractorBuilder customize(RangeExtractorBuilder builder) { return builder; };
protected RangeApplierBuilder customize(RangeApplierBuilder builder) { return builder; };
0
kawasima/solr-jdbc
src/main/java/net/unit8/solr/jdbc/command/DeleteCommand.java
[ "public class Parameter implements Item {\n private static final String SQL_WILDCARD_CHARS = \"%_%_\";\n\n\tprivate SolrValue value;\n\tprivate int index;\n\tprivate boolean needsLikeEscape;\n\tprivate String likeEscapeChar = \"%\";\n\tprivate Expression targetColumn;\n\n\tpublic Parameter(int index) {\n\t\tthis...
import net.sf.jsqlparser.statement.delete.Delete; import net.unit8.solr.jdbc.expression.Parameter; import net.unit8.solr.jdbc.impl.AbstractResultSet; import net.unit8.solr.jdbc.impl.DatabaseMetaDataImpl; import net.unit8.solr.jdbc.message.DbException; import net.unit8.solr.jdbc.message.ErrorCode; import net.unit8.solr.jdbc.parser.ConditionParser; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import java.io.IOException; import java.util.ArrayList;
package net.unit8.solr.jdbc.command; public class DeleteCommand extends Command { private transient final Delete delStmt; private ConditionParser conditionParser; public DeleteCommand(Delete stmt) { this.parameters = new ArrayList<Parameter>(); this.delStmt = stmt; } @Override public AbstractResultSet executeQuery() {
throw DbException.get(ErrorCode.METHOD_ONLY_ALLOWED_FOR_QUERY);
4
johndavidbustard/RoughWorld
src/utils/shapes/skinned/Animate.java
[ "public class GeneralMatrixDouble implements Serializable\r\n{\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic static final double EPSILON=5.9e-8f;\r\n\tpublic int width; //columns\r\n\tpublic int height; //rows\r\n\tpublic double[] value; //array of values\r\n\r\n\tpublic static void main(St...
import utils.GeneralMatrixDouble; import utils.GeneralMatrixFloat; import utils.GeneralMatrixInt; import utils.GeneralMatrixObject; import utils.GeneralMatrixString; import utils.Quaternion; import utils.shapes.human.HumanBones;
float f0 = 1.0f-f1; apos = pPose+f1; if(f1==0.0f) { for(int li=0;li<lposes.width;li++) { lpos.value[li] = lposes.value[pPose*lposes.width+li]; } } else { for(int li=0;li<lposes.width;li++) { lpos.value[li] = lposes.value[pPose*lposes.width+li]*f0+lposes.value[nPose*lposes.width+li]*f1; } } } public static float animate(float times,GeneralMatrixFloat frames,GeneralMatrixFloat lposes, GeneralMatrixFloat lpos) { float apos = 0.0f; int olw = lpos.width; int olh = lpos.height; lpos.setDimensions(lposes.width, 1); float pFrame = 0.0f; float nFrame = 0.0f; int pPose = -1; int nPose = -1; for(int i=0;i<frames.height;i++) { float f = frames.value[i]; if(f<times) { pFrame = f; pPose = i; } else { nFrame = f; nPose = i; break; } } if(pPose==-1) { apos = nPose; for(int li=0;li<lposes.width;li++) { lpos.value[li] = lposes.value[nPose*lposes.width+li]; } } else if(nPose==-1) { apos = pPose; for(int li=0;li<lposes.width;li++) { lpos.value[li] = lposes.value[pPose*lposes.width+li]; } } else { float dp = times-pFrame; float dn = nFrame-times; float d = nFrame-pFrame; if(d<GeneralMatrixFloat.EPSILON) { if(dp<dn) { apos = pPose; for(int li=0;li<lposes.width;li++) { lpos.value[li] = lposes.value[pPose*lposes.width+li]; } } else { apos = nPose; for(int li=0;li<lposes.width;li++) { lpos.value[li] = lposes.value[nPose*lposes.width+li]; } } } //* else { float f1 = dp/d; float f0 = 1.0f-f1; apos = pPose+f1; for(int li=0;li<lposes.width;li++) { lpos.value[li] = lposes.value[pPose*lposes.width+li]*f0+lposes.value[nPose*lposes.width+li]*f1; } } } lpos.width = olw; lpos.height = olh; return apos; } public static void blend(float f,GeneralMatrixFloat pbmats,GeneralMatrixFloat nbmats,GeneralMatrixFloat bmats) { float[] qa = new float[4]; float[] qb = new float[4]; float[] qc = new float[4]; for(int i=0;i<nbmats.height;i++) { int mo = i*9; Quaternion.MatrixtoQuaternion(pbmats.value,mo, qa); Quaternion.MatrixtoQuaternion(nbmats.value,mo, qb); Quaternion.slerp(qa, qb, f, qc); Quaternion.QuaterniontoMatrix(qc, bmats.value, mo); } }
public static void updateVposFromBmats(GeneralMatrixInt bones,
2
OpenIchano/Viewer
src/com/zhongyun/viewer/MyViewerHelper.java
[ "public class CameraInfo {\n\n\tprivate long cid;\n\tprivate String cameraName;\n\tprivate String cameraUser;\n\tprivate String cameraPwd;\n\tprivate Bitmap cameraThumb;\n\tprivate boolean isOnline;\n\tprivate boolean pwdIsRight;\n\tprivate String os;\n\t\n\tpublic void setCid(long cid){\n\t\tthis.cid = cid;\n\t}\n...
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.widget.Toast; import com.ichano.rvs.viewer.Viewer; import com.ichano.rvs.viewer.bean.StreamerInfo; import com.ichano.rvs.viewer.callback.RecvJpegListener; import com.ichano.rvs.viewer.constant.LoginError; import com.ichano.rvs.viewer.constant.LoginState; import com.ichano.rvs.viewer.constant.RvsJpegType; import com.ichano.rvs.viewer.constant.RvsSessionState; import com.ichano.rvs.viewer.constant.StreamerConfigState; import com.ichano.rvs.viewer.constant.StreamerPresenceState; import com.ichano.rvs.viewer.ui.ViewerInitHelper; import com.zhongyun.viewer.db.CameraInfo; import com.zhongyun.viewer.db.CameraInfoManager; import com.zhongyun.viewer.login.UserInfo; import com.zhongyun.viewer.utils.Constants; import com.zhongyun.viewer.utils.ImageDownloader; import com.zhongyun.viewer.utils.PrefUtils;
/* * Copyright (C) 2015 iChano incorporation's Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zhongyun.viewer; public class MyViewerHelper extends ViewerInitHelper{ private static final String TAG = "MyViewerHelper"; private static MyViewerHelper mViewer; private UserInfo mUserInfo; private LoginListener mLoginListener; private List<CameraStateListener> mCameraStateListeners = new ArrayList<CameraStateListener>(); private static List<CameraInfo> mCameraInfos;
private static CameraInfoManager mCameraInfoManager;
1
w-shackleton/droidpad-android
src/uk/digitalsquid/droidpad/layout/XmlDecoder.java
[ "public interface LogTag {\n\tstatic final String TAG = \"droidpad\";\n}", "public class Button extends Item {\n\tprivate static final long serialVersionUID = -7921469580817352801L;\n\t\n\tpublic final String text;\n\tpublic final int textSize;\r\n\t\r\n\tprivate boolean resetButton;\r\n\t\n\tprotected boolean tm...
import java.io.IOException; import java.io.Reader; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import uk.digitalsquid.droidpad.LogTag; import uk.digitalsquid.droidpad.buttons.Button; import uk.digitalsquid.droidpad.buttons.Layout; import uk.digitalsquid.droidpad.buttons.ModeSpec; import uk.digitalsquid.droidpad.buttons.Orientation; import uk.digitalsquid.droidpad.buttons.Slider; import uk.digitalsquid.droidpad.buttons.ToggleButton; import uk.digitalsquid.droidpad.buttons.TouchPanel; import android.sax.Element; import android.sax.ElementListener; import android.sax.RootElement; import android.sax.TextElementListener;
/* This file is part of DroidPad. * * DroidPad 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. * * DroidPad 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 DroidPad. If not, see <http://www.gnu.org/licenses/>. */ package uk.digitalsquid.droidpad.layout; public class XmlDecoder implements LogTag { private XmlDecoder() {} private static final SAXParserFactory factory = SAXParserFactory.newInstance();
public static final ModeSpec decodeLayout(Reader stream) throws IOException {
3
berlinguyinca/spectra-hash
core/src/main/java/edu/ucdavis/fiehnlab/spectra/hash/core/impl/SplashVersion1.java
[ "public interface Spectrum {\n\n /**\n * ion of a spectra\n * @return\n */\n public List<Ion> getIons();\n\n /**\n * convmerts the spectrum to a relative spectra\n * @return\n * @param scale\n */\n Spectrum toRelative(int scale);\n\n /**\n *\n * @return\n */\n ...
import edu.ucdavis.fiehnlab.spectra.hash.core.Spectrum; import edu.ucdavis.fiehnlab.spectra.hash.core.Splash; import edu.ucdavis.fiehnlab.spectra.hash.core.listener.SplashBlock; import edu.ucdavis.fiehnlab.spectra.hash.core.listener.SplashListener; import edu.ucdavis.fiehnlab.spectra.hash.core.listener.SplashingEvent; import edu.ucdavis.fiehnlab.spectra.hash.core.sort.IntensityThenMassComparator; import edu.ucdavis.fiehnlab.spectra.hash.core.sort.MassThenIntensityComparator; import edu.ucdavis.fiehnlab.spectra.hash.core.types.Ion; import edu.ucdavis.fiehnlab.spectra.hash.core.types.SpectraType; import edu.ucdavis.fiehnlab.spectra.hash.core.types.SpectrumImpl; import org.apache.commons.codec.digest.DigestUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque;
package edu.ucdavis.fiehnlab.spectra.hash.core.impl; /** * the reference implementation of the Spectral Hash Key */ public class SplashVersion1 implements Splash { private static final int PREFILTER_BASE = 3; private static final int PREFILTER_LENGTH = 10; private static final int PREFILTER_BIN_SIZE = 5; private static final int SIMILARITY_BASE = 10; private static final int SIMILARITY_LENGTH = 10; private static final int SIMILARITY_BIN_SIZE = 100; private static final char[] BASE_36_MAP = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; /** * how to scale the spectrum */ public static final int scalingOfRelativeIntensity = 100; /** * how should ions in the string representation be separeted */ private static final String ION_SEPERATOR = " "; /** * how many character should be in the spectrum block. Basically this reduces the SHA256 code down * to a fixed length of N characater */ private static final int maxCharactersForSpectrumBlockTruncation = 20; /** * Fixed precission of masses */ private static final int fixedPrecissionOfMasses = 6; /** * factor to scale m/z floating point values */ private static final long MZ_PRECISION_FACTOR = (long)Math.pow(10, fixedPrecissionOfMasses); /** * Fixed precission of intensites */ private static final int fixedPrecissionOfIntensities = 0; /** * factor to scale m/z floating point values */ private static final long INTENSITY_PRECISION_FACTOR = (long)Math.pow(10, fixedPrecissionOfIntensities); /** * Correction factor to avoid floating point issues between implementations * and processor architectures */ private static final double EPS_CORRECTION = 1.0e-7; /** * registered listeneres */ private ConcurrentLinkedDeque<SplashListener> listeners = new ConcurrentLinkedDeque<SplashListener>(); /** * adds a new listener * * @param listener listener */ public void addListener(SplashListener listener) { this.listeners.add(listener); } /** * notify listeners * * @param e event */
protected void notifyListener(SplashingEvent e) {
4
piyell/NeteaseCloudMusic
app/src/main/java/com/zsorg/neteasecloudmusic/activities/ConfigActivity.java
[ "public class ConfigAdapter extends RecyclerView.Adapter<ConfigHolder> implements OnItemCLickListener {\n\n private final LayoutInflater mInflater;\n private List<ConfigBean> mList;\n private OnItemCLickListener onItemCLickListener;\n\n public ConfigAdapter(LayoutInflater layoutInflater) {\n supe...
import android.content.Context; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import com.zsorg.neteasecloudmusic.adapters.ConfigAdapter; import com.zsorg.neteasecloudmusic.LineItemDecorator; import com.zsorg.neteasecloudmusic.R; import com.zsorg.neteasecloudmusic.models.beans.ConfigBean; import com.zsorg.neteasecloudmusic.presenters.ConfigPresenter; import com.zsorg.neteasecloudmusic.views.IConfigView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife;
package com.zsorg.neteasecloudmusic.activities; public class ConfigActivity extends AppCompatActivity implements View.OnClickListener, IConfigView { @BindView(R.id.rv_config) RecyclerView rvConfig; private ConfigAdapter mAdapter; private ConfigPresenter mPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_config); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (null!=actionBar) { actionBar.setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(this); } ButterKnife.bind(this); rvConfig.setLayoutManager(new LinearLayoutManager(this));
rvConfig.addItemDecoration(LineItemDecorator.getInstance());
1
ykaragol/checkersmaster
CheckersMaster/test/checkers/algorithm/TestGreedyAlgorithm.java
[ "public class CalculationContext{\r\n\r\n\tprivate int depth;\r\n\tprivate Player player;\r\n\tprivate IEvaluation evaluationFunction;\r\n\tprivate ISuccessor successorFunction;\r\n\tprivate IAlgorithm algorithm;\r\n\r\n\r\n\tpublic void setDepth(int depth) {\r\n\t\tthis.depth = depth;\r\n\t}\r\n\r\n\tpublic int ge...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import checkers.domain.CalculationContext; import checkers.domain.Model; import checkers.domain.Move; import checkers.domain.Player; import checkers.evaluation.MenCountEvaluation; import checkers.rules.Successors; import checkers.sandbox.SquareState;
package checkers.algorithm; public class TestGreedyAlgorithm { private GreedyAlgorithm algorithm;
private CalculationContext context;
0
sfPlayer1/Matcher
src/matcher/type/ClassInstance.java
[ "public enum NameType {\n\tPLAIN(true, false, false, 0),\n\tMAPPED(false, true, false, 0),\n\tAUX(false, false, false, 1),\n\tAUX2(false, false, false, 2),\n\n\tMAPPED_PLAIN(true, true, false, 0),\n\tMAPPED_AUX_PLAIN(true, true, false, 1),\n\tMAPPED_AUX2_PLAIN(true, true, false, 2),\n\tMAPPED_TMP_PLAIN(true, true, ...
import java.net.URI; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import matcher.NameType; import matcher.SimilarityChecker; import matcher.Util; import matcher.bcremap.AsmClassRemapper; import matcher.bcremap.AsmRemapper; import matcher.classifier.ClassifierUtil; import matcher.type.Signature.ClassSignature;
} ret = sb.toString(); } return full ? ret : ret.substring(ret.lastIndexOf('.') + 1); } public boolean isReal() { return origin != null; } public URI getOrigin() { return origin; } @Override public Matchable<?> getOwner() { return null; } @Override public ClassEnv getEnv() { return env; } public ClassNode[] getAsmNodes() { return asmNodes; } public URI getAsmNodeOrigin(int index) { if (index < 0 || index > 0 && (asmNodeOrigins == null || index >= asmNodeOrigins.length)) throw new IndexOutOfBoundsException(index); return index == 0 ? origin : asmNodeOrigins[index]; } public ClassNode getMergedAsmNode() { if (asmNodes == null) return null; if (asmNodes.length == 1) return asmNodes[0]; return asmNodes[0]; // TODO: actually merge } void addAsmNode(ClassNode node, URI origin) { if (!input) throw new IllegalStateException("not mergeable"); asmNodes = Arrays.copyOf(asmNodes, asmNodes.length + 1); asmNodes[asmNodes.length - 1] = node; if (asmNodeOrigins == null) { asmNodeOrigins = new URI[2]; asmNodeOrigins[0] = this.origin; } else { asmNodeOrigins = Arrays.copyOf(asmNodeOrigins, asmNodeOrigins.length + 1); } asmNodeOrigins[asmNodeOrigins.length - 1] = origin; } @Override public boolean hasPotentialMatch() { if (matchedClass != null) return true; if (!isMatchable()) return false; for (ClassInstance o : env.getOther().getClasses()) { if (o.isReal() && ClassifierUtil.checkPotentialEquality(this, o)) return true; } return false; } @Override public boolean isMatchable() { return matchable; } @Override public boolean setMatchable(boolean matchable) { if (!matchable && matchedClass != null) return false; this.matchable = matchable; return true; } @Override public ClassInstance getMatch() { return matchedClass; } public void setMatch(ClassInstance cls) { assert cls == null || isMatchable(); assert cls == null || cls.getEnv() != env && !cls.getEnv().isShared(); this.matchedClass = cls; } @Override public boolean isFullyMatched(boolean recursive) { if (matchedClass == null) return false; for (MethodInstance m : methods) { if (m.hasPotentialMatch() && (!m.hasMatch() || recursive && !m.isFullyMatched(true))) { return false; } } for (FieldInstance m : fields) { if (m.hasPotentialMatch() && (!m.hasMatch() || recursive && !m.isFullyMatched(true))) { return false; } } return true; } @Override public float getSimilarity() { if (matchedClass == null) return 0;
return SimilarityChecker.compare(this, matchedClass);
1
otto-de/edison-jobtrigger
src/main/java/de/otto/edison/jobtrigger/trigger/TriggerService.java
[ "@Component\n@ConfigurationProperties(prefix = \"edison.jobtrigger\")\npublic class JobTriggerProperties {\n\n @Valid\n private Jobresults jobresults = new Jobresults();\n\n @Valid\n private Scheduler scheduler = new Scheduler();\n\n @Valid\n private Security security = new Security();\n\n\n pu...
import de.otto.edison.jobtrigger.configuration.JobTriggerProperties; import de.otto.edison.jobtrigger.definition.JobDefinition; import de.otto.edison.jobtrigger.discovery.DiscoveryListener; import de.otto.edison.jobtrigger.discovery.DiscoveryService; import de.otto.edison.jobtrigger.security.BasicAuthCredentials; import org.asynchttpclient.AsyncHttpClient; import org.asynchttpclient.Response; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.scheduling.Trigger; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.net.ConnectException; import java.util.ArrayList; import java.util.Deque; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import static de.otto.edison.jobtrigger.trigger.TriggerStatus.fromHttpStatus; import static de.otto.edison.jobtrigger.trigger.TriggerStatus.fromMessage; import static de.otto.edison.jobtrigger.trigger.Triggers.periodicTrigger; import static java.lang.String.valueOf; import static java.time.Duration.of; import static java.time.temporal.ChronoUnit.MINUTES; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toList; import static org.slf4j.LoggerFactory.getLogger;
package de.otto.edison.jobtrigger.trigger; /** * @author Guido Steinacker * @since 05.09.15 */ @Service @EnableConfigurationProperties(JobTriggerProperties.class) public class TriggerService implements DiscoveryListener { private static final Logger LOG = getLogger(TriggerService.class); private DiscoveryService discoveryService; private JobScheduler scheduler; private AsyncHttpClient httpClient; private final TriggerRunnablesService triggerRunnablesService; private int maxJobResults = 1000; private final Deque<TriggerResult> lastResults = new ConcurrentLinkedDeque<>(); private final AtomicBoolean isStarted = new AtomicBoolean(false); private final AtomicLong currentIndex = new AtomicLong(0); private BasicAuthCredentials basicAuthCredentials; @Autowired public TriggerService(final DiscoveryService discoveryService, final JobScheduler scheduler, final AsyncHttpClient httpClient, final JobTriggerProperties jobTriggerProperties, final BasicAuthCredentials basicAuthCredentials, final TriggerRunnablesService triggerRunnablesService) { this.discoveryService = discoveryService; this.scheduler = scheduler; this.httpClient = httpClient; this.maxJobResults = jobTriggerProperties.getJobresults().getMax(); this.basicAuthCredentials = basicAuthCredentials; this.triggerRunnablesService = triggerRunnablesService; } @PostConstruct public void postConstruct() { discoveryService.register(this); } public void startTriggering() { final List<JobDefinition> jobDefinitions = discoveryService.allJobDefinitions(); scheduler.updateTriggers(jobDefinitions .stream() .filter(jobDefinition -> jobDefinition.getFixedDelay().isPresent() || jobDefinition.getCron().isPresent()) .map(toJobTrigger()) .collect(toList())); isStarted.set(true); } public void stopTriggering() { scheduler.stopAllTriggers(); isStarted.set(false); } @Override public void updatedJobDefinitions() { startTriggering(); } public boolean isStarted() { return isStarted.get(); } public List<TriggerResult> getLastResults() { return new ArrayList<>(lastResults); } private Runnable runnableFor(final JobDefinition jobDefinition) { return triggerRunnablesService.httpTriggerRunnable(jobDefinition, new DefaultTriggerResponseConsumer(jobDefinition)); } private Function<JobDefinition, JobTrigger> toJobTrigger() { return jobDefinition -> { try { return new JobTrigger(jobDefinition, triggerFor(jobDefinition), runnableFor(jobDefinition)); } catch (final Exception e) { final Runnable failingJobRunnable = () -> { lastResults.addFirst(new TriggerResult(nextId(), fromMessage(e.getMessage()), emptyMessage(), jobDefinition)); };
return new JobTrigger(jobDefinition, periodicTrigger(of(10, MINUTES)), failingJobRunnable);
7
domenique/tripled-framework
eventstore-core/src/test/java/eu/tripledframework/eventstore/infrastructure/ReflectionObjectConstructorTest.java
[ "public class DomainEvent {\n\n private String id;\n private String aggregateRootIdentifier;\n private int revision;\n private ZonedDateTime timestamp;\n\n public DomainEvent(String aggregateRootIdentifier) {\n this.id = UUID.randomUUID().toString();\n this.aggregateRootIdentifier = agg...
import eu.tripledframework.eventstore.domain.DomainEvent; import eu.tripledframework.eventstore.domain.MyAggregateRoot; import eu.tripledframework.eventstore.domain.NotInstantiatableAggregateRoot; import eu.tripledframework.eventstore.domain.ObjectConstructor; import eu.tripledframework.eventstore.event.AddressUpdatedEvent; import eu.tripledframework.eventstore.event.AddressUpdatedEventWhichCannotBeInvoked; import eu.tripledframework.eventstore.event.MyAggregateRootCreatedEvent; import eu.tripledframework.eventstore.event.UnMappedEvent; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.sameInstance; import static org.hamcrest.MatcherAssert.assertThat;
/* * Copyright 2015 TripleD framework. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.tripledframework.eventstore.infrastructure; public class ReflectionObjectConstructorTest { @Test void whenGivenAnEmptyListOfEvents_ShouldReturnNull() { // given ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class); // when MyAggregateRoot object = objectConstructor.construct(Collections.emptyList()); // then assertThat(object, nullValue()); } @Test void whenGivenANullEventList_ShouldReturnNull() { // given ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class); // when MyAggregateRoot object = objectConstructor.construct(null); // then assertThat(object, nullValue()); } @Test void whenGivenAnEmptyListOfEventsAndAnInstance_ShouldReturnInstance() { // given ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class); // when MyAggregateRoot instance = new MyAggregateRoot("id", "name"); MyAggregateRoot object = objectConstructor.applyDomainEvents(instance, Collections.emptyList()); // then assertThat(object, sameInstance(instance)); } @Test void whenGivenAnNullListOfEventsAndAnInstance_ShouldReturnInstance() { // given ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class); // when MyAggregateRoot instance = new MyAggregateRoot("id", "name"); MyAggregateRoot object = objectConstructor.applyDomainEvents(instance, null); // then assertThat(object, sameInstance(instance)); } @Test void whenGivenOneEvent_ShouldCreateInstance() { // given String sourceIdentifier = UUID.randomUUID().toString(); MyAggregateRootCreatedEvent event = new MyAggregateRootCreatedEvent(sourceIdentifier, "Wallstreet"); ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class); // when MyAggregateRoot instance = objectConstructor.construct(Arrays.asList(event)); // then assertThat(instance.identifier, equalTo(sourceIdentifier)); assertThat(instance.name, equalTo(event.getName())); assertThat(instance.address, nullValue()); assertThat(instance.postReconstructCalled, is(true)); assertThat(event.getId(), notNullValue()); assertThat(event.getAggregateRootIdentifier(), notNullValue()); assertThat(event.getTimestamp(), notNullValue()); } @Test void whenGivenTwoEvents_ShouldCreateInstanceWithEventsReplayed() { // given String sourceIdentifier = UUID.randomUUID().toString(); MyAggregateRootCreatedEvent event = new MyAggregateRootCreatedEvent(sourceIdentifier, "Wallstreet"); AddressUpdatedEvent secondEvent = new AddressUpdatedEvent(sourceIdentifier, "streetName streetNumber"); ObjectConstructor<MyAggregateRoot> objectConstructor = new ReflectionObjectConstructor<>(MyAggregateRoot.class); // when MyAggregateRoot instance = objectConstructor.construct(Arrays.asList(event, secondEvent)); // then assertThat(instance.identifier, equalTo(sourceIdentifier)); assertThat(instance.name, equalTo(event.getName())); assertThat(instance.address, equalTo(secondEvent.getAddress())); assertThat(instance.postReconstructCalled, is(true)); } @Test void whenGivenTwoEventsOutOfOrder_ShouldThrowException() { // given String identifier = UUID.randomUUID().toString();
DomainEvent event = new MyAggregateRootCreatedEvent(identifier, "Wallstreet");
0
emina/kodkod
src/kodkod/util/nodes/PrettyPrinter.java
[ "public final class Decl extends Decls {\n\t\n private final Variable variable;\n private final Multiplicity mult;\n private final Expression expression;\n \n /** \n * Constructs a new declaration from the specified variable and\n * expression, with the specified order.\n * \n * @ens...
import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import kodkod.ast.BinaryExpression; import kodkod.ast.BinaryFormula; import kodkod.ast.BinaryIntExpression; import kodkod.ast.ComparisonFormula; import kodkod.ast.Comprehension; import kodkod.ast.ConstantExpression; import kodkod.ast.ConstantFormula; import kodkod.ast.Decl; import kodkod.ast.Decls; import kodkod.ast.ExprToIntCast; import kodkod.ast.Expression; import kodkod.ast.Formula; import kodkod.ast.IfExpression; import kodkod.ast.IfIntExpression; import kodkod.ast.IntComparisonFormula; import kodkod.ast.IntConstant; import kodkod.ast.IntExpression; import kodkod.ast.IntToExprCast; import kodkod.ast.LeafExpression; import kodkod.ast.MultiplicityFormula; import kodkod.ast.NaryExpression; import kodkod.ast.NaryFormula; import kodkod.ast.NaryIntExpression; import kodkod.ast.Node; import kodkod.ast.NotFormula; import kodkod.ast.ProjectExpression; import kodkod.ast.QuantifiedFormula; import kodkod.ast.Relation; import kodkod.ast.RelationPredicate; import kodkod.ast.SumExpression; import kodkod.ast.UnaryExpression; import kodkod.ast.UnaryIntExpression; import kodkod.ast.Variable; import kodkod.ast.operator.ExprOperator; import kodkod.ast.operator.FormulaOperator; import kodkod.ast.operator.IntOperator; import kodkod.ast.operator.Multiplicity; import kodkod.ast.visitor.VoidVisitor;
/** @ensures appends the tokenization of the given node to this.tokens */ public void visit(ProjectExpression node) { append("project"); append("["); node.expression().accept(this); comma(); append("<"); final Iterator<IntExpression> cols = node.columns(); cols.next().accept(this); while(cols.hasNext()) { comma(); cols.next().accept(this); } append(">"); append("]"); } /** @ensures this.tokens' = concat[ this.tokens, "Int","[", * tokenize[node.intExpr], "]" ] **/ public void visit(IntToExprCast node) { append("Int"); append("["); node.intExpr().accept(this); append("]"); } /** @ensures this.tokens' = concat[ this.tokens, "int","[", * tokenize[node.expression], "]" ] **/ public void visit(ExprToIntCast node) { switch(node.op()) { case SUM: append("int"); append("["); node.expression().accept(this); append("]"); break; case CARDINALITY : append("#"); append("("); node.expression().accept(this); append(")"); break; default : throw new IllegalArgumentException("unknown operator: " + node.op()); } } /** @ensures appends the tokenization of the given node to this.tokens */ public void visit(RelationPredicate node) { switch(node.name()) { case ACYCLIC : append("acyclic"); append("["); node.relation().accept(this); append("]"); break; case FUNCTION : RelationPredicate.Function func = (RelationPredicate.Function)node; append("function"); append("["); func.relation().accept(this); colon(); func.domain().accept(this); infix("->"); keyword(func.targetMult()); func.range().accept(this); append("]"); break; case TOTAL_ORDERING : RelationPredicate.TotalOrdering ord = (RelationPredicate.TotalOrdering)node; append("ord"); append("["); ord.relation().accept(this); comma(); ord.ordered().accept(this); comma(); ord.first().accept(this); comma(); ord.last().accept(this); append("]"); break; default: throw new AssertionError("unreachable"); } } } private static class Dotifier implements VoidVisitor { private final StringBuilder graph = new StringBuilder(); private final Map<Node,Integer> ids = new LinkedHashMap<Node, Integer>(); static String apply(Node node) { final Dotifier dot = new Dotifier(); dot.graph.append("digraph {\n"); node.accept(dot); dot.graph.append("}"); return dot.graph.toString(); } private boolean visited(Node n) { if (ids.containsKey(n)) return true; ids.put(n, ids.size()); return false; } private String id(Node n) { return "N" + ids.get(n); } private void node(Node n, String label) { graph.append(id(n)); graph.append("[ label=\"" ); graph.append(ids.get(n)); graph.append("("); graph.append(label); graph.append(")\"];\n"); } private void edge(Node n1, Node n2) {
if (n2 instanceof LeafExpression || n2 instanceof ConstantFormula || n2 instanceof IntConstant) {
3
ralscha/wampspring
src/test/java/ch/rasc/wampspring/call/CallTest.java
[ "public class CallErrorMessage extends WampMessage {\n\tprivate final String callID;\n\n\tprivate final String errorURI;\n\n\tprivate final String errorDesc;\n\n\tprivate final Object errorDetails;\n\n\tpublic CallErrorMessage(CallMessage callMessage, String errorURI, String errorDesc) {\n\t\tthis(callMessage, erro...
import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ch.rasc.wampspring.config.EnableWamp; import ch.rasc.wampspring.message.CallErrorMessage; import ch.rasc.wampspring.message.CallMessage; import ch.rasc.wampspring.message.CallResultMessage; import ch.rasc.wampspring.message.WampMessage; import ch.rasc.wampspring.testsupport.BaseWampTest;
/** * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.wampspring.call; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = CallTest.Config.class) public class CallTest extends BaseWampTest { @Test public void testCallArguments() throws Exception { WampMessage receivedMessage = sendWampMessage( new CallMessage("callID", "callService.simpleTest", "argument", 12)); assertThat(receivedMessage).isInstanceOf(CallResultMessage.class); CallResultMessage result = (CallResultMessage) receivedMessage; assertThat(result.getCallID()).isEqualTo("callID"); assertThat(result.getResult()).isNull(); } @Test public void testNoParameters() throws Exception { WampMessage receivedMessage = sendWampMessage( new CallMessage("callID2", "callService.noParams")); assertThat(receivedMessage).isInstanceOf(CallResultMessage.class); CallResultMessage result = (CallResultMessage) receivedMessage; assertThat(result.getCallID()).isEqualTo("callID2"); assertThat(result.getResult()).isEqualTo("nothing here"); } @Test public void testCallOwnProcUri() throws Exception { WampMessage receivedMessage = sendWampMessage( new CallMessage("theCallId", "myOwnProcURI", "argument", 13)); assertThat(receivedMessage).isInstanceOf(CallResultMessage.class); CallResultMessage result = (CallResultMessage) receivedMessage; assertThat(result.getCallID()).isEqualTo("theCallId"); assertThat(result.getResult()).isNull(); } @Test public void testReturnValue() throws Exception { WampMessage receivedMessage = sendWampMessage( new CallMessage("12", "callService.sum", 3, 4)); assertThat(receivedMessage).isInstanceOf(CallResultMessage.class); CallResultMessage result = (CallResultMessage) receivedMessage; assertThat(result.getCallID()).isEqualTo("12"); assertThat(result.getResult()).isEqualTo(7); } @Test public void testWithError() throws Exception { WampMessage receivedMessage = sendWampMessage( new CallMessage("13", "callService.error", "theArgument"));
assertThat(receivedMessage).isInstanceOf(CallErrorMessage.class);
0
aNNiMON/HotaruFX
app/src/main/java/com/annimon/hotarufx/visual/PropertyType.java
[ "public class FontValue extends MapValue {\n\n public static Font toFont(MapValue mapValue) {\n final var map = mapValue.getMap();\n final var family = map.getOrDefault(\"family\", new StringValue(Font.getDefault().getFamily())).asString();\n final var weight = map.getOrDefault(\"weight\", N...
import com.annimon.hotarufx.lib.FontValue; import com.annimon.hotarufx.lib.MapValue; import com.annimon.hotarufx.lib.NodeValue; import com.annimon.hotarufx.lib.NumberValue; import com.annimon.hotarufx.lib.StringValue; import com.annimon.hotarufx.lib.Types; import com.annimon.hotarufx.lib.Value; import com.annimon.hotarufx.visual.objects.ObjectNode; import com.annimon.hotarufx.visual.visitors.NodeVisitor; import java.util.function.Function; import javafx.scene.Node; import javafx.scene.paint.Color; import javafx.scene.text.Font;
package com.annimon.hotarufx.visual; public enum PropertyType { BOOLEAN(Value::asBoolean, o -> NumberValue.fromBoolean(Boolean.TRUE.equals(o))), NUMBER(toNumber(), o -> NumberValue.of((Number) o)), STRING(Value::asString, o -> new StringValue(String.valueOf(o))), NODE(toNode(), fromNode()), CLIP_NODE(toClipNode(), fromNode()), PAINT(v -> Color.valueOf(v.asString()), o -> new StringValue(o.toString())), FONT(toFont(), object -> new FontValue((Font) object)); PropertyType(Function<Value, Object> fromHFX, Function<Object, Value> toHFX) { this.fromHFX = fromHFX; this.toHFX = toHFX; } private final Function<Value, Object> fromHFX; private final Function<Object, Value> toHFX; @SuppressWarnings("unchecked") public <T> Function<Value, T> getFromHFX() { return (Function<Value, T>) fromHFX; } @SuppressWarnings("unchecked") public <T> Function<T, Value> getToHFX() { return (Function<T, Value>) toHFX; } private static Function<Value, Object> toNumber() { return value -> { if (value.type() == Types.NUMBER) { return ((NumberValue) value).raw(); } return value.asDouble(); }; } private static Function<Value, Object> toNode() { return v -> ((NodeValue)v).getNode().getFxNode(); } private static Function<Value, Object> toClipNode() { return v -> {
ObjectNode node = ((NodeValue) v).getNode();
7
utapyngo/owl2vcs
src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.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 org.semanticweb.owlapi.change.OWLOntologyChangeDataVisitor; import owl2vcs.changes.AddPrefixData; import owl2vcs.changes.ModifyPrefixData; import owl2vcs.changes.RemovePrefixData; import owl2vcs.changes.RenamePrefixData; import owl2vcs.changes.SetOntologyFormatData;
package owl2vcs.changeset; public interface CustomOntologyChangeDataVisitor<R, E extends Exception> extends OWLOntologyChangeDataVisitor<R, E> {
R visit(SetOntologyFormatData data) throws E;
4
GoogleCloudPlatform/opentelemetry-operations-java
exporters/metrics/src/test/java/com/google/cloud/opentelemetry/metric/MetricTranslatorTest.java
[ "static final DoublePointData aDoublePoint =\n DoublePointData.create(\n 1599030114 * NANO_PER_SECOND,\n 1599031814 * NANO_PER_SECOND,\n Attributes.of(stringKey(\"label1\"), \"value1\", booleanKey(\"label2\"), false),\n 32d);", "static final DoubleSummaryPointData aDoubleSummaryPoin...
import static com.google.cloud.opentelemetry.metric.FakeData.aDoublePoint; import static com.google.cloud.opentelemetry.metric.FakeData.aDoubleSummaryPoint; import static com.google.cloud.opentelemetry.metric.FakeData.aGceResource; import static com.google.cloud.opentelemetry.metric.FakeData.aHistogramPoint; import static com.google.cloud.opentelemetry.metric.FakeData.aLongPoint; import static com.google.cloud.opentelemetry.metric.FakeData.aMetricData; import static com.google.cloud.opentelemetry.metric.FakeData.anInstrumentationLibraryInfo; import static com.google.cloud.opentelemetry.metric.MetricTranslator.DESCRIPTOR_TYPE_URL; import static com.google.cloud.opentelemetry.metric.MetricTranslator.METRIC_DESCRIPTOR_TIME_UNIT; import static io.opentelemetry.api.common.AttributeKey.booleanKey; import static io.opentelemetry.api.common.AttributeKey.longKey; import static io.opentelemetry.api.common.AttributeKey.stringKey; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import com.google.api.Distribution; import com.google.api.LabelDescriptor; import com.google.api.LabelDescriptor.ValueType; import com.google.api.Metric; import com.google.api.Metric.Builder; import com.google.api.MetricDescriptor; import com.google.api.MetricDescriptor.MetricKind; import com.google.common.collect.ImmutableList; import com.google.monitoring.v3.DroppedLabels; import com.google.monitoring.v3.SpanContext; import com.google.protobuf.InvalidProtocolBufferException; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.DoubleHistogramData; import io.opentelemetry.sdk.metrics.data.DoubleSumData; import io.opentelemetry.sdk.metrics.data.DoubleSummaryData; import io.opentelemetry.sdk.metrics.data.LongSumData; import io.opentelemetry.sdk.metrics.data.MetricData; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2022 Google * * 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.cloud.opentelemetry.metric; @RunWith(JUnit4.class) public class MetricTranslatorTest { @Test public void testMapMetricSucceeds() { String type = "custom.googleapis.com/OpenTelemetry/" + anInstrumentationLibraryInfo.getName(); Builder expectedMetricBuilder = Metric.newBuilder().setType(type); aLongPoint .getAttributes() .forEach((k, v) -> expectedMetricBuilder.putLabels(k.getKey(), v.toString())); Metric actualMetric = MetricTranslator.mapMetric(aLongPoint.getAttributes(), type); assertEquals(expectedMetricBuilder.build(), actualMetric); } @Test public void testMapMetricWithWierdAttributeNameSucceeds() { String type = "custom.googleapis.com/OpenTelemetry/" + anInstrumentationLibraryInfo.getName(); Attributes attributes = io.opentelemetry.api.common.Attributes.of(stringKey("test.bad"), "value"); Metric expectedMetric = Metric.newBuilder().setType(type).putLabels("test_bad", "value").build(); Metric actualMetric = MetricTranslator.mapMetric(attributes, type); assertEquals(expectedMetric, actualMetric); } @Test public void testMapMetricDescriptorSucceeds() { MetricDescriptor.Builder expectedDescriptor = MetricDescriptor.newBuilder() .setDisplayName(aMetricData.getName()) .setType(DESCRIPTOR_TYPE_URL + aMetricData.getName()) .addLabels(LabelDescriptor.newBuilder().setKey("label1").setValueType(ValueType.STRING)) .addLabels(LabelDescriptor.newBuilder().setKey("label2").setValueType(ValueType.BOOL))
.setUnit(METRIC_DESCRIPTOR_TIME_UNIT)
8
kennylbj/concurrent-java
src/main/java/producerconsumer/Main.java
[ "public class BlockingQueueConsumer implements Consumer<Item>, Runnable {\n private final BlockingQueue<Item> buffer;\n private final Random random = new Random(System.nanoTime());\n\n public BlockingQueueConsumer(BlockingQueue<Item> buffer) {\n this.buffer = buffer;\n }\n\n @Override\n pub...
import producerconsumer.blockingqueue.BlockingQueueConsumer; import producerconsumer.blockingqueue.BlockingQueueProducer; import producerconsumer.condition.ConditionConsumer; import producerconsumer.condition.ConditionProducer; import producerconsumer.semaphore.SemaphoreConsumer; import producerconsumer.semaphore.SemaphoreProducer; import java.util.concurrent.*; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;
package producerconsumer; /** * Created by kennylbj on 16/9/10. * Implement 3 versions of P/C * 1) use Semaphore * 2) use Condition * 3) use BlockingQueue * All versions support multiple producers and consumers */ public class Main { private static final int BUFFER_SIZE = 100; private static final int PRODUCER_NUM = 3; private static final int CONSUMER_NUM = 2; public static void main(String[] args) throws InterruptedException { ExecutorService pool = Executors.newCachedThreadPool(); // Buffers of all P/C Buffer<Item> semaphoreBuffer = new LinkListBuffer(BUFFER_SIZE); Buffer<Item> conditionBuffer = new LinkListBuffer(BUFFER_SIZE); BlockingQueue<Item> blockingQueueBuffer = new LinkedBlockingQueue<>(BUFFER_SIZE); // Semaphores for Semaphore version of P/C Semaphore fullCount = new Semaphore(0); Semaphore emptyCount = new Semaphore(BUFFER_SIZE); // Lock and conditions for Condition version of P/C Lock lock = new ReentrantLock(); Condition full = lock.newCondition(); Condition empty = lock.newCondition(); for (int i = 0; i < PRODUCER_NUM; i++) {
pool.execute(new SemaphoreProducer(semaphoreBuffer, fullCount, emptyCount));
5
mvescovo/item-reaper
app/src/testMock/java/com/michaelvescovo/android/itemreaper/item_details/ItemDetailsPresenterTest.java
[ "public interface DataSource {\n\n void getItems(@NonNull String userId, @NonNull String sortBy, @NonNull String caller,\n @NonNull GetItemsCallback callback);\n\n void getItem(@NonNull String itemId, @NonNull String userId, @NonNull String caller,\n @NonNull GetItemCallback c...
import com.google.firebase.auth.FirebaseAuth; import com.michaelvescovo.android.itemreaper.data.DataSource; import com.michaelvescovo.android.itemreaper.data.Item; import com.michaelvescovo.android.itemreaper.data.Repository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Arrays; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_1; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.ITEM_2; import static com.michaelvescovo.android.itemreaper.data.FakeDataSource.USER_ID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.verify;
package com.michaelvescovo.android.itemreaper.item_details; /** * @author Michael Vescovo */ @RunWith(Parameterized.class) public class ItemDetailsPresenterTest { private ItemDetailsPresenter mPresenter; @Mock private ItemDetailsContract.View mView; @Mock private Repository mRepository; @Mock private FirebaseAuth mFirebaseAuth; @Captor private ArgumentCaptor<DataSource.GetItemCallback> mItemCallbackCaptor; private Item mItem; public ItemDetailsPresenterTest(Item item) { mItem = item; } @Parameterized.Parameters public static Iterable<?> data() { return Arrays.asList( ITEM_1, ITEM_2 ); } @Before public void setup() { MockitoAnnotations.initMocks(this);
mPresenter = new ItemDetailsPresenter(mView, mRepository, USER_ID);
5
ceylon/ceylon-model
src/com/redhat/ceylon/model/loader/model/LazyModule.java
[ "public interface ArtifactResult {\n /**\n * Get name.\n *\n * @return the artifact name.\n */\n String name();\n\n /**\n * Get version.\n *\n * @return the version.\n */\n String version();\n\n /**\n * Get import type.\n *\n * @return the import type\n ...
import java.io.File; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.cmr.JDKUtils; import com.redhat.ceylon.model.cmr.PathFilter; import com.redhat.ceylon.model.loader.AbstractModelLoader; import com.redhat.ceylon.model.loader.ContentAwareArtifactResult; import com.redhat.ceylon.model.loader.JvmBackendUtil; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.ModuleImport; import com.redhat.ceylon.model.typechecker.model.Package;
package com.redhat.ceylon.model.loader.model; /** * Represents a lazy Module declaration. * * @author Stéphane Épardaud <stef@epardaud.fr> */ public abstract class LazyModule extends Module { private boolean isJava = false; protected Set<String> jarPackages = new HashSet<String>(); public LazyModule() { } @Override
public Package getDirectPackage(String name) {
7
fflewddur/archivo
src/net/straylightlabs/archivo/controller/ArchiveQueueManager.java
[ "public class Archivo extends Application {\n private Stage primaryStage;\n private final MAKManager maks;\n private final StringProperty statusText;\n private final ExecutorService rpcExecutor;\n private final UserPrefs prefs;\n private RootLayoutController rootController;\n private RecordingL...
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import net.straylightlabs.archivo.Archivo; import net.straylightlabs.archivo.model.ArchiveHistory; import net.straylightlabs.archivo.model.ArchiveStatus; import net.straylightlabs.archivo.model.Recording; import net.straylightlabs.archivo.model.Tivo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.LocalDate; import java.util.Observable; import java.util.concurrent.ConcurrentHashMap;
/* * Copyright 2015-2016 Todd Kulesza <todd@dropline.net>. * * This file is part of Archivo. * * Archivo 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. * * Archivo 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 Archivo. If not, see <http://www.gnu.org/licenses/>. */ package net.straylightlabs.archivo.controller; /** * Enqueue archive requests for processing via a background thread, and allow archive tasks to be canceled. * Alerts its observes when the queue size changes between empty and not-empty. */ public class ArchiveQueueManager extends Observable { private final Archivo mainApp; private final ExecutorService executorService; private final ConcurrentHashMap<Recording, ArchiveTask> queuedTasks; private final Lock downloadLock; private final Lock processingLock; private static final int POOL_SIZE = 2; private final static Logger logger = LoggerFactory.getLogger(ArchiveQueueManager.class); public ArchiveQueueManager(Archivo mainApp) { this.mainApp = mainApp; executorService = Executors.newFixedThreadPool(POOL_SIZE); downloadLock = new ReentrantLock(); processingLock = new ReentrantLock(); queuedTasks = new ConcurrentHashMap<>(); } public boolean enqueueArchiveTask(Recording recording, Tivo tivo, String mak) { try { ArchiveTask task = new ArchiveTask(recording, tivo, mak, mainApp.getUserPrefs(), downloadLock, processingLock); task.setOnRunning(event -> mainApp.setStatusText(String.format("Archiving %s...", recording.getFullTitle()))); task.setOnSucceeded(event -> { logger.info("ArchiveTask succeeded for {}", recording.getFullTitle()); updateArchiveHistory(recording); removeTask(recording); recording.setDateArchived(LocalDate.now());
recording.setStatus(ArchiveStatus.FINISHED);
2
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/util/CommitStatusUpdaterTest.java
[ "@ExportedBean\npublic final class CauseData {\n private final ActionType actionType;\n private final Integer sourceProjectId;\n private final Integer targetProjectId;\n private final String branch;\n private final String sourceBranch;\n private final String userName;\n private final String use...
import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.dabsquared.gitlabjenkins.cause.CauseData; import com.dabsquared.gitlabjenkins.cause.CauseDataBuilder; import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import com.dabsquared.gitlabjenkins.connection.GitLabConnectionConfig; import com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.BuildState; import com.dabsquared.gitlabjenkins.workflow.GitLabBranchBuild; import hudson.EnvVars; import hudson.Functions; import hudson.Util; import hudson.model.Cause; import hudson.model.Cause.UpstreamCause; import hudson.model.Item; import hudson.model.Run; import hudson.model.TaskListener; import hudson.plugins.git.Revision; import hudson.plugins.git.util.Build; import hudson.plugins.git.util.BuildData; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import jenkins.model.Jenkins; import org.eclipse.jgit.lib.ObjectId; import org.jenkinsci.plugins.displayurlapi.DisplayURLProvider; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.MockitoAnnotations;
package com.dabsquared.gitlabjenkins.util; /** * @author Daumantas Stulgis */ public class CommitStatusUpdaterTest { private static final int PROJECT_ID = 1; private static final String BUILD_URL = "job/Test-Job"; private static final String STAGE = "test"; private static final String REVISION = "1111111"; private static final String JENKINS_URL = "https://gitlab.org/jenkins/"; @Mock Run<?, ?> build; @Mock TaskListener taskListener; @Mock GitLabConnectionConfig gitLabConnectionConfig;
@Mock GitLabClient client;
3
MCUpdater/MCUpdater
MCU-API/src/org/mcupdater/util/ServerPackParser.java
[ "public class Version {\n\tpublic static final int MAJOR_VERSION;\n\tpublic static final int MINOR_VERSION;\n\tpublic static final int BUILD_VERSION;\n\tpublic static final String BUILD_BRANCH;\n\tpublic static final String BUILD_LABEL;\n\tstatic {\n\t\tProperties prop = new Properties();\n\t\ttry {\n\t\t\tprop.loa...
import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.mcupdater.Version; import org.mcupdater.model.ConfigFile; import org.mcupdater.model.GenericModule; import org.mcupdater.model.ModType; import org.mcupdater.model.Module; import org.mcupdater.model.PrioritizedURL; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;
NodeList nl; switch (version) { case 2: // Handle ServerPacks designed for MCUpdater 3.0 and later nl = docEle.getElementsByTagName("Import"); if(nl != null && nl.getLength() > 0) { for(int i = 0; i < nl.getLength(); i++) { Element el = (Element)nl.item(i); modList.addAll(doImportV2(el, dom)); } } nl = docEle.getElementsByTagName("Module"); if(nl != null && nl.getLength() > 0) { for(int i = 0; i < nl.getLength(); i++) { Element el = (Element)nl.item(i); Module m = getModuleV2(el); modList.add(m); } } return modList; case 1: // Handle ServerPacks designed for MCUpdater 2.7 and earlier nl = docEle.getElementsByTagName("Module"); if(nl != null && nl.getLength() > 0) { for(int i = 0; i < nl.getLength(); i++) { Element el = (Element)nl.item(i); Module m = getModuleV1(el); modList.add(m); } } return modList; default: return null; } } private static List<Module> doImportV2(Element el, Document dom) { String url = el.getAttribute("url"); if (!url.isEmpty()){ try { dom = readXmlFromUrl(url); } catch (DOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return parseDocument(dom, el.getTextContent()); } private static Module getModuleV2(Element el) { XPath xpath = XPathFactory.newInstance().newXPath(); try { String name = el.getAttribute("name"); String id = el.getAttribute("id"); String depends = el.getAttribute("depends"); String side = el.getAttribute("side"); List<PrioritizedURL> urls = new ArrayList<PrioritizedURL>(); NodeList nl; nl = (NodeList) xpath.evaluate("URL", el, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Element elURL = (Element) nl.item(i); String url = elURL.getTextContent(); int priority = parseInt(elURL.getAttribute("priority")); urls.add(new PrioritizedURL(url, priority)); } String path = (String) xpath.evaluate("ModPath", el, XPathConstants.STRING); Element elReq = (Element) el.getElementsByTagName("Required").item(0); boolean required; boolean isDefault; if (elReq == null) { required = true; isDefault = true; } else { required = parseBooleanWithDefault(elReq.getTextContent(),true); isDefault = parseBooleanWithDefault(elReq.getAttribute("isDefault"),false); } Element elType = (Element) el.getElementsByTagName("ModType").item(0); boolean inRoot = parseBooleanWithDefault(elType.getAttribute("inRoot"),false); int order = parseInt(elType.getAttribute("order")); boolean keepMeta = parseBooleanWithDefault(elType.getAttribute("keepMeta"),false); String launchArgs = elType.getAttribute("launchArgs"); String jreArgs = elType.getAttribute("jreArgs"); ModType modType = ModType.valueOf(elType.getTextContent()); boolean coremod = false; boolean jar = false; boolean library = false; boolean extract = false; boolean litemod = false; switch (modType) { case Coremod: coremod = true; break; case Extract: extract = true; break; case Jar: jar = true; break; case Library: library = true; break; case Litemod: litemod = true; break; case Option: throw new RuntimeException("Module type 'Option' not implemented"); default: break; } String md5 = (String) xpath.evaluate("MD5", el, XPathConstants.STRING);
List<ConfigFile> configs = new ArrayList<ConfigFile>();
1
Roba1993/octo-chat
src/main/java/de/robertschuette/octochat/chats/ChatHandler.java
[ "public class ChatData {\n private Chat chat;\n private String userId;\n private String userName;\n private String lastMessage;\n private String lastMessageTime;\n private boolean lastMessageUnread;\n private boolean isOnline;\n\n /**\n * Constructor to create a new chat data object.\n ...
import de.robertschuette.octochat.model.ChatData; import de.robertschuette.octochat.model.ChatDataStore; import de.robertschuette.octochat.model.ChatHandlerSettings; import de.robertschuette.octochat.model.ChatSettings; import de.robertschuette.octochat.util.Util; import javafx.scene.control.SplitPane; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import java.io.*; import java.util.ArrayList; import java.util.List;
package de.robertschuette.octochat.chats; /** * This class holds the main logic of this application and * routes the main actions. * * @author Robert Schütte */ public class ChatHandler extends SplitPane implements Runnable { private ChatDataStore cds; private List<Chat> chats; private StackPane chatArea; private Pane selectionArea; private ChatHandlerSettings chatHandlerSettings; private String xmlPath; public ChatHandler(String xmlPath) { this.xmlPath = xmlPath; // create the necessary objects chats = new ArrayList<>(); cds = new ChatDataStore(this); chatHandlerSettings = new ChatHandlerSettings(); // create the selection area selectionArea = new Pane(); // create chat area chatArea = new StackPane(); // add the panes this.getItems().addAll(selectionArea, chatArea); this.setDividerPositions(0.1f); // load the settings from the xml settings file loadChatHandlerState(); // when no chats exist - create fb and wa chat if(chats.size() < 1) { addChat(new ChatFacebook(this, new ChatSettings("Facebook"))); addChat(new ChatWhatsapp(this, new ChatSettings("Whats App"))); } // start this thread new Thread(this).start(); } /** * Register a new chat in this chat handler. The chat is now * clickable in the side and configurable over this handler. * * @param chat the chat to add */ public void addChat(Chat chat) { // add the chat to the list chats.add(chat); // set the chat not visible if one already exist if(chats.size() > 1) { chat.setVisible(false); } // add to chat window chatArea.getChildren().add(chat); // add the image addSelectionImage(chat, 0, chats.indexOf(chat) * 50); } /** * Removes the given chat from the handler. * * @param chat to remove */ public void removeChat(Chat chat) { // remove from the list chats.remove(chat); // remove from the chat area chatArea.getChildren().remove(chat); // redraw the selection area redrawSelectionArea(); } /** * This function updates a specific chat data. When a new * message was found, we send automatically a new notification. * * @param chatData the chatdata */
public void updateChatData(ChatData chatData) {
0
tangqifa/Common-App-Architecture
app/src/main/java/com/kejiwen/architecture/activity/ProductCustomerListActivity.java
[ "public class ListViewHelper<DATA> {\r\n private IDataAdapter<DATA> dataAdapter;\r\n private PullToRefreshAdapterViewBase<? extends ListView> pullToRefreshPinnedHeaderListView;\r\n private IDataSource<DATA> dataSource;\r\n private ListView mListView;\r\n private Context context;\r\n private OnStat...
import android.os.Bundle; import android.view.View; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.shizhefei.view.listviewhelper.ListViewHelper; import com.kejiwen.architecture.R; import com.kejiwen.architecture.adapter.ProductCustomerHistoryListAdapter; import com.kejiwen.architecture.adapter.ProductCustomerOnSellListAdapter; import com.kejiwen.architecture.biz.ProductCustomerHistoryDataSource; import com.kejiwen.architecture.biz.ProductCustomerOnsellDataSource; import com.kejiwen.architecture.listener.OnBackStackListener; import com.kejiwen.architecture.model.ProductItem; import java.util.List;
package com.kejiwen.architecture.activity; public class ProductCustomerListActivity extends BaseActivity implements OnBackStackListener, View.OnClickListener { private final static String TAG = "CustomerProductListActivity"; private ListViewHelper mListViewHelper; private ProductCustomerHistoryListAdapter mHistoryAdapter; private ProductCustomerOnSellListAdapter mOnSellAdapter; private int mListType; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.customer_product_list); super.onCreate(savedInstanceState); mListType = getIntent().getIntExtra("type",0); mTitleBar.setTitle("客户列表"); mTitleBar.setBackButton(R.mipmap.titlebar_back_arrow, this); PullToRefreshListView refreshListView = (PullToRefreshListView) findViewById(R.id.pullToRefreshListView); mListViewHelper = new ListViewHelper<List<ProductItem>>(refreshListView); if (mListType == 0) { // 设置数据源 mOnSellAdapter = new ProductCustomerOnSellListAdapter(this);
mListViewHelper.setDataSource(new ProductCustomerOnsellDataSource());
4
curtisullerich/attendance
src/main/java/edu/iastate/music/marching/attendance/model/interact/AbsenceManager.java
[ "public class Lang {\n\n\tpublic static final String ERROR_MESSAGE_NO_DIRECTOR = \"There is no director registered. You cannot register for an account yet.\";\n\tpublic static final String ERROR_INVALID_PRIMARY_REGISTER_EMAIL= \"Not a valid email, try logging in with your student account\";\n\tpublic static final ...
import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.code.twig.FindCommand.RootFindCommand; import com.google.code.twig.ObjectDatastore; import edu.iastate.music.marching.attendance.Lang; import edu.iastate.music.marching.attendance.model.store.Absence; import edu.iastate.music.marching.attendance.model.store.Event; import edu.iastate.music.marching.attendance.model.store.Form; import edu.iastate.music.marching.attendance.model.store.ModelFactory; import edu.iastate.music.marching.attendance.model.store.User;
LOG.warning("BLERG"); } formDayOnAbsenceWeek = aStart.withDayOfWeek(formDayOfWeek) .toDateMidnight(); break; case Tardy: DateTime checkin = absence.getCheckin(zone); formDayOnAbsenceWeek = checkin.withDayOfWeek(formDayOfWeek) .toDateMidnight(); break; case EarlyCheckOut: DateTime checkout = absence.getCheckout(zone); formDayOnAbsenceWeek = checkout.withDayOfWeek(formDayOfWeek) .toDateMidnight(); break; default: throw new UnsupportedOperationException(); } int minutesToOrFrom = form.getMinutesToOrFrom(); DateTime effectiveStartTime = form.getStartTime() .toDateTime(formDayOnAbsenceWeek).minusMinutes(minutesToOrFrom); DateTime effectiveEndTime = form.getEndTime() .toDateTime(formDayOnAbsenceWeek).plusMinutes(minutesToOrFrom); Interval effectiveFormInterval = new Interval(effectiveStartTime, effectiveEndTime); return effectiveFormInterval; } /** * This does not store any changes in the database! * * Note that this is only valid for forms A, B, and C. Form D has separate * validation that occurs when a Form D is approved AND verified. * * @param absence * @param form * @return */ private boolean shouldBeAutoApproved(Absence absence, Form form) { DateTimeZone zone = this.train.appData().get().getTimeZone(); if (form.getStatus() != Form.Status.Approved) { // form must be approved! return false; } if (absence.getStatus() != Absence.Status.Pending) { // only pending absences can be auto-approved return false; } if (form.getStudent() == null || absence.getStudent() == null) { throw new IllegalArgumentException( "Student was null in the absence or form."); } if (absence.getEvent() == null) { throw new IllegalArgumentException("Absence had a null event."); } if (!form.getStudent().equals(absence.getStudent())) { throw new IllegalArgumentException( "Can't check absence against a form from another student."); } switch (form.getType()) { case PerformanceAbsence: // Performance absence request if (absence.getEvent().getType() != Event.Type.Performance) { // nope! return false; } else { // TODO use Absence.isContainedIn(...)? if (form.getInterval(zone).contains( absence.getEvent().getInterval(zone))) { return true; } } break; case ClassConflict: Event e = absence.getEvent(); if (e.getType() != Event.Type.Rehearsal) { return false; } Interval effectiveFormInterval = getEffectiveFormInterval(absence, form, zone); return Absence.isContainedIn(absence, effectiveFormInterval); case TimeWorked: // this does not auto-approve here. It does that upon an upDateTime // of a // Form D in the forms controller break; } return false; } /** * This is deprecated because the start and end DateTime are not sufficient * to identify a single event. Type must also be specified. This is needed * in the current implementation of the mobile app, though. * * @param student * @param start * @param end * @return */ @Deprecated public Absence createOrUpdateAbsence(User student, Interval interval) { if (student == null) { throw new IllegalArgumentException(Lang.ERROR_ABSENCE_FOR_NULL_USER); }
Absence absence = ModelFactory
4
mangstadt/vinnie
src/main/java/com/github/mangstadt/vinnie/io/VObjectWriter.java
[ "public static String escapeNewlines(String string) {\n\tStringBuilder sb = null;\n\tchar prev = 0;\n\tfor (int i = 0; i < string.length(); i++) {\n\t\tchar c = string.charAt(i);\n\n\t\tif (c == '\\r' || c == '\\n') {\n\t\t\tif (sb == null) {\n\t\t\t\tsb = new StringBuilder(string.length() * 2);\n\t\t\t\tsb.append(...
import java.nio.charset.Charset; import java.util.List; import java.util.Map; import com.github.mangstadt.vinnie.SyntaxStyle; import com.github.mangstadt.vinnie.VObjectParameters; import com.github.mangstadt.vinnie.VObjectProperty; import com.github.mangstadt.vinnie.validate.AllowedCharacters; import com.github.mangstadt.vinnie.validate.VObjectValidator; import static com.github.mangstadt.vinnie.Utils.escapeNewlines; import java.io.Closeable; import java.io.Flushable; import java.io.IOException; import java.io.Writer;
/* * MIT License * * Copyright (c) 2016 Michael Angstadt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.mangstadt.vinnie.io; /** * <p> * Writes data to a vobject data stream. * </p> * <p> * <b>Example:</b> * </p> * * <pre class="brush:java"> * Writer writer = ... * VObjectWriter vobjectWriter = new VObjectWriter(writer, SyntaxStyle.NEW); * vobjectWriter.writeBeginComponent("VCARD"); * vobjectWriter.writeVersion("4.0"); * vobjectWriter.writeProperty("FN", "John Doe"); * vobjectWriter.writeEndComponent("VCARD"); * vobjectWriter.close(); * </pre> * * <p> * <b>Invalid characters</b> * </p> * <p> * If property data contains any invalid characters, the {@code writeProperty} * method throws an {@link IllegalArgumentException} and the property is not * written. A character is considered to be invalid if it cannot be encoded or * escaped, and would break the vobject syntax if written. * </p> * <p> * The rules regarding which characters are considered invalid is fairly * complex. Here are some general guidelines: * </p> * <ul> * <li>Try to limit group names, property names, and parameter names to * alphanumerics and hyphens.</li> * <li>Avoid the use of newlines, double quotes, and colons inside of parameter * values. They can be used in some contexts, but not others.</li> * </ul> * * <p> * <b>Newlines in property values</b> * </p> * <p> * All newline characters ("\r" or "\n") within property values are * automatically escaped. * </p> * <p> * In old-style syntax, the property value will be encoded in quoted-printable * encoding. * </p> * * <pre class="brush:java"> * StringWriter sw = new StringWriter(); * VObjectWriter vobjectWriter = new VObjectWriter(sw, SyntaxStyle.OLD); * vobjectWriter.writeProperty("NOTE", "one\r\ntwo"); * vobjectWriter.close(); * * assertEquals("NOTE;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:one=0D=0Atwo\r\n", sw.toString()); * </pre> * * <p> * In new-style syntax, the newline characters will be replaced with the "\n" * escape sequence (Windows newline sequences are replaced with a single "\n" * even though they consist of two characters). * </p> * * <pre class="brush:java"> * StringWriter sw = new StringWriter(); * VObjectWriter vobjectWriter = new VObjectWriter(sw, SyntaxStyle.NEW); * vobjectWriter.writeProperty("NOTE", "one\r\ntwo"); * vobjectWriter.close(); * * assertEquals("NOTE:one\\ntwo\r\n", sw.toString()); * </pre> * * <p> * <b>Quoted-printable Encoding</b> * </p> * <p> * If a property has a parameter named ENCODING that has a value of * QUOTED-PRINTABLE (case-insensitive), then the property's value will * automatically be written in quoted-printable encoding. * </p> * * <pre class="brush:java"> * StringWriter sw = new StringWriter(); * VObjectWriter vobjectWriter = new VObjectWriter(sw, ...); * * VObjectProperty note = new VObjectProperty("NOTE", "¡Hola, mundo!"); * note.getParameters().put("ENCODING", "QUOTED-PRINTABLE"); * vobjectWriter.writeProperty(note); * vobjectWriter.close(); * * assertEquals("NOTE;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:=C2=A1Hola, mundo!\r\n", sw.toString()); * </pre> * <p> * A nameless parameter may also be used for backwards compatibility with * old-style syntax. * </p> * * <pre class="brush:java"> * VObjectProperty note = new VObjectProperty("NOTE", "¡Hola, mundo!"); * note.getParameters().put(null, "QUOTED-PRINTABLE"); * vobjectWriter.writeProperty(note); * </pre> * <p> * By default, the property value is encoded under the UTF-8 character set when * encoded in quoted-printable encoding. This can be changed by specifying a * CHARSET parameter. If the character set is not recognized by the local JVM, * then UTF-8 will be used. * </p> * * <pre class="brush:java"> * StringWriter sw = new StringWriter(); * VObjectWriter vobjectWriter = new VObjectWriter(sw, ...); * * VObjectProperty note = new VObjectProperty("NOTE", "¡Hola, mundo!"); * note.getParameters().put("ENCODING", "QUOTED-PRINTABLE"); * note.getParameters().put("CHARSET", "Windows-1252"); * vobjectWriter.writeProperty(note); * vobjectWriter.close(); * * assertEquals("NOTE;ENCODING=QUOTED-PRINTABLE;CHARSET=Windows-1252:=A1Hola, mundo!\r\n", sw.toString()); * </pre> * * <p> * <b>Circumflex Accent Encoding</b> * </p> * <p> * Newlines and double quote characters are not permitted inside of parameter * values unless circumflex accent encoding is enabled. It is turned off by * default. * </p> * <p> * Note that this encoding mechanism is defined in a separate specification and * may not be supported by the consumer of the vobject data. Also note that it * can only be used with new-style syntax. * </p> * * <pre class="brush:java"> * StringWriter sw = new StringWriter(); * VObjectWriter vobjectWriter = new VObjectWriter(sw, SyntaxStyle.NEW); * vobjectWriter.setCaretEncodingEnabled(true); * * VObjectProperty note = new VObjectProperty("NOTE", "The truth is out there."); * note.getParameters().put("X-AUTHOR", "Fox \"Spooky\" Mulder"); * vobjectWriter.writeProperty(note); * vobjectWriter.close(); * * assertEquals("NOTE;X-AUTHOR=Fox ^'Spooky^' Mulder:The truth is out there.\r\n", sw.toString()); * </pre> * * <p> * <b>Line Folding</b> * </p> * <p> * Lines longer than 75 characters are automatically folded, as per the * vCard/iCalendar recommendation. * </p> * * <pre class="brush:java"> * StringWriter sw = new StringWriter(); * VObjectWriter vobjectWriter = new VObjectWriter(sw, ...); * * vobjectWriter.writeProperty("NOTE", "Lorem ipsum dolor sit amet\, consectetur adipiscing elit. Vestibulum ultricies tempor orci ac dignissim."); * vobjectWriter.close(); * * assertEquals( * "NOTE:Lorem ipsum dolor sit amet\\, consectetur adipiscing elit. Vestibulum u\r\n" + * " ltricies tempor orci ac dignissim.\r\n" * , sw.toString()); * </pre> * <p> * The line folding length can be adjusted to a length of your choosing. In * addition, passing in a "null" line length will disable line folding. * </p> * * <pre class="brush:java"> * StringWriter sw = new StringWriter(); * VObjectWriter vobjectWriter = new VObjectWriter(sw, ...); * vobjectWriter.getFoldedLineWriter().setLineLength(null); * * vobjectWriter.writeProperty("NOTE", "Lorem ipsum dolor sit amet\, consectetur adipiscing elit. Vestibulum ultricies tempor orci ac dignissim."); * vobjectWriter.close(); * * assertEquals("NOTE:Lorem ipsum dolor sit amet\\, consectetur adipiscing elit. Vestibulum ultricies tempor orci ac dignissim.\r\n", sw.toString()); * </pre> * * <p> * You may also specify what kind of folding whitespace to use. The default is a * single space character, but this can be changed to any combination of tabs * and spaces. Note that new-style syntax requires the folding whitespace to be * EXACTLY ONE character long. * </p> * * <pre class="brush:java"> * StringWriter sw = new StringWriter(); * VObjectWriter vobjectWriter = new VObjectWriter(sw, ...); * vobjectWriter.getFoldedLineWriter().setIndent("\t"); * * vobjectWriter.writeProperty("NOTE", "Lorem ipsum dolor sit amet\, consectetur adipiscing elit. Vestibulum ultricies tempor orci ac dignissim."); * vobjectWriter.close(); * * assertEquals( * "NOTE:Lorem ipsum dolor sit amet\\, consectetur adipiscing elit. Vestibulum u\r\n" + * "\tltricies tempor orci ac dignissim.\r\n" * , sw.toString()); * </pre> * @author Michael Angstadt */ public class VObjectWriter implements Closeable, Flushable { private final FoldedLineWriter writer; private boolean caretEncodingEnabled = false; private SyntaxStyle syntaxStyle; private final AllowedCharacters allowedPropertyNameChars; private final AllowedCharacters allowedGroupChars; private final AllowedCharacters allowedParameterNameChars; private AllowedCharacters allowedParameterValueChars; /** * Creates a new vobject writer. * @param writer the output stream * @param syntaxStyle the syntax style to use */ public VObjectWriter(Writer writer, SyntaxStyle syntaxStyle) { this.writer = new FoldedLineWriter(writer); this.syntaxStyle = syntaxStyle;
allowedGroupChars = VObjectValidator.allowedCharactersGroup(syntaxStyle, false);
5
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/writer/WriterFactory.java
[ "public class CsvSettings extends FlatFileSettings {\n\n public static final char DEFAULT_DELIMITER = ',';\n\n private final char delimiter;\n\n public CsvSettings(boolean includeHeaders) {\n this(includeHeaders, DEFAULT_DELIMITER);\n }\n\n public CsvSettings(boolean includeHeaders, char delim...
import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import au.com.anthonybruno.writer.csv.UnivocityCsvWriter; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import au.com.anthonybruno.writer.fixedwidth.UnivocityFixedWidthWriter; import java.io.Writer;
package au.com.anthonybruno.writer; public class WriterFactory { public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) {
return new UnivocityCsvWriter(writer, csvSettings);
3
jinahya/bit-io
src/main/java/com/github/jinahya/bit/io/AbstractBitOutput.java
[ "static int mask(final int size) {\n return MASKS[size - 1];\n}", "static int requireValidSizeByte(final boolean unsigned, final int size) {\n if (size <= 0) {\n throw new IllegalArgumentException(\"size(\" + size + \") <= 0\");\n }\n if (size > Byte.SIZE) {\n throw new IllegalArgumentEx...
import java.io.IOException; import static com.github.jinahya.bit.io.BitIoConstants.mask; import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeByte; import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeChar; import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeInt; import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeLong; import static com.github.jinahya.bit.io.BitIoConstraints.requireValidSizeShort;
package com.github.jinahya.bit.io; /*- * #%L * bit-io * %% * Copyright (C) 2014 - 2019 Jinahya, 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. * #L% */ /** * An abstract class for implementing {@link BitInput} interface. * * @author Jin Kwon &lt;jinahya_at_gmail.com&gt; * @see AbstractBitInput * @see DefaultBitOutput */ public abstract class AbstractBitOutput implements BitOutput { // ----------------------------------------------------------------------------------------------------------------- /** * Creates a new instance. */ protected AbstractBitOutput() { super(); } // ----------------------------------------------------------------------------------------------------------------- /** * Writes given {@value java.lang.Byte#SIZE}-bit unsigned integer. * * @param value the {@value java.lang.Byte#SIZE}-bit unsigned integer to write. * @throws IOException if an I/O error occurs. */ protected abstract void write(int value) throws IOException; // ----------------------------------------------------------------------------------------------------------------- /** * Writes an unsigned {@code int} value of specified bit size which is, in maximum, {@value java.lang.Byte#SIZE}. * * @param size the number of lower bits to write; between {@code 1} and {@value java.lang.Byte#SIZE}, both * inclusive. * @param value the value to write. * @throws IOException if an I/O error occurs. * @see #write(int) */ private void unsigned8(final int size, final int value) throws IOException { final int required = size - available; if (required > 0) { unsigned8(available, value >> required); unsigned8(required, value); return; } octet <<= size; octet |= value & mask(size); available -= size; if (available == 0) { assert octet >= 0 && octet < 256; write(octet); count++; octet = 0x00; available = Byte.SIZE; } } // --------------------------------------------------------------------------------------------------------- boolean @Override public void writeBoolean(final boolean value) throws IOException { writeInt(true, 1, value ? 1 : 0); } // ------------------------------------------------------------------------------------------------------------ byte @Override public void writeByte(final boolean unsigned, final int size, final byte value) throws IOException {
writeInt(unsigned, requireValidSizeByte(unsigned, size), value);
1
redferret/planet
src/worlds/planet/geosphere/GeoCell.java
[ "public class Vec2 {\n\n private float x, y;\n\n public Vec2() {\n this(0, 0);\n }\n\n public Vec2(Vec2 toCopy) {\n this(toCopy.x, toCopy.y);\n }\n\n public Vec2(float x, float y) {\n this.x = x;\n this.y = y;\n }\n\n public float getX() {\n return x;\n }\n\n public float getY() {\n retu...
import java.awt.Color; import java.util.Deque; import java.util.LinkedList; import java.util.List; import engine.util.Vec2; import java.util.Set; import worlds.planet.Util; import worlds.planet.Planet; import worlds.planet.PlanetCell; import worlds.planet.PlanetSurface; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ThreadLocalRandom; import static worlds.planet.Planet.instance; import static worlds.planet.Surface.*;
package worlds.planet.geosphere; /** * A GeoCell is a Cell representing land Geologically. The cell contains strata * and specialized methods for adding and/or removing from the strata. * * @author Richard DeSilvey */ public class GeoCell extends Mantle { /** * The list of strata for this cell */ private Deque<Layer> strata; /** * Tracks the total thickness of the strata. */ private float totalStrataThickness; /** * The total height makes adding up each layer faster. Each time a layer * is removed or it's thickness is altered the totalMass is updated. The units * are in kilograms. */ private float totalMass; /** * The total volume is calculated each time layer is added or removed or * updated and is used to determine the average density of this cell in cubic * meters. */ private float totalVolume; /** * The amount of this cell that is currently submerged in the mantel. */ private float curAmountSubmerged; private float crustTemperature; /** * A Point that is represented as the velocity for Plate Tectonics. When a * plate collides with a sibling (Cell owned by the same plate) the collision * is inelastic and will reduce it's velocity as well as moving a little * bit of it's energy through the system. */ private Vec2 velocity; public static float[][] heightMap; public final static int MAX_HEIGHT_INDEX = 17; /** * The ratio for indexing onto the height map array, by taking a cell height * and dividing it by this value will give the proper index to the height map. */ public static int heightIndexRatio = 17 / MAX_HEIGHT_INDEX; static { Color[] heightColors = {new Color(255, 255, 204), new Color(51, 153, 51), new Color(157, 166, 175), new Color(255, 255, 255)};
heightMap = Util.constructSamples(heightColors, MAX_HEIGHT_INDEX);
1
coil-lighting/udder
udder/src/main/java/com/coillighting/udder/effect/BloomEffect.java
[ "public class BoundingCube {\n\n protected double minX = 0.0;\n protected double minY = 0.0;\n protected double minZ = 0.0;\n\n protected double maxX = 0.0;\n protected double maxY = 0.0;\n protected double maxZ = 0.0;\n\n protected double width = 0.0;\n protected double height = 0.0;\n p...
import com.coillighting.udder.geometry.BoundingCube; import com.coillighting.udder.geometry.TriangularSequence; import com.coillighting.udder.mix.TimePoint; import com.coillighting.udder.model.Device; import com.coillighting.udder.model.Pixel; import static com.coillighting.udder.util.LogUtil.log;
package com.coillighting.udder.effect; /** * A multicolor Blooming Leaf that can vary the discrete threadcount in its * pattern. Easier to see than to explain this traditional weave. * * TODO Document this separately. It's a good example of what Udder was for. */ public class BloomEffect extends EffectBase { /** Checkerboard (traditional for Blooming Leaf weaves). */ public static final int DEFAULT_PALETTE_SIZE = 2; protected int[] repertoire = BloomTiling.REPERTOIRES[DEFAULT_PALETTE_SIZE]; protected Pixel[] palette = {Pixel.white(), Pixel.black()}; protected int[][] tiling = BloomTiling.TILINGS_2D[repertoire.length]; // FUTURE parameterize scale modulation // scale: device space units per thread protected double scale = 1.0; protected double scaleIncrement = 0.05; /** Reflect the effect down the middle. */ protected boolean enableBilateralSym = true; /** Reflect the reflection. (Do nothing if enableBilateralSym is false.) * Traditional for Blooming Leaves. */ protected boolean enableNestedBilateralSym = true; protected BoundingCube deviceBounds = null; protected boolean enableX = true; protected double devMinX = 0.0; protected double devWidth = 0.0; protected double xCenterOffset = 0.0; protected double xQuarterOffset = 0.0; protected boolean enableY = true; protected double devMinY = 0.0; protected double devHeight = 0.0; protected double yCenterOffset = 0.0; protected double yQuarterOffset = 0.0; // Enabling Z+reflection at the Dairy, which consists of two parallel planes, // is visually identical to rendering in XY 2D as long as this effect is // not rotated in space (which it is not). So we'll optimize by skipping // the Z axis for now. // // FUTURE: Enable the Z axis. // FUTURE: Make a volumetric demo with a legible Z axis, Cubatron-style. // protected double devMinZ = 0.0; // protected double devDepth = 0.0; // protected double zCenterOffset = 0.0; // protected double zQuarterOffset = 0.0; public Class getStateClass() { return BloomEffectState.class; } public Object getState() { return new BloomEffectState(this.copyPalette(), enableBilateralSym, enableNestedBilateralSym, enableX, enableY); } public Pixel[] copyPalette() { Pixel[] p = null; if(palette != null) { p = new Pixel[palette.length]; for(int i = 0; i < palette.length; i++) { p[i] = new Pixel(palette[i]); } } return p; } public void setState(Object state) throws ClassCastException { BloomEffectState command = (BloomEffectState) state; Pixel[] p = command.getPalette(); // Deep copy the given palette, filling in missing items with black. // Ignore extra colors. if(p != null && p.length > 0) { int size = p.length; int max = BloomTiling.REPERTOIRES.length + 1; if(size > max) { size = max; } repertoire = BloomTiling.REPERTOIRES[size]; tiling = BloomTiling.TILINGS_2D[repertoire.length]; palette = new Pixel[size]; for(int i=0; i<size; i++) { Pixel color = p[i]; if(color == null) { color = Pixel.black(); } else { color = new Pixel(color); } palette[i] = color; } } Boolean bilateral = command.getEnableBilateralSym(); if(bilateral != null) { enableBilateralSym = bilateral; } Boolean nested = command.getEnableNestedBilateralSym(); if(nested != null) { enableNestedBilateralSym = nested; } Boolean x = command.getEnableX(); if(x != null) { enableX = x; } Boolean y = command.getEnableY(); if(y != null) { enableY = y; } } public void patchDevices(Device[] devices) { super.patchDevices(devices); deviceBounds = Device.getDeviceBoundingCube(devices); devMinX = deviceBounds.getMinX(); devMinY = deviceBounds.getMinY(); devWidth = deviceBounds.getWidth(); devHeight = deviceBounds.getHeight(); xCenterOffset = devWidth * 0.5; xQuarterOffset = devWidth * 0.25; yCenterOffset = devHeight * 0.5; yQuarterOffset = devHeight * 0.25; // devMinZ = deviceBounds.getMinZ(); // devDepth = deviceBounds.getDepth(); // zCenterOffset = devDepth * 0.5; // zQuarterOffset = devDepth * 0.25; } public void animate(TimePoint timePoint) { Device dev = null; double[] xyz = null; double xoffset = 0.0; double yoffset = 0.0; // x and y palette index int px = 0; int py = 0; for (int i = 0; i < devices.length; i++) { dev = devices[i]; xyz = dev.getPoint(); // Symmetry is implemented as a transformation of each coordinate. if(enableX) { xoffset = xyz[0] - devMinX; if(enableBilateralSym) { if(xoffset > xCenterOffset) { xoffset = devWidth - xoffset; } if(enableNestedBilateralSym && xoffset > xQuarterOffset) { xoffset = xCenterOffset - xoffset; } }
px = TriangularSequence.oscillatingTriangularRootColor(xoffset, scale, repertoire);
1
nikfoundas/etcd-viewer
src/main/java/org/github/etcd/service/impl/ClusterManagerImpl.java
[ "public enum ApiVersion {\n V2, V3\n}", "public interface ClusterManager {\n\n boolean exists(String name);\n EtcdCluster getCluster(String name);\n\n EtcdCluster addCluster(String name, String etcdPeerAddress, ApiVersion apiVersion);\n void removeCluster(String name);\n\n List<EtcdCluster> getC...
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.github.etcd.service.ApiVersion; import org.github.etcd.service.ClusterManager; import org.github.etcd.service.EtcdCluster; import org.github.etcd.service.EtcdProxyFactory; import org.github.etcd.service.api.EtcdMember; import org.github.etcd.service.api.EtcdProxy; import org.github.etcd.service.api.EtcdSelfStats; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.github.etcd.service.impl; public class ClusterManagerImpl implements ClusterManager { private static final Logger log = LoggerFactory.getLogger(ClusterManager.class); private static final Comparator<EtcdMember> MEMBER_SORTER = new Comparator<EtcdMember>() { @Override public int compare(EtcdMember o1, EtcdMember o2) { return o1.getName().compareTo(o2.getName()); } }; private static final Map<String, String> STATE_MAPPINGS = new HashMap<>(); static { STATE_MAPPINGS.put("leader", "leader"); STATE_MAPPINGS.put("follower", "follower"); STATE_MAPPINGS.put("StateLeader", "leader"); STATE_MAPPINGS.put("StateFollower", "follower"); } @Inject private EtcdProxyFactory proxyFactory; private Map<String, EtcdCluster> clusters = Collections.synchronizedMap(new LinkedHashMap<String, EtcdCluster>()); private static final String DEFAULT_ETCD_CLIENT = "ETCD_CLIENT_URL"; public ClusterManagerImpl() { String etcdAddress = System.getenv(DEFAULT_ETCD_CLIENT); if (etcdAddress == null) { etcdAddress = System.getProperty(DEFAULT_ETCD_CLIENT, "http://localhost:2379"); } addCluster("default", etcdAddress, ApiVersion.V3); // addCluster("kvm", "http://192.168.122.201:2379/"); } @Override public boolean exists(String name) { return clusters.containsKey(name); } @Override public EtcdCluster getCluster(String name) { return name == null ? null : clusters.get(name); } @Override public EtcdCluster addCluster(String name, String etcdPeerAddress, ApiVersion apiVersion) { EtcdCluster cluster = new EtcdCluster(name, etcdPeerAddress, apiVersion); clusters.put(name, cluster); return cluster; } @Override public void removeCluster(String name) { clusters.remove(name); } @Override public List<EtcdCluster> getClusters() { return new ArrayList<>(clusters.values()); } @Override public List<String> getClusterNames() { return new ArrayList<>(clusters.keySet()); } @Override public void refreshCluster(String name) { if (name == null) { return; } EtcdCluster cluster = clusters.get(name); // default leader address is the provided one String leaderAddress = cluster.getAddress(); ApiVersion apiVersion = cluster.getApiVersion(); List<EtcdMember> members;
try (EtcdProxy proxy = proxyFactory.getEtcdProxy(name, leaderAddress, apiVersion)) {
5
isel-leic-mpd/mpd-2017-i41d
aula31-weather-groupingBy/src/main/java/weather/WeatherService.java
[ "public class HttpRequest implements IRequest {\n @Override\n public Iterable<String> getContent(String path) {\n List<String> res = new ArrayList<>();\n try (InputStream in = new URL(path).openStream()) {\n /*\n * Consumir o Inputstream e adicionar dados ao res\n ...
import util.HttpRequest; import weather.data.WeatherWebApi; import weather.data.dto.LocationDto; import weather.data.dto.WeatherInfoDto; import weather.model.Location; import weather.model.WeatherInfo; import java.time.LocalDate; import java.util.stream.Stream; import static java.time.LocalDate.now;
/* * Copyright (c) 2017, Miguel Gamboa * * 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 weather; /** * @author Miguel Gamboa * created on 29-03-2017 */ public class WeatherService { private final WeatherWebApi api; public WeatherService(WeatherWebApi api) { this.api = api; } public WeatherService() { api = new WeatherWebApi(new HttpRequest()); } public Stream<Location> search(String query) { return api.search(query).map(this::dtoToLocation); } private Location dtoToLocation(LocationDto loc) { return new Location( loc.getCountry(), loc.getRegion(), loc.getLatitude(), loc.getLongitude(), () -> last30daysWeather(loc.getLatitude(), loc.getLongitude()), (from, to) -> pastWeather(loc.getLatitude(), loc.getLongitude(), from, to)); }
public Stream<WeatherInfo> last30daysWeather(double lat, double log) {
5
caarmen/scrumchatter
app/src/main/java/ca/rmen/android/scrumchatter/chart/MeetingChartFragment.java
[ "public class Constants {\n public static final String TAG = \"ScrumChatter\";\n public static final String PREF_TEAM_ID = \"team_id\";\n public static final int DEFAULT_TEAM_ID = 1;\n public static final String DEFAULT_TEAM_NAME = \"Team A\";\n}", "public class Meetings {\n private static final St...
import android.database.Cursor; import android.databinding.DataBindingUtil; import android.net.Uri; import android.os.Bundle; import android.support.annotation.MainThread; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.format.DateUtils; 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 ca.rmen.android.scrumchatter.Constants; import ca.rmen.android.scrumchatter.R; import ca.rmen.android.scrumchatter.databinding.MeetingChartFragmentBinding; import ca.rmen.android.scrumchatter.meeting.Meetings; import ca.rmen.android.scrumchatter.meeting.detail.Meeting; import ca.rmen.android.scrumchatter.provider.MeetingMemberColumns; import ca.rmen.android.scrumchatter.provider.MemberColumns; import ca.rmen.android.scrumchatter.team.Teams; import ca.rmen.android.scrumchatter.util.Log; import ca.rmen.android.scrumchatter.util.TextUtils; import io.reactivex.Single;
/* * Copyright 2016-2017 Carmen Alvarez * <p/> * This file is part of Scrum Chatter. * <p/> * Scrum Chatter is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p/> * Scrum Chatter is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p/> * You should have received a copy of the GNU General Public License * along with Scrum Chatter. If not, see <http://www.gnu.org/licenses/>. */ package ca.rmen.android.scrumchatter.chart; /** * Displays charts for one meeting */ public class MeetingChartFragment extends Fragment { private static final String TAG = Constants.TAG + "/" + MeetingChartFragment.class.getSimpleName(); private static final int LOADER_MEMBER_SPEAKING_TIME = 0; private MeetingChartFragmentBinding mBinding; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.v(TAG, "onCreateView"); mBinding = DataBindingUtil.inflate(inflater, R.layout.meeting_chart_fragment, container, false); return mBinding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getLoaderManager().initLoader(LOADER_MEMBER_SPEAKING_TIME, null, mLoaderCallbacks); setHasOptionsMenu(true); loadMeeting(getActivity().getIntent().getLongExtra(Meetings.EXTRA_MEETING_ID, -1)); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.meeting_chart_menu, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_share) { ChartExportTask.export(getContext(), mBinding.memberSpeakingTimeChartContent); return true; } return super.onOptionsItemSelected(item); } private final LoaderManager.LoaderCallbacks<Cursor> mLoaderCallbacks = new LoaderManager.LoaderCallbacks<Cursor>() { @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { long meetingId = getActivity().getIntent().getLongExtra(Meetings.EXTRA_MEETING_ID, -1); String[] projection = new String[]{ MeetingMemberColumns._ID, MeetingMemberColumns.MEMBER_ID,
MemberColumns.NAME,
4
InMobi/api-monetization
java/src/test/java/com/inmobi/monetization/ads/NativeTest.java
[ "public class Native extends AdFormat {\n\n\tprivate JSONNativeResponseParser jsonParser = new JSONNativeResponseParser();\n\n\tpublic Native() {\n\t\trequestType = AdRequest.NATIVE;\n\t}\n\t\n\tprivate ArrayList<NativeResponse> loadRequestInternal(Request request) {\n\t\terrorCode = null;\n\t\tArrayList<NativeResp...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.ArrayList; import main.java.com.inmobi.monetization.ads.Native; import main.java.com.inmobi.monetization.api.request.ad.Slot; import main.java.com.inmobi.monetization.api.request.ad.Device; import main.java.com.inmobi.monetization.api.request.ad.Impression; import main.java.com.inmobi.monetization.api.request.ad.Property; import main.java.com.inmobi.monetization.api.request.ad.Request; import main.java.com.inmobi.monetization.api.response.ad.NativeResponse; import org.junit.Test;
/** * Copyright © 2015 InMobi Technologies Pte. Ltd. All rights reserved. MIT License 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. InMobi Monetization Library SUBCOMPONENTS: The InMobi Monetization Library contains subcomponents with separate copyright notices and license terms. Your use of the source code for the these subcomponents is subject to the terms and conditions of the following licenses. ------------------------------------------------------------------------------------------ For commons-codec & commons-lang3: Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ------------------------------------------------------------------------------------------ For gson: Copyright (c) 2008-2009 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 test.java.com.inmobi.monetization.ads; public class NativeTest { @Test public void test() { Native nativeAd = new Native(); Request request = new Request(); ArrayList<NativeResponse> ads; ads = nativeAd.loadRequest(request); assertNull(ads); nativeAd = new Native(); ads = nativeAd.loadRequest(request); assertNull(ads); ads = nativeAd.loadRequest(request); assertNull(ads);
Property property = null;
4
LklCBPay/javasdk
src/test/java/QueryCustomAuthTest.java
[ "@Component\r\npublic class CustomAuthClient {\r\n private static final Logger logger=LoggerFactory.getLogger(CustomAuthClient.class);\r\n \r\n @Autowired\r\n private LklCrossPayRestfulClent payRestfulClent;\r\n \r\n /**\r\n * 海关认证请求\r\n * @param customAuthReq\r\n * @param dataHead\r\n...
import org.junit.Before; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.lakala.crossborder.client.CustomAuthClient; import com.lakala.crossborder.client.entities.LklCrossPaySuperReq; import com.lakala.crossborder.client.entities.query.CustomAuthQueryReq; import com.lakala.crossborder.client.entities.query.CustomAuthQueryRes; import com.lakala.crossborder.client.enums.LklEnv; import com.lakala.crossborder.client.exception.LklClientException; import com.lakala.crossborder.client.util.DateUtil; import com.lakala.crossborder.client.util.LklCrossPayEnv;
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:client-application.xml") public class QueryCustomAuthTest { private static final Logger logger=LoggerFactory.getLogger(QueryCustomAuthTest.class); @Autowired private LklCrossPayEnv lklCrossPayEnv; @Autowired private CustomAuthClient customAuthClient; @Before public void testSetUp() { //注册应用环境 String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPg0O4rPQJL1O+jqJ4rBjFVNRAuDmBSoii9pYfPQBaescCVY0irkWWoLyfTT65TjvnPpOx+IfNzBTlB13qCEFm7algREoeUHjFgFNHiXJ2LK/R0+VWgXe5+EDFfbrFCPnmLKG3OcKDGQszP0VOf6VVTM1t56CpgaRMm1/+Tzd2TQIDAQAB"; String privKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIbyEihcDZbLfFhVpRU0knOtlzBhuWEjLBN4zd8dVzqAq52zWR04ybgZjjtlw+R9ICeJigmw2Dt3yy8SjpyMu5rYurTg/V0rGwayEuuE7aazi50nhZ/GYFRUVGIG0BoCI+73vsUmCO5EaUIJP/E0ew1bLMV7SMPynoQ8G9jXj8rXAgMBAAECgYAmfpFNcAz0UjGzZSMFbIzGcONrCsV9/zGIkHJxzgXfC2tpPgsSuetZF/kp2nrKCCOPA74by5WzSRXt5KZH5CFzuwwqIBv5cn6AiKiVmro3AnHV+qqNtfGXwLottu0VYcBEY2IPKb7SQ4pP5I0H973hnxR4qRzMAMUmEBVMiuUR+QJBAObLUBTjd7AE4Sls3/vBsYsYLYFfmw/dRHaW6jnuNxPTfVtPTGjY3V/672Vs01/f6QdtHHpMN+2xUk+acErAJTUCQQCVrvakm5R2sQwPycSO4mZW5sHKGbBosAkcY4llISVtxzSjgkPtBPVukCdNSGTuJX7+Ci8KolilrCc2XQCkH21bAkEAlcUAXd3TEL3J5BkMLRLgBTSWaytAtAXR5OdAboGA6nPHGJcYLb31wtBTxEzfyorCbRhIb7DAZpY4pQHCty+DtQJATFwCdPztYxN03MUIof+7R4/WwpwSU4WiUDozCEU9i+A46UT2E/8YmbuuYQ2Sd67nNv/I+brSUEofgus0/YUOywJBAMPu5o9guMsAjVqvXuxbkFpblYGZO/BrwiuLGDWEj4DZFqrIDmqgA6edy3HSoZ7U69BJZLTPb9DeebEiebmJZUI="; lklCrossPayEnv.registerEnv(LklEnv.SANDBOX, "RZCP161200000", privKey, pubKey); } @org.junit.Test public void testQueryCustomAuth() { CustomAuthQueryReq queryCustomAuthReq = new CustomAuthQueryReq(); queryCustomAuthReq.setOrderNo("SH20170511175909"); queryCustomAuthReq.setPayOrderId("20170511175909"); LklCrossPaySuperReq head = new LklCrossPaySuperReq(); head.setVer("3.0.0"); head.setTs(DateUtil.getCurrentTime()); head.setMerId(LklCrossPayEnv.getEnvConfig().getMerId()); try { CustomAuthQueryRes customAuthQueryRes = customAuthClient.queryCustomAuth(queryCustomAuthReq, head); logger.info("海关认证订单查询结果结果{},msg={}", new String[]{customAuthQueryRes.getRetCode(), customAuthQueryRes.getRetMsg()}); logger.info("海关受理结果:"+customAuthQueryRes.getStatus());
} catch (LklClientException e) {
5
Fedict/commons-eid
commons-eid-tests/src/test/java/be/bosa/commons/eid/client/tests/integration/LocaleTest.java
[ "public class BeIDCard implements AutoCloseable {\n\n\tprivate static final String UI_MISSING_LOG_MESSAGE = \"No BeIDCardUI set and can't load DefaultBeIDCardUI\";\n\tprivate static final String UI_DEFAULT_REQUIRES_HEAD = \"No BeIDCardUI set and DefaultBeIDCardUI requires a graphical environment\";\n\tprivate stati...
import be.bosa.commons.eid.client.BeIDCard; import be.bosa.commons.eid.client.BeIDCards; import be.bosa.commons.eid.client.FileType; import be.bosa.commons.eid.client.impl.BeIDDigest; import be.bosa.commons.eid.client.spi.BeIDCardsUI; import be.bosa.commons.eid.dialogs.DefaultBeIDCardsUI; import org.junit.Test; import java.util.Locale;
/* * Commons eID Project. * Copyright (C) 2014 - 2018 BOSA. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 3.0 as published by * the Free Software Foundation. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, see https://www.gnu.org/licenses/. */ package be.bosa.commons.eid.client.tests.integration; public class LocaleTest { @Test public void testLocale() throws Exception { try (BeIDCards cards = new BeIDCards()) { cards.setLocale(Locale.FRENCH); try (BeIDCard card = cards.getOneBeIDCard()) {
card.sign(new byte[]{0x00, 0x00, 0x00, 0x00}, BeIDDigest.PLAIN_TEXT, FileType.NonRepudiationCertificate, false);
3
RoboTricker/Transport-Pipes
src/main/java/de/robotricker/transportpipes/inventory/CraftingPipeSettingsInventory.java
[ "public class TransportPipes extends JavaPlugin {\n\n private Injector injector;\n\n private SentryService sentry;\n private ThreadService thread;\n private DiskService diskService;\n\n @Override\n public void onEnable() {\n\n if (Bukkit.getVersion().contains(\"1.13\")) {\n Legac...
import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.attribute.Attribute; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.DragType; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.RecipeChoice; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.ShapelessRecipe; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.PressurePlate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import de.robotricker.transportpipes.TransportPipes; import de.robotricker.transportpipes.config.LangConf; import de.robotricker.transportpipes.duct.pipe.CraftingPipe; import de.robotricker.transportpipes.duct.pipe.filter.ItemData; import de.robotricker.transportpipes.location.TPDirection;
package de.robotricker.transportpipes.inventory; public class CraftingPipeSettingsInventory extends DuctSettingsInventory { @Override public void create() { inv = Bukkit.createInventory(null, 6 * 9, LangConf.Key.DUCT_INVENTORY_TITLE.get(duct.getDuctType().getFormattedTypeName())); } @Override public void closeForAllPlayers(TransportPipes transportPipes) { save(null); super.closeForAllPlayers(transportPipes); } @Override public void populate() { CraftingPipe pipe = (CraftingPipe) duct;
TPDirection outputDir = pipe.getOutputDir();
4
underhilllabs/dccsched
src/com/underhilllabs/dccsched/io/RemoteWorksheetsHandler.java
[ "public class ScheduleContract {\n\n /**\n * Special value for {@link SyncColumns#UPDATED} indicating that an entry\n * has never been updated, or doesn't exist yet.\n */\n public static final long UPDATED_NEVER = -2;\n\n /**\n * Special value for {@link SyncColumns#UPDATED} indicating that...
import static com.underhilllabs.dccsched.util.ParserUtils.AtomTags.ENTRY; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; import com.underhilllabs.dccsched.provider.ScheduleContract; import com.underhilllabs.dccsched.provider.ScheduleContract.Sessions; import com.underhilllabs.dccsched.provider.ScheduleContract.Speakers; import com.underhilllabs.dccsched.provider.ScheduleContract.Vendors; import com.underhilllabs.dccsched.util.Lists; import com.underhilllabs.dccsched.util.Maps; import com.underhilllabs.dccsched.util.ParserUtils; import com.underhilllabs.dccsched.util.WorksheetEntry; import org.apache.http.client.methods.HttpGet; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap;
/* * Copyright 2010 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.underhilllabs.dccsched.io; public class RemoteWorksheetsHandler extends XmlHandler { private static final String TAG = "WorksheetsHandler"; private RemoteExecutor mExecutor; public RemoteWorksheetsHandler(RemoteExecutor executor) { super(ScheduleContract.CONTENT_AUTHORITY); mExecutor = executor; } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException {
final HashMap<String, WorksheetEntry> sheets = Maps.newHashMap();
5
anyremote/anyremote-android-client
java/anyremote/client/android/SearchForm.java
[ "public class About extends Dialog {\n\n\tprivate static Context mContext = null;\n\n\tpublic About(Context context) {\n\t\tsuper(context);\n\t\tmContext = context;\n\t}\n\n\t@Override\n\tpublic void onCreate(Bundle savedInstanceState) {\n\t\t\n\t\tsetContentView(anyremote.client.android.R.layout.about);\n\t\t\n\t\...
import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.content.IntentFilter; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.TextView; import android.widget.ListView; import android.widget.Toast; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import anyremote.client.android.R; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import anyremote.client.android.util.About; import anyremote.client.android.util.Address; import anyremote.client.android.util.AddressAdapter; import anyremote.client.android.util.BTScanner; import anyremote.client.android.util.IPScanner; import anyremote.client.android.util.ZCScanner; import anyremote.client.android.util.IScanner; import anyremote.client.android.util.ScanMessage;
// // anyRemote android client // a bluetooth/wi-fi remote control for Linux. // // Copyright (C) 2011-2016 Mikhail Fedotov <anyremote@mail.ru> // // 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, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // package anyremote.client.android; public class SearchForm extends arActivity implements OnItemClickListener, //DialogInterface.OnDismissListener, //DialogInterface.OnCancelListener, AdapterView.OnItemSelectedListener { ListView searchList; AddressAdapter dataSource; int selected = 0; Handler handler = null; IScanner scanner = null; // BT stuff private BluetoothAdapter mBtAdapter; String connectTo = ""; String connectName = ""; String connectPass = ""; boolean connectAuto = false; boolean skipDismissDialog = false; boolean deregStateRcv = false; String id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prefix = "SearchForm"; // log stuff Intent intent = getIntent(); id = intent.getStringExtra("SUBID"); log("onCreate " + id); //requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_ACTION_BAR); setContentView(R.layout.search_dialog); setResult(Activity.RESULT_CANCELED); setTitle(R.string.searchFormUnconnected); searchList = (ListView) findViewById(R.id.search_list); searchList.setOnItemClickListener(this); registerForContextMenu(searchList); dataSource = new AddressAdapter(this, R.layout.search_list_item, anyRemote.protocol.loadPrefs()); searchList.setAdapter(dataSource); searchList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); searchList.setOnItemSelectedListener(this); //searchList.setItemChecked(selected, true); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); if (dataSource.size() == 0) { // first-time run Toast.makeText(this, "Press Menu ...", Toast.LENGTH_SHORT).show(); } else { if (anyRemote.firstConnect) { anyRemote.firstConnect = false;
final Address auto = dataSource.getAutoconnectItem();
1
pmarques/SocketIO-Server
SocketIO-Netty/src/test/java/eu/k2c/socket/io/ci/usecases/UC17Handler.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.ci.AbstractHandler; 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.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.jboss.netty.handler.codec.http.QueryStringDecoder;
/** * 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 UC17Handler extends AbstractHandler { private static final Logger LOGGER = Logger.getLogger(UC17Handler.class); // 'test sending query strings to the server' private String URI; @Override public boolean validate(final String URI) { this.URI = URI; return true; } @Override
public void onConnect(final SocketIOOutbound outbound, final SocketIOSessionEventRegister eventRegister,
2
bencvt/LibShapeDraw
projects/main/src/main/java/libshapedraw/shape/WireframeLinesBlendIterable.java
[ "public interface MinecraftAccess {\n /** Tessellator.instance.startDrawing */\n public MinecraftAccess startDrawing(int mode);\n\n /** Tessellator.instance.addVertex */\n public MinecraftAccess addVertex(double x, double y, double z);\n\n /** Tessellator.instance.addVertex */\n public MinecraftAc...
import java.util.Iterator; import libshapedraw.MinecraftAccess; import libshapedraw.primitive.Color; import libshapedraw.primitive.LineStyle; import libshapedraw.primitive.ReadonlyColor; import libshapedraw.primitive.ReadonlyLineStyle; import libshapedraw.primitive.ReadonlyVector3; import libshapedraw.primitive.Vector3; import org.lwjgl.opengl.GL11;
package libshapedraw.shape; /** * A series of connected line segments that smoothly blends from one line style * to another along the segments. * <p> * For most use cases you'll want to use WireframeLinesBlend instead, which * takes a Collection of ReadonlyVector3s rather than an Iterable. Only use * this class if you want to blend based solely on the render cap, not on the * number of points. */ public class WireframeLinesBlendIterable extends WireframeLines { private LineStyle blendToLineStyle; public WireframeLinesBlendIterable(Vector3 origin, Iterable<ReadonlyVector3> relativePoints) { super(origin, relativePoints); } public WireframeLinesBlendIterable(Iterable<ReadonlyVector3> absolutePoints) { super(absolutePoints); } public LineStyle getBlendToLineStyle() { return blendToLineStyle; } public WireframeLinesBlendIterable setBlendToLineStyle(LineStyle blendToLineStyle) { this.blendToLineStyle = blendToLineStyle; return this; } /** * Convenience method. * @see LineStyle#set */ public WireframeLinesBlendIterable setBlendToLineStyle(Color color, float width, boolean visibleThroughTerrain) { if (blendToLineStyle == null) { blendToLineStyle = new LineStyle(color, width, visibleThroughTerrain); } else { blendToLineStyle.set(color, width, visibleThroughTerrain); } return this; } /** * The "blend endpoint" refers to the last line to be rendered, which * should be 100% getBlendToLineStyle(). */ protected int getBlendEndpoint() { return getRenderCap() - 1; } @Override protected void renderLines(MinecraftAccess mc, boolean isSecondary) {
final ReadonlyLineStyle fromStyle = getEffectiveLineStyle();
4
bmelnychuk/outlay
outlay/app/src/main/java/app/outlay/view/Navigator.java
[ "public class MainActivity extends DrawerActivity {\n\n private MainFragment mainFragment;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(app.outlay.R.layout.activity_single_fragment);\n\n Bundle b = getIntent...
import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import app.outlay.domain.model.Expense; import app.outlay.view.activity.LoginActivity; import app.outlay.view.activity.MainActivity; import app.outlay.view.activity.SingleFragmentActivity; import app.outlay.view.activity.SyncGuestActivity; import app.outlay.view.fragment.AnalysisFragment; import app.outlay.view.fragment.CategoriesFragment; import app.outlay.view.fragment.CategoryDetailsFragment; import app.outlay.view.fragment.ExpensesDetailsFragment; import app.outlay.view.fragment.ExpensesListFragment; import app.outlay.view.fragment.ReportFragment; import java.util.Date;
package app.outlay.view; /** * Created by Bogdan Melnychuk on 1/24/16. */ public final class Navigator { public static void goToCategoryDetails(FragmentActivity activityFrom, String categoryId) { Bundle b = new Bundle(); if (categoryId != null) { b.putString(CategoryDetailsFragment.ARG_CATEGORY_PARAM, categoryId); } changeFragment(activityFrom, CategoryDetailsFragment.class, b); } public static void goToCategoriesList(FragmentActivity from) {
SingleFragmentActivity.start(from, CategoriesFragment.class);
2
padster/Muse-EEG-Toolkit
sampleApp/src/main/java/eeg/useit/today/eegtoolkit/sampleapp/MoreDeviceDetailsActivity.java
[ "public class Constants {\n public static final String TAG = \"EEGToolkit\";\n public static final String RECORDING_PREFIX = \"data\";\n\n // HACK: Should configure these elsewhere, perhaps attributes to renderers.\n public static final double VOLTAGE_MAX = 1000.0;\n public static final double VOLTAGE_MIN = 70...
import android.databinding.DataBindingUtil; import android.databinding.Observable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.choosemuse.libmuse.Eeg; import com.choosemuse.libmuse.Muse; import com.choosemuse.libmuse.MuseManagerAndroid; import eeg.useit.today.eegtoolkit.Constants; import eeg.useit.today.eegtoolkit.common.FrequencyBands; import eeg.useit.today.eegtoolkit.common.MuseManagerUtil; import eeg.useit.today.eegtoolkit.model.EpochCollector; import eeg.useit.today.eegtoolkit.model.MergedSeries; import eeg.useit.today.eegtoolkit.model.TimeSeries; import eeg.useit.today.eegtoolkit.sampleapp.databinding.ActivityMoreDeviceDetailsBinding; import eeg.useit.today.eegtoolkit.view.Plot2DView; import eeg.useit.today.eegtoolkit.vm.FrequencyBandViewModel; import eeg.useit.today.eegtoolkit.vm.StreamingDeviceViewModel;
package eeg.useit.today.eegtoolkit.sampleapp; /** * Activity containing more example views provided by the toolkit. */ public class MoreDeviceDetailsActivity extends AppCompatActivity { public static int DURATION_SEC = 4; /** The live device VM backing this view. */ private final StreamingDeviceViewModel deviceVM = new StreamingDeviceViewModel(); /** Epoch Model */
private final EpochCollector epochCollector = new EpochCollector();
3
jentrata/jentrata
ebms-msh-api/src/main/java/org/jentrata/ebms/cpa/PartnerAgreement.java
[ "public class EbmsConstants {\n\n public static final String JENTRATA_VERSION = \"JentrataVersion\";\n\n //Jentrata Message Header keys\n public static final String SOAP_VERSION = \"JentrataSOAPVersion\";\n public static final String EBMS_VERSION = \"JentrataEBMSVersion\";\n public static final Strin...
import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import org.jentrata.ebms.EbmsConstants; import org.jentrata.ebms.MessageType; import org.jentrata.ebms.cpa.pmode.BusinessInfo; import org.jentrata.ebms.cpa.pmode.Party; import org.jentrata.ebms.cpa.pmode.PayloadService; import org.jentrata.ebms.cpa.pmode.Protocol; import org.jentrata.ebms.cpa.pmode.ReceptionAwareness; import org.jentrata.ebms.cpa.pmode.Security; import org.jentrata.ebms.cpa.pmode.Service;
package org.jentrata.ebms.cpa; /** * A Agreement between 2 trading partners * * @author aaronwalker */ public class PartnerAgreement { private String cpaId; private boolean active = true; private String agreementRef; private String mep = EbmsConstants.EBMS_V3_MEP_ONE_WAY; private String mepBinding = EbmsConstants.EBMS_V3_MEP_BINDING_PUSH; private Party initiator; private Party responder;
private Protocol protocol;
5
ls1intum/jReto
Source/test/jReto/integration/TransferCancellationTest.java
[ "public class PeerConfiguration {\n\tpublic final RunLoop runloop;\n\tpublic final LocalPeer peer1;\n\tpublic final LocalPeer peer2;\n\tpublic final List<LocalPeer> participatingPeers;\n\tpublic final List<LocalPeer> reachablePeers;\n\tpublic final List<LocalPeer> destinations;\n\n\tpublic static List<LocalPeer> de...
import static org.junit.Assert.*; import jReto.meta.PeerConfiguration; import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.Connection; import de.tum.in.www1.jReto.RemotePeer; import de.tum.in.www1.jReto.connectivity.Transfer; import de.tum.in.www1.jReto.util.CountDown;
package jReto.integration; public class TransferCancellationTest { @Test(timeout=1000) public void testTransferDataIntegrityDirect() { new TransferCancellationTest().testTransferCancellation(PeerConfiguration.directNeighborConfiguration()); } @Test(timeout=1000) public void testTransferDataIntegrity2Hop() { new TransferCancellationTest().testTransferCancellation(PeerConfiguration.twoHopRoutedConfiguration()); } @Test(timeout=1000) public void testTransferDataIntegrity4Hop() { new TransferCancellationTest().testTransferCancellation(PeerConfiguration.fourHopRoutedConfiguration()); } @Test(timeout=1000) public void testTransferDataIntegrityNontrivial() { new TransferCancellationTest().testTransferCancellation(PeerConfiguration.nontrivial2HopNetworkConfiguration()); } @Test(timeout=1000) public void testTransferDataIntegrityDisconnectedPeers() { new TransferCancellationTest().testTransferCancellation(PeerConfiguration.configurationWithDisconnectedPeers()); } int dataLength = 1000000; boolean didCancel = false; public void testTransferCancellation(final PeerConfiguration peerConfiguration) { CountDown cancellationCountDown = new CountDown(2, () -> peerConfiguration.runloop.stop()); peerConfiguration.startAndExecuteAfterDiscovery(() -> { peerConfiguration.peer2.setIncomingConnectionHandler((connectingPeer, connection) -> { connection.setOnTransfer((c, transfer) -> { transfer.setOnCompleteData((t, data) -> {}); // We don't care about the data, but need to set a data handler to keep the transfer from complaining transfer.setOnComplete(t -> fail("Transfer should not complete.")); transfer.setOnCancel(t -> { assertTrue("transfer should have cancelled state", t.getIsCancelled()); assertFalse("transfer should not be completed", t.getIsCompleted()); cancellationCountDown.countDown(); }); transfer.setOnProgress(t -> { // When we get the first progress update, we cancel the transfer. if (!didCancel) { didCancel = true; peerConfiguration.runloop.execute(() -> { transfer.cancel(); }); } }); }); }); RemotePeer destination = peerConfiguration.peer1.getPeers().stream().filter(p -> p.getUniqueIdentifier().equals(peerConfiguration.peer2.getUniqueIdentifier())).findFirst().get(); Connection connection = destination.connect();
Transfer outTransfer = connection.send(TestData.generate(dataLength));
1
jjoe64/GraphView-Demos
app/src/main/java/com/jjoe64/graphview_demos/categories/StylingExamplesFragment.java
[ "public enum FullscreenExample {\n HELLO_WORLD(R.layout.fullscreen_example_simple, HelloWorld.class),\n SCALING_XY(R.layout.fullscreen_example_simple, ScalingXY.class),\n SCALING_X(R.layout.fullscreen_example_simple, ScalingX.class),\n SCROLLING_X(R.layout.fullscreen_example_simple, ScrollingX.class),\n...
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview_demos.FullscreenExample; import com.jjoe64.graphview_demos.ItemDetailFragment; import com.jjoe64.graphview_demos.R; import com.jjoe64.graphview_demos.examples.StylingColors; import com.jjoe64.graphview_demos.examples.StylingLabels; import com.jjoe64.graphview_demos.examples.TitlesExample;
package com.jjoe64.graphview_demos.categories; /** * Created by jonas on 07.09.16. */ public class StylingExamplesFragment extends ItemDetailFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.styling_examples_content, container, false); GraphView graph = (GraphView) rootView.findViewById(R.id.graph); new StylingLabels().initGraph(graph); rootView.findViewById(R.id.cardStylingLabelsGraph).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openFullscreen(FullscreenExample.STYLING_LABELS); } }); rootView.findViewById(R.id.imgFullscreen).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openFullscreen(FullscreenExample.STYLING_LABELS); } }); rootView.findViewById(R.id.imgSource).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openSource(FullscreenExample.STYLING_LABELS); } }); graph = (GraphView) rootView.findViewById(R.id.graph2);
new StylingColors().initGraph(graph);
2
d-plaindoux/suitcase
src/main/java/org/smallibs/suitcase/match/Matcher.java
[ "public interface Case<T, R> {\n\n Optional<R> unapply(T t);\n\n interface WithoutCapture<T, R> extends Case<T, Result.WithoutCapture<R>> {\n static <T, R> WithoutCapture<T, R> adapt(Case<T, Result.WithoutCapture<R>> aCase) {\n return aCase::unapply;\n }\n }\n\n interface WithCa...
import org.smallibs.suitcase.cases.Case; import org.smallibs.suitcase.cases.Result; import org.smallibs.suitcase.utils.Functions; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import static org.smallibs.suitcase.cases.core.Cases.Constant; import static org.smallibs.suitcase.cases.core.Cases.typeOf;
/* * Copyright (C)2015 D. Plaindoux. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.smallibs.suitcase.match; /** * The Matcher defines a pattern matching rule set. * * @param <T> The matched object type * @param <R> The matching result type */ public class Matcher<T, R> implements Case.WithoutCapture<T, R> { /** * The rule set */ private final List<Rule<?>> rules; /** * The constructor */ protected Matcher() { this.rules = new LinkedList<>(); } /** * Factory * * @param <T> The matched object type * @param <R> The matching result type * @return a fresh pattern matching rule set */ public static <T, R> Matcher<T, R> create() { return new Matcher<>(); } /** * Method called in order to create a new rule. The returns a When * object able to capture a conditional or a termination. * * @param <C> The type of the capture * @param object The pattern * @return a */ public <C> WhenRuleWithoutCapture caseOf(WithoutCapture<? extends T, C> object) { return new WhenRuleWithoutCapture<>(object); } /** * Method called in order to create a new rule. The returns a When * object able to capture a conditional or a termination. * * @param <C> The type of the capture * @param object The pattern * @return a */ public <C> WhenRuleWithCapture<C> caseOf(WithCapture<? extends T, C> object) { return new WhenRuleWithCapture<>(object); } /** * Method called in order to create a new rule. The returns a When * object able to capture a conditional or a termination. * * @param <E> The class type to be matched * @param object The pattern * @return a */ public <E extends T> WhenRuleWithoutCapture<E> caseOf(Class<E> object) {
return new WhenRuleWithoutCapture<>(typeOf(object));
4
crazyhitty/Munch
app/src/main/java/com/crazyhitty/chdev/ks/munch/ui/fragments/ManageSourcesFragment.java
[ "public class SourceItem {\n private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;\n private int sourceCategoryImgId;\n\n public int getSourceCategoryImgId() {\n return sourceCategoryImgId;\n }\n\n public void setSourceCategoryImgId(int sourceCategoryImgId) {\n this...
import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.crazyhitty.chdev.ks.munch.R; import com.crazyhitty.chdev.ks.munch.models.SourceItem; import com.crazyhitty.chdev.ks.munch.sources.ISourceView; import com.crazyhitty.chdev.ks.munch.sources.SourcesPresenter; import com.crazyhitty.chdev.ks.munch.ui.adapters.SourcesRecyclerViewAdapter; import com.crazyhitty.chdev.ks.munch.utils.ItemDecorationUtil; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife;
package com.crazyhitty.chdev.ks.munch.ui.fragments; /** * Created by Kartik_ch on 12/6/2015. */ public class ManageSourcesFragment extends Fragment implements ISourceView { @Bind(R.id.recycler_view_sources) RecyclerView recyclerViewSources; private SourcesRecyclerViewAdapter mSourcesRecyclerViewAdapter; private RecyclerView.LayoutManager mLayoutManager; private SourcesPresenter mSourcesPresenter; private RecyclerView.ItemDecoration mItemDecoration; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_manage_sources, container, false); ButterKnife.bind(this, view); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mSourcesPresenter == null) { mSourcesPresenter = new SourcesPresenter(this, getActivity()); } //mLayoutManager=new LinearLayoutManager(getActivity()); mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); recyclerViewSources.setLayoutManager(mLayoutManager); mItemDecoration = new ItemDecorationUtil(2, 8, false); recyclerViewSources.addItemDecoration(mItemDecoration); new Handler().postDelayed(new Runnable() { @Override public void run() { mSourcesPresenter.getSourceItems(); } }, 500); } //no use @Override public void dataSourceSaved(String message) { } //no use @Override public void dataSourceSaveFailed(String message) { } //no use @Override public void dataSourceLoaded(List<String> sourceNames) { } @Override
public void dataSourceItemsLoaded(List<SourceItem> sourceItems) {
0
iChun/Hats
src/main/java/me/ichun/mods/hats/client/gui/window/WindowAllHats.java
[ "public class WorkspaceHats extends Workspace\n implements IHatSetter\n{\n public static final DecimalFormat FORMATTER = new DecimalFormat(\"#,###,###\");\n\n public final boolean fallback;\n public final @Nonnull LivingEntity hatEntity;\n public final HatsSavedData.HatPart hatDetails;\n publi...
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import me.ichun.mods.hats.client.gui.WorkspaceHats; import me.ichun.mods.hats.client.gui.window.element.ElementHatRender; import me.ichun.mods.hats.client.gui.window.element.ElementHatsScrollView; import me.ichun.mods.hats.common.Hats; import me.ichun.mods.hats.common.hats.HatInfo; import me.ichun.mods.hats.common.hats.HatResourceHandler; import me.ichun.mods.hats.common.hats.sort.SortHandler; import me.ichun.mods.hats.common.world.HatsSavedData; import me.ichun.mods.ichunutil.client.gui.bns.window.Window; import me.ichun.mods.ichunutil.client.gui.bns.window.constraint.Constraint; import me.ichun.mods.ichunutil.client.gui.bns.window.view.View; import me.ichun.mods.ichunutil.client.gui.bns.window.view.element.*; import net.minecraft.client.resources.I18n; import net.minecraft.util.math.MathHelper; import javax.annotation.Nonnull; import java.text.DecimalFormat; import java.util.List; import java.util.stream.Collectors;
package me.ichun.mods.hats.client.gui.window; public class WindowAllHats extends Window<WorkspaceHats> { public int age; public WindowAllHats(WorkspaceHats parent) { super(parent); disableDockingEntirely(); disableDrag(); disableTitle(); setView(new ViewAllHats(this)); } @Override public void render(MatrixStack stack, int mouseX, int mouseY, float partialTick) {
if(age <= Hats.configClient.guiAnimationTime)
3
ChillingVan/AndroidInstantVideo
app/src/main/java/com/chillingvan/instantvideo/sample/test/publisher/TestMp4MuxerActivity.java
[ "public class CameraPreviewTextureView extends GLMultiTexProducerView {\n\n private H264Encoder.OnDrawListener onDrawListener;\n private IAndroidCanvasHelper drawTextHelper = IAndroidCanvasHelper.Factory.createAndroidCanvasHelper(IAndroidCanvasHelper.MODE.MODE_ASYNC);\n private Paint textPaint;\n\n publ...
import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.Surface; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.chillingvan.canvasgl.ICanvasGL; import com.chillingvan.canvasgl.androidCanvas.IAndroidCanvasHelper; import com.chillingvan.canvasgl.glcanvas.BasicTexture; import com.chillingvan.canvasgl.glcanvas.RawTexture; import com.chillingvan.canvasgl.glview.texture.GLTexture; import com.chillingvan.canvasgl.textureFilter.BasicTextureFilter; import com.chillingvan.canvasgl.textureFilter.HueFilter; import com.chillingvan.canvasgl.textureFilter.TextureFilter; import com.chillingvan.canvasgl.util.Loggers; import com.chillingvan.instantvideo.sample.R; import com.chillingvan.instantvideo.sample.test.camera.CameraPreviewTextureView; import com.chillingvan.instantvideo.sample.util.ScreenUtil; import com.chillingvan.lib.camera.InstantVideoCamera; import com.chillingvan.lib.encoder.video.H264Encoder; import com.chillingvan.lib.muxer.MP4Muxer; import com.chillingvan.lib.publisher.CameraStreamPublisher; import com.chillingvan.lib.publisher.StreamPublisher; import java.io.IOException; import java.util.List;
/* * * * * * * Copyright (C) 2017 ChillingVan * * * * * * 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.chillingvan.instantvideo.sample.test.publisher; /** * This sample shows how to record a mp4 file. It cannot pause but only can restart. If you want to pause when recording, you need to generate a new file and merge old files and new file. */ public class TestMp4MuxerActivity extends AppCompatActivity { private CameraStreamPublisher streamPublisher; private CameraPreviewTextureView cameraPreviewTextureView; private InstantVideoCamera instantVideoCamera; private Handler handler; private HandlerThread handlerThread; private TextView outDirTxt; private String outputDir; private MediaPlayerHelper mediaPlayer = new MediaPlayerHelper(); private Surface mediaSurface; private IAndroidCanvasHelper drawTextHelper = IAndroidCanvasHelper.Factory.createAndroidCanvasHelper(IAndroidCanvasHelper.MODE.MODE_ASYNC); private Paint textPaint; private Button startButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initTextPaint(); outputDir = getExternalFilesDir(null) + "/test_mp4_encode.mp4"; setContentView(R.layout.activity_test_mp4_muxer); cameraPreviewTextureView = findViewById(R.id.camera_produce_view); cameraPreviewTextureView.setOnDrawListener(new H264Encoder.OnDrawListener() { @Override public void onGLDraw(ICanvasGL canvasGL, List<GLTexture> producedTextures, List<GLTexture> consumedTextures) { GLTexture texture = producedTextures.get(0); GLTexture mediaTexture = producedTextures.get(1); drawVideoFrame(canvasGL, texture.getSurfaceTexture(), texture.getRawTexture(), mediaTexture); } }); outDirTxt = (TextView) findViewById(R.id.output_dir_txt); outDirTxt.setText(outputDir); startButton = findViewById(R.id.test_camera_button); instantVideoCamera = new InstantVideoCamera(Camera.CameraInfo.CAMERA_FACING_FRONT, 640, 480); // instantVideoCamera = new InstantVideoCamera(Camera.CameraInfo.CAMERA_FACING_FRONT, 1280, 720); handlerThread = new HandlerThread("StreamPublisherOpen"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); playMedia(); // StreamPublisher.StreamPublisherParam streamPublisherParam = new StreamPublisher.StreamPublisherParam(); // StreamPublisher.StreamPublisherParam streamPublisherParam = new StreamPublisher.StreamPublisherParam(1080, 640, 9500 * 1000, 30, 1, 44100, 19200); StreamPublisher.StreamPublisherParam.Builder builder = new StreamPublisher.StreamPublisherParam.Builder(); StreamPublisher.StreamPublisherParam streamPublisherParam = builder .setWidth(1080) .setHeight(750) .setVideoBitRate(1500 * 1000) .setFrameRate(30) .setIframeInterval(1) .setSamplingRate(44100) .setAudioBitRate(19200) .setAudioSource(MediaRecorder.AudioSource.MIC) .createStreamPublisherParam(); streamPublisherParam.outputFilePath = outputDir; streamPublisherParam.setInitialTextureCount(2); streamPublisher.prepareEncoder(streamPublisherParam, new H264Encoder.OnDrawListener() { @Override public void onGLDraw(ICanvasGL canvasGL, List<GLTexture> producedTextures, List<GLTexture> consumedTextures) { GLTexture texture = consumedTextures.get(1); GLTexture mediaTexture = consumedTextures.get(0); drawVideoFrame(canvasGL, texture.getSurfaceTexture(), texture.getRawTexture(), mediaTexture); Loggers.i("DEBUG", "gl draw"); } }); try { streamPublisher.startPublish(); } catch (IOException e) { e.printStackTrace(); ((TextView)findViewById(R.id.test_camera_button)).setText("START"); } } }; streamPublisher = new CameraStreamPublisher(new MP4Muxer(), cameraPreviewTextureView, instantVideoCamera); streamPublisher.setOnSurfacesCreatedListener(new CameraStreamPublisher.OnSurfacesCreatedListener() { @Override public void onCreated(List<GLTexture> producedTextureList, StreamPublisher streamPublisher) { GLTexture texture = producedTextureList.get(1); GLTexture mediaTexture = producedTextureList.get(1); streamPublisher.addSharedTexture(new GLTexture(mediaTexture.getRawTexture(), mediaTexture.getSurfaceTexture())); mediaSurface = new Surface(texture.getSurfaceTexture()); } }); } private void initTextPaint() { textPaint = new Paint(); textPaint.setColor(Color.WHITE);
textPaint.setTextSize(ScreenUtil.dpToPx(getApplicationContext(), 15));
1
Chat-Wane/LSEQ
src/main/java/alma/fr/modules/GreedRandDoubleModule.java
[ "public class BaseDouble implements IBase {\n\n\tprivate final Integer baseBase;\n\n\t@Inject\n\tpublic BaseDouble(@Basebase Integer baseBase) {\n\t\tthis.baseBase = baseBase;\n\t}\n\n\tpublic Integer getBitBase(Integer depth) {\n\t\treturn baseBase + depth - 1;\n\t}\n\n\tpublic Integer getSumBit(Integer depth) {\n...
import java.math.BigInteger; import alma.fr.basecomponents.BaseDouble; import alma.fr.basecomponents.Basebase; import alma.fr.basecomponents.IBase; import alma.fr.strategiescomponents.BeginningBoundaryIdProvider; import alma.fr.strategiescomponents.EndingBoundaryIdProvider; import alma.fr.strategiescomponents.IIdProviderStrategy; import alma.fr.strategiescomponents.boundary.BoundaryValue; import alma.fr.strategiescomponents.boundary.ConstantBoundary; import alma.fr.strategiescomponents.boundary.IBoundary; import alma.fr.strategychoicecomponents.IStrategyChoice; import alma.fr.strategychoicecomponents.RandomStrategyChoice; import alma.fr.strategychoicecomponents.Strat1; import alma.fr.strategychoicecomponents.Strat2; import com.google.inject.Binder; import com.google.inject.Module;
package alma.fr.modules; /** * Constant boundary but greed and double base */ public class GreedRandDoubleModule implements Module { public void configure(Binder binder) { Integer baseBase = new Integer(5); BigInteger boundary = new BigInteger("10"); /* BASE */ binder.bind(Integer.class).annotatedWith(Basebase.class).toInstance( baseBase);
binder.bind(IBase.class).to(BaseDouble.class);
0
fvalente/LogDruid
src/logdruid/ui/table/StatRecordingEditorTable.java
[ "public class Repository {\n\tprivate static Logger logger = Logger.getLogger(DataMiner.class.getName());\n\tprivate ArrayList<Recording> recordings;\n\tprivate ArrayList<Source> sources;\n\tprivate String baseSourcePath;\n\tprivate ArrayList<DateFormat> dates;\n\tprivate boolean recursiveMode;\n\tprivate boolean o...
import javax.swing.JPanel; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextPane; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import org.apache.log4j.Logger; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.text.ParseException; import org.apache.commons.lang3.time.FastDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import logdruid.data.Repository; import logdruid.data.record.EventRecording; import logdruid.data.record.MetadataRecording; import logdruid.data.record.Recording; import logdruid.data.record.RecordingItem; import logdruid.data.record.StatRecording; import logdruid.ui.NoProcessingRegexTableRenderer; import logdruid.util.DataMiner; import logdruid.util.PatternCache;
/******************************************************************************* * LogDruid : Generate charts and reports using data gathered in log files * Copyright (C) 2016 Frederic Valente (frederic.valente@gmail.com) * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. *******************************************************************************/ package logdruid.ui.table; public class StatRecordingEditorTable extends JPanel { private static Logger logger = Logger.getLogger(DataMiner.class.getName()); private boolean DEBUG = false; static Matcher m; static ArrayList records = null; private MyTableModel model; private String[] header = { "Name", "Before", "Inside type", "Inside regex", "After", "Active", "Show", "Value" }; private ArrayList<Object[]> data = new ArrayList<Object[]>(); JTable table = null; private String theLine = ""; private JTextPane examplePane;
private Repository rep = null;
0
jurihock/voicesmith
tests/src/de/jurihock/voicesmith/services/AudioServiceTestBase.java
[ "public class AudioDeviceManager\n{\n private final Context context;\n\n public AudioDeviceManager(Context context)\n {\n this.context = context;\n }\n\n public AudioDevice getInputDevice(HeadsetMode mode) throws IOException\n {\n // TEST: Read input signal from file instead of mic d...
import java.io.IOException; import static org.mockito.Mockito.*; import android.content.Intent; import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.SmallTest; import de.jurihock.voicesmith.audio.AudioDeviceManager; import de.jurihock.voicesmith.audio.HeadsetManager; import de.jurihock.voicesmith.audio.HeadsetMode; import de.jurihock.voicesmith.io.AudioDevice; import de.jurihock.voicesmith.io.dummy.DummyInDevice; import de.jurihock.voicesmith.io.dummy.DummyOutDevice; import org.mockito.Mock;
/* * Voicesmith <http://voicesmith.jurihock.de/> * * Copyright (c) 2011-2014 Juergen Hock * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.jurihock.voicesmith.services; public abstract class AudioServiceTestBase<T extends AudioService> extends MockableServiceTestCase<T> implements ServiceListener { private ServiceFailureReason serviceFailureReason; @Mock private HeadsetManager headsetManagerMock; @Mock private AudioDeviceManager deviceManagerMock; public AudioServiceTestBase(Class<T> serviceClass) { super(serviceClass); } private static void sleep(double seconds) { try { long millis = (long)(seconds * 1000D); Thread.sleep(millis); } catch (InterruptedException exception) { return; } } @Override public void onServiceFailed(ServiceFailureReason reason) { serviceFailureReason = reason; } @Override protected void setUp() throws Exception { super.setUp(); serviceFailureReason = null; } @Override protected void startService() { super.startService(); getService().setListener(this); } @Override protected void initMocks() { super.initMocks(); doNothing().when(headsetManagerMock).restoreVolumeLevel(any(HeadsetMode.class)); doNothing().when(headsetManagerMock).setBluetoothScoOn(any(boolean.class)); doNothing().when(headsetManagerMock).registerHeadsetDetector(); doNothing().when(headsetManagerMock).unregisterHeadsetDetector(); try {
AudioDevice dummyInDevice = new DummyInDevice(getContext());
3
ev3dev-lang-java/ev3dev-lang-java
src/main/java/ev3dev/utils/io/NativeTTY.java
[ "public static final int KDGKBMODE = 0x4B44; /* gets current keyboard mode */", "public static final int KDSETMODE = 0x4B3A; /* set text/graphics mode */", "public static final int KDSKBMODE = 0x4B45; /* sets current keyboard mode */", "public static final int VT_GETMODE = 0x5601; /* get mode of acti...
import com.sun.jna.LastErrorException; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.IntByReference; import lombok.NonNull; import java.util.Arrays; import java.util.List; import static ev3dev.utils.io.NativeConstants.KDGKBMODE; import static ev3dev.utils.io.NativeConstants.KDSETMODE; import static ev3dev.utils.io.NativeConstants.KDSKBMODE; import static ev3dev.utils.io.NativeConstants.VT_GETMODE; import static ev3dev.utils.io.NativeConstants.VT_GETSTATE; import static ev3dev.utils.io.NativeConstants.VT_RELDISP; import static ev3dev.utils.io.NativeConstants.VT_SETMODE;
package ev3dev.utils.io; /** * Wrapper for basic actions on Linux VT/TTY * * @author Jakub Vaněk * @since 2.4.7 */ public class NativeTTY extends NativeDevice { /** * Initialize new TTY. * * @param dname Path to TTY device. * @throws LastErrorException when the operation fails. */ public NativeTTY(@NonNull String dname) throws LastErrorException { super(dname, NativeConstants.O_RDWR); } /** * Initialize new TTY. * * @param dname Path to TTY device. * @param flags Opening mode, e.g. read, write or both. * @throws LastErrorException when the operation fails. */ public NativeTTY(@NonNull String dname, int flags) throws LastErrorException { super(dname, flags); } /** * Initialize new TTY. * * @param dname Path to TTY device. * @param libc standard C library interface to be used. * @throws LastErrorException when the operation fails. */ public NativeTTY(@NonNull String dname, @NonNull ILibc libc) throws LastErrorException { super(dname, NativeConstants.O_RDWR, libc); } /** * Initialize new TTY. * * @param dname Path to TTY device. * @param flags Opening mode, e.g. read, write or both. * @param libc standard C library interface to be used. * @throws LastErrorException when the operation fails. */ public NativeTTY(@NonNull String dname, int flags, @NonNull ILibc libc) throws LastErrorException { super(dname, flags, libc); } /** * Get current TTY mode. TTY mode is mostly about VT switching. * * @return TTY mode. * @throws LastErrorException when the operation fails. */ public vt_mode getVTmode() throws LastErrorException { vt_mode mode = new vt_mode(); super.ioctl(VT_GETMODE, mode.getPointer()); mode.read(); return mode; } /** * Set current TTY mode. TTY mode is mostly about VT switching. * * @param mode TTY mode. * @throws LastErrorException when the operation fails. */ public void setVTmode(@NonNull vt_mode mode) throws LastErrorException { mode.write(); super.ioctl(VT_SETMODE, mode.getPointer()); } /** * Get current TTY state. * * @return TTY state. * @throws LastErrorException when the operation fails. */ public vt_stat getVTstate() throws LastErrorException { vt_stat stat = new vt_stat(); super.ioctl(VT_GETSTATE, stat.getPointer()); stat.read(); return stat; } /** * Get current keyboard mode. * * @return Keyboard mode (raw, transformed or off) - K_* constants. * @throws LastErrorException when the operation fails. */ public int getKeyboardMode() throws LastErrorException { IntByReference kbd = new IntByReference(0); super.ioctl(KDGKBMODE, kbd); return kbd.getValue(); } /** * Set keyboard mode. * * @param mode Keyboard mode (raw, transformed or off) - K_* constants. * @throws LastErrorException when the operation fails. */ public void setKeyboardMode(int mode) throws LastErrorException {
super.ioctl(KDSKBMODE, mode);
2
izumin5210/Sunazuri
app/src/main/java/info/izumin/android/sunazuri/infrastructure/InfrastructureComponent.java
[ "public interface OauthRepository {\n Single<AuthorizedUser> getToken(String code);\n}", "public interface TeamsRepository {\n Single<List<Team>> get(AuthorizedUser user);\n}", "public interface UsersRepository {\n Observable<AuthorizedUser> getCurrentUser();\n Single<List<AuthorizedUser>> getAuthor...
import dagger.Component; import info.izumin.android.sunazuri.domain.repository.OauthRepository; import info.izumin.android.sunazuri.domain.repository.TeamsRepository; import info.izumin.android.sunazuri.domain.repository.UsersRepository; import info.izumin.android.sunazuri.infrastructure.api.ApiModule; import info.izumin.android.sunazuri.infrastructure.cache.CacheModule; import info.izumin.android.sunazuri.infrastructure.entity.OauthParams; import info.izumin.android.sunazuri.infrastructure.repository.RepositoryModule; import okhttp3.OkHttpClient; import javax.inject.Singleton;
package info.izumin.android.sunazuri.infrastructure; /** * Created by izumin on 5/13/2016 AD. */ @Singleton @Component( modules = { InfrastructureModule.class, RepositoryModule.class, HttpClientModule.class, ApiModule.class, CacheModule.class } ) public interface InfrastructureComponent { TeamsRepository teamsRepository();
OauthRepository oauthRepository();
0
maoruibin/AppPlus
app/src/main/java/com/gudong/appkit/receiver/BootReceiver.java
[ "public class App extends Application {\n private static final String DB_NAME = \"appplus.db\";\n public static LiteOrm sDb;\n public static Context sContext;\n @Override\n public void onCreate() {\n super.onCreate();\n sDb = LiteOrm.newSingleInstance(this, DB_NAME);\n sContext =...
import com.gudong.appkit.dao.AppInfoEngine; import com.gudong.appkit.dao.DataHelper; import com.gudong.appkit.event.EEvent; import com.gudong.appkit.event.RxBus; import com.gudong.appkit.event.RxEvent; import com.gudong.appkit.utils.logger.Logger; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import com.gudong.appkit.App; import com.gudong.appkit.dao.AppEntity;
/* * Copyright (c) 2015 GuDong * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.gudong.appkit.receiver; /** * Created by GuDong on 12/7/15 22:49. * Contact with 1252768410@qq.com. */ public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String packageName = intent.getDataString(); if(TextUtils.isEmpty(packageName))return; if(packageName.contains("package:")){ packageName = packageName.replace("package:",""); } // receive uninstall action , now we need remove uninstalled app from list if(Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())){ // AppEntity uninstalledApp = new AppEntity(packageName);
AppEntity uninstalledApp = DataHelper.getAppByPackageName(packageName);
3
paulirotta/cascade
cascade/src/main/java/com/reactivecascade/util/NetUtil.java
[ "@NotCallOrigin\npublic class RunnableAltFuture<IN, OUT> extends AbstractAltFuture<IN, OUT> implements IRunnableAltFuture<IN, OUT> {\n private final IActionR<OUT> mAction;\n\n /**\n * Create a {@link java.lang.Runnable} which will be executed one time on the\n * {@link com.reactivecascade.i.IThreadTyp...
import android.Manifest; import android.app.Activity; import android.content.Context; import android.net.NetworkInfo; import android.net.wifi.SupplicantState; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresPermission; import android.support.annotation.WorkerThread; import android.telephony.TelephonyManager; import com.reactivecascade.functional.RunnableAltFuture; import com.reactivecascade.functional.SettableAltFuture; import com.reactivecascade.i.IAltFuture; import com.reactivecascade.i.IGettable; import com.reactivecascade.i.IThreadType; import java.io.IOException; import java.util.Collection; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.internal.framed.Header; import static android.telephony.TelephonyManager.NETWORK_TYPE_1xRTT; import static android.telephony.TelephonyManager.NETWORK_TYPE_CDMA; import static android.telephony.TelephonyManager.NETWORK_TYPE_EDGE; import static android.telephony.TelephonyManager.NETWORK_TYPE_EHRPD; import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_0; import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_A; import static android.telephony.TelephonyManager.NETWORK_TYPE_EVDO_B; import static android.telephony.TelephonyManager.NETWORK_TYPE_GPRS; import static android.telephony.TelephonyManager.NETWORK_TYPE_HSDPA; import static android.telephony.TelephonyManager.NETWORK_TYPE_HSPA; import static android.telephony.TelephonyManager.NETWORK_TYPE_HSPAP; import static android.telephony.TelephonyManager.NETWORK_TYPE_HSUPA; import static android.telephony.TelephonyManager.NETWORK_TYPE_IDEN; import static android.telephony.TelephonyManager.NETWORK_TYPE_LTE; import static android.telephony.TelephonyManager.NETWORK_TYPE_UMTS; import static android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN; import static com.reactivecascade.Async.NET_READ; import static com.reactivecascade.Async.NET_WRITE;
/* This file is part of Reactive Cascade which is released under The MIT License. See license.md , https://github.com/futurice/cascade and http://reactivecascade.com for details. This is open source for the common good. Please contribute improvements by pull request or contact paulirotta@gmail.com */ package com.reactivecascade.util; /** * OkHttp convenience wrapper methods */ public final class NetUtil extends Origin { public enum NetType {NET_2G, NET_2_5G, NET_3G, NET_3_5G, NET_4G, NET_5G} private static final int MAX_NUMBER_OF_WIFI_NET_CONNECTIONS = 6; private static final int MAX_NUMBER_OF_3G_NET_CONNECTIONS = 4; private static final int MAX_NUMBER_OF_2G_NET_CONNECTIONS = 2; @NonNull private final OkHttpClient mOkHttpClient; @NonNull private final TelephonyManager mTelephonyManager; @NonNull private final WifiManager mWifiManager; @NonNull private final IThreadType mNetReadThreadType; @NonNull private final IThreadType mNetWriteThreadType; @RequiresPermission(allOf = { Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE}) public NetUtil(@NonNull final Context context) {
this(context, NET_READ, NET_WRITE);
5
Biacode/presentations
tdd/service/src/test/java/com/barcamp/tdd/service/user/impl/UserServiceImplTest.java
[ "@Entity\n@Table(name = \"USER\")\npublic class User implements Serializable {\n private static final long serialVersionUID = 415031695037724472L;\n\n //region Properties\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n\n @Column(name = \"email\")\n private String em...
import com.barcamp.tdd.domain.user.User; import com.barcamp.tdd.repository.user.UserRepository; import com.barcamp.tdd.service.user.UserService; import com.barcamp.tdd.service.user.dto.UserCreationDto; import com.barcamp.tdd.service.user.exception.UserAlreadyExistsForEmailException; import com.barcamp.tdd.service.user.exception.UserNotFoundForIdException; import com.barcamp.tdd.test.AbstractServiceImplTest; import org.apache.commons.lang3.SerializationUtils; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Test; import static org.easymock.EasyMock.*; import static org.junit.Assert.*;
package com.barcamp.tdd.service.user.impl; /** * Author: Arthur Asatryan * Company: SFL LLC * Date: 6/18/16 * Time: 11:26 PM */ public class UserServiceImplTest extends AbstractServiceImplTest { //region Test subject and mocks @TestSubject private UserService userService = new UserServiceImpl(); @Mock private UserRepository userRepository; //endregion //region Constructors public UserServiceImplTest() { } //endregion //region Test methods //region initial @Test public void testHaveUserService() { resetAll(); // test data // expectations replayAll(); // run test scenario assertNotNull(userService); verifyAll(); } @Test public void testHaveUserRepository() { resetAll(); // test data // expectations replayAll(); // run test scenario assertNotNull(userRepository); verifyAll(); } //endregion //region create @Test public void testCreateWithInvalidArguments() { resetAll(); // test data final UserCreationDto validDto = getServiceImplTestHelper().buildUserCreationDto(); UserCreationDto invalidDto; // expectations replayAll(); // run test scenario // the dto should not be null invalidDto = null; try { userService.create(invalidDto); fail("exception should be thrown"); } catch (final IllegalArgumentException ignore) { // expected } // the email should not be null invalidDto = SerializationUtils.clone(validDto); invalidDto.setEmail(null); try { userService.create(invalidDto); fail("exception should be thrown"); } catch (final IllegalArgumentException ignore) { // expected } // the password should not be null invalidDto = SerializationUtils.clone(validDto); invalidDto.setPassword(null); try { userService.create(invalidDto); fail("exception should be thrown"); } catch (final IllegalArgumentException ignore) { // expected } verifyAll(); } @Test public void testCreateWhenUserAlreadyExists() { resetAll(); // test data final UserCreationDto dto = getServiceImplTestHelper().buildUserCreationDto(); final User user = getServiceImplTestHelper().buildUser(); // expectations expect(userRepository.findByEmail(dto.getEmail())).andReturn(user); replayAll(); // run test scenario try { userService.create(dto); fail("exception should be thrown"); } catch (final UserAlreadyExistsForEmailException ex) { // expected assertNotNull(ex); assertEquals(dto.getEmail(), ex.getEmail()); } verifyAll(); } @Test public void testCreate() { resetAll(); // test data final UserCreationDto dto = getServiceImplTestHelper().buildUserCreationDto(); // expectations expect(userRepository.findByEmail(dto.getEmail())).andReturn(null); expect(userRepository.save(isA(User.class))).andAnswer(() -> (User) getCurrentArguments()[0]); replayAll(); // run test scenario final User result = userService.create(dto); getServiceImplTestHelper().assertPersistentUserAndCreationDto(dto, result); verifyAll(); } //endregion //region getById @Test public void testGetByIdWithInvalidArguments() { resetAll(); // test data // expectations replayAll(); // run test scenario try { userService.getById(null); fail("exception should be thrown"); } catch (final IllegalArgumentException ignore) { // expected } verifyAll(); } @Test public void testGetByIdWhenUserNotFound() { resetAll(); // test data final Long id = 7L; // expectations expect(userRepository.findOne(id)).andReturn(null); replayAll(); // run test scenario try { userService.getById(id); fail("exception should be thrown");
} catch (final UserNotFoundForIdException ex) {
5
datanerds-io/avropatch
src/test/java/io/datanerds/avropatch/serialization/ConcurrencyTest.java
[ "@ThreadSafe\npublic class Patch<T> {\n\n @AvroSchema(DefaultSchema.HEADERS)\n private final Map<String, Object> headers;\n @AvroSchema(DefaultSchema.VALUE)\n private final T resource;\n @AvroSchema(DefaultSchema.TIMESTAMP)\n private final Date timestamp;\n private final List<Operation> operati...
import com.google.common.collect.ImmutableList; import io.datanerds.avropatch.Patch; import io.datanerds.avropatch.operation.Operation; import io.datanerds.avropatch.operation.OperationGenerator; import io.datanerds.avropatch.value.Bimmel; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.*; import static io.datanerds.avropatch.serialization.PatchMapper.arrayBuilder; import static io.datanerds.avropatch.serialization.PatchMapper.builder; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat;
package io.datanerds.avropatch.serialization; public class ConcurrencyTest { private static Logger logger = LoggerFactory.getLogger(ConcurrencyTest.class); private static final int NUMBER_OF_THREADS = 200; private static final int NUMBER_OF_PATCHES = 100; private static final int MAX_PATCH_SIZE = 50;
private static final List<Patch> PATCHES = Collections.unmodifiableList(generateData());
0
sfPlayer1/Matcher
src/matcher/type/ClassEnvironment.java
[ "public enum NameType {\n\tPLAIN(true, false, false, 0),\n\tMAPPED(false, true, false, 0),\n\tAUX(false, false, false, 1),\n\tAUX2(false, false, false, 2),\n\n\tMAPPED_PLAIN(true, true, false, 0),\n\tMAPPED_AUX_PLAIN(true, true, false, 1),\n\tMAPPED_AUX2_PLAIN(true, true, false, 2),\n\tMAPPED_TMP_PLAIN(true, true, ...
import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystemNotFoundException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.DoubleConsumer; import java.util.regex.Pattern; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.InnerClassNode; import org.objectweb.asm.tree.MethodNode; import matcher.NameType; import matcher.Util; import matcher.classifier.ClassifierUtil; import matcher.classifier.MatchingCache; import matcher.config.ProjectConfig; import matcher.srcprocess.Decompiler; import matcher.type.Signature.ClassSignature;
} } if (!createUnknown) return null; ClassInstance ret = new ClassInstance(id, this); addSharedCls(ret); return ret; } private Path getPath(URL url) { URI uri = null; try { uri = url.toURI(); Path ret = Paths.get(uri); if (uri.getScheme().equals("jrt") && !Files.exists(ret)) { // workaround for https://bugs.openjdk.java.net/browse/JDK-8224946 ret = Paths.get(new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), "/modules".concat(uri.getPath()), uri.getQuery(), uri.getFragment())); } return ret; } catch (URISyntaxException e) { throw new RuntimeException(e); } catch (FileSystemNotFoundException e) { try { addOpenFileSystem(FileSystems.newFileSystem(uri, Collections.emptyMap())); return Paths.get(uri); } catch (FileSystemNotFoundException e2) { throw new RuntimeException("can't find fs for "+url, e2); } catch (IOException e2) { throw new UncheckedIOException(e2); } } } static URI getContainingUri(URI uri, String clsName) { String path; if (uri.getScheme().equals("jar")) { path = uri.getSchemeSpecificPart(); int pos = path.lastIndexOf("!/"); if (pos > 0) { try { return new URI(path.substring(0, pos)); } catch (URISyntaxException e) { throw new RuntimeException(e); } } else { throw new UnsupportedOperationException("jar uri without !/: "+uri); } } else { path = uri.getPath(); } if (path == null) { throw new UnsupportedOperationException("uri without path: "+uri); } int rootPos = path.length() - ".class".length() - clsName.length(); if (rootPos <= 0 || !path.endsWith(".class") || !path.startsWith(clsName, rootPos)) { throw new UnsupportedOperationException("unknown path format: "+uri); } path = path.substring(0, rootPos - 1); try { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path, uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new RuntimeException(e); } } static ClassNode readClass(Path path, boolean skipCode) { try { ClassReader reader = new ClassReader(Files.readAllBytes(path)); ClassNode cn = new ClassNode(); reader.accept(cn, ClassReader.EXPAND_FRAMES | (skipCode ? ClassReader.SKIP_CODE : 0)); return cn; } catch (IOException e) { throw new UncheckedIOException(e); } } /** * 1st class processing pass, member+class hierarchy and signature initialization. * * Only the (known) classes are fully available at this point. */ static void processClassA(ClassInstance cls, Pattern nonObfuscatedMemberPattern) { assert !cls.isInput() || !cls.isShared(); Set<String> strings = cls.strings; for (ClassNode cn : cls.getAsmNodes()) { if (cls.isInput() && cls.getSignature() == null && cn.signature != null) { cls.setSignature(ClassSignature.parse(cn.signature, cls.getEnv())); } boolean isEnum = (cn.access & Opcodes.ACC_ENUM) != 0; for (int i = 0; i < cn.methods.size(); i++) { MethodNode mn = cn.methods.get(i); if (cls.getMethod(mn.name, mn.desc) == null) { boolean nameObfuscated = cls.isInput() && !mn.name.equals("<clinit>") && !mn.name.equals("<init>") && (!mn.name.equals("main") || !mn.desc.equals("([Ljava/lang/String;)V") || mn.access != (Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC)) && (!isEnum || !isStandardEnumMethod(cn.name, mn)) && (nonObfuscatedMemberPattern == null || !nonObfuscatedMemberPattern.matcher(cn.name+"/"+mn.name+mn.desc).matches()); cls.addMethod(new MethodInstance(cls, mn.name, mn.desc, mn, nameObfuscated, i));
ClassifierUtil.extractStrings(mn.instructions, strings);
2
caseydavenport/biermacht
src/com/biermacht/brews/xml/RecipeXmlWriter.java
[ "public class Fermentable extends Ingredient implements Parcelable {\n\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n // Name - Inherited\n // Version - Inherited\n private String type; // G...
import android.content.Context; import android.os.Environment; import android.util.Log; import com.biermacht.brews.ingredient.Fermentable; import com.biermacht.brews.ingredient.Hop; import com.biermacht.brews.ingredient.Misc; import com.biermacht.brews.ingredient.Water; import com.biermacht.brews.ingredient.Yeast; import com.biermacht.brews.recipe.BeerStyle; import com.biermacht.brews.recipe.MashProfile; import com.biermacht.brews.recipe.MashStep; import com.biermacht.brews.recipe.Recipe; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult;
Element versionElement = d.createElement("VERSION"); Element typeElement = d.createElement("TYPE"); Element amountElement = d.createElement("AMOUNT"); Element yieldElement = d.createElement("YIELD"); Element colorElement = d.createElement("COLOR"); Element addAfterBoilElement = d.createElement("ADD_AFTER_BOIL"); // Assign values nameElement.setTextContent(f.getName()); versionElement.setTextContent(f.getVersion() + ""); typeElement.setTextContent(f.getFermentableType()); amountElement.setTextContent(f.getBeerXmlStandardAmount() + ""); yieldElement.setTextContent(f.getYield() + ""); colorElement.setTextContent(f.getLovibondColor() + ""); addAfterBoilElement.setTextContent(f.isAddAfterBoil() + ""); // Attach to element. fermentableElement.appendChild(nameElement); fermentableElement.appendChild(versionElement); fermentableElement.appendChild(typeElement); fermentableElement.appendChild(amountElement); fermentableElement.appendChild(yieldElement); fermentableElement.appendChild(colorElement); fermentableElement.appendChild(addAfterBoilElement); // Attach to list of elements. fermentablesElement.appendChild(fermentableElement); } return fermentablesElement; } public Element getMiscsChild(Document d, ArrayList<Misc> l) { // Create the element. Element miscsElement = d.createElement("MISCS"); for (Misc m : l) { miscsElement.appendChild(this.getMiscChild(d, m)); } return miscsElement; } public Element getMiscChild(Document d, Misc m) { // Create the element. Element rootElement = d.createElement("MISC"); // Create a mapping of name -> value Map<String, String> map = new HashMap<String, String>(); map.put("NAME", m.getName()); map.put("VERSION", m.getVersion() + ""); map.put("TYPE", m.getType()); map.put("USE", m.getUse()); map.put("AMOUNT", String.format("%2.8f", m.getBeerXmlStandardAmount())); map.put("DISPLAY_AMOUNT", m.getDisplayAmount() + " " + m.getDisplayUnits()); map.put("DISPLAY_TIME", m.getTime() + " " + m.getTimeUnits()); map.put("AMOUNT_IS_WEIGHT", m.amountIsWeight() ? "true" : "false"); map.put("NOTES", m.getShortDescription()); map.put("USE_FOR", m.getUseFor()); for (Map.Entry<String, String> e : map.entrySet()) { String fieldName = e.getKey(); String fieldValue = e.getValue(); Element element = d.createElement(fieldName); element.setTextContent(fieldValue); rootElement.appendChild(element); } return rootElement; } public Element getYeastsChild(Document d, ArrayList<Yeast> l) { // Create the element. Element yeastsElement = d.createElement("YEASTS"); for (Yeast y : l) { Element yeastElement = d.createElement("YEAST"); // Create fields of element Element nameElement = d.createElement("NAME"); Element versionElement = d.createElement("VERSION"); Element typeElement = d.createElement("TYPE"); Element formElement = d.createElement("FORM"); Element amountElement = d.createElement("AMOUNT"); Element laboratoryElement = d.createElement("LABORATORY"); Element productIdElement = d.createElement("PRODUCT_ID"); Element minTempElement = d.createElement("MIN_TEMPERATURE"); Element maxTempElement = d.createElement("MAX_TEMPERATURE"); Element attenuationElement = d.createElement("ATTENUATION"); // Assign values nameElement.setTextContent(y.getName()); versionElement.setTextContent(y.getVersion() + ""); typeElement.setTextContent(y.getType()); formElement.setTextContent(y.getForm()); amountElement.setTextContent(y.getBeerXmlStandardAmount() + ""); laboratoryElement.setTextContent(y.getLaboratory()); productIdElement.setTextContent(y.getProductId()); minTempElement.setTextContent(y.getBeerXmlStandardFermentationTemp() + ""); maxTempElement.setTextContent(y.getBeerXmlStandardFermentationTemp() + ""); attenuationElement.setTextContent(y.getAttenuation() + ""); // Attach to element. yeastElement.appendChild(nameElement); yeastElement.appendChild(versionElement); yeastElement.appendChild(typeElement); yeastElement.appendChild(amountElement); yeastElement.appendChild(laboratoryElement); yeastElement.appendChild(productIdElement); yeastElement.appendChild(minTempElement); yeastElement.appendChild(maxTempElement); yeastElement.appendChild(attenuationElement); // Attach to list of elements. yeastsElement.appendChild(yeastElement); } return yeastsElement; }
public Element getWatersChild(Document d, ArrayList<Water> l) {
3
junicorn/roo
src/main/java/social/roo/controller/auth/GithubController.java
[ "public enum UserRole {\n\n GUEST(0, \"游客\"),\n MEMBER(1, \"注册会员-所有注册用户自动属于该角色\"),\n VIP(2, \"VIP会员-没有特殊权限,只是一个身份象征\"),\n MODERATOR(3, \"版主-可以管理若干个话题下的帖子\"),\n SUPER_MODERATOR(4, \"超级版主-可以管理所有话题下的帖子和所有会员\"),\n ADMIN(5, \"管理员-享有论坛的最高权限,可以管理整个论坛,设置整个论坛的参数\");\n\n @Getter\n private Integer id;\...
import com.blade.ioc.annotation.Inject; import com.blade.kit.JsonKit; import com.blade.mvc.WebContext; import com.blade.mvc.annotation.GetRoute; import com.blade.mvc.annotation.Param; import com.blade.mvc.annotation.Path; import com.blade.mvc.http.Session; import com.github.scribejava.core.model.OAuth2AccessToken; import com.github.scribejava.core.model.OAuthRequest; import com.github.scribejava.core.model.Response; import com.github.scribejava.core.model.Verb; import com.github.scribejava.core.oauth.OAuth20Service; import lombok.extern.slf4j.Slf4j; import social.roo.enums.UserRole; import social.roo.model.dto.Auth; import social.roo.model.dto.GithubUser; import social.roo.model.entity.PlatformUser; import social.roo.model.entity.Profile; import social.roo.model.entity.User; import social.roo.service.AccountService; import social.roo.service.PlatformService; import java.util.Date; import static social.roo.RooConst.LOGIN_SESSION_KEY;
package social.roo.controller.auth; /** * Github认证控制器 * * @author biezhi * @date 2017/10/9 */ @Slf4j @Path("auth/github") public class GithubController { @Inject private OAuth20Service githubService; @Inject private PlatformService platformService; @Inject private AccountService accountService; private static final String PROTECTED_RESOURCE_URL = "https://api.github.com/user"; @GetRoute("signin") public void signin(com.blade.mvc.http.Response response) { String authorizationUrl = githubService.getAuthorizationUrl(); log.info("authorizationUrl: {}", authorizationUrl); response.redirect(authorizationUrl); } @GetRoute("callback") public void callback(@Param String code, Session session, com.blade.mvc.http.Response response) throws Exception { log.info("Code: {}", code); final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); final Response res = execute(code, request); String body = res.getBody(); GithubUser githubUser = JsonKit.formJson(body, GithubUser.class); PlatformUser platformUser = platformService.getPlatformUser(githubUser.getLogin()); if (null != platformUser) { // 直接登录 User user = accountService.getUserById(platformUser.getUid()); Auth.saveToSession(user); Auth.saveToCookie(user.getUid()); log.info("登录成功"); } else { // 判断当前是否已经登录 User loginUser = session.attribute(LOGIN_SESSION_KEY); PlatformUser temp = new PlatformUser(); temp.setAppType("github"); temp.setCreated(new Date()); temp.setUsername(githubUser.getLogin()); Profile profile = new Profile(); if (null != loginUser) { temp.setUid(loginUser.getUid()); profile.setUid(loginUser.getUid()); profile.setUsername(githubUser.getLogin()); profile.setGithub(githubUser.getLogin()); profile.save(); Auth.saveToSession(loginUser); Auth.saveToCookie(loginUser.getUid()); } else { // 创建新用户 User user = new User(); user.setUsername(githubUser.getLogin()); user.setPassword(""); user.setEmail(githubUser.getEmail()); user.setState(1); user.setAvatar(githubUser.getAvatar_url()); user.setCreated(new Date()); user.setUpdated(new Date());
user.setRole(UserRole.MEMBER.role());
0
1014277960/DailyReader
app/src/main/java/com/wulinpeng/daiylreader/bookdetail/presenter/BookDetailPresenterImpl.java
[ "public interface IBookDetailPresenter extends IBaseContract.IBasePresenter {\n\n public void getBookDetail();\n\n public boolean checkSelf();\n\n public void removeFromSelf();\n\n public void addToSelf();\n}", "public interface IBookDetailView extends IBaseContract.IBaseView {\n\n public void onBo...
import android.content.Context; import com.wulinpeng.daiylreader.net.ReaderApiManager; import com.wulinpeng.daiylreader.bookdetail.contract.IBookDetailPresenter; import com.wulinpeng.daiylreader.bookdetail.contract.IBookDetailView; import com.wulinpeng.daiylreader.bookdetail.event.CollectionChangeEvent; import com.wulinpeng.daiylreader.bean.BookCollection; import com.wulinpeng.daiylreader.bean.BookDetail; import com.wulinpeng.daiylreader.manager.CacheManager; import com.wulinpeng.daiylreader.util.RxUtil; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import wulinpeng.com.framework.base.mvp.BasePresenter;
package com.wulinpeng.daiylreader.bookdetail.presenter; /** * @author wulinpeng * @datetime: 17/2/20 下午7:59 * @description: */ public class BookDetailPresenterImpl extends BasePresenter<IBookDetailView> implements IBookDetailPresenter { private Context context; private String bookId; private BookDetail bookDetail; public BookDetailPresenterImpl(Context context, IBookDetailView rootView, String bookId) { super(rootView); this.context = context; this.bookId = bookId; } @Override public void getBookDetail() { ReaderApiManager.INSTANCE.getBookDetail(bookId)
.compose(RxUtil.rxScheduler())
6
aschaetzle/Sempala
sempala-loader/src/main/java/de/uni_freiburg/informatik/dbis/sempala/loader/run/Main.java
[ "public final class ExtVPLoader extends Loader {\n\n\t/** The constructor */\n\tpublic ExtVPLoader(Impala wrapper, String hdfsLocation) {\n\t\tsuper(wrapper, hdfsLocation);\n\t\ttablename_output = \"extvp\";\n\t}\n\n\tprivate ArrayList<String> ExtVPTypes = new ArrayList<String>();\n\tprivate ArrayList<String> ListO...
import java.sql.SQLException; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import de.uni_freiburg.informatik.dbis.sempala.loader.ExtVPLoader; import de.uni_freiburg.informatik.dbis.sempala.loader.Loader; import de.uni_freiburg.informatik.dbis.sempala.loader.SimplePropertyTableLoader; import de.uni_freiburg.informatik.dbis.sempala.loader.SingleTableLoader; import de.uni_freiburg.informatik.dbis.sempala.loader.spark.ComplexPropertyTableLoader; import de.uni_freiburg.informatik.dbis.sempala.loader.spark.Spark; import de.uni_freiburg.informatik.dbis.sempala.loader.sql.Impala; import de.uni_freiburg.informatik.dbis.sempala.loader.sql.Impala.QueryOption;
package de.uni_freiburg.informatik.dbis.sempala.loader.run; /** * * @author Manuel Schneider <schneidm@informatik.uni-freiburg.de> * */ public class Main { /** * The main routine. * * @param args * The arguments passed to the program */ public static void main(String[] args) { // Parse command line Options options = buildOptions(); CommandLine commandLine = null; CommandLineParser parser = new BasicParser(); try { commandLine = parser.parse(options, args); } catch (ParseException e) { // Commons CLI is poorly designed and uses exceptions for missing // required options. Therefore we can not print help without // throwing // an exception. We'll just print it on every exception. System.err.println(e.getLocalizedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(100); formatter.printHelp("sempala-loader", options, true); System.exit(1); } // parse the format of the table that will be built String format = commandLine.getOptionValue(OptionNames.FORMAT.toString()); String database = commandLine.getOptionValue(OptionNames.DATABASE.toString()); Impala impala = null; Spark spark = null; if (format.equals(Format.EXTVP.toString()) || format.equals(Format.SIMPLE_PROPERTY_TABLE.toString()) || format.equals(Format.SINGLE_TABLE.toString())) { // Connect to the impala daemon if(!commandLine.hasOption(OptionNames.USER_HDFS_DIRECTORY.toString())){ System.err.println("For ExtVP format user's absolut path of HDFS direcotry -ud is also required."); System.exit(1); } try { String host = commandLine.getOptionValue(OptionNames.HOST.toString()); String port = commandLine.getOptionValue(OptionNames.PORT.toString(), "21050"); impala = new Impala(host, port, database); // Set compression codec to snappy
impala.set(QueryOption.COMPRESSION_CODEC, "SNAPPY");
7
terzerm/hover-raft
src/main/java/org/tools4j/hoverraft/command/Command.java
[ "public interface DirectPayload {\n\n int byteLength();\n\n int offset();\n\n DirectBuffer readBufferOrNull();\n\n MutableDirectBuffer writeBufferOrNull();\n\n void wrap(DirectBuffer buffer, int offset);\n\n void wrap(MutableDirectBuffer buffer, int offset);\n\n void unwrap();\n\n default bo...
import org.tools4j.hoverraft.direct.DirectPayload; import org.tools4j.hoverraft.event.Event; import org.tools4j.hoverraft.event.EventHandler; import org.tools4j.hoverraft.server.ServerContext; import org.tools4j.hoverraft.state.Transition;
/** * The MIT License (MIT) * * Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.tools4j.hoverraft.command; public interface Command extends DirectPayload, Event { CommandKey commandKey(); CommandPayload commandPayload(); default Command sourceId(final int sourceId) { commandKey().sourceId(sourceId); return this; } default Command commandIndex(final long commandIndex) { commandKey().commandIndex(commandIndex); return this; } default void copyFrom(final Command command) { writeBufferOrNull().putBytes(offset(), command.readBufferOrNull(), command.offset(), command.byteLength()); } @Override
default Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
2
ilmila/J2EEScan
src/main/java/burp/J2EELFIRetriever.java
[ "public static boolean isApacheStrutsConfigFile(byte[] response, IExtensionHelpers helpers) {\n final byte[] STRUTS_PATTERN = \"<struts\".getBytes();\n List<int[]> matchesStruts = getMatches(response, STRUTS_PATTERN, helpers);\n\n return (matchesStruts.size() > 0);\n}", "public static boolean isEtcPasswd...
import static burp.HTTPMatcher.isApacheStrutsConfigFile; import static burp.HTTPMatcher.isEtcPasswdFile; import static burp.HTTPMatcher.isEtcShadowFile; import static burp.HTTPMatcher.isIBMWSBinding; import static burp.HTTPMatcher.isSpringContextConfigFile; import burp.j2ee.Confidence; import burp.j2ee.CustomScanIssue; import burp.j2ee.Risk; import java.io.PrintWriter; import java.util.Arrays; import java.util.List;
IHttpRequestResponse ibmwebRequestResponse = cb.makeHttpRequest( baseRequestResponse.getHttpService(), helpers.stringToBytes(ibmwebLFIRequest)); byte[] ibmwebResponse = ibmwebRequestResponse.getResponse(); if (HTTPMatcher.isIBMWebExtFileWAS7(ibmwebResponse, helpers)) { cb.addScanIssue(new CustomScanIssue( baseRequestResponse.getHttpService(), requestInfo.getUrl(), ibmwebRequestResponse, "Local File Include - ibm-web-ext.xml Retrieved", "J2EEScan was able tor retrieve the IBM Application Server ibm-web-ext.xml resource through the LFI vulnerability.", LFI_REMEDY, Risk.Low, Confidence.Certain )); } } catch (Exception ex) { ex.printStackTrace(stderr); } // Try to retrieve /ibm-web-ext.xmi file try { // String ibmwebLFIRequest = requestToString.replace(baseConfigFile, "ibm-web-ext.xmi"); IHttpRequestResponse ibmwebRequestResponse = cb.makeHttpRequest( baseRequestResponse.getHttpService(), helpers.stringToBytes(ibmwebLFIRequest)); byte[] ibmwebResponse = ibmwebRequestResponse.getResponse(); if (HTTPMatcher.isIBMWebExtFileWAS6(ibmwebResponse, helpers)) { cb.addScanIssue(new CustomScanIssue( baseRequestResponse.getHttpService(), requestInfo.getUrl(), ibmwebRequestResponse, "Local File Include - ibm-web-ext.xmi Retrieved", "J2EEScan was able tor retrieve the IBM Application Server ibm-web-ext.xmi resource through the LFI vulnerability.", LFI_REMEDY, Risk.Low, Confidence.Certain )); } } catch (Exception ex) { ex.printStackTrace(stderr); } // Try to retrieve ibm-ws-bnd.xml file try { // http://www-01.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.wlp.nd.doc/ae/twlp_sec_ws_basicauth.html?cp=SSAW57_8.5.5%2F1-3-11-0-4-9-0-1 String ibmwebLFIRequest = requestToString.replace(baseConfigFile, "ibm-ws-bnd.xml"); IHttpRequestResponse ibmwebRequestResponse = cb.makeHttpRequest( baseRequestResponse.getHttpService(), helpers.stringToBytes(ibmwebLFIRequest)); byte[] ibmwebResponse = ibmwebRequestResponse.getResponse(); if (isIBMWSBinding(ibmwebResponse, helpers)) { cb.addScanIssue(new CustomScanIssue( baseRequestResponse.getHttpService(), requestInfo.getUrl(), ibmwebRequestResponse, "Local File Include - ibm-ws-bnd.xml Retrieved", "J2EEScan was able tor retrieve the IBM Application Server ibm-ws-bnd.xml resource through the LFI vulnerability.", LFI_REMEDY, Risk.Low, Confidence.Certain )); } } catch (Exception ex) { ex.printStackTrace(stderr); } // Try to retrieve weblogic.xml file try { String weblogicLFIRequest = requestToString.replace(baseConfigFile, "weblogic.xml"); IHttpRequestResponse weblogicRequestResponse = cb.makeHttpRequest( baseRequestResponse.getHttpService(), helpers.stringToBytes(weblogicLFIRequest)); byte[] weblogicResponse = weblogicRequestResponse.getResponse(); if (HTTPMatcher.isWebLogicFile(weblogicResponse, helpers)) { cb.addScanIssue(new CustomScanIssue( baseRequestResponse.getHttpService(), requestInfo.getUrl(), weblogicRequestResponse, "Local File Include - weblogic.xml Retrieved", "J2EEScan was able tor retrieve the weblogic.xml resource through the LFI vulnerability.", LFI_REMEDY, Risk.High, Confidence.Certain )); } } catch (Exception ex) { ex.printStackTrace(stderr); } // Try to retrieve the struts configuration file try { // Possibile paths: // /WEB-INF/classes/struts.xml // /WEB-INF/struts-config.xml // /WEB-INF/struts.xml final List<String> STRUTS_PATHS = Arrays.asList( helpers.urlEncode("classes/struts.xml"), "struts-config.xml", "struts.xml" ); for (String STRUT_PATH : STRUTS_PATHS) { String strutLFIRequest = requestToString.replace(baseConfigFile, STRUT_PATH); IHttpRequestResponse strutsRequestResponse = cb.makeHttpRequest( baseRequestResponse.getHttpService(), helpers.stringToBytes(strutLFIRequest)); byte[] strutsResponse = strutsRequestResponse.getResponse();
if (isApacheStrutsConfigFile(strutsResponse, helpers)) {
0
apache/geronimo-gshell
gshell-core/src/main/java/org/apache/geronimo/gshell/builtins/SourceCommand.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.geronimo.gshell.command.CommandException; import org.apache.geronimo.gshell.command.MessageSource; import org.apache.geronimo.gshell.command.Command; import org.apache.geronimo.gshell.console.IO; import org.apache.geronimo.gshell.Shell; import java.io.File; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import org.apache.commons.cli.CommandLine; import org.apache.geronimo.gshell.command.CommandSupport;
/* * 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; /** * Read and execute commands from a file/url in the current shell environment. * * @version $Rev$ $Date$ */ public class SourceCommand extends CommandSupport { private Shell shell; public SourceCommand(final Shell shell) { super("source"); this.shell = shell; } protected String getUsage() { return super.getUsage() + " <file|url>"; } protected boolean processCommandLine(final CommandLine line) throws CommandException { assert line != null; String[] args = line.getArgs();
IO io = getIO();
4
searchisko/elasticsearch-river-sysinfo
src/main/java/org/jboss/elasticsearch/river/sysinfo/SysinfoRiverPlugin.java
[ "public class JRLifecycleAction extends\n\t\tClusterAction<JRLifecycleRequest, JRLifecycleResponse, JRLifecycleRequestBuilder> {\n\n\tpublic static final JRLifecycleAction INSTANCE = new JRLifecycleAction();\n\tpublic static final String NAME = \"sysinfo_river/lifecycle\";\n\n\tprotected JRLifecycleAction() {\n\t\t...
import org.elasticsearch.action.ActionModule; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.plugins.AbstractPlugin; import org.elasticsearch.rest.RestModule; import org.elasticsearch.river.RiversModule; import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.JRLifecycleAction; import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.RestJRLifecycleAction; import org.jboss.elasticsearch.river.sysinfo.mgm.lifecycle.TransportJRLifecycleAction; import org.jboss.elasticsearch.river.sysinfo.mgm.period.JRPeriodAction; import org.jboss.elasticsearch.river.sysinfo.mgm.period.RestJRPeriodAction; import org.jboss.elasticsearch.river.sysinfo.mgm.period.TransportJRPeriodAction; import org.jboss.elasticsearch.river.sysinfo.mgm.riverslist.ListRiversAction; import org.jboss.elasticsearch.river.sysinfo.mgm.riverslist.RestListRiversAction; import org.jboss.elasticsearch.river.sysinfo.mgm.riverslist.TransportListRiversAction;
/* * JBoss, Home of Professional Open Source * Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. */ package org.jboss.elasticsearch.river.sysinfo; /** * System Info River ElasticSearch Plugin class. * * @author Vlastimil Elias (velias at redhat dot com) */ public class SysinfoRiverPlugin extends AbstractPlugin { @Inject public SysinfoRiverPlugin() { } @Override public String name() { return "river-sysinfo"; } @Override public String description() { return "River Sysinfo Plugin"; } public void onModule(RiversModule module) { module.registerRiver("sysinfo", SysinfoRiverModule.class); } public void onModule(RestModule module) { module.addRestAction(RestListRiversAction.class); module.addRestAction(RestJRLifecycleAction.class); module.addRestAction(RestJRPeriodAction.class); } public void onModule(ActionModule module) { module.registerAction(ListRiversAction.INSTANCE, TransportListRiversAction.class); module.registerAction(JRLifecycleAction.INSTANCE, TransportJRLifecycleAction.class);
module.registerAction(JRPeriodAction.INSTANCE, TransportJRPeriodAction.class);
5