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
ktisha/Crucible4IDEA
src/com/jetbrains/crucible/ui/toolWindow/details/CommentForm.java
[ "@State(name = \"CrucibleSettings\",\n storages = {\n @Storage(file = \"$APP_CONFIG$\" + \"/crucibleConnector.xml\")\n }\n)\npublic class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {\n public String SERVER_URL = \"\";\n public String USERNAME = \"\";\n\n @Override\...
import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider; import com.intellij.openapi.fileTypes.PlainTextLanguage; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.ui.*; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.crucible.configuration.CrucibleSettings; import com.jetbrains.crucible.connection.CrucibleManager; import com.jetbrains.crucible.model.Comment; import com.jetbrains.crucible.model.Review; import com.jetbrains.crucible.model.User; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.Set;
package com.jetbrains.crucible.ui.toolWindow.details; /** * User: ktisha */ public class CommentForm extends JPanel { private static final int ourBalloonWidth = 350; private static final int ourBalloonHeight = 200; private final EditorTextField myReviewTextField; private JBPopup myBalloon; private Editor myEditor; @NotNull private final Project myProject; private final boolean myGeneral; private final boolean myReply; @Nullable private FilePath myFilePath; private boolean myOK; public Review getReview() { return myReview; } private Review myReview; private Comment myParentComment; public CommentForm(@NotNull Project project, boolean isGeneral, boolean isReply, @Nullable FilePath filePath) { super(new BorderLayout()); myProject = project; myGeneral = isGeneral; myReply = isReply; myFilePath = filePath; final EditorTextFieldProvider service = ServiceManager.getService(project, EditorTextFieldProvider.class); final Set<EditorCustomization> editorFeatures = ContainerUtil.newHashSet(SoftWrapsEditorCustomization.ENABLED, SpellCheckingEditorCustomizationProvider.getInstance().getEnabledCustomization()); myReviewTextField = service.getEditorField(PlainTextLanguage.INSTANCE, project, editorFeatures); final JScrollPane pane = ScrollPaneFactory.createScrollPane(myReviewTextField); pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); add(pane); myReviewTextField.setPreferredSize(new Dimension(ourBalloonWidth, ourBalloonHeight)); myReviewTextField.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK), "postComment"); myReviewTextField.getActionMap().put("postComment", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { myOK = true; if (myBalloon != null) { myBalloon.dispose(); } } }); } @Nullable public Comment postComment() {
final Comment comment = new Comment(new User(CrucibleSettings.getInstance().USERNAME), getText(), !myOK);
4
orekyuu/Riho
src/net/orekyuu/riho/events/TestListener.java
[ "public enum FacePattern {\n NORMAL, SMILE1, SMILE2, AWAWA, FUN, JITO, SURPRISE, SYUN;\n}", "public class Loop {\n private final int loopCount;\n private static final Loop INFINITE = new Loop(-1);\n private static final Loop ONCE = Loop.of(1);\n\n private Loop(int count) {\n this.loopCount =...
import com.intellij.execution.testframework.AbstractTestProxy; import com.intellij.execution.testframework.TestStatusListener; import com.intellij.openapi.project.Project; import net.orekyuu.riho.character.FacePattern; import net.orekyuu.riho.character.Loop; import net.orekyuu.riho.character.Reaction; import net.orekyuu.riho.emotion.Emotion; import net.orekyuu.riho.topics.RihoReactionNotifier; import org.jetbrains.annotations.Nullable; import java.time.Duration; import java.util.Random;
package net.orekyuu.riho.events; public class TestListener extends TestStatusListener { private int failedCount = 0; private static final Random rand = new Random(); @Override public void testSuiteFinished(@Nullable AbstractTestProxy abstractTestProxy) { } @Override public void testSuiteFinished(@Nullable AbstractTestProxy abstractTestProxy, Project project) { super.testSuiteFinished(abstractTestProxy, project); if (abstractTestProxy == null) { return; } RihoReactionNotifier notifier = project.getMessageBus().syncPublisher(RihoReactionNotifier.REACTION_NOTIFIER); if (abstractTestProxy.isPassed() || abstractTestProxy.isIgnored()) { if (failedCount == 0) { notifier.reaction(Reaction.of(FacePattern.SMILE2, Duration.ofSeconds(5))); } else {
notifier.reaction(Reaction.of(FacePattern.SMILE2, Duration.ofSeconds(5), Emotion.SURPRISED, Loop.once()));
1
TomGrill/gdx-twitter
gdx-twitter-core-tests/src/de/tomgrill/gdxtwitter/core/tests/TwitterSystemUnitTests.java
[ "public class TwitterConfig {\n\n\t/**\n\t * Put your Consumer Key (API Key) here. Get it at <a\n\t * href=\"https://apps.twitter.com/\">https://apps.twitter.com/</a>\n\t * \n\t */\n\tpublic String TWITTER_CONSUMER_KEY = \"\";\n\n\t/**\n\t * Put your Consumer Secret (API Secret) here. Get it at <a\n\t * href=\"http...
import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.headless.HeadlessApplication; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.Constructor; import com.badlogic.gdx.utils.reflect.Field; import com.badlogic.gdx.utils.reflect.Method; import com.badlogic.gdx.utils.reflect.ReflectionException; import de.tomgrill.gdxtwitter.core.TwitterConfig; import de.tomgrill.gdxtwitter.core.TwitterSystem; import de.tomgrill.gdxtwitter.core.tests.stubs.ActivityStub; import de.tomgrill.gdxtwitter.core.tests.stubs.FragmentStub; import de.tomgrill.gdxtwitter.core.tests.stubs.GdxLifecycleListenerStub; import de.tomgrill.gdxtwitter.core.tests.stubs.GdxStub; import de.tomgrill.gdxtwitter.core.tests.stubs.PreferencesStub; import de.tomgrill.gdxtwitter.core.tests.stubs.SupportFragmentStub; import de.tomgrill.gdxtwitter.core.tests.stubs.TwitterAPIStub;
/******************************************************************************* * Copyright 2015 See AUTHORS file. * * 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.tomgrill.gdxtwitter.core.tests; @RunWith(PowerMockRunner.class) @PrepareForTest({ ClassReflection.class, Field.class, Constructor.class, Method.class }) public class TwitterSystemUnitTests { private TwitterConfig config; private ClassReflection classReflectionMock; private Field fieldMock; private Constructor constructorMock; private Method methodMock; private ActivityStub activityStub; private TwitterAPIStub twitterAPIStub;
private GdxStub gdxStub;
5
VisualizeMobile/AKANAndroid
src/br/com/visualize/akan/api/dao/CongressmanDao.java
[ "public class DatabaseHelper extends SQLiteOpenHelper {\n\t\n\tprivate static final String dbName = \"AKAN.db\";\n\t\n\tprivate static final String congressmanTable = \"CREATE TABLE [CONGRESSMAN] \"\n\t + \"([ID_CONGRESSMAN] VARCHAR(10) unique, [ID_UPDATE] INT, \"\n\t + \"[NAME_CONGRESSMAN] VARCHAR(40...
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import br.com.visualize.akan.api.helper.DatabaseHelper; import br.com.visualize.akan.domain.enumeration.Order; import br.com.visualize.akan.domain.exception.DatabaseInvalidOperationException; import br.com.visualize.akan.domain.exception.NullCongressmanException; import br.com.visualize.akan.domain.model.Congressman;
/* * File: CongressmanDao.java Purpose: Brings the implementation of class * CongressmanDao. */ package br.com.visualize.akan.api.dao; /** * This class represents the Data Access Object for the Congressman, responsible * for all data base operations like selections, insertions and updates. */ public class CongressmanDao extends Dao { private static final boolean EMPTY = true; private static final boolean NOT_EMPTY = false; private static CongressmanDao instance; private static String tableName = "CONGRESSMAN"; private static String tableColumns[ ] = { "ID_CONGRESSMAN", "ID_UPDATE", "NAME_CONGRESSMAN", "PARTY", "UF_CONGRESSMAN", "TOTAL_SPENT_CONGRESSMAN", "STATUS_CONGRESSMAN", "PHOTO_CONGRESSMAN", "RANKING_CONGRESSMAN" }; private CongressmanDao( Context context ) { CongressmanDao.database = new DatabaseHelper( context ); } /** * Return the unique instance of CongressmanDao active in the project. * <p> * * @return The unique instance of CongressmanDao. */ public static CongressmanDao getInstance( Context context ) { if( CongressmanDao.instance != null ) { /* !Nothing To Do. */ } else { CongressmanDao.instance = new CongressmanDao( context ); } return CongressmanDao.instance; } /** * Checks if database is empty. */ public boolean checkEmptyLocalDb() { sqliteDatabase = database.getReadableDatabase(); String query = "SELECT 1 FROM " + tableName; Cursor cursor = sqliteDatabase.rawQuery( query, null ); boolean isEmpty = NOT_EMPTY; if( cursor != null ) { if( cursor.getCount() <= 0 ) { cursor.moveToFirst(); isEmpty = EMPTY; } else { /* ! Nothing To Do */ } } else { isEmpty = EMPTY; } return isEmpty; } /** * Checks database version. */ public boolean checkDbVersion(int remoteVersion) { sqliteDatabase = database.getReadableDatabase(); String query = "SELECT * FROM VERSION"; Cursor cursor = sqliteDatabase.rawQuery( query, null ); cursor.moveToFirst(); int currentVersion = cursor.getInt( cursor.getColumnIndex("NUM_VERSION") ); boolean isLastVersion = currentVersion < remoteVersion; return isLastVersion; } /** * Inserts in the database a version of remote * database. * * @param int version of remote database. * * @return Result if the operation was successful or not. */ public boolean insertDbVersion( int version ) { boolean result = false; sqliteDatabase = database.getWritableDatabase(); sqliteDatabase.delete( "VERSION",null, null); ContentValues content = new ContentValues(); content.put( "NUM_VERSION", version ); result = (insertAndClose( sqliteDatabase, "VERSION", content ) > 0 ); return result; } /** * Up * * @param congressman * @return * @throws NullCongressmanException */
public boolean setFollowedCongressman( Congressman congressman )
4
BurstProject/burstcoin
src/java/nxt/http/EscrowSign.java
[ "public final class Account {\n\n public static enum Event {\n BALANCE, UNCONFIRMED_BALANCE, ASSET_BALANCE, UNCONFIRMED_ASSET_BALANCE,\n LEASE_SCHEDULED, LEASE_STARTED, LEASE_ENDED\n }\n\n public static class AccountAsset {\n\n private final long accountId;\n private final long ...
import javax.servlet.http.HttpServletRequest; import nxt.Account; import nxt.Attachment; import nxt.Constants; import nxt.Escrow; import nxt.NxtException; import nxt.util.Convert; import org.json.simple.JSONObject; import org.json.simple.JSONStreamAware;
package nxt.http; public final class EscrowSign extends CreateTransaction { static final EscrowSign instance = new EscrowSign(); private EscrowSign() { super(new APITag[] {APITag.TRANSACTIONS, APITag.CREATE_TRANSACTION}, "escrow", "decision"); } @Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { Long escrowId; try { escrowId = Convert.parseUnsignedLong(Convert.emptyToNull(req.getParameter("escrow"))); } catch(Exception e) { JSONObject response = new JSONObject(); response.put("errorCode", 3); response.put("errorDescription", "Invalid or not specified escrow"); return response; }
Escrow escrow = Escrow.getEscrowTransaction(escrowId);
3
opencb/bionetdb
bionetdb-lib/src/main/java/org/opencb/bionetdb/lib/utils/CsvInfo.java
[ "public class Node {\n\n private long uid;\n\n private String id;\n private String name;\n\n private List<Label> labels;\n\n private ObjectMap attributes;\n\n private static long counter = 0;\n\n public enum Label {\n INTERNAL_CONNFIG,\n\n UNDEFINED,\n\n PHYSICAL_ENTITY,\n ...
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.opencb.biodata.formats.protein.uniprot.v202003jaxb.Entry; import org.opencb.biodata.models.core.Gene; import org.opencb.biodata.models.metadata.Individual; import org.opencb.biodata.models.metadata.Sample; import org.opencb.biodata.models.variant.metadata.VariantFileHeaderComplexLine; import org.opencb.biodata.models.variant.metadata.VariantFileMetadata; import org.opencb.biodata.models.variant.metadata.VariantMetadata; import org.opencb.biodata.models.variant.metadata.VariantStudyMetadata; import org.opencb.bionetdb.core.models.network.Node; import org.opencb.bionetdb.core.models.network.Relation; import org.opencb.bionetdb.lib.utils.cache.GeneCache; import org.opencb.bionetdb.lib.utils.cache.ProteinCache; import org.opencb.commons.utils.FileUtils; import org.rocksdb.RocksDB; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.file.Path; import java.util.*; import static org.opencb.bionetdb.lib.utils.Utils.PREFIX_ATTRIBUTES;
REACTANT___REACTION___PHYSICAL_ENTITY_COMPLEX("REACTANT___REACTION___PHYSICAL_ENTITY_COMPLEX"), REACTANT___REACTION___UNDEFINED("REACTANT___REACTION___UNDEFINED"), REACTANT___REACTION___DNA("REACTANT___REACTION___DNA"), REACTANT___REACTION___RNA("REACTANT___REACTION___RNA"), PRODUCT___REACTION___PROTEIN("PRODUCT___REACTION___PROTEIN"), PRODUCT___REACTION___SMALL_MOLECULE("PRODUCT___REACTION___SMALL_MOLECULE"), PRODUCT___REACTION___PHYSICAL_ENTITY_COMPLEX("PRODUCT___REACTION___PHYSICAL_ENTITY_COMPLEX"), PRODUCT___REACTION___UNDEFINED("PRODUCT___REACTION___UNDEFINED"), PRODUCT___REACTION___RNA("PRODUCT___REACTION___RNA"), CONTROLLER___CATALYSIS___PROTEIN("CONTROLLER___CATALYSIS___PROTEIN"), CONTROLLER___CATALYSIS___PHYSICAL_ENTITY_COMPLEX("CONTROLLER___CATALYSIS___PHYSICAL_ENTITY_COMPLEX"), CONTROLLER___CATALYSIS___UNDEFINED("CONTROLLER___CATALYSIS___UNDEFINED"), CONTROLLER___REGULATION___PHYSICAL_ENTITY_COMPLEX("CONTROLLER___REGULATION___PHYSICAL_ENTITY_COMPLEX"), CONTROLLER___REGULATION___PROTEIN("CONTROLLER___REGULATION___PROTEIN"), CONTROLLER___REGULATION___UNDEFINED("CONTROLLER___REGULATION___UNDEFINED"), CONTROLLER___REGULATION___SMALL_MOLECULE("CONTROLLER___REGULATION___SMALL_MOLECULE"), CONTROLLER___REGULATION___RNA("CONTROLLER___REGULATION___RNA"), CONTROLLED___REGULATION___CATALYSIS("CONTROLLED___REGULATION___CATALYSIS"), CONTROLLED___CATALYSIS___REACTION("CONTROLLED___CATALYSIS___REACTION"), CONTROLLED___REGULATION___REACTION("CONTROLLED___REGULATION___REACTION"), CONTROLLED___REGULATION___PATHWAY("CONTROLLED___REGULATION___PATHWAY"), COMPONENT_OF_PATHWAY___PATHWAY___PATHWAY("COMPONENT_OF_PATHWAY___PATHWAY___PATHWAY"), COMPONENT_OF_PATHWAY___REACTION___PATHWAY("COMPONENT_OF_PATHWAY___REACTION___PATHWAY"), PATHWAY_NEXT_STEP___PATHWAY___PATHWAY("PATHWAY_NEXT_STEP___PATHWAY___PATHWAY"), PATHWAY_NEXT_STEP___CATALYSIS___REACTION("PATHWAY_NEXT_STEP___CATALYSIS___REACTION"), PATHWAY_NEXT_STEP___REACTION___REACTION("PATHWAY_NEXT_STEP___REACTION___REACTION"), PATHWAY_NEXT_STEP___REACTION___CATALYSIS("PATHWAY_NEXT_STEP___REACTION___CATALYSIS"), PATHWAY_NEXT_STEP___CATALYSIS___CATALYSIS("PATHWAY_NEXT_STEP___CATALYSIS___CATALYSIS"), PATHWAY_NEXT_STEP___REACTION___REGULATION("PATHWAY_NEXT_STEP___REACTION___REGULATION"), PATHWAY_NEXT_STEP___REACTION___PATHWAY("PATHWAY_NEXT_STEP___REACTION___PATHWAY"), PATHWAY_NEXT_STEP___REGULATION___REACTION("PATHWAY_NEXT_STEP___REGULATION___REACTION"), PATHWAY_NEXT_STEP___REGULATION___PATHWAY("PATHWAY_NEXT_STEP___REGULATION___PATHWAY"), PATHWAY_NEXT_STEP___REGULATION___CATALYSIS("PATHWAY_NEXT_STEP___REGULATION___CATALYSIS"), PATHWAY_NEXT_STEP___REGULATION___REGULATION("PATHWAY_NEXT_STEP___REGULATION___REGULATION"), PATHWAY_NEXT_STEP___CATALYSIS___REGULATION("PATHWAY_NEXT_STEP___CATALYSIS___REGULATION"), PATHWAY_NEXT_STEP___CATALYSIS___PATHWAY("PATHWAY_NEXT_STEP___CATALYSIS___PATHWAY"), PATHWAY_NEXT_STEP___PATHWAY___CATALYSIS("PATHWAY_NEXT_STEP___PATHWAY___CATALYSIS"), PATHWAY_NEXT_STEP___PATHWAY___REACTION("PATHWAY_NEXT_STEP___PATHWAY___REACTION"), PATHWAY_NEXT_STEP___PATHWAY___REGULATION("PATHWAY_NEXT_STEP___PATHWAY___REGULATION"); private final String relation; RelationFilename(String relation) { this.relation = relation; } public List<RelationFilename> getAll() { List<RelationFilename> list = new ArrayList<>(); return list; } } public CsvInfo(Path inputPath, Path outputPath) { uid = 1; this.inputPath = inputPath; this.outputPath = outputPath; csvWriters = new HashMap<>(); rocksDbManager = new RocksDbManager(); uidRocksDb = this.rocksDbManager.getDBConnection(outputPath.toString() + "/uidRocksDB", true); geneCache = new GeneCache(outputPath); proteinCache = new ProteinCache(outputPath); mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); geneReader = mapper.reader(Gene.class); proteinReader = mapper.reader(Entry.class); objWriter = mapper.writer(); logger = LoggerFactory.getLogger(this.getClass()); } public long getAndIncUid() { long ret = uid; uid++; return ret; } public void openCSVFiles(List<File> variantFiles) throws IOException { BufferedWriter bw; String filename; noAttributes = createNoAttributes(); nodeAttributes = createNodeAttributes(variantFiles); // CSV files for nodes for (Node.Label label : Node.Label.values()) { filename = label.toString() + ".csv.gz"; bw = FileUtils.newBufferedWriter(outputPath.resolve(filename)); csvWriters.put(label.toString(), bw); if (CollectionUtils.isNotEmpty(nodeAttributes.get(label.toString()))) { bw.write(getNodeHeaderLine(nodeAttributes.get(label.toString()))); bw.newLine(); } } // CSV files for relationships for (RelationFilename name : RelationFilename.values()) { filename = name.name() + ".csv.gz"; bw = FileUtils.newBufferedWriter(outputPath.resolve(filename)); // Write header bw.write(getRelationHeaderLine(name.name())); bw.newLine(); // Add writer to the map csvWriters.put(name.name(), bw); }
for (Relation.Label label : Relation.Label.values()) {
1
cwan/im-log-stats
im-log-stats-project/src/main/java/net/mikaboshi/intra_mart/tools/log_stats/ant/ReportParameterDataType.java
[ "public enum ReportType {\n\n\tHTML,\n\tCSV,\n\tTSV,\n\tVISUALIZE,\n\tTEMPLATE;\n\n\tpublic static ReportType toEnum(String s) {\n\n\t\tif (s == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\ts = s.toLowerCase();\n\n\t\tif (\"html\".equals(s)) {\n\t\t\treturn HTML;\n\t\t} else if (\"csv\".equals(s)) {\n\t\t\treturn CSV;...
import java.io.File; import java.io.FileNotFoundException; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.Date; import net.mikaboshi.intra_mart.tools.log_stats.entity.ReportType; import net.mikaboshi.intra_mart.tools.log_stats.formatter.ReportFormatter; import net.mikaboshi.intra_mart.tools.log_stats.formatter.TemplateFileReportFormatter; import net.mikaboshi.intra_mart.tools.log_stats.parser.ParserParameter; import net.mikaboshi.intra_mart.tools.log_stats.parser.Version; import net.mikaboshi.intra_mart.tools.log_stats.report.ReportParameter; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.types.DataType;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package net.mikaboshi.intra_mart.tools.log_stats.ant; /** * ログ統計レポート設定のネスト要素 * * @version 1.0.16 * @author <a href="https://github.com/cwan">cwan</a> */ public class ReportParameterDataType extends DataType { /** レポートタイプ */ private ReportType type = ReportType.HTML; /** 期間別統計の単位(分) */ private long span = 0L; /** セッションタイムアウト時間(分) */ private int sessionTimeout = 0; /** リクエスト処理時間ランクの出力件数 */ private int requestPageTimeRankSize = 0; /** * リクエスト処理時間ランクの閾値(ミリ秒) * @since 1.0.11 */ private long requestPageTimeRankThresholdMillis = -1L; /** リクエストURLランクの出力件数 */ private int requestUrlRankSize = 0; /** セッションランクの出力件数 */ private int sessionRankSize = 0; /** * JSSPページパスを表示するかどうか * @since 1.0.11 */ private Boolean jsspPath = null; /** * 最大同時リクエスト数を表示するかどうか * @since 1.0.13 */ private Boolean maxConcurrentRequest = null; /** レポート名 */ private String name = null; /** 署名 */ private String signature = null; /** * カスタムテンプレートファイルパス */ private String templateFile = null; /** * カスタムテンプレートファイルの文字コード */ private String templateCharset = Charset.defaultCharset().toString(); /** レポート出力先パス */ private String output = "report_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()); /** レポートの文字コード */ private String charset = Charset.defaultCharset().toString(); /** * visualizeのベースURL * @since 1.0.15 */ private String visualizeBaseUrl = null; public void setType(String s) { this.type = ReportType.toEnum(s); if (this.type == null) { throw new BuildException("Unsupported report type : " + s); } } /** * @param span セットする span */ public void setSpan(long span) { this.span = span; } /** * @param sessionTimeout セットする sessionTimeout */ public void setSessionTimeout(int sessionTimeout) { this.sessionTimeout = sessionTimeout; } /** * @param requestPageTimeRankSize セットする requestPageTimeRankSize */ public void setRequestPageTimeRankSize(int requestPageTimeRankSize) { this.requestPageTimeRankSize = requestPageTimeRankSize; } /** * * @param requestPageTimeRankThresholdMillis * @since 1.0.11 */ public void setRequestPageTimeRankThresholdMillis(long requestPageTimeRankThresholdMillis) { this.requestPageTimeRankThresholdMillis = requestPageTimeRankThresholdMillis; } /** * @param requestUrlRankSize セットする requestUrlRankSize */ public void setRequestUrlRankSize(int requestUrlRankSize) { this.requestUrlRankSize = requestUrlRankSize; } /** * @param sessionRankSize セットする sessionRankSize */ public void setSessionRankSize(int sessionRankSize) { this.sessionRankSize = sessionRankSize; } /** * * @param jsspPath * @since 1.0.11 */ public void setJsspPath(Boolean jsspPath) { this.jsspPath = jsspPath; } /** * * @param maxConcurrentRequest * @since 1.0.13 */ public void setMaxConcurrentRequest(Boolean maxConcurrentRequest) { this.maxConcurrentRequest = maxConcurrentRequest; } /** * @param name セットする name */ public void setName(String name) { this.name = name; } /** * @param signature セットする signature */ public void setSignature(String signature) { this.signature = signature; } public void setTemplateFile(String templateFile) { this.templateFile = templateFile; } public void setTemplateCharset(String templateCharset) { this.templateCharset = templateCharset; } public void setOutput(String output) { try { this.output = AntParameterUtil.getReportOutput(output); } catch (IllegalArgumentException e) { throw new BuildException("Parameter 'output' is invalid : " + output); } } public void setCharset(String charset) { this.charset = charset; } public void setVisualizeBaseUrl(String visualizeBaseUrl) { this.visualizeBaseUrl = visualizeBaseUrl; } /** * 設定内容を元に、ReportFormatterのインスタンスを取得する。 * @return * @throws BuildException */
public ReportFormatter getReportFormatter(
1
inouire/baggle
baggle-client/src/inouire/baggle/client/gui/modules/ServerListPanel.java
[ "public class Language {\n\n static String[] tooltip_fr = new String[]{\n \"Lister les serveurs sur le réseau officiel\",//0\n \"Lister les serveurs en réseau local\",//1\n };\n static String[] tooltip_en = new String[]{\n \"List servers of the official network\",//0\n \"List se...
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import inouire.baggle.client.Language; import inouire.baggle.client.Main; import inouire.baggle.client.gui.ColorFactory; import inouire.baggle.client.threads.ServerConnection; import inouire.baggle.datagrams.PINGDatagram; import inouire.basics.SimpleLog;
package inouire.baggle.client.gui.modules; /** * * @author edouard */ public class ServerListPanel extends JPanel{ ImageIcon[] language_icons = { new ImageIcon(getClass().getResource("/inouire/baggle/client/icons/fr.png")), new ImageIcon(getClass().getResource("/inouire/baggle/client/icons/en.png")), }; private JList serverList; private DefaultListModel serverListModel; private final static int REF_WIDTH=400; private final static int REF_HEIGHT=140; private int heightMax=0; private int cellWidth=REF_WIDTH; private boolean deadAngle=false; public ServerListPanel() { super(); serverListModel = new DefaultListModel(); serverList = new JList(serverListModel); serverList.setCellRenderer(new OneServerListCellRenderer()); serverList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); serverList.setLayoutOrientation(JList.HORIZONTAL_WRAP); serverList.setVisibleRowCount(-1); serverList.setFixedCellHeight(REF_HEIGHT); serverList.setFixedCellWidth(REF_WIDTH); // put the JList in a JScrollPane JScrollPane resultsListScrollPane = new JScrollPane(serverList); resultsListScrollPane.setMinimumSize(new Dimension(150, 50)); resultsListScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); this.setLayout(new BorderLayout()); this.add(resultsListScrollPane,BorderLayout.CENTER); addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent e) { notifyResize(); } @Override public void componentMoved(ComponentEvent e) {} @Override public void componentShown(ComponentEvent e) {} @Override public void componentHidden(ComponentEvent e) {} }); MouseListener mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { int index = getSelectedIndex(me); if(index>=0){ OneServerPanel one = (OneServerPanel) serverListModel.get(index); SimpleLog.logger.debug(one.host+":"+one.port+" - "+one.server_name +"has been clicked"); one.connectToThisServer(); } } @Override public void mouseExited(MouseEvent arg0) { clearHighlight(); repaint(); } }; serverList.addMouseListener(mouseListener); MouseMotionListener mouseMotionListener = new MouseMotionListener(){ @Override public void mouseDragged(MouseEvent me) { } @Override public void mouseMoved(MouseEvent me) { clearHighlight(); int index = getSelectedIndex(me); if(index>=0){ OneServerPanel selectedServer = (OneServerPanel)serverListModel.get(index); selectedServer.highlighted=true; serverList.setToolTipText(selectedServer.players); }else{ serverList.setToolTipText(null); } repaint(); } }; serverList.addMouseMotionListener(mouseMotionListener); } private int getSelectedIndex(MouseEvent me){ if(me.getY()>heightMax){ return -1; } if(me.getX()<cellWidth){ return serverList.locationToIndex(me.getPoint()); } if(me.getY()<heightMax-REF_HEIGHT){ return serverList.locationToIndex(me.getPoint()); } if(deadAngle){ return -1; }else{ return serverList.locationToIndex(me.getPoint()); } } private void clearHighlight(){ for(int k=0;k<serverListModel.getSize();k++){ ((OneServerPanel)serverListModel.get(k)).highlighted=false; } } public void notifyResize() { int width=serverList.getSize().width; if(width < REF_WIDTH){ cellWidth=width; heightMax = serverListModel.size() * REF_HEIGHT; }else{ cellWidth=width/2; if(serverListModel.size()%2==1){ deadAngle=true; heightMax = ((serverListModel.size()/2)+1) * REF_HEIGHT; }else{ deadAngle=false; heightMax = serverListModel.size() * REF_HEIGHT / 2; } } serverList.setFixedCellWidth(cellWidth); } public void resetList(){ serverListModel.removeAllElements(); repaint(); }
public synchronized void addServer(String ip, int port,PINGDatagram pingD){
4
ArthurHub/Android-Fast-Image-Loader
fastimageloader/src/main/java/com/theartofdev/fastimageloader/impl/DiskCacheImpl.java
[ "public interface Decoder {\n\n /**\n * Load image from disk file on the current thread and set it in the image request object.\n */\n void decode(MemoryPool memoryPool, ImageRequest imageRequest, File file, ImageLoadSpec spec);\n}", "public final class ImageLoadSpec {\n\n //region: Fields and Co...
import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.format.DateUtils; import com.theartofdev.fastimageloader.Decoder; import com.theartofdev.fastimageloader.ImageLoadSpec; import com.theartofdev.fastimageloader.MemoryPool; import com.theartofdev.fastimageloader.impl.util.FILLogger; import com.theartofdev.fastimageloader.impl.util.FILUtils; import java.io.File; import java.text.NumberFormat; import java.util.Arrays; import java.util.Comparator; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" package com.theartofdev.fastimageloader.impl; /** * Disk cache for image handler.<br> */ public class DiskCacheImpl implements com.theartofdev.fastimageloader.DiskCache { //region: Fields and Consts /** * The key to persist stats last scan data */ protected static final String STATS_LAST_SCAN = "DiskImageCache_lastCheck"; /** * The key to persist stats cache size data */ protected static final String STATS_CACHE_SIZE = "DiskImageCache_size"; /** * The max size of the cache (50MB) */ protected final long mMaxSize; /** * The bound to delete cached data to this size */ protected final long mMaxSizeLowerBound; /** * The max time image is cached without use before delete */ protected final long mCacheTtl; /** * The interval to execute cache scan even when max size has not reached */ protected final long SCAN_INTERVAL = 2 * DateUtils.DAY_IN_MILLIS; /** * the folder that the image cached on disk are located */ protected final File mCacheFolder; /** * Application context */ protected final Context mContext; /** * Threads service for all read operations. */ protected final ThreadPoolExecutor mReadExecutorService; /** * Threads service for scan of cached folder operation. */ protected final ThreadPoolExecutor mScanExecutorService; /** * The time of the last cache check */ private long mLastCacheScanTime = -1; /** * the current size of the cache */ private long mCurrentCacheSize; //endregion /** * @param context the application object to read config stuff * @param cacheFolder the folder to keep the cached image data * @param maxSize the max size of the disk cache in bytes * @param cacheTtl the max time a cached image remains in cache without use before deletion */ public DiskCacheImpl(Context context, File cacheFolder, long maxSize, long cacheTtl) {
FILUtils.notNull(context, "context");
4
Kaysoro/KaellyBot
src/main/java/commands/model/AbstractCommand.java
[ "public class Constants {\n\n /**\n * Application name\n */\n public final static String name = \"Kaelly\";\n\n /**\n * Application version\n */\n public final static String version = \"1.6.4\";\n\n /**\n * Changelog\n */\n public final static String changelog = \"https://r...
import data.Constants; import data.Guild; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.*; import discord4j.core.object.entity.channel.GuildMessageChannel; import discord4j.core.object.entity.channel.MessageChannel; import discord4j.core.object.entity.channel.PrivateChannel; import discord4j.core.object.entity.channel.TextChannel; import discord4j.rest.util.Permission; import discord4j.rest.util.PermissionSet; import enums.Language; import exceptions.BadUseCommandDiscordException; import exceptions.BasicDiscordException; import exceptions.DiscordException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import util.Reporter; import util.Translator; import java.util.regex.Matcher; import java.util.regex.Pattern;
package commands.model; /** * Created by steve on 14/07/2016. */ public abstract class AbstractCommand implements Command { private final static Logger LOG = LoggerFactory.getLogger(AbstractCommand.class); protected String name; protected String pattern; protected DiscordException badUse; private boolean isPublic; private boolean isUsableInMP; private boolean isAdmin; private boolean isHidden; protected AbstractCommand(String name, String pattern){ super(); this.name = name; this.pattern = pattern; this.isPublic = true; this.isUsableInMP = true; this.isAdmin = false; this.isHidden = false; badUse = new BadUseCommandDiscordException(); } @Override public final void request(MessageCreateEvent event, Message message) { Language lg = Translator.getLanguageFrom(message.getChannel().block()); try { Matcher m = getMatcher(message); boolean isFound = m.find(); // Caché si la fonction est désactivée/réservée aux admin et que l'auteur n'est pas super-admin if ((!isPublic() || isAdmin()) && message.getAuthor()
.map(user -> user.getId().asLong() != Constants.authorId).orElse(false))
0
ScreamingHawk/fate-sheets
app/src/main/java/link/standen/michael/fatesheets/adapter/CoreCharacterEditSectionAdapter.java
[ "public class CharacterEditAspectsFragment extends CharacterEditAbstractFragment {\n\n\t@Override\n\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n\t\t\t\t\t\t\t Bundle savedInstanceState) {\n\t\treturn inflater.inflate(R.layout.character_edit_aspects, container, false);\n\t}\n\n\t@Overrid...
import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import link.standen.michael.fatesheets.R; import link.standen.michael.fatesheets.fragment.CharacterEditAspectsFragment; import link.standen.michael.fatesheets.fragment.CharacterEditDescriptionFragment; import link.standen.michael.fatesheets.fragment.CoreCharacterEditSkillsFragment; import link.standen.michael.fatesheets.fragment.CoreCharacterEditStressFragment; import link.standen.michael.fatesheets.fragment.CoreCharacterEditStuntsFragment;
package link.standen.michael.fatesheets.adapter; /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the sections. */ public class CoreCharacterEditSectionAdapter extends FragmentPagerAdapter { private final Context context; public CoreCharacterEditSectionAdapter(FragmentManager fm, Context context) { super(fm); this.context = context; } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). switch (position) { case 0:
return new CharacterEditDescriptionFragment();
1
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/processors/impl/MetricsAggregationsProccessor.java
[ "public class ElasticEdmEntitySet extends EdmEntitySetImpl {\n\n private ElasticCsdlEntitySet csdlEntitySet;\n private ElasticEdmProvider provider;\n\n /**\n * Initialize fields.\n * \n * @param provider\n * the EDM provider\n * @param container\n * the EDM ent...
import org.apache.olingo.commons.api.data.AbstractEntityCollection; import org.apache.olingo.commons.api.edm.EdmEntityType; import org.apache.olingo.server.api.ODataApplicationException; import org.apache.olingo.server.api.uri.UriInfo; import org.elasticsearch.action.search.SearchResponse; import com.hevelian.olastic.core.edm.ElasticEdmEntitySet; import com.hevelian.olastic.core.elastic.parsers.MetricsAggregationsParser; import com.hevelian.olastic.core.elastic.requests.AggregateRequest; import com.hevelian.olastic.core.elastic.requests.ESRequest; import com.hevelian.olastic.core.elastic.requests.creators.MetricsAggregationsRequestCreator; import com.hevelian.olastic.core.processors.AbstractESCollectionProcessor; import com.hevelian.olastic.core.processors.data.InstanceData;
package com.hevelian.olastic.core.processors.impl; /** * Custom Elastic processor for handling metrics aggregations. * * @author rdidyk */ public class MetricsAggregationsProccessor extends AbstractESCollectionProcessor { private String countAlias; @Override protected ESRequest createRequest(UriInfo uriInfo) throws ODataApplicationException { AggregateRequest request = new MetricsAggregationsRequestCreator().create(uriInfo); countAlias = request.getCountAlias(); return request; } @Override protected InstanceData<EdmEntityType, AbstractEntityCollection> parseResponse(
SearchResponse response, ElasticEdmEntitySet entitySet) {
0
hufeiya/CoolSignIn
AndroidClient/app/src/main/java/com/hufeiya/SignIn/net/AsyncHttpHelper.java
[ "public class CategorySelectionActivity extends AppCompatActivity {\n\n private static final String EXTRA_PLAYER = \"player\";\n private User user;\n\n public static void start(Activity activity, User user, ActivityOptionsCompat options) {\n Intent starter = getStartIntent(activity, user);\n ...
import android.content.Context; import android.util.Log; import android.view.View; import com.google.gson.Gson; import com.hufeiya.SignIn.activity.CategorySelectionActivity; import com.hufeiya.SignIn.activity.QuizActivity; import com.hufeiya.SignIn.application.MyApplication; import com.hufeiya.SignIn.fragment.CategorySelectionFragment; import com.hufeiya.SignIn.fragment.SignInFragment; import com.hufeiya.SignIn.jsonObject.JsonSignInfo; import com.hufeiya.SignIn.jsonObject.JsonUser; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.PersistentCookieStore; import com.loopj.android.http.RequestParams; import com.qiniu.android.http.ResponseInfo; import com.qiniu.android.storage.UpCompletionHandler; import com.qiniu.android.storage.UploadManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import cz.msebera.android.httpclient.Header;
package com.hufeiya.SignIn.net; /** * Created by hufeiya on 15-12-1. */ public class AsyncHttpHelper { private static AsyncHttpClient client = new AsyncHttpClient();
public static JsonUser user;
6
ChristinGorman/baxter
src/test/java/no/gorman/please/timeline/TimelineServletTest.java
[ "public class DB {\n\n private static final Logger log = LoggerFactory.getLogger(DB.class);\n\n\n private final Connection connection;\n final List<Runnable> onSuccessActions = new ArrayList<>(); //to be run when transaction completes successfully\n\n public DB(Connection connection) {\n this.con...
import com.google.gson.Gson; import no.gorman.database.DB; import no.gorman.database.DBTestRunner; import no.gorman.database.Where; import no.gorman.please.RegisteredUser; import no.gorman.please.common.Child; import no.gorman.please.common.DayCareCenter; import no.gorman.please.common.GrownUp; import org.fest.assertions.Assertions; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.atomic.AtomicReference; import static java.util.Arrays.asList; import static no.gorman.database.DatabaseColumns.*; import static no.gorman.please.LoginServlet.LOGGED_IN; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package no.gorman.please.timeline; @RunWith(DBTestRunner.class) public class TimelineServletTest { Child one = new Child(); Child two = new Child(); Child three = new Child(); Child four = new Child(); GrownUp grownup = new GrownUp();
DayCareCenter daycare = DayCareCenter.withName("test");
5
baishui2004/common_gui_tools
src/main/java/bs/tool/commongui/plugins/more/EscapeCharacterTool.java
[ "public abstract class AbstractGuiJPanel extends JPanel {\n\n private static final long serialVersionUID = 1L;\n\n public AbstractGuiJPanel() {\n }\n\n /**\n * 获取当前面板.\n */\n public JPanel getContextPanel() {\n return this;\n }\n\n /**\n * 给面板增加指定标题及字体的Label.\n */\n pu...
import bs.tool.commongui.AbstractGuiJPanel; import bs.tool.commongui.GuiUtils; import bs.tool.commongui.utils.EscapeUtils; import bs.tool.commongui.utils.LanguageUtils; import bs.tool.commongui.utils.SimpleMouseListener; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent;
package bs.tool.commongui.plugins.more; /** * 字符转义工具. */ public class EscapeCharacterTool extends AbstractGuiJPanel { private static final long serialVersionUID = 1L; /** * 字符文本域. */ private JTextArea unescapeTextArea = createJTextArea(GuiUtils.font14_un); /** * 转义文本域. */ private JTextArea escapeTextArea = createJTextArea(GuiUtils.font14_un); /** * 帮助文本域. */ private JTextArea helpTextArea = createJTextArea(GuiUtils.font14_un); /** * 字符类型. */
private String[] characterTypes = new String[]{LanguageUtils.CONST_HTML, LanguageUtils.CONST_XML,
3
yDelouis/selfoss-android
app/src/main/java/fr/ydelouis/selfoss/rest/SelfossRestWrapper.java
[ "@DatabaseTable(daoClass = ArticleDao.class)\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Article implements Parcelable {\n\n\tprivate static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\tstatic {\n\t\tDATETIME_FORMAT.setTimeZone(TimeZone.getTimeZone(\"UTC\...
import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.OrmLiteDao; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.rest.RestService; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import fr.ydelouis.selfoss.entity.Article; import fr.ydelouis.selfoss.entity.ArticleType; import fr.ydelouis.selfoss.entity.Tag; import fr.ydelouis.selfoss.model.ArticleSyncActionDao; import fr.ydelouis.selfoss.model.DatabaseHelper; import fr.ydelouis.selfoss.sync.ArticleSyncAction; import fr.ydelouis.selfoss.util.ArticleContentParser; import fr.ydelouis.selfoss.util.SelfossImageLoader;
package fr.ydelouis.selfoss.rest; @EBean public class SelfossRestWrapper { @RestService protected SelfossRest rest; @OrmLiteDao(helper = DatabaseHelper.class)
protected ArticleSyncActionDao articleSyncActionDao;
3
wrey75/WaveCleaner
src/main/java/com/oxande/xmlswing/components/FrameUI.java
[ "public class AttributeDefinition {\r\n\t\r\n\tpublic final static Map<String, String> ALIGNS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CLOSE_OPERATIONS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CURSORS = new HashMap<String, String>();\r\n\tpub...
import javax.swing.ImageIcon; import javax.swing.JFrame; import org.w3c.dom.Element; import com.oxande.xmlswing.AttributeDefinition; import com.oxande.xmlswing.AttributesController; import com.oxande.xmlswing.Parser; import com.oxande.xmlswing.AttributeDefinition.ClassType; import com.oxande.xmlswing.UnexpectedTag; import com.oxande.xmlswing.jcode.JavaClass; import com.oxande.xmlswing.jcode.JavaCode; import com.oxande.xmlswing.jcode.JavaMethod;
package com.oxande.xmlswing.components; /** * Implementation of a Frame. You should never use * directly this class as the normal implementation * comes from the {@link JFrameUI} class. * * @author wrey75 * */ public class FrameUI extends WindowUI { public static final AttributeDefinition[] PROPERTIES = { new AttributeDefinition( "title", "setTitle", ClassType.STRING ), new AttributeDefinition( "resizable", "setResizable", ClassType.BOOLEAN ), };
public static final AttributesController CONTROLLER = new AttributesController(WindowUI.CONTROLLER, PROPERTIES);
1
melloc/roguelike
engine/src/main/java/edu/brown/cs/roguelike/engine/proc/RandomMonsterGenerator.java
[ "public class Config {\n\n\tpublic enum ConfigType {\n\t\tMONSTER,WEAPON_ADJ,WEAPON_TYPE,KEY_BINDING\n\t}\n\n\tpublic static final String CFG_EXT = \".cfg\";\n\n\t/**\n\t * All of the required configuration files\n\t */\n\tpublic static final HashMap<ConfigType,String> REQUIRED_FILES = \n\t\t\tnew HashMap<ConfigTyp...
import java.util.ArrayList; import edu.brown.cs.roguelike.engine.config.Config; import edu.brown.cs.roguelike.engine.config.ConfigurationException; import edu.brown.cs.roguelike.engine.config.MonsterTemplate; import edu.brown.cs.roguelike.engine.entities.Monster; import edu.brown.cs.roguelike.engine.level.Level; import edu.brown.cs.roguelike.engine.level.Room; import edu.brown.cs.roguelike.engine.level.Tile;
package edu.brown.cs.roguelike.engine.proc; public class RandomMonsterGenerator implements MonsterGenerator { ArrayList<MonsterTemplate> templates; RandomGen rand = new RandomGen(System.nanoTime()); @Override public void populateLevel(Level level) throws ConfigurationException { int roomNum; Config c = new Config("../config"); templates = c.loadMonsterTemplate(); for (int i = 0 ; i < getMonsterCount(); i++) { roomNum = rand.getRandom(level.getRooms().size()); Room r = level.getRooms().get(roomNum); addMonster(level,r,getRandomMonster(level)); } }
private Monster getRandomMonster(Level level) {
3
mmonkey/Destinations
src/main/java/com/github/mmonkey/destinations/commands/BringCommand.java
[ "public class PlayerTeleportBringEvent extends AbstractPlayerTeleportEvent implements PlayerTeleportEvent.Bring {\n\n /**\n * PlayerTeleportBringEvent constructor\n *\n * @param player Player\n * @param location Location\n * @param rotation Vector3d\n */\n public PlayerTeleportBringE...
import com.github.mmonkey.destinations.events.PlayerTeleportBringEvent; import com.github.mmonkey.destinations.events.PlayerTeleportPreEvent; import com.github.mmonkey.destinations.teleportation.TeleportationService; import com.github.mmonkey.destinations.utilities.FormatUtil; import com.github.mmonkey.destinations.utilities.MessagesUtil; 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.args.GenericArguments; 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.concurrent.CopyOnWriteArrayList;
package com.github.mmonkey.destinations.commands; public class BringCommand implements CommandExecutor { public static final String[] ALIASES = {"bring", "tpaccept", "tpyes"}; /** * Get the Command Specifications for this command * * @return CommandSpec */ public static CommandSpec getCommandSpec() { return CommandSpec.builder() .permission("destinations.tpa") .description(Text.of("/bring [player] or /tpaccept [player] or /tpyes [player]")) .extendedDescription(Text.of("Teleports a player that has issued a call request to your current location.")) .executor(new BringCommand()) .arguments(GenericArguments.optional(GenericArguments.firstParsing(GenericArguments.player(Text.of("player"))))) .build(); } @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { if (!(src instanceof Player)) { return CommandResult.empty(); } Player target = (Player) src; Player caller = args.getOne("player").isPresent() ? (Player) args.getOne("player").get() : null; if (caller == null) { int numCallers = TeleportationService.instance.getNumCallers(target); switch (numCallers) { case 0: target.sendMessage(MessagesUtil.error(target, "bring.empty")); return CommandResult.success(); case 1: Player calling = TeleportationService.instance.getFirstCaller(target); return executeBring(calling, target); default: return listCallers(target, args); } } if (TeleportationService.instance.isCalling(caller, target)) { return executeBring(caller, target); } target.sendMessage(MessagesUtil.error(target, "bring.not_found", caller.getName())); return CommandResult.success(); } private CommandResult listCallers(Player target, CommandContext args) { List<String> callList = TeleportationService.instance.getCalling(target); List<Text> list = new CopyOnWriteArrayList<>(); callList.forEach(caller -> list.add(getBringAction(caller))); PaginationService paginationService = Sponge.getServiceManager().provide(PaginationService.class).get(); paginationService.builder().title(MessagesUtil.get(target, "bring.title")).contents(list).padding(Text.of("-")).sendTo(target); return CommandResult.success(); } private CommandResult executeBring(Player caller, Player target) { TeleportationService.instance.removeCall(caller, target); Sponge.getGame().getEventManager().post(new PlayerTeleportPreEvent(caller, caller.getLocation(), caller.getRotation()));
Sponge.getGame().getEventManager().post(new PlayerTeleportBringEvent(caller, target.getLocation(), target.getRotation()));
0
GoogleCloudPlatform/healthcare-api-dicom-fuse
src/main/java/com/google/dicomwebfuse/dao/spec/InstancePathBuilder.java
[ "public static final String DATASETS = \"/datasets/\";", "public static final String DICOM_STORES = \"/dicomStores/\";", "public static final String DICOM_WEB = \"/dicomWeb\";", "public static final String INSTANCES = \"/instances/\";", "public static final String LOCATIONS = \"/locations/\";", "public st...
import static com.google.dicomwebfuse.dao.Constants.DATASETS; import static com.google.dicomwebfuse.dao.Constants.DICOM_STORES; import static com.google.dicomwebfuse.dao.Constants.DICOM_WEB; import static com.google.dicomwebfuse.dao.Constants.INSTANCES; import static com.google.dicomwebfuse.dao.Constants.LOCATIONS; import static com.google.dicomwebfuse.dao.Constants.PROJECTS; import static com.google.dicomwebfuse.dao.Constants.SERIES; import static com.google.dicomwebfuse.dao.Constants.STUDIES; import com.google.dicomwebfuse.exception.DicomFuseException;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.dicomwebfuse.dao.spec; public class InstancePathBuilder implements PathBuilder { private QueryBuilder queryBuilder; public InstancePathBuilder(QueryBuilder queryBuilder) { this.queryBuilder = queryBuilder; } @Override
public String toPath() throws DicomFuseException {
8
Gikkman/Java-Twirk
src/main/java/com/gikk/twirk/types/usernotice/DefaultUsernoticeBuilder.java
[ "public interface TagMap extends Map<String, String>{\n //***********************************************************\n\t// \t\t\t\tPUBLIC\n\t//***********************************************************\n\t/**Fetches a certain field value that might have been present in the tag.\n\t * If the field was not prese...
import com.gikk.twirk.types.TagMap; import com.gikk.twirk.types.TwitchTags; import com.gikk.twirk.types.emote.Emote; import com.gikk.twirk.types.twitchMessage.TwitchMessage; import com.gikk.twirk.types.usernotice.subtype.Raid; import com.gikk.twirk.types.usernotice.subtype.Ritual; import com.gikk.twirk.types.usernotice.subtype.Subscription; import java.util.List;
package com.gikk.twirk.types.usernotice; class DefaultUsernoticeBuilder implements UsernoticeBuilder{ String rawLine; List<Emote> emotes; String messageID; int roomID; long sentTimestamp; String systemMessage; Subscription subscription; Raid raid; Ritual ritual; String message; @Override public Usernotice build(TwitchMessage message) { this.rawLine = message.getRaw(); this.emotes = message.getEmotes();
TagMap map = message.getTagMap();
0
huyongli/TigerVideo
TigerVideoPlayer/src/main/java/cn/ittiger/player/ui/VideoControllerView.java
[ "public final class PlayerManager implements IPlayer.PlayCallback {\n private static final String TAG = \"PlayerManager\";\n private static volatile PlayerManager sPlayerManager;\n private AbsSimplePlayer mPlayer;\n private PlayStateObservable mPlayStateObservable;\n private String mVideoUrl;\n pr...
import android.content.Context; import android.os.Build; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import cn.ittiger.player.PlayerManager; import cn.ittiger.player.R; import cn.ittiger.player.listener.FullScreenToggleListener; import cn.ittiger.player.listener.UIStateChangeListener; import cn.ittiger.player.listener.VideoControllerViewListener; import cn.ittiger.player.listener.VideoTouchListener; import cn.ittiger.player.state.ScreenState; import cn.ittiger.player.util.Utils;
package cn.ittiger.player.ui; /** * 底部播放控制视图 * @author: ylhu * @time: 2017/12/12 */ public class VideoControllerView extends RelativeLayout implements UIStateChangeListener, View.OnClickListener, VideoControllerViewListener, VideoTouchListener, SeekBar.OnSeekBarChangeListener { private static final int PROGRESS_UPDATE_INTERNAL = 300; private static final int PROGRESS_UPDATE_INITIAL_INTERVAL = 100; protected View mVideoControllerInternalView; /** * 底部 视频当前播放时间 */ protected TextView mVideoPlayTimeView; /** * 底部 视频总时长 */ protected TextView mVideoTotalTimeView; /** * 底部 视频播放进度 */ protected SeekBar mVideoPlaySeekBar; /** * 底部 全屏播放按钮 */ protected ImageView mVideoFullScreenButton; /** * 控制条不显示后,显示播放进度的进度条(不可点击) */ protected ProgressBar mBottomProgressBar; /** * 当前屏幕播放状态 */
protected int mCurrentScreenState = ScreenState.SCREEN_STATE_NORMAL;
5
bit-man/SwissArmyJavaGit
javagit/src/main/java/edu/nyu/cs/javagit/client/cli/CliGitAdd.java
[ "public final class JavaGitConfiguration {\n\n /*\n * The path to our git binaries. Default to null, which means that the git command is available\n * via the system PATH environment variable.\n */\n private static File gitPath = null;\n\n /*\n * The version string fpr the locally-installed git binaries....
import edu.nyu.cs.javagit.api.JavaGitConfiguration; import edu.nyu.cs.javagit.api.JavaGitException; import edu.nyu.cs.javagit.api.commands.GitAddOptions; import edu.nyu.cs.javagit.api.commands.GitAddResponse; import edu.nyu.cs.javagit.client.GitAddResponseImpl; import edu.nyu.cs.javagit.client.IGitAdd; import edu.nyu.cs.javagit.utilities.CheckUtilities; import edu.nyu.cs.javagit.utilities.ExceptionMessageMap; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer;
if (options.ignoreErrors()) { command.add("--ignore-errors"); } } if (paths != null && paths.size() > 0) { for (File file : paths) { command.add(file.getPath()); } } return command; } /** * Parser class that implements <code>IParser</code> for implementing a parser for * &lt;git-add&gt; output. */ public static class GitAddParser implements IParser { private int lineNum; private GitAddResponseImpl response; private boolean error = false; private List<Error> errorList; public GitAddParser() { lineNum = 0; response = new GitAddResponseImpl(); } public void parseLine(String line) { if (line == null || line.length() == 0) { return; } lineNum++; if (isError(line)) { error = true; errorList.add(new Error(lineNum, line)); } else if (isComment(line)) response.setComment(lineNum, line); else processLine(line); } private boolean isError(String line) { if (line.trim().startsWith("fatal") || line.trim().startsWith("error")) { if (errorList == null) { errorList = new ArrayList<Error>(); } return true; } return false; } private boolean isComment(String line) { if (line.startsWith("Nothing specified") || line.contains("nothing added") || line.contains("No changes") || line.contains("Maybe you wanted to say") || line.contains("usage")) { return true; } return false; } /** * Lines that start with "add" have the second token as the name of the file added by * &lt;git-add&gt. * * @param line */ private void processLine(String line) { if (line.startsWith("add")) { StringTokenizer st = new StringTokenizer(line); if (st.nextToken().equals("add") && st.hasMoreTokens()) { String extractedFileName = filterFileName(st.nextToken()); if (extractedFileName != null && extractedFileName.length() > 0) { File file = new File(extractedFileName); response.add(file); } } } else { processSpaceDelimitedFilePaths(line); } } private void processSpaceDelimitedFilePaths(String line) { if (!line.startsWith("\\s+")) { StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { File file = new File(st.nextToken()); response.add(file); } } } public String filterFileName(String token) { if (token.length() > 0 && enclosedWithSingleQuotes(token)) { int firstQuote = token.indexOf("'"); int nextQuote = token.indexOf("'", firstQuote + 1); if (nextQuote > firstQuote) { return token.substring(firstQuote + 1, nextQuote); } } return null; } public boolean enclosedWithSingleQuotes(String token) { return token.matches("'.*'"); } public void processExitCode(int code) { } /** * Gets a <code>GitAddResponse</code> object containing the info generated by &lt;git-add&gt; command. * If there was an error generated while running &lt;git-add&gt; then it throws an exception. * * @return GitAddResponse object containing &lt;git-add&gt; response. * @throws JavaGitException If there are any errors generated by &lt;git-add&gt; command. */ public GitAddResponse getResponse() throws JavaGitException { if (error) {
throw new JavaGitException(401000, ExceptionMessageMap.getMessage("401000") +
4
ToxicBakery/Screenshot-Redaction
app/src/main/java/com/ToxicBakery/app/screenshot_redaction/dictionary/impl/DictionaryEnglishNames.java
[ "public class CopyBus extends ADefaultBus<ICopyConfiguration> {\n\n private static volatile CopyBus instance;\n\n public static CopyBus getInstance() {\n if (instance == null) {\n synchronized (CopyBus.class) {\n if (instance == null) {\n instance = new Copy...
import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.util.Log; import com.ToxicBakery.app.screenshot_redaction.R; import com.ToxicBakery.app.screenshot_redaction.bus.CopyBus; import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard; import com.ToxicBakery.app.screenshot_redaction.copy.CopyToSdCard.ICopyConfiguration; import com.ToxicBakery.app.screenshot_redaction.copy.WordListRawResourceCopyConfiguration; import com.ToxicBakery.app.screenshot_redaction.dictionary.IDictionary; import org.mapdb.DB; import org.mapdb.DBMaker; import java.io.IOException; import java.util.Locale; import java.util.Set; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers;
package com.ToxicBakery.app.screenshot_redaction.dictionary.impl; public class DictionaryEnglishNames implements IDictionary { private static final String TAG = "DictionaryEnglishNames"; private static DictionaryEnglishNames instance; @VisibleForTesting final ICopyConfiguration copyConfiguration; private final CopyBus copyBus; private Set<String> words; DictionaryEnglishNames(@NonNull Context context) {
copyConfiguration = new WordListRawResourceCopyConfiguration(context, R.raw.wordlist_english_names);
3
ketao1989/ourea
ourea-spring/src/main/java/com/taocoder/ourea/spring/consumer/ConsumerProxyFactoryBean.java
[ "public class Constants {\n\n public static final String ZK_PATH_PREFIX = \"/ourea\";\n\n public static final String PATH_SEPARATOR = \"/\";\n\n public static final String GROUP_KEY = \"group\";\n\n public static final String VERSION_KEY = \"version\";\n\n public static final String INTERFACE_KEY = \...
import com.taocoder.ourea.core.common.Constants; import com.taocoder.ourea.core.common.PropertiesUtils; import com.taocoder.ourea.core.config.ThriftClientConfig; import com.taocoder.ourea.core.config.ZkConfig; import com.taocoder.ourea.core.consumer.ConsumerProxyFactory; import com.taocoder.ourea.core.loadbalance.ILoadBalanceStrategy; import com.taocoder.ourea.core.loadbalance.RoundRobinLoadBalanceStrategy; import com.taocoder.ourea.spring.ConfigUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.io.Resource; import java.util.Properties;
/* * Copyright (c) 2015 taocoder.com. All Rights Reserved. */ package com.taocoder.ourea.spring.consumer; /** * @author tao.ke Date: 16/5/1 Time: 下午2:18 */ public class ConsumerProxyFactoryBean implements FactoryBean<ConsumerProxyFactory>, InitializingBean, ApplicationListener<ApplicationEvent> { private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerProxyFactoryBean.class); /** * zk配置 */
private ZkConfig zkConfig;
3
DanielShum/MaterialAppBase
app/src/main/java/com/daililol/material/appbase/example/ExampleNavigationDrawerActivity.java
[ "public abstract class BaseNavigationDrawerActivity extends BaseFragmentActivity implements DrawerListener,\nAdapterView.OnItemClickListener{\n\n\n /**\n * An activity will be created like this\n * -------------------------------------- ---------------------------------------\n * | __ ...
import android.graphics.Color; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.os.Bundle; import android.os.Message; import android.support.v4.app.FragmentTransaction; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.LinearLayout; import com.daililol.material.appbase.base.BaseNavigationDrawerActivity; import com.daililol.material.appbase.component.BaseNavigationDrawerListAdapter; import com.daililol.material.appbase.utility.Converter; import com.daililol.material.appbase.utility.DrawableUtil; import com.daililol.material.appbase.widget.ExtendableListView;
package com.daililol.material.appbase.example; /** * Created by DennyShum on 8/20/15. */ public class ExampleNavigationDrawerActivity extends BaseNavigationDrawerActivity{ @Override protected void onActivityCreated(Bundle savedInstanceState) { FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragmentReplacement, new ExampleListViewFragment()).commit(); } @Override protected int setupContentVew() { return R.layout.example_navigation_drawer_activity; } @Override protected Drawable setupThemeColor() { return null; } @Override protected void onMenuItemSelected(MenuItem menu) { } @Override
protected void setupNavigationDrawerItem(ExtendableListView listView, BaseNavigationDrawerListAdapter navigationListAdapter) {
1
andrewflynn/bettersettlers
app/src/main/java/com/nut/bettersettlers/fragment/dialog/ExpansionDialogFragment.java
[ "public class MainActivity extends FragmentActivity {\n\tprivate static final String STATE_SHOW_GRAPH = \"STATE_SHOW_GRAPH\";\n\tprivate static final String STATE_SHOW_PLACEMENTS = \"STATE_SHOW_PLACEMENTS\";\n\tprivate static final String STATE_THEFT_ORDER = \"STATE_THEFT_ORDER\";\n\tprivate static final String STA...
import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import com.nut.bettersettlers.R; import com.nut.bettersettlers.activity.MainActivity; import com.nut.bettersettlers.data.MapSize; import com.nut.bettersettlers.data.MapSizePair; import com.nut.bettersettlers.fragment.MapFragment; import com.nut.bettersettlers.util.Analytics; import com.nut.bettersettlers.util.Consts;
package com.nut.bettersettlers.fragment.dialog; public class ExpansionDialogFragment extends DialogFragment { private static final String SIZE_KEY = "SIZE"; private MapSizePair mMapSizePair; public static ExpansionDialogFragment newInstance(MapSizePair sizePair) { ExpansionDialogFragment f = new ExpansionDialogFragment(); Bundle args = new Bundle(); args.putParcelable(SIZE_KEY, sizePair); f.setArguments(args); f.setStyle(STYLE_NO_TITLE, 0); return f; } @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Analytics.trackView(getActivity(), Analytics.VIEW_EXPANSIONS_MENU); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.expansion, container, false); mMapSizePair = getArguments().getParcelable(SIZE_KEY); ImageView smallButton = (ImageView) view.findViewById(R.id.expansion_small_item); smallButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Analytics.track(getActivity(), Analytics.CATEGORY_EXPANSION_MENU, Analytics.ACTION_BUTTON, Analytics.EXPANSION_SMALL); choice(mMapSizePair.reg); } }); ImageView largeButton = (ImageView) view.findViewById(R.id.expansion_large_item); largeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Analytics.track(getActivity(), Analytics.CATEGORY_EXPANSION_MENU, Analytics.ACTION_BUTTON, Analytics.EXPANSION_LARGE); choice(mMapSizePair.exp); } }); getDialog().getWindow().getAttributes().windowAnimations = R.style.FadeDialogAnimation; return view; } private void choice(MapSize size) {
final MainActivity mainActivity = (MainActivity) getActivity();
0
OlgaKuklina/GitJourney
app/src/main/java/com/oklab/gitjourney/activities/MainActivity.java
[ "public class DeleteUserAuthorizationAsyncTask extends AsyncTask<String, Integer, Boolean> {\n private static final String TAG = DeleteUserAuthorizationAsyncTask.class.getSimpleName();\n private final Activity activity;\n private UserSessionData currentSessionData;\n\n public DeleteUserAuthorizationAsyn...
import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import com.google.firebase.analytics.FirebaseAnalytics; import com.oklab.gitjourney.R; import com.oklab.gitjourney.adapters.FirebaseAnalyticsWrapper; import com.oklab.gitjourney.asynctasks.DeleteUserAuthorizationAsyncTask; import com.oklab.gitjourney.asynctasks.UserProfileAsyncTask; import com.oklab.gitjourney.data.GitHubUserProfileDataEntry; import com.oklab.gitjourney.data.UpdaterService; import com.oklab.gitjourney.data.UserSessionData; import com.oklab.gitjourney.fragments.ContributionsByDateListFragment; import com.oklab.gitjourney.fragments.MainViewFragment; import com.oklab.gitjourney.parsers.GitHubUserProfileDataParser; import com.oklab.gitjourney.parsers.Parser; import com.oklab.gitjourney.services.TakeScreenshotService; import com.oklab.gitjourney.utils.Utils;
}); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override protected void onStart() { super.onStart(); firebaseAnalytics.setCurrentScreen(this, "MainActivityFirebaseAnalytics"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); Bundle bundle = new Bundle(); bundle.putString(FirebaseAnalytics.Param.ITEM_ID, Integer.toString(item.getItemId())); bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "MainActivityNavigationItemSelected"); firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle); if (id == R.id.github_events) { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } else if (id == R.id.profile) { String currentSessionData = prefs.getString("userSessionData", null); if (currentSessionData != null) { Intent intent = new Intent(this, GeneralActivity.class); startActivity(intent); return true; } } else if (id == R.id.personal) { String currentSessionData = prefs.getString("userSessionData", null); if (currentSessionData != null) { Parser<GitHubUserProfileDataEntry> parser = new GitHubUserProfileDataParser(); userProfileAsyncTask = new UserProfileAsyncTask<GitHubUserProfileDataEntry>(this, this, parser); userProfileAsyncTask.execute(); return true; } } else if (id == R.id.settings) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; } else if (id == R.id.sing_out) { new DeleteUserAuthorizationAsyncTask(this).execute(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void OnProfilesLoaded(GitHubUserProfileDataEntry dataEntry) { Log.v(TAG, "OnProfilesLoaded "); userProfileAsyncTask = null; String currentSessionData = prefs.getString("userSessionData", null); UserSessionData userSessionData = UserSessionData.createUserSessionDataFromString(currentSessionData); Intent intent = new Intent(this, UserProfileActivity.class); intent.putExtra("profile", dataEntry); startActivity(intent); } @Override protected void onDestroy() { super.onDestroy(); if (userProfileAsyncTask != null) { userProfileAsyncTask.cancel(true); } } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class CalendarYearPagerAdapter extends FragmentPagerAdapter { public CalendarYearPagerAdapter(FragmentManager fm) { super(fm); } @Override public android.support.v4.app.Fragment getItem(int position) { Log.v(TAG, "position - " + position); // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below).
return MainViewFragment.newInstance(position);
4
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/ServerForge.java
[ "public class Player{\n private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>();\n private EntityPlayer entityPlayer;\n private InventoryBase inventory;\n\n public enum GameMode{\n SURVIVAL,\n CREATIVE,\n ADVENTURE\n }\n\n private Player(EntityPlayer ...
import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLServerStartingEvent; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import src.john01dav.serverforge.api.Player; import src.john01dav.serverforge.api.ServerForgeCommand; import src.john01dav.serverforge.events.EventManager; import src.john01dav.serverforge.loader.PluginLoader; import src.john01dav.serverforge.permissions.PermissionsManager; import java.util.ArrayList;
package src.john01dav.serverforge; @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") public class ServerForge{ public static final String VERSION = "PRE-ALPHA 0.0.1"; private EventManager eventManager; private PermissionsManager permissionsManager; private PluginLoader pluginLoader; private FMLServerStartingEvent serverStartingEvent; @Mod.Instance("ServerForge") public static ServerForge instance; public static void info(String info){ System.out.println("[SERVERFORGE INFO]: " + info); } public static void error(String error){ System.out.println("[SERVERFORGE ERROR]: " + error); } @Mod.EventHandler public void serverStartingEvent(FMLServerStartingEvent e){ info("Starting ServerForge..."); this.serverStartingEvent = e; eventManager = new EventManager(); eventManager.onServerStart(); permissionsManager = new PermissionsManager(); permissionsManager.onServerStart(); pluginLoader = new PluginLoader(); pluginLoader.onServerStart(); this.serverStartingEvent = null; info("ServerForge started"); } /** * Registers a command for use in the server, can only be called from onServerStart() or it's submethods * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") * @param command The command object to register * @param aliases Array containing the aliases for this command */
public void registerCommand(String name, ServerForgeCommand command, String[] aliases){
1
salk31/RedQueryBuilder
redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/RedQueryBuilder.java
[ "public class Select extends Query implements ColumnResolver {\n\n private final Button add = new Button(\"Add condition\");\n\n private final XWidget<Expression> xcondition = new XWidget<Expression>();\n\n private HashMap<Expression, Object> currentGroup;\n\n private int currentGroupRowId;\n\n priva...
import java.util.ArrayList; import java.util.List; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.ui.SimplePanel; import com.redspr.redquerybuilder.core.client.command.CommandBuilder; import com.redspr.redquerybuilder.core.client.command.dml.Select; import com.redspr.redquerybuilder.core.client.engine.Session; import com.redspr.redquerybuilder.core.client.engine.TableEvent; import com.redspr.redquerybuilder.core.client.engine.TableEventHandler; import com.redspr.redquerybuilder.core.client.expression.ExpressionColumn; import com.redspr.redquerybuilder.core.client.table.TableFilter; import com.redspr.redquerybuilder.core.client.util.ObjectArray; import com.redspr.redquerybuilder.core.shared.meta.Column;
/******************************************************************************* * Copyright (c) 2010-2013 Redspr Ltd. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Sam Hough - initial API and implementation *******************************************************************************/ package com.redspr.redquerybuilder.core.client; public class RedQueryBuilder implements EntryPoint { private void createCommandBuilder(final Configuration config, String sql, List args) throws Exception { final Session session = new Session(config); final CommandBuilder builder = new CommandBuilder(session, sql, args); session.getMsgBus().addHandler(TableEvent.TYPE, new TableEventHandler() { @Override public void onTable(TableEvent e) { if (session.getFilters().size() > 0) { config.fireOnTableChange(session.getFilters()); // XXX need to do distinct? ObjectArray expr = ObjectArray.newInstance(); TableFilter tf = session.getFilters().get(0); String alias = tf.getAlias(); for (Column col : tf.getTable().getColumns()) { expr.add(new ExpressionColumn(session, null, alias, col.getName())); } builder.getSelect().setExpressions(expr); } else { builder.getSelect().setExpressions(null); } } });
builder.addValueChangeHandler(new ValueChangeHandler<Select>() {
0
mszubert/2048
src/main/java/put/ci/cevo/games/serializers/NTuplesSerializer.java
[ "public class NTuple {\n\n\tprivate final int numValues;\n\tprivate final int[] locations;\n\tprivate final double[] LUT;\n\n\t/**\n\t * Watch out: Locations are margin-based (not 0-based)\n\t */\n\tpublic NTuple(int numValues, int[] locations, double[] weights) {\n\t\tPreconditions.checkArgument(locations.length >...
import java.io.IOException; import java.util.List; import put.ci.cevo.games.encodings.ntuple.NTuple; import put.ci.cevo.games.encodings.ntuple.NTuples; import put.ci.cevo.games.encodings.ntuple.expanders.SymmetryExpander; import put.ci.cevo.util.serialization.ObjectSerializer; import put.ci.cevo.util.serialization.SerializationException; import put.ci.cevo.util.serialization.SerializationInput; import put.ci.cevo.util.serialization.SerializationManager; import put.ci.cevo.util.serialization.SerializationOutput; import put.ci.cevo.util.serialization.serializers.AutoRegistered;
package put.ci.cevo.games.serializers; @AutoRegistered(defaultSerializer = true) public final class NTuplesSerializer implements ObjectSerializer<NTuples> { @Override public void save(SerializationManager manager, NTuples object, SerializationOutput output) throws IOException, SerializationException { manager.serialize(object.getMain(), output); manager.serialize(object.getSymmetryExpander(), output); } @Override
public NTuples load(SerializationManager manager, SerializationInput input) throws IOException,
4
jboz/plantuml-builder
src/test/java/ch/ifocusit/plantuml/PlantUmlBuilderTest.java
[ "public enum AssociationType {\n\n LINK(\"-\"),\n DIRECTION(\"-->\"),\n BI_DIRECTION(\"<->\"),\n INHERITANCE(\"<|--\");\n\n private String symbol;\n\n AssociationType(String symbol) {\n this.symbol = symbol;\n }\n\n @Override\n public String toString() {\n return symbol;\n ...
import ch.ifocusit.plantuml.classdiagram.model.Association.AssociationType; import ch.ifocusit.plantuml.classdiagram.model.Cardinality; import ch.ifocusit.plantuml.classdiagram.model.attribute.SimpleAttribute; import ch.ifocusit.plantuml.classdiagram.model.clazz.Clazz; import ch.ifocusit.plantuml.classdiagram.model.clazz.SimpleClazz; import org.junit.Test; import static org.fest.assertions.Assertions.*;
/*- * Plantuml builder * * Copyright (C) 2017 Focus IT * * 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 ch.ifocusit.plantuml; public class PlantUmlBuilderTest { private static final String CR = PlantUmlBuilder.NEWLINE; @Test public void buildInterface() { final String diagram = new PlantUmlBuilder().addType(SimpleClazz.create("Vehicule", Clazz.Type.INTERFACE)).build(); assertThat(diagram).isEqualTo("interface \"Vehicule\"" + CR + CR); } @Test public void buildClassNoField() { final String diagram = new PlantUmlBuilder().addType(SimpleClazz.create("Wheel", Clazz.Type.CLASS)).build(); assertThat(diagram).isEqualTo("class \"Wheel\"" + CR + CR); } @Test public void buildClassWithManyFields() { final String diagram = new PlantUmlBuilder() .addType(SimpleClazz.create("Car", Clazz.Type.CLASS, new SimpleAttribute("brand", "String"), new SimpleAttribute("wheels", "Collection<Wheel>"))) .build(); assertThat(diagram).isEqualTo("class \"Car\" {" + CR + " brand : String" + CR + " wheels : Collection<Wheel>" + CR + "}" + CR + CR); } @Test public void buildEnum() { final String diagram = new PlantUmlBuilder() .addType(SimpleClazz.create("Devise", Clazz.Type.ENUM, new SimpleAttribute("CHF", null), new SimpleAttribute("EUR", null), new SimpleAttribute("USD", null))) .build(); assertThat(diagram).isEqualTo("enum \"Devise\" {" + CR + " CHF" + CR + " EUR" + CR + " USD" + CR + "}" + CR + CR); } @Test public void buildAssociations() throws Exception { String diagram = new PlantUmlBuilder()
.addAssociation("Vehicule", "Car", AssociationType.INHERITANCE)
0
asrulhadi/wap
src/java/org/homeunix/wap/XSS/OutputAnalysisXSS.java
[ "public class LinesToCorrect {\n String nameFile;\n Map<Integer, String> MapLinesToCorrect;\n Map<Integer, String[]> MapLinesToCorrectArray;\n\n \n public LinesToCorrect (String filename){\n this.nameFile = filename;\n MapLinesToCorrect = new LinkedHashMap<Integer, String>();\n }\n\n...
import org.homeunix.wap.utils.LinesToCorrect; import org.homeunix.wap.utils.GlobalDataApp; import org.homeunix.wap.utils.ManageFiles; import org.homeunix.wap.table.tainted.ListVulners; import org.homeunix.wap.table.symbol.SymbolTable; import org.homeunix.wap.table.symbol.MethodTable; import org.homeunix.wap.table.symbol.MethodSymbol; import java.util.*; import java.io.*;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.homeunix.wap.XSS; /** * * @author iberiam */ public class OutputAnalysisXSS { //public static void outputAnalysisWithCorrection (String type_analyse, String filename) throws IOException{ public static void outputAnalysisWithCorrection (String type_analyse, String filename, LinesToCorrect ltc, int num_file) throws IOException{ FileWriter out_FileOfPaths; File dir = null; BufferedWriter bufferWritter = null; Date date = new Date(System.currentTimeMillis()); int i = GlobalDataXSS.MainLinesToCorrect.size(); if (type_analyse.equals("project") == true){ dir = new File(System.getProperty("base.dir") + File.separator + "NewFiles"); // Se ja houve analises anteriores apaga dir if (GlobalDataApp.numAnalysis == 0 && dir.exists() == true && num_file == i){
ManageFiles r = new ManageFiles(dir.toString());
2
LetsCoders/MassiveTanks
src/main/java/pl/letscode/tanks/engine/Game.java
[ "public class GameModel {\n\n\tprivate final List<Player> players;\n\tprivate final List<TankObject> tanks;\n\tprivate final List<BulletObject> bullets;\n\tprivate final MapMatrix map;\n\t\n\t/* Constructors */\n\t\n\tGameModel(List<Player> players, List<TankObject> tanks,\n\t\t\tList<BulletObject> bullets, MapMatr...
import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.dyn4j.Listener; import org.dyn4j.dynamics.BodyFixture; import org.dyn4j.dynamics.World; import com.google.common.base.Objects; import pl.letscode.tanks.engine.model.GameModel; import pl.letscode.tanks.engine.objects.PhysicsObject; import pl.letscode.tanks.engine.objects.Shootable; import pl.letscode.tanks.engine.objects.bullet.BulletObject; import pl.letscode.tanks.engine.objects.tank.TankObject; import pl.letscode.tanks.events.server.json.PlayerStateDTO; import pl.letscode.tanks.map.MapMatrix; import pl.letscode.tanks.map.terrain.TerrainObject; import pl.letscode.tanks.player.Player;
package pl.letscode.tanks.engine; /** * Aggregate root, contains whole state. World object also has to be here as it * contains references to Body objects. * * Need to somehow keep them in sync. * * @author edhendil * */ public class Game { private final long id; private final GameModel model; private final World world; /* Constructors */ Game(long id, GameModel model, World world) { this.id = id; this.model = model; this.world = world; } /* Read model */ public long getId() { return this.id; }
public Collection<Player> getPlayers() {
8
bupt1987/JgFramework
src/main/java/com/zhaidaosi/game/jgframework/Router.java
[ "@SuppressWarnings(\"resource\")\npublic class BaseFile {\n\n private static final Logger log = LoggerFactory.getLogger(BaseFile.class);\n\n\n public static Set<Class<?>> getClasses(String pack, boolean recursive) {\n return getClasses(pack, \"\", recursive);\n }\n\n /**\n * 从包package中获取所有的Cl...
import com.zhaidaosi.game.jgframework.common.BaseFile; import com.zhaidaosi.game.jgframework.common.BaseRunTimer; import com.zhaidaosi.game.jgframework.common.BaseString; import com.zhaidaosi.game.jgframework.handler.BaseHandler; import com.zhaidaosi.game.jgframework.handler.IBaseHandler; import com.zhaidaosi.game.jgframework.message.IBaseMessage; import com.zhaidaosi.game.jgframework.message.InMessage; import com.zhaidaosi.game.jgframework.message.OutMessage; import io.netty.channel.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Set;
package com.zhaidaosi.game.jgframework; public class Router { private static final Logger log = LoggerFactory.getLogger(Router.class); private static HashMap<String, IBaseHandler> handlers = new HashMap<>(); private static final String classSuffix = "Handler"; public static final String ERROR_HANDLERNAME = "_error_"; public static final String HEART_HANDLERNAME = "_heart_"; public static final String WAIT_HANDLERNAME = "_wait_"; /** * 初始化handler */ public static void init() { Set<Class<?>> classes = BaseFile.getClasses(Boot.SERVER_HANDLER_PACKAGE_PATH, classSuffix, true); for (Class<?> c : classes) { String className = c.getName(); IBaseHandler handler; try { handler = (IBaseHandler) c.newInstance(); // 只取Handler前面部分 String handlerName = className.replace(Boot.SERVER_HANDLER_PACKAGE_PATH + ".", "").replace(classSuffix, "").toLowerCase(); handler.setHandlerName(handlerName); handlers.put(handlerName, handler); log.info("handler类 : " + className + " 加载完成"); } catch (InstantiationException | IllegalAccessException e) { log.error("handler类 : " + className + " 加载失败", e); } } } /** * 运行handler * @param im * @param ch * @return * @throws Exception */
public static IBaseMessage run(InMessage im, Channel ch) throws Exception {
4
enguerrand/xdat
src/main/java/org/xdat/gui/panels/ScatterChart2DPanel.java
[ "public class Main extends JFrame {\n\tpublic static final long serialVersionUID = 10L;\n\tprivate MainMenuBar mainMenuBar;\n\tprivate Session currentSession;\n\tprivate List<ChartFrame> chartFrames = new LinkedList<>();\n\tprivate final BuildProperties buildProperties;\n\tprivate final ClusterFactory clusterFactor...
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import org.jetbrains.annotations.Nullable; import org.xdat.Main; import org.xdat.chart.ParallelCoordinatesChart; import org.xdat.chart.ScatterChart2D; import org.xdat.chart.ScatterPlot2D; import org.xdat.data.AxisType; import org.xdat.data.DataSheet; import org.xdat.data.Design; import org.xdat.data.Parameter;
/* * Copyright 2014, Enguerrand de Rochefort * * This file is part of xdat. * * xdat 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. * * xdat 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 xdat. If not, see <http://www.gnu.org/licenses/>. * */ package org.xdat.gui.panels; public class ScatterChart2DPanel extends ChartPanel { static final long serialVersionUID = 1L; private Main mainWindow; private int yAxisOffset = 0; public ScatterChart2DPanel(Main mainWindow, ScatterChart2D chart) { super(chart); this.mainWindow = mainWindow; } public void paintComponent(Graphics g) { super.paintComponent(g); ScatterChart2D chart = (ScatterChart2D) this.getChart();
ScatterPlot2D plot = chart.getScatterPlot2D();
3
mmonkey/Destinations
src/main/java/com/github/mmonkey/destinations/commands/HomeCommand.java
[ "public class HomeCommandElement extends SelectorCommandElement {\n\n /**\n * HomeCommandElement constructor\n *\n * @param key Text\n */\n public HomeCommandElement(@Nullable Text key) {\n super(key);\n }\n\n @Override\n protected Iterable<String> getChoices(CommandSource sour...
import com.github.mmonkey.destinations.commands.elements.HomeCommandElement; import com.github.mmonkey.destinations.entities.HomeEntity; import com.github.mmonkey.destinations.entities.PlayerEntity; import com.github.mmonkey.destinations.events.PlayerTeleportHomeEvent; import com.github.mmonkey.destinations.events.PlayerTeleportPreEvent; import com.github.mmonkey.destinations.persistence.cache.PlayerCache; import com.github.mmonkey.destinations.utilities.BlockUtil; 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.args.GenericArguments; 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.text.Text; import org.spongepowered.api.world.Location; import java.util.Set;
package com.github.mmonkey.destinations.commands; public class HomeCommand implements CommandExecutor { public static final String[] ALIASES = {"home", "h"}; /** * Get the Command Specifications for this command * * @return CommandSpec */ public static CommandSpec getCommandSpec() { return CommandSpec.builder() .permission("destinations.home.use") .description(Text.of("/home [name]")) .extendedDescription(Text.of("Teleport to the nearest home or to the named home.")) .executor(new HomeCommand()) .arguments(GenericArguments.optional(new HomeCommandElement(Text.of("name")))) .build(); } @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { if (!(src instanceof Player)) { return CommandResult.empty(); } String name = (String) args.getOne("name").orElse(""); Player player = (Player) src; PlayerEntity playerEntity = PlayerCache.instance.get(player);
Set<HomeEntity> homes = playerEntity.getHomes();
1
Bernardo-MG/repository-pattern-java
src/test/java/com/wandrell/pattern/test/integration/repository/access/h2/eclipselink/ITModifyH2EclipselinkJpaRepository.java
[ "public class PersistenceContextPaths {\n\n /**\n * Eclipselink JPA persistence.\n */\n public static final String ECLIPSELINK = \"classpath:context/persistence/jpa-eclipselink.xml\";\n\n /**\n * Hibernate JPA persistence.\n */\n public static final String HIBERNATE = \"classpath:context...
import com.wandrell.pattern.test.util.config.properties.DatabaseScriptsPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.JdbcPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.JpaPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.PersistenceProviderPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.QueryPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.RepositoryPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.TestPropertiesPaths; import com.wandrell.pattern.test.util.config.properties.UserPropertiesPaths; import com.wandrell.pattern.test.util.test.integration.repository.access.AbstractITModify; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import com.wandrell.pattern.test.util.config.context.PersistenceContextPaths; import com.wandrell.pattern.test.util.config.context.RepositoryContextPaths; import com.wandrell.pattern.test.util.config.context.TestContextPaths;
/** * The MIT License (MIT) * <p> * Copyright (c) 2015 the original author or authors. * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * 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.wandrell.pattern.test.integration.repository.access.h2.eclipselink; /** * Integration tests for * {@link com.wandrell.pattern.repository.jpa.JpaRepository JPARepository} * implementing {@code AbstractITModify}, using an H2 in-memory database and * Eclipselink-based JPA. * * @author Bernardo Martínez Garrido * @see com.wandrell.pattern.repository.jpa.JpaRepository JPARepository */ @ContextConfiguration(locations = { TestContextPaths.DEFAULT, TestContextPaths.ENTITY_MODIFIABLE, PersistenceContextPaths.ECLIPSELINK,
RepositoryContextPaths.JPA })
1
evolvingstuff/RecurrentJava
src/loss/LossSoftmax.java
[ "public class Graph {\n\tboolean applyBackprop;\n\t\n\tList<Runnable> backprop = new ArrayList<>();\n\t\n\tpublic Graph() {\n\t\tthis.applyBackprop = true;\n\t}\n\t\n\tpublic Graph(boolean applyBackprop) {\n\t\tthis.applyBackprop = applyBackprop;\n\t}\n\t\n\tpublic void backward() {\n\t\tfor (int i = backprop.size(...
import java.util.ArrayList; import java.util.List; import autodiff.Graph; import matrix.Matrix; import model.Model; import datastructs.DataSequence; import datastructs.DataStep; import util.Util;
package loss; public class LossSoftmax implements Loss { /** * */ private static final long serialVersionUID = 1L; @Override public void backward(Matrix logprobs, Matrix targetOutput) throws Exception { int targetIndex = getTargetIndex(targetOutput); Matrix probs = getSoftmaxProbs(logprobs, 1.0); for (int i = 0; i < probs.w.length; i++) { logprobs.dw[i] = probs.w[i]; } logprobs.dw[targetIndex] -= 1; } @Override public double measure(Matrix logprobs, Matrix targetOutput) throws Exception { int targetIndex = getTargetIndex(targetOutput); Matrix probs = getSoftmaxProbs(logprobs, 1.0); double cost = -Math.log(probs.w[targetIndex]); return cost; }
public static double calculateMedianPerplexity(Model model, List<DataSequence> sequences) throws Exception {
2
k0shk0sh/FastAccess
app/src/main/java/com/fastaccess/ui/modules/apps/folders/create/CreateFolderView.java
[ "public class FolderModel extends SugarRecord implements Parcelable {\n\n @Unique private String folderName;\n private long createdDate;\n private int orderIndex;\n private int color;\n private int appsCount;\n @Ignore private List<AppsModel> folderApps;\n\n public String getFolderName() {\n ...
import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TextInputLayout; import android.support.v4.content.ContextCompat; import android.text.Editable; import android.view.Gravity; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import com.amulyakhare.textdrawable.TextDrawable; import com.fastaccess.R; import com.fastaccess.data.dao.FolderModel; import com.fastaccess.helper.Bundler; import com.fastaccess.helper.InputHelper; import com.fastaccess.helper.ViewHelper; import com.fastaccess.ui.base.BaseBottomSheetDialog; import com.fastaccess.ui.modules.apps.folders.create.CreateFolderMvp.OnNotifyFoldersAdapter; import com.fastaccess.ui.widgets.FontButton; import org.xdty.preference.colorpicker.ColorPickerDialog; import java.util.Date; import butterknife.BindView; import butterknife.OnClick; import butterknife.OnTextChanged; import icepick.State;
package com.fastaccess.ui.modules.apps.folders.create; /** * Created by Kosh on 11 Oct 2016, 8:27 PM */ public class CreateFolderView extends BaseBottomSheetDialog implements CreateFolderMvp.View { private long folderId; @State int selectedColor = Color.parseColor("#FF2A456B"); @State String fName; @BindView(R.id.folderImage) ImageView folderImage; @BindView(R.id.folderName) TextInputLayout folderName;
@BindView(R.id.cancel) FontButton cancel;
6
iminto/baicai
src/main/java/com/baicai/controller/index/InvestController.java
[ "public abstract class BaseController implements HandlerInterceptor{\r\n\tprotected Logger logger = LoggerFactory.getLogger(this.getClass());\r\n\t\r\n\t/**\r\n\t * preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用\r\n\t * @param request\r\n\t * @param response\r\n\t * @param handler\r\n\t * @return\r\n\t * @throw...
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import com.baicai.controller.common.BaseController; import com.baicai.domain.project.Project; import com.baicai.domain.system.ErrorMsg; import com.baicai.domain.system.Pagination; import com.baicai.service.project.ProjectService; import com.baicai.corewith.util.NumberHelper;
package com.baicai.controller.index; @Controller @RequestMapping
public class InvestController extends BaseController{
0
PedroCarrillo/Expense-Tracker-App
ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/ui/reminders/ReminderFragment.java
[ "public class RemindersAdapter extends BaseRecyclerViewAdapter<RemindersAdapter.ViewHolder> {\n\n private List<Reminder> mReminderList;\n private int lastPosition = -1;\n private RemindersAdapterOnClickHandler onRecyclerClickListener;\n\n public class ViewHolder extends BaseViewHolder implements Compoun...
import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.ActionMode; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.pedrocarrillo.expensetracker.R; import com.pedrocarrillo.expensetracker.adapters.RemindersAdapter; import com.pedrocarrillo.expensetracker.custom.DefaultRecyclerViewItemDecorator; import com.pedrocarrillo.expensetracker.entities.Category; import com.pedrocarrillo.expensetracker.entities.Reminder; import com.pedrocarrillo.expensetracker.interfaces.IUserActionsMode; import com.pedrocarrillo.expensetracker.ui.MainActivity; import com.pedrocarrillo.expensetracker.ui.MainFragment; import com.pedrocarrillo.expensetracker.utils.DialogManager; import com.pedrocarrillo.expensetracker.utils.RealmManager; import java.util.ArrayList; import java.util.List;
package com.pedrocarrillo.expensetracker.ui.reminders; /** * Created by pcarrillo on 17/09/2015. */ public class ReminderFragment extends MainFragment implements RemindersAdapter.RemindersAdapterOnClickHandler { public static final int RQ_REMINDER = 1002; private RecyclerView rvReminders;
private List<Reminder> mReminderList;
3
enebo/racob
unittest/org/racob/test/vbscript/ScriptTest2.java
[ "public class ActiveXComponent extends Dispatch {\n\n\t/**\n\t * Normally used to create a new connection to a microsoft application. The\n\t * passed in parameter is the name of the program as registered in the\n\t * registry. It can also be the object name.\n\t * <p>\n\t * This constructor causes a new Windows ob...
import org.racob.activeX.ActiveXComponent; import org.racob.com.ComException; import org.racob.com.ComThread; import org.racob.com.Dispatch; import org.racob.com.DispatchEvents; import org.racob.com.DispatchProxy; import org.racob.com.STA; import org.racob.com.Variant; import org.racob.test.BaseTestCase;
package org.racob.test.vbscript; /** * This example demonstrates how to make calls between two different STA's. * First, to create an STA, you need to extend the STA class and override its * OnInit() method. This method will be called in the STA's thread so you can * use it to create your COM components that will run in that STA. If you then * try to call methods on those components from other threads (STA or MTA) - * this will fail. You cannot create a component in an STA and call its methods * from another thread. You can use the DispatchProxy to get a proxy to any * Dispatch that lives in another STA. This object has to be created in the STA * that houses the Dispatch (in this case it's created in the OnInit method). * Then, another thread can call the toDispatch() method of DispatchProxy to get * a local proxy. At most ONE (!) thread can call toDispatch(), and the call can * be made only once. This is because a IStream object is used to pass the * proxy, and it is only written once and closed when you read it. If you need * multiple threads to access a Dispatch pointer, then create that many * DispatchProxy objects. * <p> * May need to run with some command line options (including from inside * Eclipse). Look in the docs area at the Jacob usage document for command line * options. */ public class ScriptTest2 extends BaseTestCase { public void testScript2() { try {
ComThread.InitSTA();
2
badvision/jace
src/main/java/jace/hardware/massStorage/ProdosVirtualDisk.java
[ "public class Emulator {\r\n\r\n public static Emulator instance;\r\n public static EmulatorUILogic logic = new EmulatorUILogic();\r\n public static Thread mainThread;\r\n\r\n// public static void main(String... args) {\r\n// mainThread = Thread.currentThread();\r\n// instance = new Emulat...
import jace.Emulator; import jace.EmulatorUILogic; import jace.apple2e.MOS65C02; import jace.core.Computer; import jace.core.RAM; import static jace.hardware.ProdosDriver.*; import jace.hardware.ProdosDriver.MLI_COMMAND_TYPE; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (C) 2012 Brendan Robert (BLuRry) brendan.robert@gmail.com. * * 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; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * 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 jace.hardware.massStorage; /** * Representation of a Prodos Volume which maps to a physical folder on the * actual hard drive. This is used by CardMassStorage in the event the disk path * is a folder and not a disk image. FreespaceBitmap and the various Node * classes are used to represent the filesystem structure. * * @author Brendan Robert (BLuRry) brendan.robert@gmail.com */ public class ProdosVirtualDisk implements IDisk { public static final int VOLUME_START = 2; public static final int FREESPACE_BITMAP_START = 6; byte[] ioBuffer; File physicalRoot; private final DiskNode[] physicalMap; DirectoryNode rootDirectory; FreespaceBitmap freespaceBitmap; public ProdosVirtualDisk(File rootPath) throws IOException { ioBuffer = new byte[BLOCK_SIZE]; physicalMap = new DiskNode[MAX_BLOCK]; initDiskStructure(); setPhysicalPath(rootPath); } @Override
public void mliRead(int block, int bufferAddress, RAM memory) throws IOException {
4
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/dagger/component/ViewModelComponent.java
[ "@Module\npublic class ViewModelModule {\n @Provides\n StoryListViewModel providesStoryListViewModel() {\n return new StoryListViewModel();\n }\n\n @Provides\n StoryDetailViewModel providesStoryDetailViewModel() {\n return new StoryDetailViewModel();\n }\n\n @Provides\n LoginVi...
import dagger.Component; import io.dwak.holohackernews.app.dagger.module.ViewModelModule; import io.dwak.holohackernews.app.ui.about.AboutActivity; import io.dwak.holohackernews.app.ui.login.LoginActivity; import io.dwak.holohackernews.app.ui.storydetail.StoryDetailFragment; import io.dwak.holohackernews.app.ui.storylist.MainActivity; import io.dwak.holohackernews.app.ui.storylist.StoryListFragment;
package io.dwak.holohackernews.app.dagger.component; @Component(dependencies = AppComponent.class, modules = ViewModelModule.class) public interface ViewModelComponent { void inject(MainActivity activity); void inject(StoryListFragment fragment); void inject(StoryDetailFragment fragment); void inject(LoginActivity activity);
void inject(AboutActivity.AboutFragment aboutFragment);
1
swarmcom/jSynapse
src/main/java/org/swarmcom/jsynapse/service/message/MessageServiceImpl.java
[ "public interface MessageRepository extends MongoRepository<Message, String> {\n\n List<Message> findByRoomId(String roomId);\n}", "public class Message {\n @Id\n String id;\n\n @NotNull\n @JsonProperty\n String msgtype;\n\n @Indexed\n String roomId;\n\n String body;\n\n public Strin...
import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import org.swarmcom.jsynapse.dao.MessageRepository; import org.swarmcom.jsynapse.domain.Message; import org.swarmcom.jsynapse.domain.Room; import org.swarmcom.jsynapse.service.room.RoomService; import javax.inject.Inject; import static org.swarmcom.jsynapse.domain.Message.Messages;
/* * (C) Copyright 2015 eZuce 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 org.swarmcom.jsynapse.service.message; @Service @Validated public class MessageServiceImpl implements MessageService {
private final MessageRepository messageRepository;
0
gambitproject/gte
lib-algo/src/lse/math/games/io/ExtensiveFormXMLReader.java
[ "public class Rational \r\n{\r\n\tpublic static final Rational ZERO = new Rational(BigInteger.ZERO, BigInteger.ONE);\r\n\tpublic static final Rational ONE = new Rational(BigInteger.ONE, BigInteger.ONE);\r\n\tpublic static final Rational NEGONE = new Rational(BigInteger.ONE.negate(), BigInteger.ONE);\r\n\tpublic Big...
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.w3c.dom.Document; import lse.math.games.Rational; import lse.math.games.tree.ExtensiveForm; import lse.math.games.tree.Outcome; import lse.math.games.tree.Node; import lse.math.games.tree.Iset; import lse.math.games.tree.Move; import lse.math.games.tree.Player;
} if (parentNode != null) { log.fine("XMLReader: processing child of " + parentNode.uid()); parentNode.addChild(node); } // process iset // if parent is an iset use that // if iset ref exists use that (make sure player is not also set) // if player exists create a new iset for that (don't add to dictionary) // else throw an error String isetId = getAttribute(elem, "iset"); if (elem.getParentNode() != null && "iset".equals(elem.getParentNode().getNodeName())) { if (isetId != null) { log.warning("Warning: @iset attribute is set for a node nested in an iset tag. Ignored."); } isetId = getAttribute(elem.getParentNode(), "id"); } String playerId = getAttribute(elem, "player"); Player player = (playerId != null) ? getPlayer(playerId) : Player.CHANCE; Iset iset = null; if (isetId == null) { iset = tree.createIset(player); singletons.add(iset); // root is already taken care of } else { //if (elem.@player != undefined) trace("Warning: @player attribute is set for a node that references an iset. Ignored."); //look it up in the map, if it doesn't exist create it and add it iset = isets.get(isetId); if (iset == null) { iset = tree.createIset(isetId, player); isets.put(isetId, iset); } else { if (player != Player.CHANCE) { if (iset.player() != Player.CHANCE && player != iset.player()) { log.warning("Warning: @player attribute conflicts with earlier iset player assignment. Ignored."); } iset.setPlayer(player); } } } tree.addToIset(node, iset); // set up the moves processMove(elem, node, parentNode); /* String moveId = getAttribute(elem, "move"); if (moveId != null) { String moveIsetId = parentNode.iset() != null ? parentNode.iset().name() : ""; Move move = moves.get(moveIsetId + "::" + moveId); if (move == null) { move = tree.createMove(moveId); moves.put(moveIsetId + "::" + moveId, move); } node.reachedby = move; } else if (parentNode != null) { // assume this comes from a chance node node.reachedby = tree.createMove(); log.fine("Node " + id + " has a parent, but no incoming probability or move is specified"); } String probStr = getAttribute(elem, "prob"); if (probStr != null && node.reachedby != null) { node.reachedby.prob = Rational.valueOf(probStr); } else if (node.reachedby != null) { log.fine("Warning: @move is missing probability. Prior belief OR chance will be random."); } */ log.fine("node: " + id + ", iset: " + isetId + ", pl: " + (getAttribute(elem, "player") == null ? getAttribute(elem.getParentNode(), "player") : getAttribute(elem, "player")) + (node.reachedby != null ? ", mv: " + node.uid() : "")); for (org.w3c.dom.Node child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { if ("node".equals(child.getNodeName())) { processNode(child, node); } else if ("outcome".equals(child.getNodeName())) { processOutcome(child, node); } else { log.warning("Ignoring unknown element:\r\n" + child); } } } private void processOutcome(org.w3c.dom.Node elem, Node parent) { // Create wrapping node // get parent from dictionary... if it doesn't exist then the outcome must be the root Node wrapNode = parent != null ? tree.createNode() : tree.root(); if (parent != null) parent.addChild(wrapNode); processMove(elem, wrapNode, parent); /* String moveId = getAttribute(elem, "move"); if (moveId != null) { String moveIsetId = (parent != null && parent.iset() != null) ? parent.iset().name() : ""; Move move = moveId != null ? moves.get(moveIsetId + "::" + moveId) : null; if (move == null && moveId != null) { move = tree.createMove(moveId); moves.put(moveIsetId + "::" + moveId, move); } wrapNode.reachedby = move; } else if (parent != null) { wrapNode.reachedby = tree.createMove(); log.fine("Node " + wrapNode.uid() + " has a parent, but no incoming probability or move is specified"); } String probStr = getAttribute(elem, "prob"); if (probStr != null && wrapNode.reachedby != null) { wrapNode.reachedby.prob = Rational.valueOf(probStr); } else if (wrapNode.reachedby != null) { log.fine("Warning: @move is missing probability. Prior belief OR chance will be random."); } */ Outcome outcome = tree.createOutcome(wrapNode); for (org.w3c.dom.Node child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { if ("payoff".equals(child.getNodeName())) { String playerId = getAttribute(child, "player");
Rational payoff = Rational.valueOf(getAttribute(child, "value"));
0
kkrugler/yalder
tools/src/main/java/org/krugler/yalder/tools/ModelBuilderTool.java
[ "public abstract class BaseLanguageDetector {\n\n public static final double DEFAULT_ALPHA = 0.000002;\n public static final double DEFAULT_DAMPENING = 0.001;\n\n protected static final double MIN_LANG_PROBABILITY = 0.1;\n protected static final double MIN_GOOD_LANG_PROBABILITY = 0.99;\n \n protec...
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.krugler.yalder.BaseLanguageDetector; import org.krugler.yalder.BaseLanguageModel; import org.krugler.yalder.DetectionResult; import org.krugler.yalder.LanguageLocale; import org.krugler.yalder.ModelBuilder; import org.krugler.yalder.hash.HashLanguageDetector; import org.krugler.yalder.hash.HashLanguageModel; import org.krugler.yalder.text.TextLanguageDetector; import org.krugler.yalder.text.TextLanguageModel;
String text = pieces[1]; boolean correct = false; detector.reset(); detector.addText(text); Collection<DetectionResult> results = detector.detect(); if (results.isEmpty()) { System.out.println(String.format("'%s' detected as '<unknown>': %s", language, text)); } else { DetectionResult result = results.iterator().next(); if (language.equals(result.getLanguage())) { correct = true; } else { System.out.println(String.format("'%s' detected as '%s': %s", language, result.getLanguage(), text)); } } Map<LanguageLocale, Integer> mapToIncrement = correct ? correctLines : incorrectLines; Integer curCount = mapToIncrement.get(language); mapToIncrement.put(language, curCount == null ? 1 : curCount + 1); } long deltaTime = System.currentTimeMillis() - startTime; System.out.println(String.format("Detecting %d lines took %dms", lines.size(), deltaTime)); int totalCorrect = 0; int totalIncorrect = 0; for (LanguageLocale language : supportedLanguages) { Integer correctCountAsObj = correctLines.get(language); int correctCount = correctCountAsObj == null ? 0 : correctCountAsObj; totalCorrect += correctCount; Integer incorrectCountAsObj = incorrectLines.get(language); int incorrectCount = incorrectCountAsObj == null ? 0 : incorrectCountAsObj; totalIncorrect += incorrectCount; int languageCount = correctCount + incorrectCount; if (languageCount > 0) { System.out.println(String.format("'%s' error rate = %.2f", language, (100.0 * incorrectCount)/languageCount)); } } System.out.println(String.format("Total error rate = %.2f", (100.0 * totalIncorrect)/(totalCorrect +totalIncorrect))); } private void changeMode() throws IOException { String curMode = _binaryMode ? "binary" : "text"; String yesNo = readInputLine(String.format("Switch from current mode of %s (y/n)?: ", curMode)); if (yesNo.equalsIgnoreCase("y")) { _binaryMode = !_binaryMode; _builder.setBinaryMode(_binaryMode); _models = null; } } private void pruneModels() { if (_models.isEmpty()) { System.err.println("Models must be built or loaded first before pruning"); return; } String minNGramCountAsStr = readInputLine("Enter minimum normalized ngram count: "); if (minNGramCountAsStr.trim().isEmpty()) { return; } int minNGramCount = Integer.parseInt(minNGramCountAsStr); int totalPruned = 0; for (BaseLanguageModel model : _models) { totalPruned += model.prune(minNGramCount); } System.out.println(String.format("Pruned %d ngrams by setting min count to 20", totalPruned)); } private void loadModels() throws IOException { String dirname = readInputLine("Enter path to directory containing models: "); if (dirname.length() == 0) { return; } File dirFile = new File(dirname); if (!dirFile.exists()) { System.out.println("Directory must exist"); return; } if (!dirFile.isDirectory()) { System.out.println(String.format("%s is not a directory", dirFile)); return; } String modelSuffix = readInputLine("Enter type of model (bin or txt): "); boolean isBinary = modelSuffix.equals("bin"); System.out.println(String.format("Loading models from files in '%s'...", dirFile.getCanonicalPath())); Set<BaseLanguageModel> newModels = new HashSet<>(); for (File file : FileUtils.listFiles(dirFile, new String[]{"txt", "bin"}, true)) { String filename = file.getName(); Pattern p = Pattern.compile(String.format("yalder_model_(.+).%s", modelSuffix)); Matcher m = p.matcher(filename); if (!m.matches()) { continue; } // Verify that language is valid LanguageLocale.fromString(m.group(1)); // Figure out if it's binary or text BaseLanguageModel model = null; if (isBinary) { DataInputStream dis = new DataInputStream(new FileInputStream(file)); HashLanguageModel binaryModel = new HashLanguageModel(); binaryModel.readAsBinary(dis); dis.close(); model = binaryModel; } else { InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
TextLanguageModel textModel = new TextLanguageModel();
8
exoplatform/task
services/src/main/java/org/exoplatform/task/dao/jpa/TaskDAOImpl.java
[ "public static String TASK_COWORKER = \"coworker\";", "public static String TASK_MANAGER = \"status.project.manager\";", "public static String TASK_MENTIONED_USERS = \"mentionedUsers\";", "public static String TASK_PARTICIPATOR = \"status.project.participator\";", "public static String TASK_PROJECT = \"stat...
import static org.exoplatform.task.dao.condition.Conditions.TASK_COWORKER; import static org.exoplatform.task.dao.condition.Conditions.TASK_MANAGER; import static org.exoplatform.task.dao.condition.Conditions.TASK_MENTIONED_USERS; import static org.exoplatform.task.dao.condition.Conditions.TASK_PARTICIPATOR; import static org.exoplatform.task.dao.condition.Conditions.TASK_PROJECT; import java.util.*; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Order; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.exoplatform.commons.utils.ListAccess; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.task.dao.OrderBy; import org.exoplatform.task.dao.TaskHandler; import org.exoplatform.task.dao.TaskQuery; import org.exoplatform.task.dao.condition.SingleCondition; import org.exoplatform.task.domain.Status; import org.exoplatform.task.domain.Task;
} int oldRank = currentTask.getRank(); int prevRank = prevTask != null ? prevTask.getRank() : 0; int nextRank = nextTask != null ? nextTask.getRank() : 0; int newRank = prevRank + 1; if (newStatus != null && currentTask.getStatus().getId() != newStatus.getId()) { oldRank = 0; currentTask.setStatus(newStatus); } EntityManager em = getEntityManager(); StringBuilder sql = null; if (newRank == 1 || oldRank == 0) { int increment = 1; StringBuilder exclude = new StringBuilder(); if (nextRank == 0) { for (int i = currentTaskIndex - 1; i >= 0; i--) { Task task = find(orders[i]); if (task.getRank() > 0) { break; } // Load coworker to avoid they will be deleted when save task task.getCoworker(); task.setRank(newRank + currentTaskIndex - i); update(task); if (exclude.length() > 0) { exclude.append(','); } exclude.append(task.getId()); increment++; } } //Update rank of tasks have rank >= newRank with rank := rank + increment sql = new StringBuilder("UPDATE TaskTask as ta SET ta.rank = ta.rank + ").append(increment) .append(" WHERE ta.rank >= ").append(newRank); if (exclude.length() > 0) { sql.append(" AND ta.id NOT IN (").append(exclude.toString()).append(")"); } } else if (oldRank < newRank) { //Update all task where oldRank < rank < newRank: rank = rank - 1 sql = new StringBuilder("UPDATE TaskTask as ta SET ta.rank = ta.rank - 1") .append(" WHERE ta.rank > ").append(oldRank) .append(" AND ta.rank < ").append(newRank); newRank --; } else if (oldRank > newRank) { //Update all task where newRank <= rank < oldRank: rank = rank + 1 sql = new StringBuilder("UPDATE TaskTask as ta SET ta.rank = ta.rank + 1") .append(" WHERE ta.rank >= ").append(newRank) .append(" AND ta.rank < ").append(oldRank); newRank ++; } if (sql != null && sql.length() > 0) { // Add common condition sql.append(" AND ta.completed = FALSE AND ta.status.id = ").append(currentTask.getStatus().getId()); //TODO: This block code is temporary workaround because the update is require transaction EntityTransaction trans = em.getTransaction(); boolean active = false; if (!trans.isActive()) { trans.begin(); active = true; } em.createQuery(sql.toString()).executeUpdate(); if (active) { trans.commit(); } } currentTask.setRank(newRank); update(currentTask); } @Override public ListAccess<Task> findTasksByLabel(long labelId, List<Long> projectIds, String username, OrderBy orderBy) { TaskQuery query = new TaskQuery(); if (projectIds != null) { query.setProjectIds(projectIds); } if (orderBy != null) { query.setOrderBy(Arrays.asList(orderBy)); } if (labelId > 0) { query.setLabelIds(Arrays.asList(labelId)); } else { query.setIsLabelOf(username); } return findTasks(query); } @Override public Set<String> getCoworker(long taskid) { TypedQuery<String> query = getEntityManager().createNamedQuery("Task.getCoworker", String.class); query.setParameter("taskid", taskid); List<String> tags = query.getResultList(); return new HashSet<String>(tags); } @Override public Task getTaskWithCoworkers(long id) { TypedQuery<Task> query = getEntityManager().createNamedQuery("Task.getTaskWithCoworkers", Task.class); query.setParameter("taskid", id); try { return cloneEntity((Task)query.getSingleResult()); } catch (PersistenceException e) { log.error("Error when fetching task " + id + " with coworkers", e); return null; } } protected Path buildPath(SingleCondition condition, Root<Task> root) { String field = condition.getField(); Join join = null; Path path = null;
if (TASK_PROJECT.equals(condition.getField())) {
4
Predelnik/ChibiPaintMod
src/chibipaint/ChibiPaint.java
[ "public abstract class CPCommonController implements ICPController\n{\n\nprotected int selectionFillAlpha = 255;\npublic boolean transformPreviewHQ = true;\nprotected boolean useInteractivePreviewFloodFill = false;\nprotected boolean useInteractivePreviewMagicWand = false;\n\npublic void setSelectionAction (selecti...
import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.PixelGrabber; import java.net.URL; import java.net.URLConnection; import chibipaint.controller.CPCommonController; import chibipaint.controller.CPControllerApplet; import chibipaint.engine.CPArtwork; import chibipaint.file.CPChibiFile; import chibipaint.gui.CPMainGUI; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*;
/* * ChibiPaintMod * Copyright (c) 2012-2014 Sergey Semushin * Copyright (c) 2006-2008 Marc Schefer * * This file is part of ChibiPaintMod (previously ChibiPaint). * * ChibiPaintMod 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. * * ChibiPaintMod 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 ChibiPaintMod. If not, see <http://www.gnu.org/licenses/>. */ package chibipaint; public class ChibiPaint extends JApplet { /** * */ private static final long serialVersionUID = 1L; private CPControllerApplet controller; private CPMainGUI mainGUI; private boolean floatingMode = false; private JPanel floatingPlaceholder; private JFrame floatingFrame; @Override public void init () { try { SwingUtilities.invokeAndWait (new Runnable () { @Override public void run () { createApplet (); } }); } catch (Exception e) { e.printStackTrace (); } } @Override public void destroy () { // The following bit of voodoo prevents the Java plugin // from leaking too much. In many cases it will keep // a reference to this JApplet object alive forever. // So have to make sure that we remove references // to the rest of ChibiPaintMod so that they can be // garbage collected normally. setContentPane (new JPanel ()); setJMenuBar (null); floatingPlaceholder = null; floatingFrame = null; controller = null; mainGUI = null; } void createApplet () { controller = new CPControllerApplet (this); controller.setArtwork (createArtwork ()); controller.artwork.setAppletEmulation (true); // FIXME: set a default tool so that we can start drawing
controller.setTool (CPCommonController.T_PEN);
0
maxdemarzi/grittier_ext
src/main/java/com/maxdemarzi/likes/Likes.java
[ "public enum RelationshipTypes implements RelationshipType {\n BLOCKS,\n FOLLOWS,\n MUTES,\n LIKES,\n REPLIED_TO\n}", "@Path(\"/users\")\npublic class Users {\n\n private final GraphDatabaseService db;\n private static final ObjectMapper objectMapper = new ObjectMapper();\n\n public Users...
import com.fasterxml.jackson.databind.ObjectMapper; import com.maxdemarzi.RelationshipTypes; import com.maxdemarzi.users.Users; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.graphdb.*; import javax.ws.rs.Path; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Comparator; import java.util.Map; import static com.maxdemarzi.Properties.*; import static com.maxdemarzi.Time.getLatestTime; import static com.maxdemarzi.Time.utc; import static com.maxdemarzi.posts.Posts.getAuthor; import static com.maxdemarzi.posts.Posts.userRepostedPost; import static com.maxdemarzi.users.Users.getPost; import static java.util.Collections.reverseOrder;
package com.maxdemarzi.likes; @Path("/users/{username}/likes") public class Likes { private final GraphDatabaseService db; private static final ObjectMapper objectMapper = new ObjectMapper(); public Likes(@Context DatabaseManagementService dbms ) { this.db = dbms.database( "neo4j" );; } @GET public Response getLikes(@PathParam("username") final String username, @QueryParam("limit") @DefaultValue("25") final Integer limit, @QueryParam("since") final Long since, @QueryParam("username2") final String username2) throws IOException { ArrayList<Map<String, Object>> results = new ArrayList<>(); Long latest = getLatestTime(since); try (Transaction tx = db.beginTx()) {
Node user = Users.findUser(username, tx);
1
jeffprestes/brasilino
android/Brasilino/app/src/main/java/com/paypal/developer/brasilino/fragment/MainFragment.java
[ "public class Home extends ActionBarActivity implements View.OnTouchListener{\n\n private ImageView imgEsquerda;\n private ImageView imgDireita;\n private ImageView imgCima;\n private ImageView imgBaixo;\n\n private String ip;\n\n private BufferedWriter escritorLinhas = null;\n private OutputSt...
import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.NotificationManagerCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.android.volley.Response; import com.android.volley.VolleyError; import com.paypal.developer.brasilino.Home; import com.paypal.developer.brasilino.PermissionActivity; import com.paypal.developer.brasilino.R; import com.paypal.developer.brasilino.application.CarrinhoApplication; import com.paypal.developer.brasilino.domain.Token; import com.paypal.developer.brasilino.domain.User; import com.paypal.developer.brasilino.domain.UserRoot; import com.paypal.developer.brasilino.service.PaymentService; import com.paypal.developer.brasilino.util.Util; import com.paypal.developer.brasilino.util.WebServerHelper;
package com.paypal.developer.brasilino.fragment; public class MainFragment extends Fragment { private TextView mTvInformation; private Button mBtPurchase; private PaymentService paymentService; private RadioGroup rdbTime; private RadioButton rdbFive; private boolean lastTimeIsFive; public MainFragment() {} private SharedPreferences sp; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); mTvInformation = ((TextView) rootView.findViewById(R.id.tvInformation)); rdbTime = (RadioGroup) rootView.findViewById(R.id.rdb); rdbFive = (RadioButton) rootView.findViewById(R.id.rdbCinco); sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mBtPurchase = ((Button) rootView.findViewById(R.id.btPurchase)); mBtPurchase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle infoBundle = null; //TODO: Refazer a logica de desabilitar a cobrança do paypal para Ricardo //Criar outra variavel em SharedPreferences if (sp.getString("ip", "").endsWith("tht")){ goHome(); } else if(CarrinhoApplication.getDatasource().getToken() == null) {
Intent permissionIntent = new Intent(getActivity(), PermissionActivity.class);
1
GoogleCloudPlatform/bigquery-data-lineage
src/test/java/com/google/cloud/solutions/datalineage/PolicyPropagationPipelineTest.java
[ "public static <T extends Message> ImmutableList<T>\nparseAsList(Collection<String> jsons, Class<T> protoClass) {\n return jsons\n .stream()\n .map(json -> ProtoJsonConverter.parseJson(json, protoClass))\n .filter(Objects::nonNull)\n .collect(toImmutableList());\n}", "@SuppressWarnings(\"unch...
import static com.google.cloud.solutions.datalineage.converter.ProtoJsonConverter.parseAsList; import static com.google.cloud.solutions.datalineage.converter.ProtoJsonConverter.parseJson; import com.google.cloud.datacatalog.v1beta1.Tag; import com.google.cloud.solutions.datalineage.model.BigQueryTableEntity; import com.google.cloud.solutions.datalineage.model.LineageMessages.ColumnEntity; import com.google.cloud.solutions.datalineage.model.LineageMessages.ColumnLineage; import com.google.cloud.solutions.datalineage.model.LineageMessages.ColumnPolicyTags; import com.google.cloud.solutions.datalineage.model.LineageMessages.CompositeLineage; import com.google.cloud.solutions.datalineage.model.LineageMessages.DataEntity; import com.google.cloud.solutions.datalineage.model.LineageMessages.DataEntity.DataEntityTypes; import com.google.cloud.solutions.datalineage.model.LineageMessages.JobInformation; import com.google.cloud.solutions.datalineage.model.LineageMessages.TableLineage; import com.google.cloud.solutions.datalineage.model.LineageMessages.TargetPolicyTags; import com.google.cloud.solutions.datalineage.model.TagsForCatalog; import com.google.cloud.solutions.datalineage.testing.FakeBigQueryServiceFactory; import com.google.cloud.solutions.datalineage.testing.FakeDataCatalogStub; import com.google.cloud.solutions.datalineage.testing.TestResourceLoader; import com.google.cloud.solutions.datalineage.transform.CatalogTagsPropagationTransform; import com.google.cloud.solutions.datalineage.transform.PolicyTagsPropagationTransform; import com.google.common.collect.ImmutableList; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.values.PCollection; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.solutions.datalineage; @RunWith(JUnit4.class) public final class PolicyPropagationPipelineTest { @Rule public final transient TestPipeline testPipeline = TestPipeline.create(); @Test public void tagPropagation_noMonitoredTags_targetEntryIdWithEmptyTags() { FakeDataCatalogStub fakeStub = FakeDataCatalogStub.buildWithTestData( ImmutableList.of("datacatalog-objects/TableA_entry.json", "datacatalog-objects/simple_report_view_entry.json", "datacatalog-objects/OutputTable_entry.json"), ImmutableList.of( "datacatalog-objects/TableA_tags.json", "datacatalog-objects/simple_report_view_tags.json")); PCollection<TagsForCatalog> tags = testPipeline .apply(Create.of( parseJson(TestResourceLoader.load( "composite-lineages/complete_composite_lineage_tableA_simple_report_view_outputTable.json"), CompositeLineage.class))) .apply(
CatalogTagsPropagationTransform
7
Piasy/decaf-mind-compiler
decaf_PA3/src/decaf/typecheck/BuildSym.java
[ "public final class Driver {\n\n\tprivate static Driver driver;\n\n\tprivate Option option;\n\n\tprivate List<DecafError> errors;\n\n\tprivate Lexer lexer;\n\n\tprivate Parser parser;\n\n\tpublic static Driver getDriver() {\n\t\treturn driver;\n\t}\n\n\tpublic void issueError(DecafError error) {\n\t\terrors.add(err...
import java.util.Iterator; import decaf.Driver; import decaf.tree.Tree; import decaf.error.BadArrElementError; import decaf.error.BadInheritanceError; import decaf.error.BadOverrideError; import decaf.error.BadVarTypeError; import decaf.error.ClassNotFoundError; import decaf.error.DecafError; import decaf.error.DeclConflictError; import decaf.error.NoMainClassError; import decaf.error.OverridingVarError; import decaf.scope.ClassScope; import decaf.scope.GlobalScope; import decaf.scope.LocalScope; import decaf.scope.ScopeStack; import decaf.symbol.Class; import decaf.symbol.Function; import decaf.symbol.Symbol; import decaf.symbol.Variable; import decaf.type.BaseType; import decaf.type.FuncType;
issueError(new NoMainClassError(Driver.getDriver().getOption() .getMainClassName())); } table.close(); } // visiting declarations @Override public void visitClassDef(Tree.ClassDef classDef) { table.open(classDef.symbol.getAssociatedScope()); for (Tree f : classDef.fields) { f.accept(this); } table.close(); } @Override public void visitVarDef(Tree.VarDef varDef) { varDef.type.accept(this); if (varDef.type.type.equal(BaseType.VOID)) { issueError(new BadVarTypeError(varDef.getLocation(), varDef.name)); // for argList varDef.symbol = new Variable(".error", BaseType.ERROR, varDef .getLocation()); return; } Variable v = new Variable(varDef.name, varDef.type.type, varDef.getLocation()); Symbol sym = table.lookup(varDef.name, true); if (sym != null) { if (table.getCurrentScope().equals(sym.getScope())) { issueError(new DeclConflictError(v.getLocation(), v.getName(), sym.getLocation())); } else if ((sym.getScope().isFormalScope() || sym.getScope() .isLocalScope())) { issueError(new DeclConflictError(v.getLocation(), v.getName(), sym.getLocation())); } else { table.declare(v); } } else { table.declare(v); } varDef.symbol = v; } @Override public void visitMethodDef(Tree.MethodDef funcDef) { funcDef.returnType.accept(this); Function f = new Function(funcDef.statik, funcDef.name, funcDef.returnType.type, funcDef.body, funcDef.getLocation()); funcDef.symbol = f; Symbol sym = table.lookup(funcDef.name, false); if (sym != null) { issueError(new DeclConflictError(funcDef.getLocation(), funcDef.name, sym.getLocation())); } else { table.declare(f); } table.open(f.getAssociatedScope()); for (Tree.VarDef d : funcDef.formals) { d.accept(this); f.appendParam(d.symbol); } funcDef.body.accept(this); table.close(); } // visiting types @Override public void visitTypeIdent(Tree.TypeIdent type) { switch (type.typeTag) { case Tree.VOID: type.type = BaseType.VOID; break; case Tree.INT: type.type = BaseType.INT; break; case Tree.BOOL: type.type = BaseType.BOOL; break; ////////////////////////////////////////////////////////////////////////////////////////////// case Tree.DOUBLE: type.type = BaseType.DOUBLE; break; ////////////////////////////////////////////////////////////////////////////////////////////// default: type.type = BaseType.STRING; } } @Override public void visitTypeClass(Tree.TypeClass typeClass) { Class c = table.lookupClass(typeClass.name); if (c == null) { issueError(new ClassNotFoundError(typeClass.getLocation(), typeClass.name)); typeClass.type = BaseType.ERROR; } else { typeClass.type = c.getType(); } } @Override public void visitTypeArray(Tree.TypeArray typeArray) { typeArray.elementType.accept(this); if (typeArray.elementType.type.equal(BaseType.ERROR)) { typeArray.type = BaseType.ERROR; } else if (typeArray.elementType.type.equal(BaseType.VOID)) { issueError(new BadArrElementError(typeArray.getLocation())); typeArray.type = BaseType.ERROR; } else { typeArray.type = new decaf.type.ArrayType( typeArray.elementType.type); } } // for VarDecl in LocalScope @Override public void visitBlock(Tree.Block block) {
block.associatedScope = new LocalScope(block);
2
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/client/impl/NoteOpsTextImpl.java
[ "public class Messages extends NLS {\n\n private static final String BUNDLE_NAME = \"messages\"; //$NON-NLS-1$\n\n public static String Plugin_Configs_Shell_Title;\n public static String Plugin_Configs_QuickOrgnize_Shell_Title;\n public static String Plugin_Configs_Title;\n public static String Plugi...
import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang3.StringUtils; import org.lttpp.eemory.Messages; import org.lttpp.eemory.client.NoteOps; import org.lttpp.eemory.client.StoreClientFactory; import org.lttpp.eemory.client.metadata.EDAMLimits; import org.lttpp.eemory.client.model.ENNote; import org.lttpp.eemory.enml.ENML; import org.lttpp.eemory.exception.EDAMDataModel; import org.lttpp.eemory.exception.NoDataFoundException; import org.lttpp.eemory.util.ListUtil; import org.w3c.dom.DOMException; import org.xml.sax.SAXException; import com.evernote.clients.NoteStoreClient; import com.evernote.edam.error.EDAMNotFoundException; import com.evernote.edam.error.EDAMSystemException; import com.evernote.edam.error.EDAMUserException; import com.evernote.edam.type.Note; import com.evernote.thrift.TException;
package org.lttpp.eemory.client.impl; public class NoteOpsTextImpl extends NoteOps { public NoteOpsTextImpl(final StoreClientFactory factory) { super(factory); } @Override public void updateOrCreate(final ENNote args) throws EDAMUserException, EDAMSystemException, EDAMNotFoundException, TException, ParserConfigurationException, SAXException, IOException, DOMException, NoDataFoundException { if (ListUtil.isNullOrEmptyList(args.getContent())) { throw new NoDataFoundException(Messages.Plugin_Error_NoText); } if (shouldUpdate(args)) { update(args); } else { create(args); } } private void create(final ENNote args) throws EDAMUserException, EDAMSystemException, EDAMNotFoundException, TException, ParserConfigurationException, SAXException, IOException { Note note = new Note();
note.setTitle(StringUtils.abbreviate(args.getName(), EDAMLimits.EDAM_NOTE_TITLE_LEN_MAX));
3
data-integrations/salesforce
src/main/java/io/cdap/plugin/salesforce/plugin/source/batch/SalesforceBulkRecordReader.java
[ "public class BulkAPIBatchException extends RuntimeException {\n private BatchInfo batchInfo;\n\n public BulkAPIBatchException(String message, BatchInfo batchInfo) {\n super(String.format(\"%s. BatchId='%s', Reason='%s'\", message, batchInfo.getId(), batchInfo.getStateMessage()));\n this.batchInfo = batchIn...
import com.google.common.annotations.VisibleForTesting; import com.sforce.async.AsyncApiException; import com.sforce.async.BatchInfo; import com.sforce.async.BatchStateEnum; import com.sforce.async.BulkConnection; import io.cdap.cdap.api.data.schema.Schema; import io.cdap.plugin.salesforce.BulkAPIBatchException; import io.cdap.plugin.salesforce.SalesforceConnectionUtil; import io.cdap.plugin.salesforce.authenticator.Authenticator; import io.cdap.plugin.salesforce.authenticator.AuthenticatorCredentials; import io.cdap.plugin.salesforce.plugin.source.batch.util.SalesforceSourceConstants; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.csv.QuoteMode; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.Map;
/* * Copyright © 2019 Cask Data, 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 io.cdap.plugin.salesforce.plugin.source.batch; /** * RecordReader implementation, which reads a single Salesforce batch from bulk job * provided in InputSplit */ public class SalesforceBulkRecordReader extends RecordReader<Schema, Map<String, ?>> { private static final Logger LOG = LoggerFactory.getLogger(SalesforceBulkRecordReader.class); private final Schema schema; private CSVParser csvParser; private Iterator<CSVRecord> parserIterator; private Map<String, ?> value; private String jobId; private BulkConnection bulkConnection; private String batchId; private String[] resultIds; private int resultIdIndex; public SalesforceBulkRecordReader(Schema schema) { this(schema, null, null, null); } @VisibleForTesting SalesforceBulkRecordReader(Schema schema, String jobId, String batchId, String[] resultIds) { this.schema = schema; this.resultIdIndex = 0; this.jobId = jobId; this.batchId = batchId; this.resultIds = resultIds; } /** * Get csv from a single Salesforce batch * * @param inputSplit specifies batch details * @param taskAttemptContext task context * @throws IOException can be due error during reading query * @throws InterruptedException interrupted sleep while waiting for batch results */ @Override public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { SalesforceSplit salesforceSplit = (SalesforceSplit) inputSplit; jobId = salesforceSplit.getJobId(); batchId = salesforceSplit.getBatchId(); LOG.debug("Executing Salesforce Batch Id: '{}' for Job Id: '{}'", batchId, jobId); Configuration conf = taskAttemptContext.getConfiguration(); try { AuthenticatorCredentials credentials = SalesforceConnectionUtil.getAuthenticatorCredentials(conf); bulkConnection = new BulkConnection(Authenticator.createConnectorConfig(credentials)); resultIds = waitForBatchResults(bulkConnection); LOG.debug("Batch {} returned {} results", batchId, resultIds.length); setupParser(); } catch (AsyncApiException e) { throw new RuntimeException("There was issue communicating with Salesforce", e); } } /** * Reads single record from csv. * * @return returns false if no more data to read */ @Override public boolean nextKeyValue() throws IOException { if (parserIterator == null) { return false; } while (!parserIterator.hasNext()) { if (resultIdIndex == resultIds.length) { // No more result ids to process. return false; } // Close CSV parser for previous result. if (csvParser != null && !csvParser.isClosed()) { // this also closes the inputStream csvParser.close(); csvParser = null; } try { // Parse the next result. setupParser(); } catch (AsyncApiException e) { throw new IOException("Failed to query results", e); } } value = parserIterator.next().toMap(); return true; } @Override public Schema getCurrentKey() { return schema; } @Override public Map<String, ?> getCurrentValue() { return value; } @Override public float getProgress() { return 0.0f; } @Override public void close() throws IOException { if (csvParser != null && !csvParser.isClosed()) { // this also closes the inputStream csvParser.close(); csvParser = null; } } @VisibleForTesting void setupParser() throws IOException, AsyncApiException { if (resultIdIndex >= resultIds.length) { throw new IllegalArgumentException(String.format("Invalid resultIdIndex %d, should be less than %d", resultIdIndex, resultIds.length)); } InputStream queryResponseStream = bulkConnection.getQueryResultStream(jobId, batchId, resultIds[resultIdIndex]); CSVFormat csvFormat = CSVFormat.DEFAULT .withHeader() .withQuoteMode(QuoteMode.ALL) .withAllowMissingColumnNames(false); csvParser = CSVParser.parse(queryResponseStream, StandardCharsets.UTF_8, csvFormat); if (csvParser.getHeaderMap().isEmpty()) { throw new IllegalStateException("Empty response was received from Salesforce, but csv header was expected."); } parserIterator = csvParser.iterator(); resultIdIndex++; } /** * Wait until a batch with given batchId succeeds, or throw an exception * * @param bulkConnection bulk connection instance * @return array of batch result ids * @throws AsyncApiException if there is an issue creating the job * @throws InterruptedException sleep interrupted */ private String[] waitForBatchResults(BulkConnection bulkConnection) throws AsyncApiException, InterruptedException { BatchInfo info = null; for (int i = 0; i < SalesforceSourceConstants.GET_BATCH_RESULTS_TRIES; i++) { try { info = bulkConnection.getBatchInfo(jobId, batchId); } catch (AsyncApiException e) { if (i == SalesforceSourceConstants.GET_BATCH_RESULTS_TRIES - 1) { throw e; } LOG.warn("Failed to get info for batch {}. Will retry after some time.", batchId, e); continue; } if (info.getState() == BatchStateEnum.Completed) { return bulkConnection.getQueryResultList(jobId, batchId).getResult(); } else if (info.getState() == BatchStateEnum.Failed) {
throw new BulkAPIBatchException("Batch failed", info);
0
JanWiemer/jacis
src/test/java/org/jacis/objectadapter/microstream/JacisStoreWithMicrostreamCloningTxTest.java
[ "@JacisApi\r\npublic class JacisTransactionHandle {\r\n\r\n /** The id of the transaction */\r\n private final String txId;\r\n /** Description for the transaction giving some more information about the purpose of the transaction (for logging and debugging) */\r\n private final String txDescription;\r\n /** A ...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.jacis.container.JacisTransactionHandle; import org.jacis.exception.JacisStaleObjectException; import org.jacis.plugin.txadapter.local.JacisLocalTransaction; import org.jacis.store.JacisStore; import org.jacis.testhelper.JacisTestHelper; import org.jacis.testhelper.TestObject; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright (c) 2016. Jan Wiemer */ package org.jacis.objectadapter.microstream; @SuppressWarnings("CodeBlock2Expr") public class JacisStoreWithMicrostreamCloningTxTest { private static final Logger log = LoggerFactory.getLogger(JacisStoreWithMicrostreamCloningTxTest.class);
protected JacisStore<String, TestObject> createTestStore(JacisTestHelper testHelper) {
3
eckig/graph-editor
core/src/main/java/de/tesis/dynaware/grapheditor/core/skins/defaults/DefaultConnectorSkin.java
[ "public abstract class GConnectorSkin extends GSkin<GConnector> {\n\n /**\n * Creates a new {@link GConnectorSkin}.\n *\n * @param connector the {@link GConnector} represented by the skin\n */\n public GConnectorSkin(final GConnector connector) {\n super(connector);\n }\n\n /**\n ...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.tesis.dynaware.grapheditor.GConnectorSkin; import de.tesis.dynaware.grapheditor.GConnectorStyle; import de.tesis.dynaware.grapheditor.core.connectors.DefaultConnectorTypes; import de.tesis.dynaware.grapheditor.core.skins.defaults.utils.AnimatedColor; import de.tesis.dynaware.grapheditor.core.skins.defaults.utils.ColorAnimationUtils; import de.tesis.dynaware.grapheditor.model.GConnector; import javafx.css.PseudoClass; import javafx.scene.Node; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Polygon; import javafx.util.Duration;
/* * Copyright (C) 2005 - 2014 by TESIS DYNAware GmbH */ package de.tesis.dynaware.grapheditor.core.skins.defaults; /** * The default connector skin. * * <p> * A connector that uses this skin must have one of the 8 types defined in {@link DefaultConnectorTypes}. If the * connector does not have one of these types, it will be set to <b>left-input</b>. * </p> */ public class DefaultConnectorSkin extends GConnectorSkin { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultConnectorSkin.class); private static final String STYLE_CLASS_BASE = "default-connector"; private static final PseudoClass PSEUDO_CLASS_ALLOWED = PseudoClass.getPseudoClass("allowed"); private static final PseudoClass PSEUDO_CLASS_FORBIDDEN = PseudoClass.getPseudoClass("forbidden"); private static final String ALLOWED = "-animated-color-allowed"; private static final String FORBIDDEN = "-animated-color-forbidden"; private static final double SIZE = 25; private final Pane root = new Pane(); private final Polygon polygon = new Polygon(); private final AnimatedColor animatedColorAllowed; private final AnimatedColor animatedColorForbidden; /** * Creates a new default connector skin instance. * * @param connector the {@link GConnector} the skin is being created for */
public DefaultConnectorSkin(final GConnector connector) {
4
idega/com.idega.company
src/java/com/idega/company/companyregister/business/CompanyRegisterBusinessBean.java
[ "public interface Company extends IDOEntity {\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getGroup\n\t */\n\tpublic Group getGroup();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getType\n\t */\n\tpublic CompanyType getType();\n\n\t/**\n\t * @see com.idega.company.data.CompanyBMPBean#getNam...
import java.rmi.RemoteException; import java.util.Collection; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.FinderException; import com.idega.business.IBOLookupException; import com.idega.business.IBORuntimeException; import com.idega.business.IBOServiceBean; import com.idega.company.data.Company; import com.idega.company.data.CompanyHome; import com.idega.company.data.IndustryCode; import com.idega.company.data.IndustryCodeHome; import com.idega.company.data.OperationForm; import com.idega.company.data.OperationFormHome; import com.idega.company.data.UnregisterType; import com.idega.company.data.UnregisterTypeHome; import com.idega.core.location.business.AddressBusiness; import com.idega.core.location.data.Address; import com.idega.core.location.data.AddressHome; import com.idega.core.location.data.Commune; import com.idega.core.location.data.CommuneHome; import com.idega.core.location.data.PostalCode; import com.idega.core.location.data.PostalCodeHome; import com.idega.data.IDOLookup; import com.idega.user.business.UserBusiness; import com.idega.user.data.User; import com.idega.user.data.UserHome;
if(address != null) { address = address.trim(); if(!address.equals("")) { addressBean.setStreetName(addressBusiness.getStreetNameFromAddressString(address)); addressBean.setStreetNumber(addressBusiness.getStreetNumberFromAddressString(address)); } } } catch(Exception re) { logger.log(Level.SEVERE, "Exception while handling company address", re); } Commune communeBean = addressBean.getCommune(); if(communeBean == null) { try { if(commune != null) { commune = commune.trim(); if(!commune.equals("")) { communeBean = getCommuneHome().findByCommuneCode(commune); } } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding commune entry", re); } } addressBean.setCommune(communeBean); company_registry.setLastChange(CompanyRegisterImportFile.getSQLDateFromStringFormat(dateOfLastChange.trim(), logger, RECORDS_DATE_FORMAT)); company_registry.setRegisterDate(CompanyRegisterImportFile.getSQLDateFromStringFormat(registerDate.trim(), logger, RECORDS_DATE_FORMAT)); company_registry.setUnregisterDate(CompanyRegisterImportFile.getSQLDateFromStringFormat(unregistrationDate.trim(), logger, RECORDS_DATE_FORMAT)); PostalCode postalCodeBean = addressBean.getPostalCode(); if(postalCodeBean == null) { try { if(postalCode != null) { postalCode = postalCode.trim(); if(!postalCode.equals("")) { postalCodeBean = getPostalCodeHome().findByPostalCode(postalCode); } } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding a postal code entry", re); } } addressBean.setPostalCode(postalCodeBean); addressBean.store(); try { @SuppressWarnings("unchecked") Collection<Address> addreses = company_registry.getGeneralGroup().getAddresses(getAddressHome().getAddressType1()); String pk1 = ((Integer) addressBean.getPrimaryKey()).toString(); boolean addressSet = false; for(Iterator<Address> it = addreses.iterator(); it.hasNext(); ) { Address adr = it.next(); String pk2 = ((Integer) adr.getPrimaryKey()).toString(); if(pk1.equals(pk2)) { addressSet = true; break; } } if(!addressSet) { company_registry.setAddress(addressBean); } } catch(Exception e) { logger.log(Level.SEVERE, "Exception while all address entries for a company", e); } Commune legalCommune = company_registry.getLegalCommune(); if(legalCommune == null) { try { if(legalAddress != null) { legalAddress = legalAddress.trim(); if(!legalAddress.equals("")) { legalCommune = getCommuneHome().findByCommuneCode(legalAddress); } } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding a commune entry", re); } } company_registry.setLegalCommune(legalCommune); Commune workCommune = company_registry.getWorkingArea(); if(workCommune == null) { try { if(workingArea != null) { workingArea = workingArea.trim(); if(!workingArea.equals("")) { workCommune = getCommuneHome().findByCommuneCode(workingArea); } } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding a commune entry", re); } } company_registry.setWorkingArea(workCommune); try { OperationForm operationFormBean = ((OperationFormHome) IDOLookup.getHome(OperationForm.class)).findOperationFormByUniqueCode(operationForm); if(operationFormBean != null) { company_registry.setOperationForm(operationFormBean); } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding a OperationForm entry", re); } try { IndustryCode industryCodeBean = ((IndustryCodeHome) IDOLookup.getHome(IndustryCode.class)).findIndustryByUniqueCode(industryCode); if(industryCodeBean != null) { company_registry.setIndustryCode(industryCodeBean); } } catch(FinderException re) { } catch(Exception re) { logger.log(Level.SEVERE, "Exception while finding a IndustryCode entry", re); } try {
UnregisterType unregisterTypeBean = ((UnregisterTypeHome) IDOLookup.getHome(UnregisterType.class)).findUnregisterTypeByUniqueCode(unregistrationType);
7
ProjectInfinity/ReportRTS
src/main/java/com/nyancraft/reportrts/command/sub/BroadcastMessage.java
[ "public class RTSFunctions {\n\n private static ReportRTS plugin = ReportRTS.getPlugin();\n private static DataProvider data = plugin.getDataProvider();\n\n private static final int SECOND_MILLIS = 1000;\n private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;\n private static final int HOUR_MI...
import com.nyancraft.reportrts.RTSFunctions; import com.nyancraft.reportrts.RTSPermissions; import com.nyancraft.reportrts.ReportRTS; import com.nyancraft.reportrts.data.NotificationType; import com.nyancraft.reportrts.event.TicketBroadcastEvent; import com.nyancraft.reportrts.util.BungeeCord; import com.nyancraft.reportrts.util.Message; import org.bukkit.command.CommandSender; import java.io.IOException;
package com.nyancraft.reportrts.command.sub; public class BroadcastMessage { private static ReportRTS plugin = ReportRTS.getPlugin(); /** * Initial handling of the Broadcast sub-command. * @param sender player that sent the command * @param args arguments * @return true if command handled correctly */ public static boolean handleCommand(CommandSender sender, String[] args) { if(!RTSPermissions.canBroadcast(sender)) return true; if(args.length < 2) return false; args[0] = null; String message = String.join(" ", args); try {
BungeeCord.globalNotify(Message.broadcast(sender.getName(), message), -1, NotificationType.NOTIFYONLY);
3
cytomine/Cytomine-java-client
src/main/java/be/cytomine/client/collections/AttachedFileCollection.java
[ "public class Cytomine {\n\n private static final Logger log = LogManager.getLogger(Cytomine.class);\n static Cytomine CYTOMINE;\n\n CytomineConnection defaultCytomineConnection;\n private String host;\n private String login;\n private String pass;\n private String publicKey;\n private Strin...
import be.cytomine.client.Cytomine; import be.cytomine.client.CytomineConnection; import be.cytomine.client.CytomineException; import be.cytomine.client.models.AttachedFile; import be.cytomine.client.models.Model;
package be.cytomine.client.collections; /* * Copyright (c) 2009-2020. Authors: see NOTICE file. * * 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 AttachedFileCollection extends Collection { public AttachedFileCollection() { this(0,0); } public AttachedFileCollection(int offset, int max) { super(AttachedFile.class, max, offset); }
public AttachedFileCollection(Model model) {
4
axxepta/project-argon
src/main/java/de/axxepta/oxygen/actions/SaveFileToArgonAction.java
[ "public enum BaseXSource {\r\n\r\n /**\r\n * Database.\r\n */\r\n DATABASE(\"argon\"),\r\n// /**\r\n// * RESTXQ.\r\n// */\r\n// RESTXQ(\"argonquery\"),\r\n /**\r\n * Repository.\r\n */\r\n REPO(\"argonrepo\");\r\n\r\n private final String protocol;\r\n\r\n BaseXSource...
import de.axxepta.oxygen.api.BaseXSource; import de.axxepta.oxygen.customprotocol.ArgonChooserDialog; import de.axxepta.oxygen.customprotocol.CustomProtocolURLUtils; import de.axxepta.oxygen.utils.ConnectionWrapper; import de.axxepta.oxygen.utils.Lang; import de.axxepta.oxygen.utils.WorkspaceUtils; import ro.sync.exml.workspace.api.PluginWorkspace; import ro.sync.exml.workspace.api.PluginWorkspaceProvider; import ro.sync.exml.workspace.api.editor.WSEditor; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.IOException; import java.net.URL;
package de.axxepta.oxygen.actions; /** * Store the current editor's content to BaseX. The URL can be chosen from a dialog. If no encoding can be obtained from * the editor content, the default UTF-8 will be used. */ public class SaveFileToArgonAction extends AbstractAction { private static final PluginWorkspace workspace = PluginWorkspaceProvider.getPluginWorkspace(); public SaveFileToArgonAction(String name, Icon icon) { super(name, icon); } @Override public void actionPerformed(ActionEvent e) { ArgonChooserDialog urlChooser = new ArgonChooserDialog((Frame) workspace.getParentFrame(), Lang.get(Lang.Keys.dlg_saveas), ArgonChooserDialog.Type.SAVE); URL[] url = urlChooser.selectURLs(); WSEditor editorAccess = workspace.getCurrentEditorAccess(PluginWorkspace.MAIN_EDITING_AREA); if (url != null) {
BaseXSource source = CustomProtocolURLUtils.sourceFromURL(url[0]);
0
Stay/PullRecycler
app/src/main/java/com/stay4it/sample/SampleSectionListFragment.java
[ "public abstract class BaseSectionListFragment<T> extends BaseListFragment<SectionData<T>> {\n protected static final int VIEW_TYPE_SECTION_HEADER = 1;\n protected static final int VIEW_TYPE_SECTION_CONTENT = 2;\n\n @Override\n protected BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {\n ...
import android.os.Bundle; 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.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.stay4it.R; import com.stay4it.core.BaseSectionListFragment; import com.stay4it.model.ConstantValues; import com.stay4it.widgets.pull.BaseViewHolder; import com.stay4it.widgets.pull.PullRecycler; import com.stay4it.widgets.pull.layoutmanager.ILayoutManager; import com.stay4it.widgets.pull.layoutmanager.MyGridLayoutManager; import com.stay4it.widgets.pull.layoutmanager.MyLinearLayoutManager; import com.stay4it.widgets.pull.layoutmanager.MyStaggeredGridLayoutManager; import com.stay4it.widgets.pull.section.SectionData; import java.util.ArrayList; import java.util.Random;
package com.stay4it.sample; /** * Created by Stay on 8/3/16. * Powered by www.stay4it.com */ public class SampleSectionListFragment extends BaseSectionListFragment<String> { private int random; @Override protected BaseViewHolder onCreateSectionViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_sample_list_item, parent, false); return new SampleViewHolder(view); } @Override protected ILayoutManager getLayoutManager() { random = new Random().nextInt(3); switch (random) { case 0: return new MyLinearLayoutManager(getContext()); case 1: return new MyGridLayoutManager(getContext(), 3); case 2: return new MyStaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); } return super.getLayoutManager(); } @Override protected RecyclerView.ItemDecoration getItemDecoration() { if (random == 0) { return super.getItemDecoration(); } else { return null; } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); recycler.setRefreshing(); } @Override public void onRefresh(final int action) { if (mDataList == null) { mDataList = new ArrayList<>(); } recycler.postDelayed(new Runnable() { @Override public void run() {
if (action == PullRecycler.ACTION_PULL_TO_REFRESH) {
3
lakeinchina/librestreaming
librestreaming/src/main/java/me/lake/librestreaming/client/RESAudioClient.java
[ "public class RESSoftAudioCore {\n RESCoreParameters resCoreParameters;\n private final Object syncOp = new Object();\n private MediaCodec dstAudioEncoder;\n private MediaFormat dstAudioFormat;\n //filter\n private Lock lockAudioFilter = null;\n private BaseSoftAudioFilter audioFilter;\n //A...
import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import me.lake.librestreaming.core.RESSoftAudioCore; import me.lake.librestreaming.filter.softaudiofilter.BaseSoftAudioFilter; import me.lake.librestreaming.model.RESConfig; import me.lake.librestreaming.model.RESCoreParameters; import me.lake.librestreaming.rtmp.RESFlvDataCollecter; import me.lake.librestreaming.tools.LogTools;
package me.lake.librestreaming.client; /** * Created by lake on 16-5-24. */ public class RESAudioClient { RESCoreParameters resCoreParameters; private final Object syncOp = new Object(); private AudioRecordThread audioRecordThread; private AudioRecord audioRecord; private byte[] audioBuffer; private RESSoftAudioCore softAudioCore; public RESAudioClient(RESCoreParameters parameters) { resCoreParameters = parameters; }
public boolean prepare(RESConfig resConfig) {
2
fabian7593/MagicalCamera
magicalcamera/src/main/java/com/frosquivel/magicalcamera/MagicalCamera.java
[ "public class ActionPictureObject {\n\n //the max of quality photo\n public static final int BEST_QUALITY_PHOTO = 4000;\n\n //The photo name for uxiliar save picture\n public static final String photoNameAuxiliar = \"MagicalCamera\";\n\n //properties\n //my intent curret fragment (only use for fra...
import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.graphics.Bitmap; import com.frosquivel.magicalcamera.Objects.ActionPictureObject; import com.frosquivel.magicalcamera.Objects.FaceRecognitionObject; import com.frosquivel.magicalcamera.Objects.MagicalCameraObject; import com.frosquivel.magicalcamera.Objects.PrivateInformationObject; import com.frosquivel.magicalcamera.Utilities.PictureUtils; import static android.graphics.Color.RED;
} } public void takeFragmentPhoto(final android.support.v4.app.Fragment fragment) { if (magicalCameraObject.getActionPicture().takeFragmentPhoto()) { Runnable runnable = new Runnable() { @Override public void run() { fragment.startActivityForResult(getIntentFragment(), MagicalCamera.TAKE_PHOTO); } }; askPermissions(runnable, CAMERA); } } public void selectFragmentPicture(final android.support.v4.app.Fragment fragment, final String header) { if (magicalCameraObject.getActionPicture().selectedFragmentPicture()) { Runnable runnable = new Runnable() { @Override public void run() { fragment.startActivityForResult( Intent.createChooser(getIntentFragment(), header), MagicalCamera.SELECT_PHOTO); } }; askPermissions(runnable, EXTERNAL_STORAGE); } } private void askPermissions(final Runnable runnable){ magicalPermissions.askPermissions(runnable); } private void askPermissions(final Runnable runnable, final String operationType){ magicalPermissions.askPermissions(runnable, operationType); } //Face detector methods public Bitmap faceDetector(int stroke, int color){ return magicalCameraObject.getFaceRecognition().faceDetector(stroke, color, magicalCameraObject.getActivity(), magicalCameraObject.getActionPicture().getActionPictureObject().getMyPhoto()); } public Bitmap faceDetector(){ return magicalCameraObject.getFaceRecognition().faceDetector(5, RED, magicalCameraObject.getActivity(), magicalCameraObject.getActionPicture().getActionPictureObject().getMyPhoto()); } public FaceRecognitionObject getFaceRecognitionInformation(){ return magicalCameraObject.getFaceRecognition().getFaceRecognitionInformation(); } //Image information methods public boolean initImageInformation() { return magicalCameraObject.getPrivateInformation().getImageInformation(magicalCameraObject.getUriPaths().getUriPathsObject().getRealPath()); } public PrivateInformationObject getPrivateInformation() { return magicalCameraObject.getPrivateInformation().getPrivateInformationObject(); } /** * *********************************************** * This methods save the photo in memory device * with diferents params * ********************************************** */ public String savePhotoInMemoryDevice(Bitmap bitmap, String photoName, boolean autoIncrementNameByDate) { return magicalCameraObject.getSaveEasyPhoto().writePhotoFile(bitmap, photoName, "MAGICAL CAMERA", PNG, autoIncrementNameByDate, magicalCameraObject.getActivity()); } public String savePhotoInMemoryDevice(Bitmap bitmap, String photoName, Bitmap.CompressFormat format, boolean autoIncrementNameByDate) { return magicalCameraObject.getSaveEasyPhoto().writePhotoFile(bitmap, photoName, "MAGICAL CAMERA", format, autoIncrementNameByDate, magicalCameraObject.getActivity()); } public String savePhotoInMemoryDevice(Bitmap bitmap, String photoName, String directoryName, boolean autoIncrementNameByDate) { return magicalCameraObject.getSaveEasyPhoto().writePhotoFile(bitmap, photoName, directoryName, PNG, autoIncrementNameByDate, magicalCameraObject.getActivity()); } public String savePhotoInMemoryDevice(Bitmap bitmap, String photoName, String directoryName, Bitmap.CompressFormat format, boolean autoIncrementNameByDate) { return magicalCameraObject.getSaveEasyPhoto().writePhotoFile(bitmap, photoName, directoryName, format, autoIncrementNameByDate, magicalCameraObject.getActivity()); } //get variables public String getRealPath(){ return magicalCameraObject.getUriPaths().getUriPathsObject().getRealPath(); } public Bitmap getPhoto(){ return magicalCameraObject.getActionPicture().getActionPictureObject().getMyPhoto(); } public void setPhoto(Bitmap bitmap){ magicalCameraObject.getActionPicture().getActionPictureObject().setMyPhoto(bitmap); } public void resultPhoto(int requestCode, int resultCode, Intent data){ magicalCameraObject.getActionPicture().resultPhoto(requestCode, resultCode, data); } public void resultPhoto(int requestCode, int resultCode, Intent data, int rotateType){ magicalCameraObject.getActionPicture().resultPhoto(requestCode, resultCode, data, rotateType); } public Intent getIntentFragment(){ return magicalCameraObject.getActionPicture().getActionPictureObject().getIntentFragment(); } public void setResizePhoto(int resize){ magicalCameraObject.getActionPicture().getActionPictureObject().setResizePhoto(resize); } //methods to rotate picture public Bitmap rotatePicture(int rotateType){ if(getPhoto() != null)
return PictureUtils.rotateImage(getPhoto(), rotateType);
4
blacklocus/jres
jres-core/src/main/java/com/blacklocus/jres/request/index/JresUpdateDocument.java
[ "@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = \"@class\")\npublic interface JresBulkable {\n\n /**\n * @return bulk command\n */\n Object getAction();\n\n /**\n * @return (optional) payload of action, e.g. index operation is followed by the document ...
import com.blacklocus.jres.request.JresBulkable; import com.blacklocus.jres.request.JresJsonRequest; import com.blacklocus.jres.request.bulk.JresBulk; import com.blacklocus.jres.response.index.JresIndexDocumentReply; import com.blacklocus.misc.NoNullsMap; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableMap; import org.apache.http.client.methods.HttpPost; import javax.annotation.Nullable; import static com.blacklocus.jres.strings.JresPaths.slashedPath;
/** * Copyright 2015 BlackLocus * * 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.blacklocus.jres.request.index; /** * <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-update.html">Update Document API</a> */ @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) public class JresUpdateDocument extends JresJsonRequest<JresIndexDocumentReply> implements JresBulkable { private @Nullable String index; private @Nullable String type; private String id; private Object document; private Boolean docAsUpsert; private Integer retryOnConflict; // for JSON deserialization JresUpdateDocument() { super(JresIndexDocumentReply.class); } /** * Update a document. If it does not exist will create one (<code>doc_as_upsert:true</code>). Note in ElasticSearch * "update" means to modify an existing document (e.g. merge or overwrite particular fields). To overwrite an * existing document with some id is not an ElasticSearch "update" operation, but rather an "index" * ({@link JresIndexDocument}) operation. * <p/> * `index` or `type` are nullable if this operation is to be included in a {@link JresBulk} request which specifies * a default index or type, respectively. */ public JresUpdateDocument(@Nullable String index, @Nullable String type, String id, Object document) { this(index, type, id, document, true, 0); } /** * Update a document. If it does not exist will create one. Note in ElasticSearch "update" means to modify an * existing document (e.g. merge or overwrite particular fields). To overwrite an existing document with some id is * not an ElasticSearch "update" operation, but rather an "index" ({@link JresIndexDocument}) operation. * <p/> * `index` or `type` are nullable if this operation is to be included in a {@link JresBulk} request which specifies * a default index or type, respectively. * * @param docAsUpsert If false, prevents ElasticSearch from automatically creating a new document. */ public JresUpdateDocument(@Nullable String index, @Nullable String type, String id, Object document, Boolean docAsUpsert, Integer retryOnConflict) { super(JresIndexDocumentReply.class); this.index = index; this.type = type; this.id = id; this.document = document; this.docAsUpsert = docAsUpsert; this.retryOnConflict = retryOnConflict; } @Nullable @JsonProperty public String getIndex() { return index; } public void setIndex(@Nullable String index) { this.index = index; } @Nullable @JsonProperty public String getType() { return type; } public void setType(@Nullable String type) { this.type = type; } @JsonProperty public String getId() { return id; } public void setId(String id) { this.id = id; } @JsonProperty public Object getDocument() { return document; } public void setDocument(Object document) { this.document = document; } @JsonProperty public Boolean getDocAsUpsert() { return docAsUpsert; } public void setDocAsUpsert(Boolean docAsUpsert) { this.docAsUpsert = docAsUpsert; } @JsonProperty public Integer getRetryOnConflict() { return retryOnConflict; } public void setRetryOnConflict(Integer retryOnConflict) { this.retryOnConflict = retryOnConflict; } @Override public String getJsonTypeInfo() { return JresUpdateDocument.class.getName(); } @Override public String getHttpMethod() { return HttpPost.METHOD_NAME; } @Override public String getPath() { String path = slashedPath(index, type, id) + "_update"; if (retryOnConflict != null) { path += "?retry_on_conflict=" + retryOnConflict; } return path; } @Override public Object getPayload() { return ImmutableMap.builder() .put("doc", document) .put("doc_as_upsert", docAsUpsert) .build(); } @Override public Object getAction() {
return ImmutableMap.of("update", NoNullsMap.of(
4
GlitchCog/ChatGameFontificator
src/main/java/com/glitchcog/fontificator/gui/controls/panel/ControlPanelDebug.java
[ "public class FontificatorProperties extends Properties\n{\n private static final Logger logger = Logger.getLogger(FontificatorProperties.class);\n\n private static final long serialVersionUID = 1L;\n\n /**\n * Copy of properties to compare with when checking if there have been changes\n */\n pr...
import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JToggleButton; import javax.swing.Timer; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import com.glitchcog.fontificator.config.FontificatorProperties; import com.glitchcog.fontificator.config.loadreport.LoadConfigReport; import com.glitchcog.fontificator.gui.DebugAppender; import com.glitchcog.fontificator.gui.chat.ChatWindow; import com.glitchcog.fontificator.gui.component.ColorButton; import com.glitchcog.fontificator.gui.component.LabeledSlider; import com.glitchcog.fontificator.gui.controls.ControlWindow; import com.glitchcog.fontificator.sprite.SpriteFont;
package com.glitchcog.fontificator.gui.controls.panel; /** * Control Panel containing debugging options and information * * @author Matt Yanos */ public class ControlPanelDebug extends ControlPanelBase { private static final long serialVersionUID = 1L; /** * Whether debugging is activated, which should correspond to when this panel is displayed */ private boolean debugging;
private ControlWindow ctrlWindow;
6
concentricsky/android-viewer-for-khan-academy
src/com/concentricsky/android/khanacademy/app/HomeActivity.java
[ "public class KADataService extends Service {\n \n\tpublic final String LOG_TAG = getClass().getSimpleName();\n\t\n\tpublic static final int RESULT_SUCCESS = 0;\n\tpublic static final int RESULT_ERROR = 1;\n\tpublic static final int RESULT_CANCELLED = 2;\n\t\n\tprivate KADataBinder mBinder = new KADataBinder(thi...
import static com.concentricsky.android.khanacademy.Constants.ACTION_BADGE_EARNED; import static com.concentricsky.android.khanacademy.Constants.ACTION_LIBRARY_UPDATE; import static com.concentricsky.android.khanacademy.Constants.ACTION_TOAST; import static com.concentricsky.android.khanacademy.Constants.EXTRA_BADGE; import static com.concentricsky.android.khanacademy.Constants.EXTRA_MESSAGE; import static com.concentricsky.android.khanacademy.Constants.PARAM_TOPIC_ID; import static com.concentricsky.android.khanacademy.Constants.REQUEST_CODE_RECURRING_LIBRARY_UPDATE; import static com.concentricsky.android.khanacademy.Constants.TAG_LIST_FRAGMENT; import static com.concentricsky.android.khanacademy.Constants.UPDATE_DELAY_FROM_FIRST_RUN; import java.sql.SQLException; import java.util.Calendar; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.concentricsky.android.khan.R; import com.concentricsky.android.khanacademy.Constants; import com.concentricsky.android.khanacademy.MainMenuDelegate; import com.concentricsky.android.khanacademy.data.KADataService; import com.concentricsky.android.khanacademy.data.db.Badge; import com.concentricsky.android.khanacademy.data.db.Topic; import com.concentricsky.android.khanacademy.data.db.User; import com.concentricsky.android.khanacademy.util.Log; import com.concentricsky.android.khanacademy.util.ObjectCallback;
private boolean userHasAcceptedTOS() { return getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) .getBoolean(Constants.SETTING_ACKNOWLEDGEMENT, false); } private void showTOSAcknowledgement() { View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_tos, null, false); // Use this LinkMovementMethod (as opposed to just the xml setting android:autoLink="web") to allow for named links. TextView mustAccept = (TextView) contentView.findViewById(R.id.dialog_tos_must_accept); TextView notEndorsed = (TextView) contentView.findViewById(R.id.dialog_tos_not_endorsed); mustAccept.setMovementMethod(LinkMovementMethod.getInstance()); notEndorsed.setMovementMethod(LinkMovementMethod.getInstance()); new AlertDialog.Builder(this) .setCancelable(false) .setView(contentView) .setPositiveButton(getString(R.string.button_i_accept), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Store the fact that the user has accepted. getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) .edit() .putBoolean(Constants.SETTING_ACKNOWLEDGEMENT, true) .apply(); } }) .setNegativeButton(getString(R.string.button_quit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); } /* * API TOS * * We must display prominently: * * "This product uses the Khan Academy API but is not endorsed or certified by Khan Academy (www.khanacademy.org)." * and * "All Khan Academy content is available for free at www.khanacademy.org" * * * Among the "Trademark and Brand Usage Policy": * As another example, the use by an organization that is incorporating our content in a paid offering is NOT "non-commercial" * * WE WILL: * a. require all users of Your Application to affirmatively agree to be bound by the Khan Academy Terms of Service and the Khan Academy Privacy Policy ; b. notify Khan Academy if any users of Your Application are "repeat infringers" as that term is defined in the Khan Academy Terms of Service ; c. notify Khan Academy if you receive any complaint (including a copyright or other right holder) based on any content that is hosted by Khan Academy; d. in connection with your use of the Khan Academy API and the Khan Academy Platform, comply with all applicable local, state, national, and international laws and regulations, including, without limitation, copyright and other laws protecting proprietary rights (including the DMCA) and all applicable export control laws and regulations and country-specific economic sanctions implemented by the United States Office of Foreign Assets Control. For clarity, the foregoing does not limit your representations in Section 4, above; e. provide any information and/or other materials related to Your Applications reasonably requested by Khan Academy from time to time to verify your compliance with these API Terms. * and WILL NOT do a bunch of the usual things. * * * * (non-Javadoc) * @see com.concentricsky.android.khanacademy.app.LifecycleTraceActivity#onStart() */ @Override protected void onStart() { super.onStart(); if (!userHasAcceptedTOS()) { showTOSAcknowledgement(); } mainMenuDelegate = new MainMenuDelegate(this); requestDataService(new ObjectCallback<KADataService>() { @Override public void call(KADataService dataService) { topic = dataService.getRootTopic(); if (topic != null) { // It is important to create the AbstractListFragment programmatically here as opposed to // specifying it in the xml layout. If it is specified in xml, we end up with an // error about "Content view not yet created" when clicking a list item after restoring // a fragment from the back stack. setListForTopic(topic, TopicListFragment.class, true); } } }); IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_LIBRARY_UPDATE); filter.addAction(ACTION_BADGE_EARNED); filter.addAction(ACTION_TOAST); LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter); } @Override protected void onStop() { mainMenuDelegate = null; LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); super.onStop(); } @Override public boolean onCreateOptionsMenu(final Menu menu) { Log.d(LOG_TAG, "onCreateOptionsMenu"); mainMenu = menu; // We use a different menu in this activity, so we skip the delegate's onCreateOptionsMenu. getMenuInflater().inflate(R.menu.home, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { Log.d(LOG_TAG, "onPrepareOptionsMenu"); requestDataService(new ObjectCallback<KADataService>() { @Override public void call(KADataService dataService) {
User user = dataService.getAPIAdapter().getCurrentUser();
2
tomasbjerre/git-changelog-lib
src/test/java/se/bjurr/gitchangelog/api/TemplatesTest.java
[ "public static GitChangelogApi gitChangelogApiBuilder() {\n return new GitChangelogApi();\n}", "public static final String ZERO_COMMIT = \"0000000000000000000000000000000000000000\";", "public static void mock(final RestClient mock) {\n mockedRestClient = mock;\n}", "public class GitHubMockInterceptor imple...
import static java.nio.charset.StandardCharsets.UTF_8; import static se.bjurr.gitchangelog.api.GitChangelogApi.gitChangelogApiBuilder; import static se.bjurr.gitchangelog.api.GitChangelogApiConstants.ZERO_COMMIT; import static se.bjurr.gitchangelog.internal.integrations.rest.RestClient.mock; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.After; import org.junit.Before; import org.junit.Test; import se.bjurr.gitchangelog.internal.integrations.github.GitHubMockInterceptor; import se.bjurr.gitchangelog.internal.integrations.github.GitHubServiceFactory; import se.bjurr.gitchangelog.internal.integrations.jira.JiraClientFactory; import se.bjurr.gitchangelog.internal.integrations.rest.RestClientMock; import se.bjurr.gitchangelog.test.ApprovalsWrapper;
package se.bjurr.gitchangelog.api; public class TemplatesTest { private GitChangelogApi baseBuilder; @Before public void before() throws Exception { JiraClientFactory.reset(); final RestClientMock mockedRestClient = new RestClientMock(); mockedRestClient // .addMockedResponse( "/repos/tomasbjerre/git-changelog-lib/issues?state=all", new String( Files.readAllBytes( Paths.get(TemplatesTest.class.getResource("/github-issues.json").toURI())), UTF_8)) // .addMockedResponse( "/jira/rest/api/2/issue/JIR-1234?fields=parent,summary,issuetype,labels,description,issuelinks", new String( Files.readAllBytes( Paths.get( TemplatesTest.class.getResource("/jira-issue-jir-1234.json").toURI())), UTF_8)) // .addMockedResponse( "/jira/rest/api/2/issue/JIR-5262?fields=parent,summary,issuetype,labels,description,issuelinks", new String( Files.readAllBytes( Paths.get( TemplatesTest.class.getResource("/jira-issue-jir-5262.json").toURI())), UTF_8)); mock(mockedRestClient);
final GitHubMockInterceptor gitHubMockInterceptor = new GitHubMockInterceptor();
3
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/model/DCE.java
[ "public class Configuration {\n\tpublic enum Sections {\n\t\tMACROSCOPY, MICROSCOPY, CYTOPATHOLOGY, LIQUID_CYTOPATHOLOGY, CONCLUSION, OTHERS;\n\t}\n\n\tpublic enum Criteria {\n\t\tONE_REPORT_ONE_REGISTRY, MANY_REPORT_ONE_REGISTRY, MANY_REPORT_MANY_REGISTRY;\n\t}\n\n\tpublic enum Classifiers {\n\t\tNAIVE, BAYES, BAY...
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import org.apache.log4j.Logger; import org.hibernate.annotations.Index; import br.usp.ime.icdc.Configuration; import br.usp.ime.icdc.Constants; import br.usp.ime.icdc.dao.DAOFactory; import br.usp.ime.icdc.dao.PatientDAO; import br.usp.ime.icdc.run.loader.DCELoader;
package br.usp.ime.icdc.model; @Entity public class DCE implements Report { @Id @GeneratedValue private Long id; @Column @Index(name = "internalid_ndx") private Integer hospitalId; // Longest known (939586) contains 21448 characters. @Column(length = 30000) @Deprecated private String text; // TODO change fields to aggregation, with classes that implements a well-defined interface. @Column(length = 100000) private String macroscopy; @Column(length = 100000) private String microscopy; @Column(length = 100000) private String cytopathology; @Column(length = 100000) private String liquidCytopathology; @Column(length = 100000) private String others; // bidirectional relationship @ManyToOne @JoinColumn(name = "patient_fk") private Patient rgh; public DCE() { } public void setRgh(Patient rgh) { this.rgh = rgh; } @Deprecated public DCE(Integer hospitalId, String text) { this.hospitalId = hospitalId; this.text = text; } public DCE(Integer hospitalId, String macroscopy, String microscopy, String cytopathology, String liquidCytopathology, String others) { this.hospitalId = hospitalId; this.macroscopy = macroscopy; this.microscopy = microscopy; this.cytopathology = cytopathology; this.liquidCytopathology = liquidCytopathology; this.others = others; }
public DCE(Integer hospitalId, Map<Configuration.Sections, String> sections) {
0
TheClimateCorporation/mirage
samples/src/main/java/com/climate/mirage/app/SettingsActivity.java
[ "public class Mirage {\n\n\t/**\n\t * Location of where the resource came from\n\t */\n\tpublic static enum Source {\n\t\tMEMORY,\n\t\tDISK,\n\t\tEXTERNAL\n\t}\n\n\tpublic static final Executor THREAD_POOL_EXECUTOR = new MirageExecutor();\n\n\tprivate static final String TAG = Mirage.class.getSimpleName();\n\tpriva...
import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import com.climate.mirage.Mirage; import com.climate.mirage.cache.disk.CompositeDiskCache; import com.climate.mirage.cache.disk.DiskCache; import com.climate.mirage.cache.disk.DiskLruCacheWrapper; import com.climate.mirage.cache.memory.BitmapLruCache; import java.io.File;
package com.climate.mirage.app; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); setContentView(ll); Button btn = new Button(this); ll.addView(btn); btn.setText("Clear Cache"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Mirage.get(SettingsActivity.this).clearCache(); } }); btn = new Button(this); ll.addView(btn); btn.setText("Standard Cache Settings"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Mirage.get(SettingsActivity.this)
.setDefaultMemoryCache(new BitmapLruCache(0.25f))
4
zhenglu1989/web-sso
ki4so-core/src/main/java/com/github/ebnew/ki4so/core/service/KnightServiceImpl.java
[ "public class KnightApp implements Serializable {\n\n private static final long serialVersionUID = -1850808070447330706L;\n\n\n /**\n * 应用id\n */\n private String appId;\n\n /**\n * 应用名称\n */\n\n private String appName;\n\n /***\n * 应用所在的主机地址\n */\n\n private String host...
import com.github.ebnew.ki4so.core.app.KnightApp; import com.github.ebnew.ki4so.core.app.KnightAppService; import com.github.ebnew.ki4so.core.authentication.KnightAuthentication; import com.github.ebnew.ki4so.core.authentication.KnightAuthenticationManager; import com.github.ebnew.ki4so.core.authentication.KnightCredential; import com.github.ebnew.ki4so.core.authentication.status.KnightUserLoggedStatusStore; import com.github.ebnew.ki4so.core.authentication.status.KnightUserLoginStatus; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List;
package com.github.ebnew.ki4so.core.service; /** * @author zhenglu * @since 15/4/29 */ public class KnightServiceImpl implements KnightService { private Logger logger = Logger.getLogger(KnightServiceImpl.class); private KnightAuthenticationManager authenticationManager; private KnightAppService appService; private KnightUserLoggedStatusStore userLoggedStatusStore; @Override public LoginResult login(KnightCredential credential) { //若没有凭据,则返回空 if(credential == null){ return null; } LoginResult result = new LoginResult(); result.setSuccess(false); //调用认证处理器进行认证 try{
KnightAuthentication authentication = authenticationManager.authentication(credential);
2
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework
src/main/java/yourwebproject2/controller/UserController.java
[ "public class AuthenticationFailedException extends ServletException {\n private static final long serialVersionUID = -8799659324455306881L;\n\n public AuthenticationFailedException(String message) {\n super(message);\n }\n}", "public class JWTTokenAuthFilter extends OncePerRequestFilter {\n pr...
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import yourwebproject2.auth.AuthenticationFailedException; import yourwebproject2.auth.JWTTokenAuthFilter; import yourwebproject2.framework.api.APIResponse; import yourwebproject2.framework.controller.BaseController; import yourwebproject2.model.dto.UserDTO; import yourwebproject2.model.entity.User; import yourwebproject2.service.MailJobService; import yourwebproject2.service.UserService; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.Date; import java.util.HashMap;
package yourwebproject2.controller; /** * @author: kameshr * * Referred: https://github.com/mpetersen/aes-example, http://niels.nu/blog/2015/json-web-tokens.html */ @Controller @RequestMapping("user") public class UserController extends BaseController { private static Logger LOG = LoggerFactory.getLogger(UserController.class); private @Autowired UserService userService; private @Autowired MailJobService mailJobService; /** * Authenticate a user * * @param userDTO * @return */ @RequestMapping(value = "/authenticate", method = RequestMethod.POST, headers = {JSON_API_CONTENT_HEADER}) public @ResponseBody APIResponse authenticate(@RequestBody UserDTO userDTO, HttpServletRequest request, HttpServletResponse response) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, AuthenticationFailedException { Validate.isTrue(StringUtils.isNotBlank(userDTO.getEmail()), "Email is blank"); Validate.isTrue(StringUtils.isNotBlank(userDTO.getEncryptedPassword()), "Encrypted password is blank"); String password = decryptPassword(userDTO); LOG.info("Looking for user by email: "+userDTO.getEmail()); User user = userService.findByEmail(userDTO.getEmail()); HashMap<String, Object> authResp = new HashMap<>(); if(userService.isValidPass(user, password)) { LOG.info("User authenticated: "+user.getEmail()); userService.loginUser(user, request); createAuthResponse(user, authResp); } else { throw new AuthenticationFailedException("Invalid username/password combination"); } return APIResponse.toOkResponse(authResp); } /** * Register new user * POST body expected in the format - {"user":{"displayName":"Display Name", "email":"something@somewhere.com"}} * * @param userDTO * @return */ @RequestMapping(value = "/register", method = RequestMethod.POST, headers = {JSON_API_CONTENT_HEADER}) public @ResponseBody APIResponse register(@RequestBody UserDTO userDTO, HttpServletRequest request) throws NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException { Validate.isTrue(StringUtils.isNotBlank(userDTO.getEmail()), "Email is blank"); Validate.isTrue(StringUtils.isNotBlank(userDTO.getEncryptedPassword()), "Encrypted password is blank"); Validate.isTrue(StringUtils.isNotBlank(userDTO.getDisplayName()), "Display name is blank"); String password = decryptPassword(userDTO); LOG.info("Looking for user by email: "+userDTO.getEmail()); if(userService.isEmailExists(userDTO.getEmail())) { return APIResponse.toErrorResponse("Email is taken"); } LOG.info("Creating user: "+userDTO.getEmail()); User user = new User(); user.setEmail(userDTO.getEmail()); user.setDisplayName(userDTO.getDisplayName()); user.setPassword(password); user.setEnabled(true); user.setRole(User.Role.USER); userService.registerUser(user, request); HashMap<String, Object> authResp = new HashMap<>(); createAuthResponse(user, authResp); return APIResponse.toOkResponse(authResp); } private void createAuthResponse(User user, HashMap<String, Object> authResp) { String token = Jwts.builder().setSubject(user.getEmail()) .claim("role", user.getRole().name()).setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, JWTTokenAuthFilter.JWT_KEY).compact();
1
giancosta86/EasyPmd
src/main/java/info/gianlucacosta/easypmd/pmdscanner/PmdScanner.java
[ "public class NoOpPmdScannerStrategy implements PmdScannerStrategy {\n\n @Override\n public Set<ScanMessage> scan(Path path) {\n return Collections.emptySet();\n }\n}", "public class LinkedPmdScanningStrategy implements PmdScannerStrategy {\n\n private final PMD pmd;\n private final RuleSets...
import java.util.logging.Logger; import info.gianlucacosta.easypmd.pmdscanner.strategies.NoOpPmdScannerStrategy; import info.gianlucacosta.easypmd.pmdscanner.strategies.LinkedPmdScanningStrategy; import info.gianlucacosta.easypmd.pmdscanner.strategies.CacheBasedLinkedPmdScanningStrategy; import info.gianlucacosta.easypmd.pmdscanner.messages.ScanError; import info.gianlucacosta.easypmd.ide.options.Options; import java.nio.file.Path; import java.util.Collections; import java.util.Set;
/* * ==========================================================================%%# * EasyPmd * ===========================================================================%% * Copyright (C) 2009 - 2017 Gianluca Costa * ===========================================================================%% * 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>. * ==========================================================================%## */ package info.gianlucacosta.easypmd.pmdscanner; /** * Scans files using PMD, returning a list of ScanMessage for each scanned file */ public class PmdScanner { private static final Logger logger = Logger.getLogger(PmdScanner.class.getName()); private final PmdScannerStrategy strategy; public PmdScanner(Options options) { if (options.getRuleSets().isEmpty()) { logger.info(() -> "Setting a NOP scanning strategy"); strategy = new NoOpPmdScannerStrategy(); return; } if (options.isUseScanMessagesCache()) { logger.info(() -> "Setting a cached scanning strategy"); strategy = new CacheBasedLinkedPmdScanningStrategy(options); } else { logger.info(() -> "Setting a non-cached scanning strategy");
strategy = new LinkedPmdScanningStrategy(options);
1
handexing/geekHome
geekHome-backend/src/main/java/com/geekhome/controller/MenuController.java
[ "public enum ErrorCode {\n\t\n\tEXCEPTION(\"程序异常\", \"00001\"),\n\tUSER_NOT_EXIST(\"用户未注册\", \"00002\"),\n VERIFY_CODE_WRONG(\"验证码错误\",\"00003\"),\n OLD_PWD_WRONG(\"旧密码错误\",\"00004\"),\n USERNAME_PASSWORD_WRONG(\"用户名或密码错误\",\"00005\"),\n TODAY_HAVE_SIGN(\"今日已签到\",\"00006\");\n\n\tprivate String errorMsg...
import java.util.ArrayList; import java.util.List; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import com.geekhome.common.vo.ErrorCode; import com.geekhome.common.vo.ExecuteResult; import com.geekhome.entity.Menu; import com.geekhome.entity.dao.MenuDao; import com.geekhome.entity.service.MenuService;
package com.geekhome.controller; @RestController @RequestMapping("menu") public class MenuController { Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired MenuService menuService; @Autowired
private MenuDao menuDao;
3
DDoS/JICI
src/main/java/ca/sapon/jici/parser/expression/ClassAccess.java
[ "public interface SourceIndexed {\n int getStart();\n\n int getEnd();\n}", "public class Environment {\n // TODO make me thread safe\n private static final Map<String, Class<?>> DEFAULT_CLASSES = new HashMap<>();\n private final Map<String, Class<?>> classes = new LinkedHashMap<>(DEFAULT_CLASSES);\...
import ca.sapon.jici.lexer.TokenID; import ca.sapon.jici.parser.name.TypeName; import ca.sapon.jici.SourceIndexed; import ca.sapon.jici.evaluator.Environment; import ca.sapon.jici.evaluator.type.LiteralReferenceType; import ca.sapon.jici.evaluator.type.Type; import ca.sapon.jici.evaluator.value.ObjectValue; import ca.sapon.jici.evaluator.value.Value; import ca.sapon.jici.lexer.Token;
/* * This file is part of JICI, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/> * * 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 ca.sapon.jici.parser.expression; public class ClassAccess implements Expression { private static final LiteralReferenceType TYPE = LiteralReferenceType.of(Class.class); private final TypeName typeName; private final SourceIndexed source; private int start; private int end; private Type type = null; private Class<?> typeClass = null; public ClassAccess(Token voidToken, int end) {
if (voidToken.getID() != TokenID.KEYWORD_VOID) {
7
SergiusIW/collider
demos-core/src/com/matthewmichelotti/collider/demos/comps/CCoagParticle.java
[ "public final class HBCircle extends HBPositioned {\n\tdouble startRad;\n\tdouble velRad;\n\t\n\tHBCircle(Collider collider) {\n\t\tsuper(collider);\n\t}\n\n\t@Override\n\tvoid init() {\n\t\tsuper.init();\n\t\tthis.startRad = 0.0;\n\t\tthis.velRad = 0.0;\n\t}\n\n\t@Override\n\tvoid markTransitionStart() {\n\t\tdoub...
import com.badlogic.gdx.graphics.Color; import com.matthewmichelotti.collider.HBCircle; import com.matthewmichelotti.collider.HBRect; import com.matthewmichelotti.collider.demos.Component; import com.matthewmichelotti.collider.demos.Game; import com.matthewmichelotti.collider.demos.GameEngine; import com.matthewmichelotti.collider.demos.Geom;
/* * Copyright 2013-2014 Matthew D. Michelotti * * 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.matthewmichelotti.collider.demos.comps; /** * A circular particle that can merge (aka coagulate) with other particles. * @author Matthew Michelotti */ public class CCoagParticle extends Component { public final static Color COLOR = new Color(0.1f, 0.4f, 1.0f, 1.0f); public CCoagParticle() { super(Game.engine.makeCircle()); double x = -CBounds.PAD + Math.random()*(GameEngine.SCREEN_WIDTH + 2*CBounds.PAD); double y = -CBounds.PAD + Math.random()*(GameEngine.SCREEN_HEIGHT + 2*CBounds.PAD); HBCircle circ = circ(); circ.setPos(x, y); circ.setVel(1000*(.5 - Math.random()), 1000*(.5 - Math.random())); circ.setDiam(3); circ.commit(Double.POSITIVE_INFINITY); if(!isInBounds()) throw new RuntimeException(); } @Override public boolean canInteract(Component other) { return other instanceof CCoagParticle || other instanceof CBounds; } @Override public boolean interactsWithBullets() {return false;} @Override public void onCollide(Component other) { if(isDeleted()) return; if(other instanceof CCoagParticle) { HBCircle circ = circ(); HBCircle oCirc = other.circ(); double area = Geom.area(circ); double oArea = Geom.area(oCirc); double newArea = area + oArea; circ.setDiam(Geom.area2Diam(newArea)); circ.setVelX(circ.getVelX()*area/newArea + oCirc.getVelX()*oArea/newArea); circ.setVelY(circ.getVelY()*area/newArea + oCirc.getVelY()*oArea/newArea); circ.setX(circ.getX()*area/newArea + oCirc.getX()*oArea/newArea); circ.setY(circ.getY()*area/newArea + oCirc.getY()*oArea/newArea); circ.commit(Double.POSITIVE_INFINITY); ((CCoagParticle)other).delete(); if(circ.getDiam() > 2*CBounds.PAD) { new CCircFade(circ, COLOR, .3, null); delete(); } } } @Override public void onSeparate(Component other) { if(other instanceof CBounds) { HBCircle circ = circ();
HBRect rect = other.rect();
1
joachimhs/Embriak
backend/src/main/java/no/haagensoftware/netty/webserver/plugin/PostSenseRouterPlugin.java
[ "public interface ServerInfo {\n\n\tpublic String getWebappPath();\n public String getDocumentsPath();\n}", "public class FileServerHandler extends SimpleChannelUpstreamHandler {\r\n\tprivate static Logger logger = Logger.getLogger(FileServerHandler.class.getName());\r\n\t\r\n private String rootPath;\r\n ...
import java.util.LinkedHashMap; import no.haagensoftware.netty.webserver.ServerInfo; import no.haagensoftware.netty.webserver.handler.FileServerHandler; import no.haagensoftware.riak.RiakEnv; import org.haagensoftware.netty.webserver.spi.NettyWebserverRouterPlugin; import org.haagensoftware.netty.webserver.spi.PropertyConstants; import org.haagensoftware.netty.webserver.util.IntegerParser; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
package no.haagensoftware.netty.webserver.plugin; /** * A simple router plugin to be able to serve the Haagen-Software.no website. * @author joahaa * */ public class PostSenseRouterPlugin extends NettyWebserverRouterPlugin { private LinkedHashMap<String, SimpleChannelUpstreamHandler> routes; private ServerInfo serverInfo; public PostSenseRouterPlugin(ServerInfo serverInfo, RiakEnv dbEnv) { //authenticationContext = new AuthenticationContext(dbEnv);
int scriptCacheSeconds = IntegerParser.parseIntegerFromString(System.getProperty(PropertyConstants.SCRIPTS_CACHE_SECONDS), 0);
4
cocolove2/LISDemo
library-lis/src/main/java/com/cocolover2/lis/ShowImageView.java
[ "public interface OnImageClickListener {\n void onImgClick();\n}", "public class ImageCache {\n private static LruCache<String, Bitmap> mCache;\n\n private ImageCache() {\n }\n\n public static LruCache<String, Bitmap> getInstance() {\n if (mCache == null)\n synchronized (ImageCach...
import android.graphics.Bitmap; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cocolover2.lis.interf.OnImageClickListener; import com.cocolover2.lis.utils.ImageCache; import com.cocolover2.lis.utils.ImageUtils; import uk.co.senab.photoview.PhotoView; import uk.co.senab.photoview.PhotoViewAttacher;
package com.cocolover2.lis; public class ShowImageView extends Fragment { private String key_prefix = "big_img_";
private PhotoView imageView;
3
markusfisch/ShaderEditor
app/src/main/java/de/markusfisch/android/shadereditor/fragment/AbstractSamplerPropertiesFragment.java
[ "public class AddUniformActivity extends AbstractContentActivity {\n\tpublic static final String STATEMENT = \"statement\";\n\tpublic static final int PICK_IMAGE = 1;\n\tpublic static final int CROP_IMAGE = 2;\n\tpublic static final int PICK_TEXTURE = 3;\n\n\tpublic static void setAddUniformResult(Activity activity...
import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.support.v4.app.Fragment; import android.text.InputFilter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.Locale; import java.util.regex.Pattern; import de.markusfisch.android.shadereditor.R; import de.markusfisch.android.shadereditor.activity.AddUniformActivity; import de.markusfisch.android.shadereditor.opengl.ShaderRenderer; import de.markusfisch.android.shadereditor.opengl.TextureParameters; import de.markusfisch.android.shadereditor.view.SoftKeyboard; import de.markusfisch.android.shadereditor.widget.TextureParametersView;
view.findViewById(R.id.save).setOnClickListener(v -> saveSamplerAsync()); if (activity.getCallingActivity() == null) { addUniformView.setVisibility(View.GONE); addUniformView.setChecked(false); textureParameterView.setVisibility(View.GONE); } initSizeView(); initNameView(); return view; } private void initSizeView() { setSizeView(sizeBarView.getProgress()); sizeBarView.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged( SeekBar seekBar, int progressValue, boolean fromUser) { setSizeView(progressValue); } @Override public void onStartTrackingTouch( SeekBar seekBar) { } @Override public void onStopTrackingTouch( SeekBar seekBar) { } }); } private void setSizeView(int power) { int size = getPower(power); sizeView.setText(String.format( Locale.US, "%d x %d", size, size)); } private void initNameView() { nameView.setFilters(new InputFilter[]{ (source, start, end, dest, dstart, dend) -> NAME_PATTERN .matcher(source) .find() ? null : ""}); } // this AsyncTask is running for a short and finite time only // and it's perfectly okay to delay garbage collection of the // parent instance until this task has ended @SuppressLint("StaticFieldLeak") private void saveSamplerAsync() { final Context context = getActivity(); if (context == null || inProgress) { return; } final String name = nameView.getText().toString(); final TextureParameters tp = new TextureParameters(); textureParameterView.setParameters(tp); final String params = tp.toString(); if (name.trim().length() < 1) { Toast.makeText( context, R.string.missing_name, Toast.LENGTH_SHORT).show(); return; } else if (!name.matches(TEXTURE_NAME_PATTERN) || name.equals(ShaderRenderer.UNIFORM_BACKBUFFER)) { Toast.makeText( context, R.string.invalid_texture_name, Toast.LENGTH_SHORT).show(); return; } SoftKeyboard.hide(context, nameView); final int size = getPower(sizeBarView.getProgress()); inProgress = true; progressView.setVisibility(View.VISIBLE); new AsyncTask<Void, Void, Integer>() { @Override protected Integer doInBackground(Void... nothings) { return saveSampler(context, name, size); } @Override protected void onPostExecute(Integer messageId) { inProgress = false; progressView.setVisibility(View.GONE); Activity activity = getActivity(); if (activity == null) { return; } if (messageId > 0) { Toast.makeText( activity, messageId, Toast.LENGTH_SHORT).show(); return; } if (addUniformView.isChecked()) {
AddUniformActivity.setAddUniformResult(
0
nikku/silent-disco
server/src/test/java/de/nixis/web/disco/db/DatabaseTest.java
[ "public class Position {\n\n public enum Status {\n PLAYING,\n STOPPED\n }\n\n private String trackId;\n\n private Date date;\n\n private Status status;\n\n private int position;\n\n public Position(String trackId, int position, Status status) {\n this.trackId = trackId;\n this.date = new Date();...
import static org.fest.assertions.Assertions.assertThat; import java.net.UnknownHostException; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.github.jmkgreen.morphia.Datastore; import com.github.jmkgreen.morphia.Key; import de.nixis.web.disco.db.entity.Position; import de.nixis.web.disco.db.entity.Position.Status; import de.nixis.web.disco.db.entity.Room; import de.nixis.web.disco.db.entity.Track; import de.nixis.web.disco.db.entity.SoundCloudUser; import de.nixis.web.disco.dto.TrackPosition;
package de.nixis.web.disco.db; /** * * @author nico.rehwaldt */ public class DatabaseTest { private Datastore datastore; @Before public void before() throws UnknownHostException { datastore = Disco.createDatastore("localhost", "test-disco"); Disco.DATA_STORE = datastore; } @After public void after() { Disco.DATA_STORE = null; datastore.delete(datastore.find(Track.class)); datastore.delete(datastore.find(Room.class)); datastore.getMongo().close(); } @Test public void databaseTest() throws UnknownHostException { Room room = new Room("FOO"); datastore.save(room); Track track = new Track("1234112", "http://foo/aw", "http://foo", "foo", new SoundCloudUser("klaus", "http://klaus"), 200000, "FOO"); Key<Track> key = datastore.save(track); Object id = key.getId(); assertThat(datastore.exists(key)).isNotNull(); Track fromDB = datastore.get(Track.class, id); assertThat(fromDB).isNotNull(); assertThat(fromDB.getId()).isEqualTo(track.getId()); Room roomFromDB = datastore.find(Room.class, "name =", fromDB.getRoomName()).get(); assertThat(roomFromDB).isNotNull(); assertThat(roomFromDB.getId()).isEqualTo(room.getId()); } @Test public void shouldCreateRoom() { // when Room room = Disco.getRoom("foobar"); Room roomAgain = Disco.getRoom("foobar"); // then assertThat(room.getName()).isEqualTo("foobar"); assertThat(roomAgain.getName()).isEqualTo(room.getName()); } @Test public void shouldAddTrack() { // given Room room = Disco.getRoom("foobar"); // when Track track = Disco.addTrack(new Track(), room.getName(), null); List<Track> tracks = Disco.getTracks(room.getName()); Track firstTrack = tracks.get(0); // then assertThat(track.getRoomName()).isEqualTo(room.getName()); assertThat(tracks).hasSize(1); assertThat(firstTrack.getTrackId()).isEqualTo(track.getTrackId()); } @Test public void shouldPlayTrack() { // given Room room = Disco.getRoom("foobar"); Track track = Disco.addTrack(new Track(), room.getName(), null); // when Room roomNotPlaying = Disco.getRoom(room.getName()); Disco.startPlay(track.getTrackId(), 0); Room roomPlaying = Disco.getRoom(room.getName()); Position positionInitial = roomNotPlaying.getPosition(); Position positionPlaying = roomPlaying.getPosition(); // then assertThat(positionInitial).isNull(); assertThat(positionPlaying).isNotNull(); assertThat(positionPlaying.getTrackId()).isEqualTo(track.getTrackId()); assertThat(positionPlaying.getStatus()).isEqualTo(Status.PLAYING); } @Test public void shouldPlayTrackAtPosition() { // given Room room = Disco.getRoom("foobar"); Track track = Disco.addTrack(new Track(), room.getName(), null); // when Disco.startPlay(track.getTrackId(), 2000); Room roomPlaying = Disco.getRoom(room.getName()); Position positionPlaying = roomPlaying.getPosition(); // then assertThat(positionPlaying.getPosition()).isEqualTo(2000); } @Test public void shouldStopTrack() { // given Room room = Disco.getRoom("foobar"); Track track = Disco.addTrack(new Track(), room.getName(), null); // when Disco.startPlay(track.getTrackId(), 0); Disco.stopPlay(track.getTrackId()); Room roomAfterStop = Disco.getRoom(room.getName()); Position positionAfterStop = roomAfterStop.getPosition(); // then assertThat(positionAfterStop).isNotNull(); assertThat(positionAfterStop.getTrackId()).isEqualTo(track.getTrackId()); assertThat(positionAfterStop.getStatus()).isEqualTo(Status.STOPPED); } @Test public void shouldIncrementPositionOnAdd() { // given Room room = Disco.getRoom("foobar"); // when Track track0 = Disco.addTrack(new Track(), room.getName(), null); Track track1 = Disco.addTrack(new Track(), room.getName(), null); Track track2 = Disco.addTrack(new Track(), room.getName(), null); // then assertThat(track0.getPosition()).isLessThan(track1.getPosition()); assertThat(track1.getPosition()).isLessThan(track2.getPosition()); } @Test public void shouldMoveTrack() { // given Room room = Disco.getRoom("foobar"); Track track0 = Disco.addTrack(new Track(), room.getName(), null); Track track1 = Disco.addTrack(new Track(), room.getName(), null); Track track2 = Disco.addTrack(new Track(), room.getName(), null); // when // move track0 behind track1
Disco.moveTrack(track0.getTrackId(), new TrackPosition(1));
5
melloc/roguelike
engine/src/main/java/edu/brown/cs/roguelike/engine/level/Tile.java
[ "public final class Vec2i implements Serializable {\r\n\tprivate static final long serialVersionUID = 5659632794862666943L;\r\n\t\r\n\t/**\r\n\t * Since {@link Vec2i} instances are immutable, their x and y fields may be accessed without getters.\r\n\t */\r\n\tpublic final int x, y;\r\n\t\r\n\t/**\r\n\t * Creates a ...
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.UUID; import com.googlecode.lanterna.terminal.Terminal.Color; import cs195n.Vec2i; import edu.brown.cs.roguelike.engine.entities.Entity; import edu.brown.cs.roguelike.engine.entities.MainCharacter; import edu.brown.cs.roguelike.engine.entities.Stackable; import edu.brown.cs.roguelike.engine.graphics.Drawable; import edu.brown.cs.roguelike.engine.pathfinding.AStarNode; import edu.brown.cs.roguelike.engine.save.Saveable;
package edu.brown.cs.roguelike.engine.level; /** * A tile object to make up each physical level * * @author jte * */ public class Tile extends AStarNode<Tile> implements Saveable, Drawable { // The Space I belong to protected Space space;
protected Vec2i location = null;
0
hpgrahsl/kafka-connect-mongodb
src/main/java/at/grahsl/kafka/connect/mongodb/MongoDbSinkTask.java
[ "public abstract class CdcHandler {\n\n private final MongoDbSinkConnectorConfig config;\n\n public CdcHandler(MongoDbSinkConnectorConfig config) {\n this.config = config;\n }\n\n public MongoDbSinkConnectorConfig getConfig() {\n return this.config;\n }\n\n public abstract Optional<W...
import at.grahsl.kafka.connect.mongodb.cdc.CdcHandler; import at.grahsl.kafka.connect.mongodb.converter.SinkConverter; import at.grahsl.kafka.connect.mongodb.converter.SinkDocument; import at.grahsl.kafka.connect.mongodb.processor.PostProcessor; import at.grahsl.kafka.connect.mongodb.writemodel.strategy.WriteModelStrategy; import com.mongodb.BulkWriteException; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.MongoException; import com.mongodb.bulk.BulkWriteResult; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.BulkWriteOptions; import com.mongodb.client.model.WriteModel; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.errors.RetriableException; import org.apache.kafka.connect.sink.SinkRecord; import org.apache.kafka.connect.sink.SinkTask; import org.bson.BsonDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream;
/* * Copyright (c) 2017. Hans-Peter Grahsl (grahslhp@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package at.grahsl.kafka.connect.mongodb; public class MongoDbSinkTask extends SinkTask { private static Logger LOGGER = LoggerFactory.getLogger(MongoDbSinkTask.class); private static final BulkWriteOptions BULK_WRITE_OPTIONS = new BulkWriteOptions().ordered(true); private MongoDbSinkConnectorConfig sinkConfig; private MongoClient mongoClient; private MongoDatabase database; private int remainingRetries; private int deferRetryMs;
private Map<String, PostProcessor> processorChains;
3
littlezhou/SSM-1
smart-engine/src/main/java/org/smartdata/server/engine/RuleManager.java
[ "public class SmartConfKeys {\n public static final String SMART_DFS_ENABLED = \"smart.dfs.enabled\";\n public static final boolean SMART_DFS_ENABLED_DEFAULT = true;\n\n public static final String SMART_CONF_DIR_KEY = \"smart.conf.dir\";\n public static final String SMART_HADOOP_CONF_DIR_KEY = \"smart.hadoop.co...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.smartdata.AbstractService; import org.smartdata.action.ActionRegistry; import org.smartdata.conf.SmartConfKeys; import org.smartdata.metastore.MetaStore; import org.smartdata.metastore.MetaStoreException; import org.smartdata.model.CmdletDescriptor; import org.smartdata.model.DetailedRuleInfo; import org.smartdata.model.RuleInfo; import org.smartdata.model.RuleState; import org.smartdata.model.rule.RuleExecutorPluginManager; import org.smartdata.model.rule.RulePluginManager; import org.smartdata.model.rule.TimeBasedScheduleInfo; import org.smartdata.model.rule.TranslateResult; import org.smartdata.rule.parser.SmartRuleStringParser; import org.smartdata.rule.parser.TranslationContext; import org.smartdata.server.engine.rule.ExecutorScheduler; import org.smartdata.server.engine.rule.FileCopy2S3Plugin; import org.smartdata.server.engine.rule.FileCopyDrPlugin; import org.smartdata.server.engine.rule.RuleExecutor; import org.smartdata.server.engine.rule.RuleInfoRepo; import org.smartdata.server.engine.rule.SmallFilePlugin; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.concurrent.ConcurrentHashMap;
/** * 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.smartdata.server.engine; /** * Manage and execute rules. We can have 'cache' here to decrease the needs to execute a SQL query. */ public class RuleManager extends AbstractService { private ServerContext serverContext; private StatesManager statesManager; private CmdletManager cmdletManager; private MetaStore metaStore; private boolean isClosed = false; public static final Logger LOG = LoggerFactory.getLogger(RuleManager.class.getName()); private ConcurrentHashMap<Long, RuleInfoRepo> mapRules = new ConcurrentHashMap<>(); public ExecutorScheduler execScheduler; public RuleManager( ServerContext context, StatesManager statesManager, CmdletManager cmdletManager) { super(context); int numExecutors = context .getConf() .getInt( SmartConfKeys.SMART_RULE_EXECUTORS_KEY, SmartConfKeys.SMART_RULE_EXECUTORS_DEFAULT); execScheduler = new ExecutorScheduler(numExecutors); this.statesManager = statesManager; this.cmdletManager = cmdletManager; this.serverContext = context; this.metaStore = context.getMetaStore(); RuleExecutorPluginManager.addPlugin(new FileCopyDrPlugin(context.getMetaStore()));
RuleExecutorPluginManager.addPlugin(new FileCopy2S3Plugin());
5
amao12580/BookmarkHelper
app/src/main/java/pro/kisscat/www/bookmarkhelper/converter/support/impl/chrome/impl/xingchen/XingchenBrowserAble.java
[ "public class ChromeBrowserAble extends BasicBrowser {\n public String TAG = null;\n\n protected List<Bookmark> fetchBookmarks(java.io.File file) throws FileNotFoundException {\n JSONReader jsonReader = null;\n List<Bookmark> result = new LinkedList<>();\n try {\n jsonReader = ...
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.io.FileNotFoundException; import java.util.LinkedList; import java.util.List; import pro.kisscat.www.bookmarkhelper.converter.support.impl.chrome.ChromeBrowserAble; import pro.kisscat.www.bookmarkhelper.entry.app.Bookmark; import pro.kisscat.www.bookmarkhelper.database.SQLite.DBHelper; import pro.kisscat.www.bookmarkhelper.util.Path; import pro.kisscat.www.bookmarkhelper.util.log.LogHelper; import pro.kisscat.www.bookmarkhelper.util.storage.ExternalStorageUtil; import pro.kisscat.www.bookmarkhelper.util.storage.InternalStorageUtil;
package pro.kisscat.www.bookmarkhelper.converter.support.impl.chrome.impl.xingchen; /** * Created with Android Studio. * Project:BookmarkHelper * User:ChengLiang * Mail:stevenchengmask@gmail.com * Date:2016/12/8 * Time:17:54 * <p> * 星尘浏览器 */ public class XingchenBrowserAble extends ChromeBrowserAble { protected List<Bookmark> fetchBookmarksByHomePage(String filePath_origin, String filePath_cp) { String origin_dir = filePath_origin + Path.FILE_SPLIT + "databases" + Path.FILE_SPLIT; String fileUserDBName_origin = "useraction.db"; String origin_file = origin_dir + fileUserDBName_origin; String cp_file = filePath_cp + fileUserDBName_origin; LogHelper.v(TAG + ":开始读取已登录用户的书签sqlite数据库:" + origin_dir); List<Bookmark> result = new LinkedList<>(); LogHelper.v(TAG + ":origin file path:" + origin_file); LogHelper.v(TAG + ":tmp file path:" + cp_file); try { ExternalStorageUtil.copyFile(origin_file, cp_file, this.getName()); } catch (Exception e) { LogHelper.e(e.getMessage()); return result; } SQLiteDatabase sqLiteDatabase = null; Cursor cursor = null; String tableName = "ntp"; boolean tableExist; String[] columns = new String[]{"title", "url", "timestamp"}; try { sqLiteDatabase = DBHelper.openReadOnlyDatabase(cp_file); tableExist = DBHelper.checkTableExist(sqLiteDatabase, tableName); if (!tableExist) { LogHelper.v(TAG + ":database table " + tableName + " not exist."); return result; } cursor = sqLiteDatabase.query(false, tableName, columns, null, null, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { while (cursor.moveToNext()) { long timestamp = cursor.getLong(cursor.getColumnIndex("timestamp")); if (timestamp > 0) { Bookmark item = new Bookmark(); item.setTitle(cursor.getString(cursor.getColumnIndex("title"))); item.setUrl(cursor.getString(cursor.getColumnIndex("url"))); result.add(item); } } } } finally { if (cursor != null) { cursor.close(); } if (sqLiteDatabase != null) { sqLiteDatabase.close(); } } LogHelper.v(TAG + ":读取已登录用户书签sqlite数据库结束"); return result; } protected List<Bookmark> fetchBookmarks(String originPathDir, String originFileName, String cpPath) { List<Bookmark> result = new LinkedList<>(); String originFilePathFull = originPathDir + originFileName;
if (InternalStorageUtil.isExistFile(originFilePathFull)) {
6
researchgate/restler
restler-service/src/main/java/net/researchgate/restler/service/resources/AccountResource.java
[ "public class RestDslException extends RuntimeException {\n //TODO: generialize types, rethink them.\n // TODO: need something like generic conflict state\n public enum Type {\n // DB constraint violation\n DUPLICATE_KEY,\n\n // Entity provided is not valid\n ENTITY_ERROR,\n\n ...
import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Singleton; import net.researchgate.restdsl.exceptions.RestDslException; import net.researchgate.restdsl.queries.ServiceQueryParams; import net.researchgate.restdsl.queries.ServiceQueryParamsImpl; import net.researchgate.restdsl.resources.ServiceResource; import net.researchgate.restler.domain.Account; import net.researchgate.restler.domain.AccountStats; import net.researchgate.restler.service.exceptions.ServiceException; import net.researchgate.restler.service.model.AccountModel; import org.bson.types.ObjectId; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response;
package net.researchgate.restler.service.resources; /** * Account resource */ @Path("/accounts") @Singleton @Produces(MediaType.APPLICATION_JSON) public class AccountResource extends ServiceResource<Account, ObjectId> { private AccountModel accountModel; private static final ServiceQueryParams SERVICE_QUERY_PARAMS = ServiceQueryParamsImpl.builder() .defaultFields(Sets.newHashSet("id", "mentorAccountId", "publicationUids", "deleted")) // .addDefaultCriteriaItem("deleted", Collections.singletonList(false)) .defaultLimit(13) .build(); @Inject public AccountResource(AccountModel accountModel) throws RestDslException { super(accountModel, Account.class, ObjectId.class); this.accountModel = accountModel; } @GET @Path("/{id}/stats") public AccountStats getAccountStats(@PathParam("id") String id) { Account account = accountModel.getOne(getId(id)); if (account == null) {
throw new ServiceException("Account with id '" + id + "' not found", Response.Status.NOT_FOUND);
6
AstartesGuardian/WebDAV-Server
WebDAV-Server/src/webdav/server/virtual/entity/local/RsRoot.java
[ "public class FileSystemPath\r\n{\r\n public FileSystemPath(String fileName, FileSystemPath parent)\r\n {\r\n this.fileName = fileName;\r\n this.parent = parent;\r\n this.fileSystemPathManager = parent.fileSystemPathManager;\r\n }\r\n public FileSystemPath(String fileName, FileSyste...
import http.FileSystemPath; import http.server.exceptions.UserRequiredException; import http.server.exceptions.WrongResourceTypeException; import http.server.message.HTTPEnvRequest; import webdav.server.resource.IResource; import webdav.server.resource.ResourceType;
package webdav.server.virtual.entity.local; public class RsRoot extends RsLocalDirectory { public RsRoot() { super(""); } @Override public boolean delete(HTTPEnvRequest env) throws UserRequiredException { throw new WrongResourceTypeException(); } @Override public boolean moveTo(FileSystemPath oldPath, FileSystemPath newPath, HTTPEnvRequest env) throws UserRequiredException { throw new WrongResourceTypeException(); } @Override public boolean rename(String newName, HTTPEnvRequest env) throws UserRequiredException { throw new WrongResourceTypeException(); } @Override
public IResource creates(ResourceType resourceType, HTTPEnvRequest env) throws UserRequiredException
4
PathwayAndDataAnalysis/causalpath
src/main/java/org/panda/causalpath/run/CausalityAnalysisSingleMethodInterface.java
[ "public class CausalitySearcher implements Cloneable\n{\n\t/**\n\t * If that is false, then we are interested in conflicting relations.\n\t */\n\tprivate int causal;\n\n\t/**\n\t * If this is false, then we don't care if the target site of a relation and the site on the data matches.\n\t */\n\tprivate boolean force...
import org.panda.causalpath.analyzer.CausalitySearcher; import org.panda.causalpath.analyzer.ThresholdDetector; import org.panda.causalpath.data.ActivityData; import org.panda.causalpath.data.ProteinData; import org.panda.causalpath.network.GraphWriter; import org.panda.causalpath.network.Relation; import org.panda.causalpath.resource.NetworkLoader; import org.panda.causalpath.resource.ProteomicsFileReader; import org.panda.causalpath.resource.ProteomicsLoader; import org.panda.resource.ResourceDirectory; import org.panda.resource.siteeffect.SiteEffectCollective; import org.panda.resource.tcga.ProteomicsFileRow; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set;
package org.panda.causalpath.run; /** * This class provides a single basic method interface to the causality analysis, which is specifically designed to be * used by tools in other programming languages, such as R. * * @author Ozgun Babur */ public class CausalityAnalysisSingleMethodInterface { /** * Reads the proteomics platform and data files, and generates a ChiBE SIF graph. * * @param platformFile Name of the antibody reference file * @param idColumn Column name of IDs * @param symbolsColumn Column name of gene symbols * @param sitesColumn Column name for phosphorylation sites * @param effectColumn Column name for effect of the site on activity * @param valuesFile Name of the measurements file * @param valueColumn Name of the values column in the measurements file * @param valueThreshold The value threshold to be considered as significant * @param graphType Either "compatible" or "conflicting" * @param doSiteMatch option to enforce matching a phosphorylation site in the network with * the annotation of antibody * @param siteMatchProximityThreshold when site matching is on, this parameter sets the proxomity threshold for a * site number in the relation to match the site whose change is observed in the data * @param siteEffectProximityThreshold when the site effect is not known, we can approximate it with the known * effect of proximate sites. This parameter sets the proximity threshold for using the proximate sites for that * prediction. * @param geneCentric Option to produce a gene-centric or an antibody-centric graph * @param colorSaturationValue The value that maps to the most saturated color * @param outputFilePrefix If the user provides xxx, then xxx.sif and xxx.format are generated * @param customNetworkDirectory The directory that the network will be downloaded and SignedPC * directory will be created in. Pass null to use default * @throws IOException */ public static void generateCausalityGraph(String platformFile, String idColumn, String symbolsColumn, String sitesColumn, String modificationColumn, String effectColumn, String valuesFile, String valueColumn, double valueThreshold, String graphType, boolean doSiteMatch, int siteMatchProximityThreshold, int siteEffectProximityThreshold, boolean geneCentric, double colorSaturationValue, String outputFilePrefix, String customNetworkDirectory) throws IOException { if (customNetworkDirectory != null) ResourceDirectory.set(customNetworkDirectory); // Read platform file List<ProteomicsFileRow> rows = ProteomicsFileReader.readAnnotation(platformFile, idColumn, symbolsColumn, sitesColumn, modificationColumn, effectColumn); // Read values List<String> vals = Collections.singletonList(valueColumn); ProteomicsFileReader.addValues(rows, valuesFile, idColumn, vals, 0D, false); // Fill-in missing effect SiteEffectCollective sec = new SiteEffectCollective(); sec.fillInMissingEffect(rows, siteEffectProximityThreshold); generateCausalityGraph(rows, valueThreshold, graphType, doSiteMatch, siteMatchProximityThreshold, geneCentric, colorSaturationValue, outputFilePrefix); } /** * For the given proteomics data, generates a ChiBE SIF graph. * * @param rows The proteomics data rows that are read from an external source * @param valueThreshold The value threshold to be considered as significant * @param graphType Either "compatible" or "conflicting" * @param doSiteMatch option to enforce matching a phosphorylation site in the network with * the annotation of antibody * @param geneCentric Option to produce a gene-centric or an antibody-centric graph * @param colorSaturationValue The value that maps to the most saturated color * @param outputFilePrefix If the user provides xxx, then xxx.sif and xxx.format are generated * @throws IOException */ public static void generateCausalityGraph(Collection<ProteomicsFileRow> rows, double valueThreshold, String graphType, boolean doSiteMatch, int siteMatchProximityThreshold, boolean geneCentric, double colorSaturationValue, String outputFilePrefix) throws IOException { ProteomicsLoader loader = new ProteomicsLoader(rows, null); // Associate change detectors loader.associateChangeDetector(new ThresholdDetector(valueThreshold, ThresholdDetector.AveragingMethod.ARITHMETIC_MEAN), data -> data instanceof ProteinData); loader.associateChangeDetector(new ThresholdDetector(0.1, ThresholdDetector.AveragingMethod.ARITHMETIC_MEAN), data -> data instanceof ActivityData); // Load signed relations Set<Relation> relations = NetworkLoader.load(); loader.decorateRelations(relations); // Prepare causality searcher
CausalitySearcher cs = new CausalitySearcher(!graphType.toLowerCase().startsWith("conflict"));
0
Meituan-Dianping/walle
plugin/src/main/java/com/android/apksigner/core/DefaultApkSignerEngine.java
[ "public enum DigestAlgorithm {\n /** SHA-1 */\n SHA1(\"SHA-1\"),\n\n /** SHA2-256 */\n SHA256(\"SHA-256\");\n\n private final String mJcaMessageDigestAlgorithm;\n\n private DigestAlgorithm(String jcaMessageDigestAlgoritm) {\n mJcaMessageDigestAlgorithm = jcaMessageDigestAlgoritm;\n }\n\n...
import com.android.apksigner.core.internal.apk.v1.DigestAlgorithm; import com.android.apksigner.core.internal.apk.v1.V1SchemeSigner; import com.android.apksigner.core.internal.apk.v2.V2SchemeSigner; import com.android.apksigner.core.internal.util.ByteArrayOutputStreamSink; import com.android.apksigner.core.internal.util.MessageDigestSink; import com.android.apksigner.core.internal.util.Pair; import com.android.apksigner.core.util.DataSink; import com.android.apksigner.core.util.DataSource; import java.io.IOException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set;
private boolean isDone() { return mDone; } } private static class OutputApkSigningBlockRequestImpl implements OutputApkSigningBlockRequest { private final byte[] mApkSigningBlock; private volatile boolean mDone; private OutputApkSigningBlockRequestImpl(byte[] apkSigingBlock) { mApkSigningBlock = apkSigingBlock.clone(); } @Override public byte[] getApkSigningBlock() { return mApkSigningBlock.clone(); } @Override public void done() { mDone = true; } private boolean isDone() { return mDone; } } /** * JAR entry inspection request which obtain the entry's uncompressed data. */ private static class GetJarEntryDataRequest implements InspectJarEntryRequest { private final String mEntryName; private final Object mLock = new Object(); private boolean mDone; private ByteArrayOutputStreamSink mBuf; private GetJarEntryDataRequest(String entryName) { mEntryName = entryName; } @Override public String getEntryName() { return mEntryName; } @Override public DataSink getDataSink() { synchronized (mLock) { checkNotDone(); if (mBuf == null) { mBuf = new ByteArrayOutputStreamSink(); } return mBuf; } } @Override public void done() { synchronized (mLock) { if (mDone) { return; } mDone = true; } } private boolean isDone() { synchronized (mLock) { return mDone; } } private void checkNotDone() throws IllegalStateException { synchronized (mLock) { if (mDone) { throw new IllegalStateException("Already done"); } } } private byte[] getData() { synchronized (mLock) { if (!mDone) { throw new IllegalStateException("Not yet done"); } return (mBuf != null) ? mBuf.getData() : new byte[0]; } } } /** * JAR entry inspection request which obtains the digest of the entry's uncompressed data. */ private static class GetJarEntryDataDigestRequest implements InspectJarEntryRequest { private final String mEntryName; private final String mJcaDigestAlgorithm; private final Object mLock = new Object(); private boolean mDone; private DataSink mDataSink; private MessageDigest mMessageDigest; private byte[] mDigest; private GetJarEntryDataDigestRequest(String entryName, String jcaDigestAlgorithm) { mEntryName = entryName; mJcaDigestAlgorithm = jcaDigestAlgorithm; } @Override public String getEntryName() { return mEntryName; } @Override public DataSink getDataSink() { synchronized (mLock) { checkNotDone(); if (mDataSink == null) {
mDataSink = new MessageDigestSink(new MessageDigest[] {getMessageDigest()});
4
junjunguo/PocketMaps
PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/activities/Analytics.java
[ "public class SportCategory {\n private String text;\n private Integer imageId;\n private Calorie.Type sportMET;\n\n public SportCategory(String text, Integer imageId, Calorie.Type activityMET) {\n this.text = text;\n this.imageId = imageId;\n this.sportMET = activityMET;\n }\n\n...
import android.os.Bundle; import android.os.Handler; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Spinner; import android.widget.TextView; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.LegendRenderer; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import com.junjunguo.pocketmaps.R; import com.junjunguo.pocketmaps.model.SportCategory; import com.junjunguo.pocketmaps.model.listeners.TrackingListener; import com.junjunguo.pocketmaps.map.Tracking; import com.junjunguo.pocketmaps.util.Calorie; import com.junjunguo.pocketmaps.util.SetStatusBarColor; import com.junjunguo.pocketmaps.util.UnitCalculator; import com.junjunguo.pocketmaps.fragments.SpinnerAdapter; import com.junjunguo.pocketmaps.util.Variable; import java.util.ArrayList; import java.util.Locale;
package com.junjunguo.pocketmaps.activities; /** * This file is part of PocketMaps * <p> * Created by GuoJunjun <junjunguo.com> on July 04, 2015. */ public class Analytics extends AppCompatActivity implements TrackingListener { // status ----------------- public static boolean startTimer = true; /** * a sport category spinner: to choose with type of sport which also has MET value in its adapter */ private Spinner spinner; private TextView durationTV, avgSpeedTV, maxSpeedTV, distanceTV, distanceUnitTV, caloriesTV, maxSpeedUnitTV, avgSpeedUnitTV; // duration private Handler durationHandler; private Handler calorieUpdateHandler; // graph ----------------- /** * max value for it's axis (minimum 0) * <p/> * <li>X axis: time - hours</li> <li>Y1 (left) axis: speed - km/h</li> <li>Y2 (right) axis: distance - km</li> */ private double maxXaxis, maxY1axis, maxY2axis; /** * has a new point needed to update to graph view */ private boolean hasNewPoint; private GraphView graph; private LineGraphSeries<DataPoint> speedGraphSeries; private LineGraphSeries<DataPoint> distanceGraphSeries; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_analytics); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } // set status bar new SetStatusBarColor().setStatusBarColor(findViewById(R.id.statusBarBackgroundDownload), getResources().getColor(R.color.my_primary), this); // status initSpinner(); initStatus(); durationHandler = new Handler(); calorieUpdateHandler = new Handler(); // graph initGraph(); } // ---------- status --------------- private void initSpinner() { spinner = (Spinner) findViewById(R.id.activity_analytics_spinner); ArrayList<SportCategory> spinnerList = new ArrayList<>(); spinnerList.add(new SportCategory("walk/run", R.drawable.ic_directions_run_white_24dp, Calorie.Type.Run)); spinnerList.add(new SportCategory("bike", R.drawable.ic_directions_bike_white_24dp, Calorie.Type.Bike)); spinnerList.add(new SportCategory("car", R.drawable.ic_directions_car_white_24dp, Calorie.Type.Car));
SpinnerAdapter adapter = new SpinnerAdapter(this, R.layout.analytics_activity_type, spinnerList);
6
cattaka/AdapterToolbox
example/src/androidTest/java/net/cattaka/android/adaptertoolbox/example/TreeItemAdapterExampleActivityTest.java
[ "public class MyTreeItemAdapter extends AbsChoosableTreeItemAdapter<\n MyTreeItemAdapter,\n MyTreeItemAdapter.ViewHolder,\n MyTreeItem,\n MyTreeItemAdapter.WrappedItem\n > {\n public static ITreeItemAdapterRef<MyTreeItemAdapter, ViewHolder, MyTreeItem, WrappedItem> REF = new IT...
import android.support.test.rule.ActivityTestRule; import android.view.View; import net.cattaka.android.adaptertoolbox.example.adapter.MyTreeItemAdapter; import net.cattaka.android.adaptertoolbox.example.data.MyTreeItem; import net.cattaka.android.adaptertoolbox.example.test.MockSnackbarLogic; import net.cattaka.android.adaptertoolbox.example.test.RecyclerViewAnimatingIdlingResource; import net.cattaka.android.adaptertoolbox.example.test.TestUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.contrib.RecyclerViewActions.scrollToPosition; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static net.cattaka.android.adaptertoolbox.example.test.TestUtils.find; import static net.cattaka.android.adaptertoolbox.example.test.TestUtils.waitForIdlingResource; import static net.cattaka.android.adaptertoolbox.example.test.TestUtils.withIdInRecyclerView; import static org.hamcrest.Matchers.containsString; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify;
package net.cattaka.android.adaptertoolbox.example; /** * Created by cattaka on 16/06/05. */ public class TreeItemAdapterExampleActivityTest { @Rule public ActivityTestRule<TreeItemAdapterExampleActivity> mActivityTestRule = new ActivityTestRule<>(TreeItemAdapterExampleActivity.class, false, true); RecyclerViewAnimatingIdlingResource mRecyclerViewAnimatingIdlingResource; @Before public void before() { mRecyclerViewAnimatingIdlingResource = new RecyclerViewAnimatingIdlingResource(mActivityTestRule.getActivity().mRecyclerView); // registerIdlingResources(mRecyclerViewAnimatingIdlingResource); } @After public void after() { // unregisterIdlingResources(mRecyclerViewAnimatingIdlingResource); } @Test public void openCloseAll() { TreeItemAdapterExampleActivity activity = mActivityTestRule.getActivity();
MyTreeItemAdapter adapter = (MyTreeItemAdapter) activity.mRecyclerView.getAdapter();
0
zerg000000/mario-ai
src/main/java/ch/idsia/scenarios/test/EvaluateJLink.java
[ "public class LargeSRNAgent extends BasicMarioAIAgent implements Agent, Evolvable\n{\n\nprivate SRN srn;\nfinal int numberOfOutputs = Environment.numberOfKeys;\nfinal int numberOfInputs = 101;\nstatic private final String name = \"LargeSRNAgent\";\n\npublic LargeSRNAgent()\n{\n super(name);\n srn = new SRN(nu...
import ch.idsia.benchmark.mario.simulation.SimulationOptions; import ch.idsia.evolution.SRN; import ch.idsia.tools.MarioAIOptions; import ch.idsia.agents.Agent; import ch.idsia.agents.learning.LargeSRNAgent; import ch.idsia.benchmark.mario.engine.GlobalOptions;
/* * Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius * 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. * Neither the name of the Mario AI nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER 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 ch.idsia.scenarios.test; /** * Created by IntelliJ IDEA. * User: koutnij * Date: Jul 27, 2009 * Time: 4:34:37 PM */ public class EvaluateJLink { /** * returns {in, rec, out} array. Just to make math and java codes fully independent. */ public static int[] getDimension() { return new int[]{getInputSize() * getInputSize() * 2 + 3, 6, 6}; } /** * returns length of an edge of the input window square */ public static int getInputSize() { return 7; } public double evaluateLargeSRN(double[][] inputs, double[][] recurrent, double[][] output, int level, int seed) { // System.out.println(inputs.length+" "+inputs[0].length); // System.out.println(recurrent.length+" "+recurrent[0].length); // System.out.println(output.length+" "+output[0].length);
SRN srn = new SRN(inputs, recurrent, output, recurrent.length, output[0].length);
3
ajonkisz/TraVis
src/travis/view/project/graph/connection/ConnectionPainter.java
[ "public class UIHelper {\n\n private static final UIHelper INSTANCE = new UIHelper();\n\n public enum MessageType {\n INFORMATION, WARNING, ERROR\n }\n\n public enum Mode {\n ATTACH, PLAYBACK\n }\n\n private Mode mode;\n\n private final JFileChooser fc;\n private volatile File ...
import travis.controller.UIHelper; import travis.model.script.TraceInfo; import travis.view.Util; import travis.view.project.graph.ComponentData; import travis.view.project.graph.ControlPoint; import travis.view.project.graph.TreeRepresentation; import travis.view.settings.Settings; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Set; import java.util.concurrent.LinkedBlockingDeque;
/* * ConnectionPainter.java * * Copyright (C) 2011-2012, Artur Jonkisz, <travis.source@gmail.com> * * This file is part of TraVis. * See https://github.com/ajonkisz/TraVis for more info. * * TraVis 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. * * TraVis 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 TraVis. If not, see <http://www.gnu.org/licenses/>. */ package travis.view.project.graph.connection; public class ConnectionPainter { private static final float MIN_ALPHA = 0.1f; private static final float MAX_ALPHA = 0.6f; private final TreeRepresentation treeRep; private final LinkedBlockingDeque<TraceInfo> traces; private Collection<GraphBspline> oldSplines; private volatile ExecutionPoint execPoint; private volatile BufferedImage image; private volatile boolean needRepaint; public ConnectionPainter(TreeRepresentation treeRep) { this.treeRep = treeRep; traces = new LinkedBlockingDeque<TraceInfo>(); oldSplines = new LinkedHashSet<GraphBspline>(); needRepaint = true; } public ExecutionPoint getExecutionPoint() { return execPoint; } public void reset() { traces.clear(); oldSplines.clear(); needRepaint = true; } public void setNeedRepaint(boolean needRepaint) { this.needRepaint = needRepaint; } public Collection<GraphBspline> getSplines() { return oldSplines; } public void lineTo(TraceInfo trace) { needRepaint = true; traces.addFirst(trace); while (traces.size() > Settings.getInstance().getCachedTracesNo()) { traces.removeLast(); } } public void createConnections(ControlPoint cpStart, TraceInfo previousTrace, Iterator<TraceInfo> it, ConnectionData data, boolean isFirst) { for (; it.hasNext(); ) { TraceInfo trace = it.next();
ComponentData cd = treeRep.getMethods()[trace.getMethodId()];
3
6thsolution/EasyMVP
easymvp-compiler/src/main/java/easymvp/compiler/generator/decorator/BaseDecorator.java
[ "public class DelegateClassGenerator extends ClassGenerator {\n private final ClassName viewClass;\n private ClassName presenterClass;\n private ViewType viewType;\n private int resourceID = -1;\n private String presenterFieldNameInView = \"\";\n private String presenterViewQualifiedName;\n pri...
import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import easymvp.compiler.generator.DelegateClassGenerator; import java.util.concurrent.atomic.AtomicInteger; import javax.lang.model.element.Modifier; import static easymvp.compiler.util.ClassNames.BUNDLE; import static easymvp.compiler.util.ClassNames.CONTEXT; import static easymvp.compiler.util.ClassNames.PROVIDER; import static easymvp.compiler.util.ClassNames.WEAK_REFERENCE;
package easymvp.compiler.generator.decorator; /** * @author Saeed Masoumi (saeed@6thsolution.com) */ public abstract class BaseDecorator { protected static final String FIELD_PRESENTER = "presenter"; protected static final String METHOD_ON_LOADER_RESET = "onLoaderReset"; private static final String METHOD_INITIALIZE = "initialize"; private static final String METHOD_ATTACH_VIEW = "attachView"; private static final String METHOD_DETACH_VIEW = "detachView"; private static final String METHOD_DESTROY = "destroy"; private static final String METHOD_GET_LOADER_MANAGER = "getLoaderManager"; private static final String CLASS_PRESENTER_FACTORY = "PresenterFactory"; private static final String CLASS_PRESENTER_LOADER_CALLBACKS = "PresenterLoaderCallbacks"; private static final String METHOD_ON_CREATE_LOADER = "onCreateLoader"; private static final String METHOD_ON_LOAD_FINISHED = "onLoadFinished"; private static final String FIELD_PRESENTER_DELIVERED = "presenterDelivered"; private static final AtomicInteger LOADER_ID = new AtomicInteger(500);
protected DelegateClassGenerator delegateClassGenerator;
0
aleven/jpec-server
src/test/java/TestRegolaPec.java
[ "public class RegolaPecBL {\n\n\tprotected static final Logger logger = LoggerFactory.getLogger(RegolaPecBL.class);\n\n\tpublic static synchronized List<RegolaPec> regole(EntityManagerFactory emf, RegolaPecEventoEnum evento) throws Exception {\n\t\tRegolaPecFilter filtro = new RegolaPecFilter();\n\t\tfiltro.setEven...
import it.attocchi.jpec.server.bl.RegolaPecBL; import it.attocchi.jpec.server.bl.RegolaPecEventoEnum; import it.attocchi.jpec.server.entities.RegolaPec; import it.attocchi.jpec.server.protocollo.AzioneContext; import it.attocchi.jpec.server.protocollo.AzioneEsito; import it.attocchi.jpec.server.protocollo.AzioneEsito.AzioneEsitoStato; import java.util.List; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import junit.framework.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
public class TestRegolaPec { protected final Logger logger = LoggerFactory.getLogger(TestRegolaPec.class); @Test public void test() throws Exception { logger.info(this.getClass().getName()); try { EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpec-server-pu_TEST");
List<RegolaPec> regoleImporta = RegolaPecBL.regole(emf, RegolaPecEventoEnum.IMPORTA_MESSAGGIO);
2
jaredrummler/TrueTypeParser
lib-truetypeparser/src/main/java/com/jaredrummler/fontreader/fonts/GlyphSubstitutionTable.java
[ "public class AdvancedTypographicTableFormatException extends RuntimeException {\n\n /**\n * Instantiate ATT format exception.\n */\n public AdvancedTypographicTableFormatException() {\n super();\n }\n\n /**\n * Instantiate ATT format exception.\n *\n * @param message\n * a message string\n ...
import java.util.Map; import com.jaredrummler.fontreader.complexscripts.fonts.AdvancedTypographicTableFormatException; import com.jaredrummler.fontreader.complexscripts.fonts.GlyphClassTable; import com.jaredrummler.fontreader.complexscripts.fonts.GlyphCoverageTable; import com.jaredrummler.fontreader.complexscripts.fonts.GlyphDefinitionTable; import com.jaredrummler.fontreader.complexscripts.scripts.ScriptProcessor; import com.jaredrummler.fontreader.complexscripts.util.CharAssociation; import com.jaredrummler.fontreader.truetype.GlyphTable; import com.jaredrummler.fontreader.util.GlyphSequence; import com.jaredrummler.fontreader.util.GlyphTester; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
int gi = ss.getGlyph(); int ci; if ((ci = getCoverageIndex(gi)) < 0) { return false; } else { int[] ga = getAlternatesForCoverageIndex(ci, gi); int ai = ss.getAlternatesIndex(ci); int go; if ((ai < 0) || (ai >= ga.length)) { go = gi; } else { go = ga[ai]; } if ((go < 0) || (go > 65535)) { go = 65535; } ss.putGlyph(go, ss.getAssociation(), Boolean.TRUE); ss.consume(1); return true; } } /** * Obtain glyph alternates for coverage index. * * @param ci * coverage index * @param gi * original glyph index * @return sequence of glyphs to substitute for input glyph * @throws IllegalArgumentException * if coverage index is not valid */ public abstract int[] getAlternatesForCoverageIndex(int ci, int gi) throws IllegalArgumentException; static GlyphSubstitutionSubtable create(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) { if (format == 1) { return new AlternateSubtableFormat1(id, sequence, flags, format, coverage, entries); } else { throw new UnsupportedOperationException(); } } } private static class AlternateSubtableFormat1 extends AlternateSubtable { private int[][] gaa; // glyph alternates array, ordered by coverage index AlternateSubtableFormat1(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) { super(id, sequence, flags, format, coverage, entries); populate(entries); } /** {@inheritDoc} */ public List getEntries() { List entries = new ArrayList(gaa.length); for (int i = 0, n = gaa.length; i < n; i++) { entries.add(gaa[i]); } return entries; } /** {@inheritDoc} */ public int[] getAlternatesForCoverageIndex(int ci, int gi) throws IllegalArgumentException { if (gaa == null) { return null; } else if (ci >= gaa.length) { throw new IllegalArgumentException( "coverage index " + ci + " out of range, maximum coverage index is " + gaa.length); } else { return gaa[ci]; } } private void populate(List entries) { int i = 0; int n = entries.size(); int[][] gaa = new int[n][]; for (Iterator it = entries.iterator(); it.hasNext(); ) { Object o = it.next(); if (o instanceof int[]) { gaa[i++] = (int[]) o; } else { throw new AdvancedTypographicTableFormatException("illegal entries entry, must be int[]: " + o); } } assert i == n; assert this.gaa == null; this.gaa = gaa; } } private abstract static class LigatureSubtable extends GlyphSubstitutionSubtable { public LigatureSubtable(String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries) { super(id, sequence, flags, format, coverage); } /** {@inheritDoc} */ public int getType() { return GSUB_LOOKUP_TYPE_LIGATURE; } /** {@inheritDoc} */ public boolean isCompatible(GlyphSubtable subtable) { return subtable instanceof LigatureSubtable; } /** {@inheritDoc} */ public boolean substitute(GlyphSubstitutionState ss) { int gi = ss.getGlyph(); int ci; if ((ci = getCoverageIndex(gi)) < 0) { return false; } else { LigatureSet ls = getLigatureSetForCoverageIndex(ci, gi); if (ls != null) { boolean reverse = false;
GlyphTester ignores = ss.getIgnoreDefault();
8
mpostelnicu/wicket-spring-jpa-bootstrap-boilerplate
web/src/main/java/org/sample/web/pages/HomePage.java
[ "public final class Roles {\r\n\tpublic static final String USER=\"USER\";\r\n\tpublic static final String ADMIN=\"ADMIN\";\r\n}\r", "public class IconPanel<C extends Page> extends Panel {\n\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate final BookmarkablePageLink<Void> bookmarkablePageLink;...
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.model.Model; import org.sample.web.app.security.Roles; import org.sample.web.components.IconPanel; import org.sample.web.pages.lists.ListCategoryDummyPage; import org.sample.web.pages.lists.ListDummyPage; import org.sample.web.pages.nav.AbstractNavPage;
package org.sample.web.pages; /** * @author mpostelnicu * */ @AuthorizeInstantiation({ Roles.USER }) public class HomePage extends AbstractNavPage { private static final long serialVersionUID = 1L; public HomePage() { super(); listIcons.add(new IconPanel<ListDummyPage>(listIcons.newChildId(), Model.of("Dummy"), ListDummyPage.class, "fa-book"));
listIcons.add(new IconPanel<ListCategoryDummyPage>(listIcons.newChildId(),
2
etheriau/jatetoolkit
src/main/java/uk/ac/shef/dcs/oak/jate/util/Utility.java
[ "public class JATEProperties {\r\n private static final Logger _logger = Logger.getLogger(JATEProperties.class);\r\n\r\n private final Properties _properties = new Properties();\r\n private static JATEProperties _ref = null;\r\n\r\n //public static final String NP_FILTER_PATTERN = \"[^a-zA-Z0-9\\\\-]\";...
import java.io.IOException; import java.util.HashSet; import java.util.Set; import uk.ac.shef.dcs.oak.jate.JATEProperties; import uk.ac.shef.dcs.oak.jate.core.npextractor.CandidateTermExtractor; import uk.ac.shef.dcs.oak.jate.util.control.IStopList; import uk.ac.shef.dcs.oak.jate.util.control.Lemmatizer; import uk.ac.shef.dcs.oak.jate.util.control.StopList;
package uk.ac.shef.dcs.oak.jate.util; /** Newly added. Contains the common utility functions for NCValue Algorithm and Chi Square Algorithm. * **/ public class Utility{ /** Returns the input string after lemmatization. */ public static String getLemma(String context, IStopList stoplist, Lemmatizer lemmatizer) throws IOException{ String stopremoved = CandidateTermExtractor.applyTrimStopwords(context.trim(), stoplist, lemmatizer); String lemma=null; if(stopremoved!=null) lemma = lemmatizer.normalize(stopremoved.toLowerCase().trim()); return lemma; } /** Returns the input string after lemmatization. */ //Ankit: Removing this method as it is not really required. /* public static String getLemma(String context) throws IOException{ StopList stoplist = new StopList(true); Lemmatizer lemmatizer = new Lemmatizer(); String stopremoved = CandidateTermExtractor.applyTrimStopwords(context.trim(), stoplist, lemmatizer); String lemma=null; if(stopremoved!=null) lemma = lemmatizer.normalize(stopremoved.toLowerCase().trim()); return lemma; } */ public static String getLemmaChiSquare(String context, StopList stoplist, Lemmatizer lemmatizer) throws IOException{ String stopremoved = CandidateTermExtractor.applyTrimStopwords(context.trim(), stoplist, lemmatizer); String lemma=null; if(stopremoved!=null) lemma = lemmatizer.normalize(stopremoved.toLowerCase().trim()); //Ankit: unnecessary output information //else{ // _logger.info("null lemma" + context.trim()); //} return lemma; } /** Returns the sentence after modifying it by replacing the characters which are not in the character set [a-zA-Z0-9 -] by a space. */ public static String getModifiedSent(String sentence) { StringBuilder modified_sent = new StringBuilder(); String[] split_sent = sentence.split(" "); for(String s: split_sent){
s= CandidateTermExtractor.applyCharacterReplacement(s, JATEProperties.TERM_CLEAN_PATTERN);
0
emop/EmopAndroid
src/com/emop/client/fragment/RebateListFragment.java
[ "public class WebViewActivity extends BaseActivity {\r\n\tpublic final static int WEB_DONE = 1;\r\n\tpublic final static int WEB_MSG = 2;\r\n\tpublic final static int WEB_LOADING = 3;\r\n\tpublic final static int WEB_LOADED = 4;\t\r\n\t\r\n\tprivate ProgressBar processBar = null;\r\n\tprivate WebView web = null;\r\...
import java.util.TreeSet; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Rect; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.Spannable; import android.text.SpannableString; import android.text.style.StrikethroughSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.view.Window; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.ListView; import android.widget.TextView; import com.baidu.mobstat.StatService; import com.emop.client.R; import com.emop.client.WebViewActivity; import com.emop.client.io.FmeiClient; import com.emop.client.provider.QueryParam; import com.emop.client.provider.model.Rebate; import com.emop.client.utils.TimeHelper;
convertView = getLayoutInflater(null).inflate(R.layout.rebate_list_item, null); /* convertView.setLongClickable(true); convertView.setOnLongClickListener(new OnLongClickListener(){ @Override public boolean onLongClick(View v) { View img = v.findViewById(R.id.pic_url); Log.d("image tag:", "imag tag:" + img.getTag()); // TODO Auto-generated method stub return false; } }); */ } Items tag = (Items)convertView.getTag(); if(tag == null){ tag = new Items(convertView); convertView.setTag(tag); } final RebateItem item = this.getItem(position); if(tag.title != null){ tag.title.setText(item.title); } if(tag.picUrl != null){ tag.picUrl.setTag(item.picUrl); Bitmap bm = client.tmpImgLoader.cache.get(item.picUrl, winWidth, true, false); ImageView img = (ImageView)tag.picUrl; if(bm != null){ img.setScaleType(ScaleType.CENTER_CROP); img.setImageBitmap(bm); }else { img.setScaleType(ScaleType.CENTER_INSIDE); img.setImageResource(R.drawable.loading); client.tmpImgLoader.runTask(new Runnable(){ @Override public void run() { final Bitmap newBm = client.tmpImgLoader.cache.get(item.picUrl, winWidth, true, true); if(newBm != null){ handler.post(new Runnable(){ @Override public void run() { if(isRunning){ View v = getListView().findViewWithTag(item.picUrl); if(v != null){ ImageView v2 = (ImageView)v; v2.setScaleType(ScaleType.CENTER_CROP); v2.setImageBitmap(newBm); } } } }); } } }); } } if(tag.price != null){ String price = item.price; SpannableString spanText = new SpannableString("¥" + price); spanText.setSpan(new StrikethroughSpan(), 1, 1 + price.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tag.price.setText(spanText); } if(tag.couponPrice != null){ tag.couponPrice.setText("¥" + item.couponPrice); } if(tag.couponRate != null){ tag.couponRate.setText(String.format("%1$1.1f 折", item.couponRate / 1000)); } if(tag.endTime != null){ String time = TimeHelper.formatRemainHour(item.endTime, 10); tag.endTime.setText(time); } return convertView; } /** * 加入一个商品到折扣列表。如果商品已经存在,则忽略操作。 */ public void add(RebateItem item){ if(loadedItem.add(item.numIId)){ super.add(item); } } public void clear(){ super.clear(); this.loadedItem.clear(); } } class DataLoaderCallback implements LoaderCallbacks<Cursor>{ //public Lock loading = public boolean isLoading = false; private Uri dataSource = null; private boolean isLoadMore = false; private int pageSize = 20; private int pageNo = 0; public DataLoaderCallback(Uri source, boolean isLoadMore){ this.dataSource = source; this.isLoadMore = isLoadMore; } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { Builder b = dataSource.buildUpon(); if(isLoadMore){ //加载下一页数据。 pageNo++; } b.appendQueryParameter(QueryParam.PAGE_SIZE, pageSize + ""); b.appendQueryParameter(QueryParam.PAGE_NO, pageNo + ""); return new CursorLoader(getActivity(), b.build(),
new String[] { BaseColumns._ID, Rebate.NUM_IID, Rebate.TITLE, Rebate.PIC_URL, Rebate.COUPON_PRICE,
3
treasure-lau/CSipSimple
app/src/main/java/com/csipsimple/service/SipService.java
[ "public class MediaState implements Parcelable {\n\n /**\n * Primary key for the parcelable object\n */\n public int primaryKey = -1;\n\n /**\n * Whether the microphone is currently muted\n */\n public boolean isMicrophoneMute = false;\n\n /**\n * Whether the audio routes to the s...
import android.app.Activity; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.database.ContentObserver; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo.DetailedState; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Parcelable; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.RemoteException; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.view.SurfaceView; import android.widget.Toast; import com.csipsimple.R; import com.csipsimple.api.ISipConfiguration; import com.csipsimple.api.ISipService; import com.csipsimple.api.MediaState; import com.csipsimple.api.SipCallSession; import com.csipsimple.api.SipConfigManager; import com.csipsimple.api.SipManager; import com.csipsimple.api.SipManager.PresenceStatus; import com.csipsimple.api.SipMessage; import com.csipsimple.api.SipProfile; import com.csipsimple.api.SipProfileState; import com.csipsimple.api.SipUri; import com.csipsimple.db.DBProvider; import com.csipsimple.models.Filter; import com.csipsimple.pjsip.PjSipCalls; import com.csipsimple.pjsip.PjSipService; import com.csipsimple.pjsip.UAStateReceiver; import com.csipsimple.service.receiver.DynamicReceiver4; import com.csipsimple.service.receiver.DynamicReceiver5; import com.csipsimple.ui.incall.InCallMediaControl; import com.csipsimple.utils.Compatibility; import com.csipsimple.utils.CustomDistribution; import com.csipsimple.utils.ExtraPlugins; import com.csipsimple.utils.ExtraPlugins.DynActivityPlugin; import com.csipsimple.utils.Log; import com.csipsimple.utils.PreferencesProviderWrapper; import com.csipsimple.utils.PreferencesWrapper; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Semaphore; import java.util.regex.Matcher; import java.util.regex.Pattern;
public void confAdjustRxLevel(float speakVolume) throws SameThreadException { if(pjService != null) { pjService.confAdjustRxLevel(0, speakVolume); } } /** * Add a buddy to list * @param buddyUri the sip uri of the buddy to add */ public int addBuddy(String buddyUri) throws SameThreadException { int retVal = -1; if(pjService != null) { Log.d(THIS_FILE, "Trying to add buddy " + buddyUri); retVal = pjService.addBuddy(buddyUri); } return retVal; } /** * Remove a buddy from buddies * @param buddyUri the sip uri of the buddy to remove */ public void removeBuddy(String buddyUri) throws SameThreadException { if(pjService != null) { pjService.removeBuddy(buddyUri); } } private boolean holdResources = false; /** * Ask to take the control of the wifi and the partial wake lock if * configured */ private synchronized void acquireResources() { if(holdResources) { return; } // Add a wake lock for CPU if necessary if (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_PARTIAL_WAKE_LOCK)) { PowerManager pman = (PowerManager) getSystemService(Context.POWER_SERVICE); if (wakeLock == null) { wakeLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.SipService"); wakeLock.setReferenceCounted(false); } // Extra check if set reference counted is false ??? if (!wakeLock.isHeld()) { wakeLock.acquire(); } } // Add a lock for WIFI if necessary WifiManager wman = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifiLock == null) { int mode = WifiManager.WIFI_MODE_FULL; if(Compatibility.isCompatible(9) && prefsWrapper.getPreferenceBooleanValue(SipConfigManager.LOCK_WIFI_PERFS)) { mode = 0x3; // WIFI_MODE_FULL_HIGH_PERF } wifiLock = wman.createWifiLock(mode, "com.csipsimple.SipService"); wifiLock.setReferenceCounted(false); } if (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.LOCK_WIFI) && !wifiLock.isHeld()) { WifiInfo winfo = wman.getConnectionInfo(); if (winfo != null) { DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState()); // We assume that if obtaining ip addr, we are almost connected // so can keep wifi lock if (dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) { if (!wifiLock.isHeld()) { wifiLock.acquire(); } } } } holdResources = true; } private synchronized void releaseResources() { if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); } if (wifiLock != null && wifiLock.isHeld()) { wifiLock.release(); } holdResources = false; } private static final int TOAST_MESSAGE = 0; private Handler serviceHandler = new ServiceHandler(this); private static class ServiceHandler extends Handler { WeakReference<SipService> s; public ServiceHandler(SipService sipService) { s = new WeakReference<SipService>(sipService); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); SipService sipService = s.get(); if(sipService == null) { return; } if (msg.what == TOAST_MESSAGE) { if (msg.arg1 != 0) { Toast.makeText(sipService, msg.arg1, Toast.LENGTH_LONG).show(); } else { Toast.makeText(sipService, (String) msg.obj, Toast.LENGTH_LONG).show(); } } } };
public UAStateReceiver getUAStateReceiver() {
7