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
tusharm/go-artifactory-plugin
src/main/java/com/tw/go/plugins/artifactory/model/GoArtifactFactory.java
[ "public static ConfigElement<Map<String, String>> buildProperties = new BuildPropertiesConfigElement();", "public static ConfigElement<String> path = new PathConfigElement();", "public static ConfigElement<UriConfig> uriConfig = new UriConfigElement();", "public class UriConfig {\n private String uri;\n ...
import static com.google.common.collect.Collections2.transform; import static com.tw.go.plugins.artifactory.task.config.ConfigElement.buildProperties; import static com.tw.go.plugins.artifactory.task.config.ConfigElement.path; import static com.tw.go.plugins.artifactory.task.config.ConfigElement.uriConfig; import java.io.File; import java.util.Collection; import java.util.Map; import org.apache.commons.lang.text.StrSubstitutor; import com.google.common.base.Function; import com.thoughtworks.go.plugin.api.task.TaskConfig; import com.thoughtworks.go.plugin.api.task.TaskExecutionContext; import com.tw.go.plugins.artifactory.task.config.UriConfig; import com.tw.go.plugins.artifactory.utils.filesystem.DirectoryScanner;
package com.tw.go.plugins.artifactory.model; public class GoArtifactFactory { public Collection<GoArtifact> createArtifacts(final TaskConfig config, TaskExecutionContext context) {
DirectoryScanner scanner = new DirectoryScanner(context.workingDir());
4
threerings/game-gardens
toybox/src/main/java/com/threerings/toybox/lobby/table/TableListView.java
[ "public class TableMatchConfig extends MatchConfig\n{\n /** The minimum number of seats at this table. */\n public int minSeats;\n\n /** The starting setting for the number of seats at this table. */\n public int startSeats;\n\n /** The maximum number of seats at this table. */\n public int maxSea...
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.SimpleSlider; import com.samskivert.swing.VGroupLayout; import com.samskivert.swing.util.SwingUtil; import com.threerings.crowd.client.PlaceView; import com.threerings.crowd.data.PlaceObject; import com.threerings.media.SafeScrollPane; import com.threerings.util.MessageBundle; import com.threerings.parlor.client.SeatednessObserver; import com.threerings.parlor.client.TableDirector; import com.threerings.parlor.client.TableObserver; import com.threerings.parlor.data.Table; import com.threerings.parlor.data.TableConfig; import com.threerings.parlor.data.TableLobbyObject; import com.threerings.parlor.game.client.GameConfigurator; import com.threerings.parlor.game.client.SwingGameConfigurator; import com.threerings.toybox.data.TableMatchConfig; import com.threerings.toybox.data.ToyBoxGameConfig; import com.threerings.toybox.util.ToyBoxContext; import com.threerings.toybox.lobby.data.LobbyCodes; import com.threerings.toybox.lobby.data.LobbyObject; import static com.threerings.toybox.lobby.Log.log;
// // ToyBox library - framework for matchmaking networked games // Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.toybox.lobby.table; /** * A view that displays the tables in a table lobby. It displays two separate lists, one of tables * being matchmade and another of games in progress. These tables are updated dynamically as they * proceed through the matchmaking process. UI mechanisms for creating and joining tables are also * provided. */ public class TableListView extends JPanel implements PlaceView, TableObserver, ActionListener, SeatednessObserver { /** * Creates a new table list view, suitable for providing the user interface for table-style * matchmaking in a table lobby. */
public TableListView (ToyBoxContext ctx, ToyBoxGameConfig config)
2
zhaoxuyang/koala--Android-Plugin-Runtime-
MainApp/src/com/example/mainapp/MainActivity.java
[ "public class ApkFile {\n\n public String name;\n \n public String apkName;\n \n public ArrayList<String> nativeLibs = new ArrayList<String>();\n \n public float version;\n \n}", "public interface CopyPluginListener {\n\n\t/**\n\t * 扫描开始\n\t */\n\tvoid onCopyStart();\n\n\t/**\n\t * 扫描结束\n\...
import java.io.File; import java.util.ArrayList; import android.app.Activity; import android.app.ApkFile; import android.app.CopyPluginListener; import android.app.InstallPluginListener; import android.app.PluginInfo; import android.app.PluginManager; import android.app.ProgressDialog; import android.app.ScanPluginListener; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener;
package com.example.mainapp; public class MainActivity extends Activity implements ScanPluginListener, OnItemClickListener, InstallPluginListener, CopyPluginListener{ private ProgressDialog mDialog; private ListView mListView; private PluginsAdapter mAdapter; private ArrayList<ApkFile> apks = new ArrayList<ApkFile>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mListView = (ListView) findViewById(R.id.list); mListView.setOnItemClickListener(this); mDialog = new ProgressDialog(this); mDialog.setMessage("scanning"); File dir = getFilesDir(); dir = new File(dir, "koala"); PluginManager.getInstance().init(this, getDir("dexout", Context.MODE_PRIVATE).getAbsolutePath(), dir.getAbsolutePath()); ApkFile apk = new ApkFile(); apk.apkName = "CppEmptyTest.apk"; apk.name = "cocos2dx"; apk.nativeLibs.add("libcpp_empty_test.so"); apk.version = 1.0f; apks.add(apk); apk = new ApkFile(); apk.apkName = "PluginApp.apk"; apk.name = "simpledemo"; apk.nativeLibs.add("libhello-jni.so"); apk.version = 1.0f; apks.add(apk); PluginManager.getInstance().copyApksFromAsset(apks, getAssets(), this); } @Override
public void onScanEnd(ArrayList<PluginInfo> arg0) {
3
shagwood/micro-genie
micro-genie-dw-service/src/main/java/io/microgenie/service/AppConfiguration.java
[ "public abstract class ApplicationFactory implements Closeable{\n\n\tpublic ApplicationFactory(){}\n\n\tpublic abstract EventFactory events();\n\tpublic abstract QueueFactory queues();\n\tpublic abstract FileStoreFactory blobs();\n\tpublic abstract <T extends DatabaseFactory> T database();\n}", "public class ...
import io.dropwizard.Configuration; import io.microgenie.application.ApplicationFactory; import io.microgenie.application.StateChangeConfiguration; import io.microgenie.aws.AwsApplicationFactory; import io.microgenie.aws.config.AwsConfig; import io.microgenie.service.commands.CommandConfiguration; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper;
package io.microgenie.service; /*** * Application Configuration Factory * <p> * This class contains common configuration elements to configure micro-genie service * functionality * @author shawn */ public class AppConfiguration extends Configuration { private static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; private String dateFormat = ISO_8601_DATE_FORMAT; /** default to ISO 8601 UTC date format **/ private ApiConfiguration api; private StateChangeConfiguration stateChanges; private CommandConfiguration commands; private AwsConfig aws; private ApplicationFactory appFactory; /*** * AWS related configuration * @return awsConfig */ @JsonProperty("aws") public AwsConfig getAws() { return aws; } /*** * AWS related configuration * @param aws */ @JsonProperty("aws") public void setAws(AwsConfig aws) { this.aws = aws; } /*** * State Change Configuration * @return stateChangeConfiguration */ @JsonProperty("stateChanges") public StateChangeConfiguration getStateChanges() { return stateChanges; } /** * State Change Configuration * @param stateChanges */ @JsonProperty("stateChanges") public void setStateChanges(StateChangeConfiguration stateChanges) { this.stateChanges = stateChanges; } /*** * API Documentation configuration * @return apiDocumentation configuration */ @JsonProperty("api") public ApiConfiguration getApi() { return this.api; } /** * API Documentation configuration * @param api */ @JsonProperty("api") public void setApi(ApiConfiguration api) { this.api = api; } /*** * The date format to use with JSON date fields, unless specifically overridden by other configurations * @return dateFormat */ @JsonProperty("dateFormat") public String getDateFormat() { return dateFormat; } @JsonProperty("dateFormat") public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; } /** * Command Configuration * @return commandConfiguration */ @JsonProperty("commands") public CommandConfiguration getCommands() { return commands; } /*** * Command Configuration * @param commands - Set command configuration */ @JsonProperty("commands") public void setCommands(CommandConfiguration commands) { this.commands = commands; } /** * Get the application factory * @return appFactory */ public ApplicationFactory getAppFactory() { return appFactory; } /** * Build the application factory * @return appFactory * @throws IllegalStateException - If no valid configuration was found */ public ApplicationFactory buildAppFactory(final ObjectMapper mapper) throws IllegalStateException { if(this.aws!=null){
this.appFactory = new AwsApplicationFactory(this.getAws(), mapper);
2
d-plaindoux/suitcase
src/test/java/org/smallibs/suitcase/match/ListMatcherTest.java
[ "static <T> Case.WithoutCapture<T, T> Any() {\n return new Case0<T, T>(Optional::of).$();\n}", "static <T> Case.WithoutCapture<T, T> Constant(T value) {\n return new Case0<T, T>(p -> Objects.deepEquals(p, value) ? Optional.of(p) : Optional.empty()).$();\n}", "static <T> Var.WithoutInnerCapture<T, T> Var()...
import static org.smallibs.suitcase.utils.Functions.function; import junit.framework.TestCase; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.smallibs.suitcase.cases.core.Cases.Any; import static org.smallibs.suitcase.cases.core.Cases.Constant; import static org.smallibs.suitcase.cases.core.Cases.Var; import static org.smallibs.suitcase.cases.lang.Lists.Cons; import static org.smallibs.suitcase.cases.lang.Lists.Empty;
/* * Copyright (C)2015 D. Plaindoux. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.smallibs.suitcase.match; public class ListMatcherTest { @Test public void shouldMatchLisContainingAnObject() throws MatchingException { final Matcher<List<Integer>, Boolean> isEmpty = Matcher.create();
isEmpty.caseOf(Cons(Constant(1), Any())).then(true);
1
joshsh/rdfagents
rdfagents-demos/src/main/java/net/fortytwo/rdfagents/SparqlDescribeQueryProvider.java
[ "public class Commitment {\n\n public enum Decision {\n AGREE_AND_NOTIFY, // Query and Subscribe\n AGREE_SILENTLY, // Query only\n REFUSE // Query and Subscribe\n }\n\n private final Decision decision;\n private final ErrorExplanation explanation;\n\n public Commi...
import info.aduna.iteration.CloseableIteration; import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.query.QueryProvider; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.Dataset; import net.fortytwo.rdfagents.model.RDFAgent; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.BindingSet; import org.openrdf.query.GraphQuery; import org.openrdf.query.GraphQueryResult; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.impl.MapBindingSet; import org.openrdf.query.parser.ParsedGraphQuery; import org.openrdf.query.parser.QueryParserUtil; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.http.HTTPRepository; import org.openrdf.sail.SailConnection; import org.openrdf.sail.SailException; import java.util.Collection; import java.util.LinkedList;
package net.fortytwo.rdfagents; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class SparqlDescribeQueryProvider extends QueryProvider<Value, Dataset> { private static final String BASE_URI = "http://example.org/baseURI#"; private final Repository repo;
public SparqlDescribeQueryProvider(final RDFAgent agent,
5
YagelNasManit/environment.monitor
environment.monitor.runner/src/main/java/org/yagel/monitor/ScheduleRunnerImpl.java
[ "public class ScheduleRunnerException extends RuntimeException {\n\n public ScheduleRunnerException(String message) {\n super(message);\n }\n}", "public class MongoConnector {\n\n private final static String MONITOR_DB = \"monitor_tmp_newDomain\";\n private final static Logger log = Logger.getLogger(MongoC...
import org.apache.log4j.Logger; import org.yagel.monitor.exception.ScheduleRunnerException; import org.yagel.monitor.mongo.MongoConnector; import org.yagel.monitor.plugins.JarScanner; import org.yagel.monitor.status.collector.MonitorStatusCollectorLoader; import org.yagel.monitor.status.collector.ProxyCollectorLoader; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
package org.yagel.monitor; public class ScheduleRunnerImpl implements ScheduleRunner { private static Logger log = Logger.getLogger(ScheduleRunnerImpl.class); private static ScheduleRunnerImpl scheduleRunnerImpl; private MonitorStatusCollectorLoader collectorLoader; private ClassLoader classLoader; private ScheduledExecutorService executor; private MonitorConfig config; private Map<String, EnvironmentMonitorJobImpl> tasks = new WeakHashMap<>(); private ScheduleRunnerImpl(ClassLoader classLoader) { this.classLoader = classLoader; JarScanner jarScanner = new JarScanner(classLoader, this.getPluginPath()); jarScanner.scanJar();
this.collectorLoader = new ProxyCollectorLoader(jarScanner.getStatusCollectorLoader());
4
kakao/hbase-tools
hbase0.98/hbase-manager-0.98/src/test/java/com/kakao/hbase/manager/ManagerTest.java
[ "@SuppressWarnings(\"unused\")\npublic class TestBase extends SecureTestUtil {\n protected static final String TEST_TABLE_CF = \"d\";\n protected static final String TEST_TABLE_CF2 = \"e\";\n protected static final String TEST_NAMESPACE = \"unit_test\";\n protected static final int MAX_WAIT_ITERATION = ...
import org.junit.Test; import com.kakao.hbase.TestBase; import com.kakao.hbase.common.Args; import com.kakao.hbase.common.HBaseClient; import com.kakao.hbase.common.InvalidTableException; import com.kakao.hbase.common.util.AlertSender; import com.kakao.hbase.common.util.AlertSenderTest; import com.kakao.hbase.common.util.Util; import com.kakao.hbase.manager.command.Command; import com.kakao.hbase.specific.HBaseAdminWrapper; import joptsimple.OptionException; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.junit.Assert;
/* * Copyright 2015 Kakao Corporation * * 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.kakao.hbase.manager; public class ManagerTest extends TestBase { public ManagerTest() { super(ManagerTest.class); } @Test public void testDisabledTable() throws Exception { admin.disableTable(tableName); try {
Util.validateTable(admin, tableName);
6
psidnell/ofexport2
src/main/java/org/psidnell/omnifocus/visitor/KeepMarkedVisitor.java
[ "@JsonPropertyOrder(alphabetic=true)\npublic class Context extends NodeImpl implements ContextHierarchyNode{\n\n public static final String TYPE = \"Context\";\n\n private List<Task> tasks = new LinkedList<>();\n\n private List<Context> contexts = new LinkedList<>();\n\n private String parentContextId;\...
import org.psidnell.omnifocus.model.Context; import org.psidnell.omnifocus.model.ContextHierarchyNode; import org.psidnell.omnifocus.model.Folder; import org.psidnell.omnifocus.model.Node; import org.psidnell.omnifocus.model.Project; import org.psidnell.omnifocus.model.ProjectHierarchyNode; import org.psidnell.omnifocus.model.Task;
/* * Copyright 2015 Paul Sidnell * * 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.psidnell.omnifocus.visitor; /** * @author psidnell * * Keep marked items, delete others. */ public class KeepMarkedVisitor implements Visitor { private static final VisitorDescriptor WHAT = new VisitorDescriptor().visitAll().filterAll(); private boolean projectMode; private boolean cascade; public KeepMarkedVisitor (boolean projectMode, boolean cascade) { this.projectMode = projectMode; this.cascade = cascade; } @Override public VisitorDescriptor getWhat() { return WHAT; } @Override public void enter(Context node) throws Exception { markPath(node); } @Override public void enter(Folder node) throws Exception { markPath(node); } @Override public void enter(Project node) throws Exception { markPath(node); } @Override public void enter(Task node) throws Exception { markPath(node); } @Override public boolean includeUp(Context c) { return c.isMarked(); } @Override public boolean includeUp(Folder f) { return f.isMarked(); } @Override public boolean includeUp(Project p) { return p.isMarked(); } @Override public boolean includeUp(Task t) { return t.isMarked(); } private void markPath (Node node) { // NOPMD it's confused and thinks it's unused if (node.isMarked()) { if (projectMode) {
((ProjectHierarchyNode)node).getProjectPath().stream().forEach((n)->n.setMarked(true));
5
mgilangjanuar/GoSCELE
app/src/main/java/com/mgilangjanuar/dev/goscele/modules/auth/provider/AuthProvider.java
[ "public abstract class BaseProvider extends AsyncTask<String, Integer, List<Elements>> {\n\n protected Map<String, String> cookies = new HashMap<>();\n\n public BaseProvider() {\n super();\n }\n\n @Override\n @Deprecated\n protected List<Elements> doInBackground(String... params) {\n ...
import android.app.ProgressDialog; import android.text.TextUtils; import com.mgilangjanuar.dev.goscele.base.BaseProvider; import com.mgilangjanuar.dev.goscele.modules.auth.listener.AuthListener; import com.mgilangjanuar.dev.goscele.modules.common.model.CookieModel; import com.mgilangjanuar.dev.goscele.modules.common.model.UserModel; import com.mgilangjanuar.dev.goscele.utils.Constant; import org.jsoup.Connection; import org.jsoup.select.Elements; import java.util.List;
package com.mgilangjanuar.dev.goscele.modules.auth.provider; /** * Created by mgilangjanuar (mgilangjanuar@gmail.com) * * @since 2017 */ public class AuthProvider extends BaseProvider { private String username; private String password;
private AuthListener authListener;
1
fralalonde/iostream
src/main/java/ca/rbon/iostream/channel/part/ByteIn.java
[ "public class BufferedInputOf<T> extends BufferedInputStream implements WrapperOf<T> {\n\n final Resource<T> closer;\n\n /**\n * <p>\n * Constructor for BufferedInputOf.\n * </p>\n *\n * @param cl a {@link ca.rbon.iostream.resource.Resource} object.\n * @param is a {@link java.io.Input...
import java.io.IOException; import java.nio.charset.Charset; import ca.rbon.iostream.wrap.BufferedInputOf; import ca.rbon.iostream.wrap.BufferedReaderOf; import ca.rbon.iostream.wrap.DataInputOf; import ca.rbon.iostream.wrap.InputStreamOf; import ca.rbon.iostream.wrap.ObjectInputOf; import ca.rbon.iostream.wrap.ReaderOf; import ca.rbon.iostream.wrap.ZipInputOf;
package ca.rbon.iostream.channel.part; public interface ByteIn<T> { InputStreamOf<T> inputStream() throws IOException; BufferedInputOf<T> bufferedInputStream(int bufferSize) throws IOException; BufferedInputOf<T> bufferedInputStream() throws IOException; ZipInputOf<T> zipInputStream(Charset charset, int bufferSize) throws IOException; ZipInputOf<T> zipInputStream(String charsetName, int bufferSize) throws IOException; ZipInputOf<T> zipInputStream(Charset charset) throws IOException; ZipInputOf<T> zipInputStream(String charsetName) throws IOException; ZipInputOf<T> zipInputStream(int bufferSize) throws IOException; ZipInputOf<T> zipInputStream() throws IOException; DataInputOf<T> dataInputStream(int bufferSize) throws IOException; DataInputOf<T> dataInputStream() throws IOException; /** * Build a buffered object input stream. NOTE: Unlike other input streams, * closing an ObjectInputStream does NOT close the underlying stream. * * @param bufferSize the size of the read buffer * @return an ObjectInputOf * @throws IOException if something bad happens */ ObjectInputOf<T> objectInputStream(int bufferSize) throws IOException; /** * Build a unbuffered object input stream. NOTE: Unlike other input streams, * closing an ObjectInputStream does NOT close the underlying stream. * * @return an ObjectInputOf * @throws IOException if something bad happens */ ObjectInputOf<T> objectInputStream() throws IOException; // UNBUFFERED /** * Build an unbuffered reader using the specified charset. * * @param charset The ;@link Charset} to use * @return A ;@link ReaderOf} proxy extending the ;@link Reader} class * @throws IOException If the reader can not be built */
ReaderOf<T> reader(Charset charset) throws IOException;
5
Consoar/zhangshangwuda
src/zq/whu/zhangshangwuda/ui/lessons/LessonsLoginActivity.java
[ "public class SwipeBackSherlockActivity extends UmengSherlockActivity implements\n\t\tSwipeBackActivityBase {\n\tprivate SwipeBackActivityHelper mHelper;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tmHelper = new SwipeBackActivityHelper(this);\...
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import zq.whu.zhangshangwuda.base.SwipeBackSherlockActivity; import zq.whu.zhangshangwuda.db.LessonsDb; import zq.whu.zhangshangwuda.entity.Lessons; import zq.whu.zhangshangwuda.tools.BosCrypto; import zq.whu.zhangshangwuda.tools.Constants; import zq.whu.zhangshangwuda.tools.LessonsSharedPreferencesTool; import zq.whu.zhangshangwuda.tools.LessonsTool; import zq.whu.zhangshangwuda.ui.R; import zq.whu.zhangshangwuda.views.toast.ToastUtil; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.view.MenuItem; import com.umeng.analytics.MobclickAgent;
package zq.whu.zhangshangwuda.ui.lessons; public class LessonsLoginActivity extends SwipeBackSherlockActivity { private Button LoginButton = null; private EditText AccountView; private EditText PasswordView; public String Account; public String Password; private ProgressDialog pd = null; private EditText YZMView; private ImageView YZMimg; private static Bitmap YZMbm = null; private static String yzmURL = "http://202.114.74.198/GenImg"; private static String BaseURL = "http://202.114.74.198/servlet/Login"; private static String MasterCookie; private ImageView bottomImg; public Bitmap getYZM(String url, String cookie) { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); httpget.addHeader("Cookie", cookie); try { HttpResponse httpResponse = httpclient.execute(httpget); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { byte[] data = EntityUtils.toByteArray(httpResponse.getEntity()); Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); // 提取Cookie Header[] headers = httpResponse.getAllHeaders(); cookie = ""; for (int i = 0; i < headers.length; i++) { if (headers[i].getName().contains("Cookie")) { String tempcookie = headers[i].getValue(); tempcookie = tempcookie.substring(0, tempcookie.indexOf(";")); cookie = cookie + tempcookie + ";"; } } MasterCookie = cookie.substring(0, cookie.length() - 1); return bitmap; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } return null; } class refreshYZMThread implements Runnable { @Override public void run() { // TODO Auto-generated method stub refreshYZM(); } } public void refreshYZM() { MasterCookie = getFirstCookie("http://202.114.74.198/"); YZMbm = getYZM(yzmURL, MasterCookie); YZMhandler.sendEmptyMessage(0); } Handler YZMhandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); YZMimg.setImageBitmap(YZMbm); } }; @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { bottomImg.setVisibility(View.GONE); } else { bottomImg.setVisibility(View.VISIBLE); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MobclickAgent.updateOnlineConfig(this); setContentView(R.layout.lessons_login); getSupportActionBar().setDisplayHomeAsUpEnabled(true); findViews(); InitConfig(); LessonsSharedPreferencesTool.setLessonsId(getApplicationContext(), 0); Account = AccountView.getText().toString(); Password = PasswordView.getText().toString(); new Thread(new refreshYZMThread()).start(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; } return false; } class LoginButtonListener implements OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub SaveConfig(); Account = AccountView.getText().toString(); Password = PasswordView.getText().toString(); // pd = ProgressDialog.show( // LessonsLoginActivity.this, // null, // LessonsLoginActivity.this.getResources().getString( // R.string.Loading_Tip), true, true);// 显示ProgressBar if (YZMbm != null) { LoginButton.setEnabled(false); new Thread(new LogInThread()).start(); } else {
ToastUtil.showToast(LessonsLoginActivity.this, "要先连上网哦~");
7
marpies/vk-ane
android/src/com/marpies/ane/vk/functions/AuthFunction.java
[ "public interface IAIRVKActivityResultCallback extends AndroidActivityWrapper.ActivityResultCallback {\n\n}", "public class AIRVKEvent {\n\n\tpublic static final String VK_AUTH_ERROR = \"vkAuthError\";\n\tpublic static final String VK_AUTH_SUCCESS = \"vkAuthSuccess\";\n\tpublic static final String VK_TOKEN_UPDATE...
import java.util.ArrayList; import android.content.Intent; import com.adobe.air.AndroidActivityWrapper; import com.adobe.air.IAIRVKActivityResultCallback; import com.adobe.fre.FREArray; import com.adobe.fre.FREContext; import com.adobe.fre.FREObject; import com.marpies.ane.vk.data.AIRVKEvent; import com.marpies.ane.vk.utils.AIR; import com.marpies.ane.vk.utils.FREObjectUtils; import com.marpies.ane.vk.utils.VKAccessTokenUtils; import com.vk.sdk.VKAccessToken; import com.vk.sdk.VKCallback; import com.vk.sdk.VKSdk; import com.vk.sdk.api.VKError;
/* * Copyright 2016 Marcel Piestansky (http://marpies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marpies.ane.vk.functions; public class AuthFunction extends BaseFunction implements IAIRVKActivityResultCallback { @Override public FREObject call( FREContext context, FREObject[] args ) { super.call( context, args ); ArrayList<String> permissions = (args[0] == null) ? null : (ArrayList<String>) FREObjectUtils.getListOfString( (FREArray) args[0] ); AndroidActivityWrapper.GetAndroidActivityWrapper().addActivityResultListener( this ); AIR.log( "AuthFunction | VKSdk::login" );
VKSdk.login( AIR.getContext().getActivity(), (permissions != null) ? permissions.toArray( new String[0] ) : null );
5
jeick/jamod
src/main/java/net/wimpi/modbus/io/ModbusUDPTransport.java
[ "public interface Modbus {\n\n\t/**\n\t * JVM flag for debug mode. Can be set passing the system property\n\t * net.wimpi.modbus.debug=false|true (-D flag to the jvm).\n\t */\n\tpublic static final boolean debug = \"true\".equals(System\n\t\t\t.getProperty(\"net.wimpi.modbus.debug\"));\n\n\t/**\n\t * Defines the cl...
import java.io.DataOutput; import java.io.IOException; import java.io.InterruptedIOException; import net.wimpi.modbus.Modbus; import net.wimpi.modbus.ModbusIOException; import net.wimpi.modbus.msg.ModbusMessage; import net.wimpi.modbus.msg.ModbusRequest; import net.wimpi.modbus.msg.ModbusResponse; import net.wimpi.modbus.net.UDPTerminal;
/*** * Copyright 2002-2010 jamod development team * * 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.wimpi.modbus.io; /** * Class that implements the Modbus UDP transport flavor. * * @author Dieter Wimberger * @version 1.0 (29/04/2002) */ public class ModbusUDPTransport implements ModbusTransport { // instance attributes private UDPTerminal m_Terminal; private BytesOutputStream m_ByteOut; private BytesInputStream m_ByteIn; /** * Constructs a new <tt>ModbusTransport</tt> instance, for a given * <tt>UDPTerminal</tt>. * <p> * * @param terminal * the <tt>UDPTerminal</tt> used for message transport. */ public ModbusUDPTransport(UDPTerminal terminal) { m_Terminal = terminal; m_ByteOut = new BytesOutputStream(Modbus.MAX_IP_MESSAGE_LENGTH); m_ByteIn = new BytesInputStream(Modbus.MAX_IP_MESSAGE_LENGTH); }// constructor public void close() throws IOException { // ? }// close public void writeMessage(ModbusMessage msg) throws ModbusIOException { try { synchronized (m_ByteOut) { m_ByteOut.reset(); msg.writeTo((DataOutput) m_ByteOut); m_Terminal.sendMessage(m_ByteOut.toByteArray()); } } catch (Exception ex) { throw new ModbusIOException("I/O exception - failed to write."); } }// write public ModbusRequest readRequest() throws ModbusIOException { try { ModbusRequest req = null; synchronized (m_ByteIn) { m_ByteIn.reset(m_Terminal.receiveMessage()); m_ByteIn.skip(7); int functionCode = m_ByteIn.readUnsignedByte(); m_ByteIn.reset(); req = ModbusRequest.createModbusRequest(functionCode); req.readFrom(m_ByteIn); } return req; } catch (Exception ex) { throw new ModbusIOException("I/O exception - failed to read."); } }// readRequest
public ModbusResponse readResponse() throws ModbusIOException {
4
ceylon/ceylon-js
src/main/java/com/redhat/ceylon/compiler/js/Stitcher.java
[ "public class MetamodelVisitor extends Visitor {\n\n final MetamodelGenerator gen;\n\n public MetamodelVisitor(Module module) {\n this.gen = new MetamodelGenerator(module);\n }\n\n /** Returns the in-memory model as a collection of maps.\n * The top-level map represents the module. */\n pu...
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.ceylon.CeylonUtils; import com.redhat.ceylon.cmr.impl.ShaSigner; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.FileUtil; import com.redhat.ceylon.compiler.js.loader.MetamodelVisitor; import com.redhat.ceylon.compiler.js.loader.ModelEncoder; import com.redhat.ceylon.compiler.js.util.JsIdentifierNames; import com.redhat.ceylon.compiler.js.util.JsJULLogger; import com.redhat.ceylon.compiler.js.util.JsOutput; import com.redhat.ceylon.compiler.js.util.Options; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.model.typechecker.model.Module;
} final TypeChecker tc = langmodtc.getTypeChecker(); tc.process(true); if (tc.getErrors() > 0) { return 1; } //Compile these files final List<File> includes = new ArrayList<File>(); for (String filename : line.split(",")) { filename = filename.trim(); final boolean isJsSrc = filename.endsWith(".js"); final boolean isDir = filename.endsWith("/"); final boolean exclude = filename.charAt(0)=='-'; if (exclude) { filename = filename.substring(1); } final File src = ".".equals(filename) ? clSrcFileDir : new File(isJsSrc ? LANGMOD_JS_SRC : clSrcFileDir, isJsSrc || isDir ? filename : String.format("%s.ceylon", filename)); if (!addFiles(includes, src, exclude)) { final File src2 = new File(clJsFileDir, isDir ? filename : String.format("%s.ceylon", filename)); if (!addFiles(includes, src2, exclude)) { throw new IllegalArgumentException("Invalid Ceylon language module source " + src + " or " + src2); } } } if (includes.isEmpty()) { return 0; } //Compile only the files specified in the line //Set this before typechecking to share some decls that otherwise would be private JsCompiler jsc = new JsCompiler(tc, opts, true) .stopOnErrors(false) .setSourceFiles(includes); if (!jsc.generate()) { jsc.printErrorsAndCount(new OutputStreamWriter(System.out)); return 1; } else { // We still call this here for any warning there might be jsc.printErrorsAndCount(new OutputStreamWriter(System.out)); } if (names == null) { names = jsc.getNames(); } File compsrc = new File(tmpout, "delete/me/delete-me.js"); if (compsrc.exists() && compsrc.isFile() && compsrc.canRead()) { try { writer.outputFile(compsrc); } finally { compsrc.delete(); } } else { System.out.println("Can't find generated js for language module in " + compsrc.getAbsolutePath()); return 1; } return 0; } private static boolean addFiles(final List<File> includes, final File src, boolean exclude) { if (src.exists() && src.isFile() && src.canRead()) { if (exclude) { System.out.println("EXCLUDING " + src); compiledFiles.add(src); } else if (!compiledFiles.contains(src)) { includes.add(src); compiledFiles.add(src); } } else if (src.exists() && src.isDirectory()) { for (File sub : src.listFiles()) { if (!compiledFiles.contains(sub)) { includes.add(sub); compiledFiles.add(sub); } } } else { return false; } return true; } private static int encodeModel(final File moduleFile) throws IOException { final String name = moduleFile.getName(); final File file = new File(moduleFile.getParentFile(), name.substring(0,name.length()-3)+ArtifactContext.JS_MODEL); System.out.println("Generating language module compile-time model in JSON..."); TypeCheckerBuilder tcb = new TypeCheckerBuilder().usageWarnings(false); tcb.addSrcDirectory(clSrcDir); TypeChecker tc = tcb.getTypeChecker(); tc.process(true); MetamodelVisitor mmg = null; final ErrorCollectingVisitor errVisitor = new ErrorCollectingVisitor(tc); for (PhasedUnit pu : tc.getPhasedUnits().getPhasedUnits()) { pu.getCompilationUnit().visit(errVisitor); if (errVisitor.getErrorCount() > 0) { errVisitor.printErrors(false, false); System.out.println("whoa, errors in the language module " + pu.getCompilationUnit().getLocation()); return 1; } if (mmg == null) { mmg = new MetamodelVisitor(pu.getPackage().getModule()); } pu.getCompilationUnit().visit(mmg); } mod = tc.getPhasedUnits().getPhasedUnits().get(0).getPackage().getModule(); try (FileWriter writer = new FileWriter(file)) { JsCompiler.beginWrapper(writer); writer.write("ex$.$CCMM$="); ModelEncoder.encodeModel(mmg.getModel(), writer); writer.write(";\n"); final JsOutput jsout = new JsOutput(mod, "UTF-8", true) { @Override public Writer getWriter() throws IOException { return writer; } }; jsout.outputFile(new File(LANGMOD_JS_SRC, "MODEL.js")); JsCompiler.endWrapper(writer); } finally {
ShaSigner.sign(file, new JsJULLogger(), true);
3
braintree/braintree_android_encryption
BraintreeAndroidEncryption/src/androidTest/java/com/braintreegateway/encryption/test/AesTest.java
[ "public class Base64\n{\n private static final Encoder encoder = new Base64Encoder();\n \n /**\n * encode the input data producing a base 64 encoded byte array.\n *\n * @return a byte array containing the base 64 encoded data.\n */\n public static byte[] encode(\n byte[] data)\...
import java.util.Arrays; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.BadPaddingException; import javax.crypto.NoSuchPaddingException; import android.test.AndroidTestCase; import com.braintree.org.bouncycastle.util.encoders.Base64; import com.braintreegateway.encryption.Aes; import com.braintreegateway.encryption.Random; import com.braintreegateway.encryption.BraintreeEncryptionException; import com.braintreegateway.encryption.util.AesDecrypter;
package com.braintreegateway.encryption.test; public class AesTest extends AndroidTestCase { private byte[] aesKey; private byte[] aesIV; private final String dataToEncrypt = "test data"; @Override public void setUp() {
aesKey = Random.secureRandomBytes(Aes.KEY_LENGTH);
2
liucijus/jinsist
mock/src/main/java/jinsist/mock/Mock.java
[ "public interface Expectations {\n <ReturnType, MockType> void recordStub(\n Class<MockType> classToMock,\n MockType instance,\n Method method,\n Arguments arguments,\n ReturnType result\n );\n\n <MockType> Object execute(\n Class<MockType> ...
import jinsist.expectations.Expectations; import jinsist.mock.delegators.MockExecutor; import jinsist.mock.delegators.SetupRecorder; import jinsist.proxy.Delegator; import jinsist.proxy.Proxy;
package jinsist.mock; public class Mock<MockType> { private Class<MockType> mockClass; public MockType getInstance() { return instance; } private MockType instance; private Expectations expectations; public Mock(Class<MockType> mockClass, Expectations expectations) {
MockType instance = new Proxy<>(mockClass).instance(new MockExecutor<>(expectations, mockClass));
4
Leaking/WeGit
app/src/main/java/com/quinn/githubknife/ui/adapter/EventAdapter.java
[ "public enum OctIcon implements Icon {\n\n\t\n\t\n\tSTAR(0xf02a),\n FORK(0xf002),\n FILE(0xf011),\n\tFOLDER(0xf016),\n\tSEARCH(0xf02e),\n\tBRANCH(0xf020),\n\tEMAIL(0xf03b),\n\tLOCATE(0xf060),\n\tCOMPANY(0xf037),\n\tBLOG(0xf05C),\n\tJOIN(0xf046),\n\tREPO(0xf001),\n\tPUSH(0xf01f),\n\tCOMMIT(0xf07e),\n\tCODE(0xf...
import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.github.quinn.iconlibrary.icons.OctIcon; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import com.quinn.githubknife.R; import com.quinn.githubknife.ui.widget.AnimateFirstDisplayListener; import com.quinn.githubknife.ui.widget.RecycleItemClickListener; import com.quinn.githubknife.utils.BitmapUtils; import com.quinn.githubknife.utils.TimeUtils; import com.quinn.httpknife.github.Event; import com.quinn.httpknife.github.GithubConstants; import com.quinn.httpknife.payload.IssuePayload; import com.quinn.httpknife.payload.MenberPayload; import java.util.List;
package com.quinn.githubknife.ui.adapter; /** * Created by Quinn on 7/25/15. */ public class EventAdapter extends RecyclerView.Adapter<EventAdapter.ViewHolder>{ private static final String TAG = "EventAdapter"; private Context context; private List<Event> dataItems; private ImageLoader imageLoader; private DisplayImageOptions option; private RecycleItemClickListener itemClickListener; private ImageLoadingListener imageLoadingListener = new AdapterImageLoaderListener(); public EventAdapter(Context context,List<Event> dataItems){ this.context = context; this.dataItems = dataItems; this.imageLoader = ImageLoader.getInstance(); this.option = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true) .considerExifParams(true).build(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final LayoutInflater mInflater = LayoutInflater.from(parent .getContext()); final View sView = mInflater.inflate(R.layout.item_eventlist, parent, false); return new ViewHolder(sView,itemClickListener); } @Override public void onViewRecycled(ViewHolder holder) { super.onViewRecycled(holder); Log.i(TAG, "onViewRecycled"); // imageLoader.cancelDisplayTask(holder.avatar); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Event event = dataItems.get(position); holder.avatar.setTag(event.getActor().getAvatar_url()); imageLoader.displayImage(event.getActor().getAvatar_url(), holder.avatar, option, imageLoadingListener); holder.happenTime.setText(TimeUtils.getRelativeTime(event.getCreated_at())); setItemTextAndIcon(holder.event,holder.eventType,position); } @Override public int getItemCount() { return dataItems.size(); } public void setItemTextAndIcon(TextView tv,ImageView img,int position){ Event event = dataItems.get(position); String eventType = event.getType(); if(eventType.equals(GithubConstants.WATCH_EVENT)){ tv.setText(Html.fromHtml(event.getActor().getLogin() + " <b>starred</b> " + event.getRepo().getName())); BitmapUtils.setIconFont(context, img, OctIcon.STAR, R.color.theme_color); }else if(eventType.equals(GithubConstants.ForkEvent)){ tv.setText(Html.fromHtml(event.getActor().getLogin() + " <b>forked</b> " + event.getRepo().getName())); BitmapUtils.setIconFont(context, img, OctIcon.FORK, R.color.theme_color); }else if(eventType.equals(GithubConstants.CreateEvent)){ tv.setText(Html.fromHtml(event.getActor().getLogin() + " <b>created repo</b> " + event.getRepo().getName())); BitmapUtils.setIconFont(context, img, OctIcon.REPO, R.color.theme_color); }else if(eventType.equals(GithubConstants.PullRequestEvent)){ tv.setText(Html.fromHtml(event.getActor().getLogin() + " <b>opened pull request</b> " + event.getRepo().getName())); BitmapUtils.setIconFont(context, img, OctIcon.PUSH, R.color.theme_color); }else if(eventType.equals(GithubConstants.MemberEvent)){
MenberPayload payload = (MenberPayload)dataItems.get(position).getPayload();
5
PushOCCRP/Push-Android
app/src/main/java/com/pushapp/press/adapter/PostListAdapter.java
[ "public class HomeActivity extends AppCompatActivity implements OnFragmentInteractionListener, LanguageListener, ImageCacheDelegate, ArticlesDelegate {\n\n private Toolbar mToolbarView;\n private ObservableListView mListView;\n private AQuery aq;\n static boolean isSearchShown = false;\n private Menu...
import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.engine.GlideException; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.google.gson.Gson; import com.pushapp.press.HomeActivity; import com.pushapp.press.interfaces.CacheManager.ImageCacheDelegate; import com.pushapp.press.util.DateUtil; import com.pushapp.press.R; import com.pushapp.press.model.Article; import com.pushapp.press.util.Language; import com.pushapp.press.util.SettingsManager; import com.pushapp.press.util.TypefaceManager; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List;
package com.pushapp.press.adapter; /** * @author Bryan Lamtoo. * Heavily edited by Christopher Guess */ public class PostListAdapter extends ArrayAdapter<Article> implements ImageCacheDelegate { // Android's "findItemByID request is really really expensive apparently. // This is the standard "ViewHolder" pattern which handles the requests at the time // The object is created. // All references to setting the fields should go through here private static class ViewHolderItem { ImageView imageView; TextView headline; String tag; TextView dateView; } private List<Article> itemsList; private HashMap<String, ArrayList<Article>> itemsHash; private List<String> categories; private Integer articlesPerCategory; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); private LayoutInflater inflater;
private TypefaceManager fontManager;
6
witwall/sfntly-java
src/main/java/com/google/typography/font/sfntly/table/core/HorizontalDeviceMetricsTable.java
[ "public class ReadableFontData extends FontData {\n\n public static ReadableFontData createReadableFontData(byte[] b) {\n ByteArray<?> ba = new MemoryByteArray(b);\n return new ReadableFontData(ba);\n }\n\n\n /**\n * Flag on whether the checksum has been set.\n */\n private volatile boolean checksumSe...
import com.google.typography.font.sfntly.data.ReadableFontData; import com.google.typography.font.sfntly.data.WritableFontData; import com.google.typography.font.sfntly.table.Header; import com.google.typography.font.sfntly.table.Table; import com.google.typography.font.sfntly.table.TableBasedTableBuilder;
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.typography.font.sfntly.table.core; /** * A Horizontal Device Metrics table - 'hdmx'. * * @author raph@google.com (Raph Levien) */ public class HorizontalDeviceMetricsTable extends Table { private int numGlyphs; private enum Offset { version(0), numRecords(2), sizeDeviceRecord(4), records(8), // Offsets within a device record deviceRecordPixelSize(0), deviceRecordMaxWidth(1), deviceRecordWidths(2); private final int offset; private Offset(int offset) { this.offset = offset; } }
private HorizontalDeviceMetricsTable(Header header, ReadableFontData data, int numGlyphs) {
0
slide-lig/jlcm
src/main/java/fr/liglab/jlcm/internals/ExplorationStep.java
[ "public final class ExtensionsIterator {\n\tprivate final AtomicInteger index;\n\tprivate final int max;\n\n\t/**\n\t * will provide an iterator on frequent items (in increasing order) in\n\t * [0,to[\n\t */\n\tpublic ExtensionsIterator(final int to) {\n\t\tthis.index = new AtomicInteger(0);\n\t\tthis.max = to;\n\t...
import java.util.Arrays; import java.util.Calendar; import fr.liglab.jlcm.internals.Counters.ExtensionsIterator; import fr.liglab.jlcm.internals.Dataset.TransactionsIterable; import fr.liglab.jlcm.internals.Selector.WrongFirstParentException; import fr.liglab.jlcm.io.FileReader; import fr.liglab.jlcm.util.ItemsetsFactory; import gnu.trove.map.hash.TIntIntHashMap;
/* This file is part of jLCM - see https://github.com/martinkirch/jlcm/ Copyright 2013,2014 Martin Kirchgessner, Vincent Leroy, Alexandre Termier, Sihem Amer-Yahia, Marie-Christine Rousset, Université Joseph Fourier and CNRS 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 or see the LICENSE.txt file joined with this program. 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 fr.liglab.jlcm.internals; /** * Represents an LCM recursion step. Its also acts as a Dataset factory. */ public final class ExplorationStep implements Cloneable { public static boolean verbose = false; public static boolean ultraVerbose = false; public final ExplorationStep parent; /** * Initialized with the given/parent's threshold * Set it to another value if you want to over/under-filter when calling next() */ public int childrenThreshold; /** * closure of parent's pattern UNION extension */ public final int[] pattern; /** * Extension item that led to this recursion step (internal ID) * Already included in "pattern". */ public final int core_item; public final Dataset dataset; public final Counters counters; /** * Selectors chain - may be null when empty */ protected Selector selectChain; protected final ExtensionsIterator candidates; /** * When an extension fails first-parent test, it ends up in this map. Keys * are non-first-parent items associated to their actual first parent. */ private final TIntIntHashMap failedFPTests; /** * Start exploration on a dataset contained in a file. * * @param minimumSupport * @param path * to an input file in ASCII format. Each line should be a * transaction containing space-separated item IDs. */ public ExplorationStep(int minimumSupport, String path) { this.parent = null; this.core_item = Integer.MAX_VALUE; this.selectChain = null; this.childrenThreshold = minimumSupport; FileReader reader = new FileReader(path); this.counters = new Counters(minimumSupport, reader); reader.close(this.counters.renaming); this.pattern = this.counters.closure; this.dataset = new Dataset(this.counters, reader); this.candidates = this.counters.getExtensionsIterator(); this.failedFPTests = new TIntIntHashMap(); } /** * Start exploration on an abstract dataset, using an absolute frequency * threshold */ public ExplorationStep(int minimumSupport, Iterable<TransactionReader> source) { this.parent = null; this.core_item = Integer.MAX_VALUE; this.selectChain = null; this.childrenThreshold = minimumSupport; this.counters = new Counters(minimumSupport, source.iterator()); this.pattern = this.counters.closure; TransactionsRenameAndSortDecorator filtered = new TransactionsRenameAndSortDecorator(source.iterator(), this.counters.renaming); this.dataset = new Dataset(this.counters, filtered); this.candidates = this.counters.getExtensionsIterator(); this.failedFPTests = new TIntIntHashMap(); } /** * Start exploration on an abstract dataset, using a relative frequency * threshold */ public ExplorationStep(double minimumSupport, Iterable<TransactionReader> source) { this.parent = null; this.core_item = Integer.MAX_VALUE; this.selectChain = null; this.counters = new Counters(minimumSupport, source.iterator()); this.childrenThreshold = this.counters.minSupport; this.pattern = this.counters.closure; TransactionsRenameAndSortDecorator filtered = new TransactionsRenameAndSortDecorator(source.iterator(), this.counters.renaming); this.dataset = new Dataset(this.counters, filtered); this.candidates = this.counters.getExtensionsIterator(); this.failedFPTests = new TIntIntHashMap(); } private ExplorationStep(ExplorationStep parent, int childrenThreshold, int[] pattern, int core_item, Dataset dataset, Counters counters, Selector selectChain, ExtensionsIterator candidates, TIntIntHashMap failedFPTests) { super(); this.childrenThreshold = childrenThreshold; this.parent = parent; this.pattern = pattern; this.core_item = core_item; this.dataset = dataset; this.counters = counters; this.selectChain = selectChain; this.candidates = candidates; this.failedFPTests = failedFPTests; } /** * Finds an extension for current pattern in current dataset and returns the * corresponding ExplorationStep (extensions are enumerated by ascending * item IDs - in internal rebasing) Returns null when all valid extensions * have been generated */ public ExplorationStep next() { if (this.candidates == null) { return null; } while (true) { int candidate = this.candidates.next(); if (candidate < 0) { return null; } try { if (this.selectChain == null || this.selectChain.select(candidate, this)) { TransactionsIterable support = this.dataset.getSupport(candidate); // System.out.println("extending "+Arrays.toString(this.pattern)+ // " with "+ // candidate+" ("+this.counters.getReverseRenaming()[candidate]+")"); Counters candidateCounts = new Counters(this.childrenThreshold, support.iterator(), candidate, this.counters.maxFrequent); int greatest = Integer.MIN_VALUE; for (int i = 0; i < candidateCounts.closure.length; i++) { if (candidateCounts.closure[i] > greatest) { greatest = candidateCounts.closure[i]; } } if (greatest > candidate) {
throw new WrongFirstParentException(candidate, greatest);
2
pierre/collector
src/test/java/com/ning/metrics/collector/guice/TestHealthChecksModule.java
[ "public interface CollectorConfig\n{\n @Config(\"collector.dfs.block.size\")\n @Default(\"134217728\")\n long getHadoopBlockSize();\n\n @Config(\"collector.hadoop.ugi\")\n @Default(\"nobody,nobody\")\n String getHadoopUgi();\n\n // Whether to forward events to ActiveMQ\n\n @Config(\"collecto...
import com.google.inject.Injector; import com.yammer.metrics.reporting.AdminServlet; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; import com.ning.metrics.collector.binder.config.CollectorConfig; import com.ning.metrics.collector.hadoop.processing.EventSpoolDispatcher; import com.ning.metrics.collector.hadoop.processing.PersistentWriterFactory; import com.ning.metrics.collector.hadoop.processing.WriterStats; import com.ning.metrics.collector.healthchecks.HadoopHealthCheck; import com.ning.metrics.collector.healthchecks.RealtimeHealthCheck; import com.ning.metrics.collector.healthchecks.WriterHealthCheck; import com.ning.metrics.collector.realtime.EventQueueProcessor; import com.ning.metrics.collector.realtime.EventQueueProcessorImpl; import com.ning.metrics.collector.realtime.GlobalEventQueueStats; import com.ning.metrics.serialization.hadoop.FileSystemAccess; import com.google.inject.AbstractModule; import com.google.inject.Guice;
/* * Copyright 2010-2012 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.metrics.collector.guice; public class TestHealthChecksModule { @Test(groups = "fast") public void testConfigure() { try { final Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(FileSystemAccess.class).toInstance(Mockito.mock(FileSystemAccess.class)); bind(EventQueueProcessor.class).toInstance(Mockito.mock(EventQueueProcessorImpl.class)); bind(GlobalEventQueueStats.class).toInstance(Mockito.mock(GlobalEventQueueStats.class)); bind(EventSpoolDispatcher.class).toInstance(Mockito.mock(EventSpoolDispatcher.class)); bind(PersistentWriterFactory.class).toInstance(Mockito.mock(PersistentWriterFactory.class));
bind(WriterStats.class).toInstance(Mockito.mock(WriterStats.class));
3
senseobservationsystems/sense-android-library
sense-android-library/src/nl/sense_os/service/motion/StandardMotionSensor.java
[ "public static class DataPoint implements BaseColumns {\n\n public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE\n + \"/vnd.sense_os.data_point\";\n public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE\n + \"/vnd.sense_os.data_poi...
import java.util.List; import nl.sense_os.service.R; import nl.sense_os.service.constants.SenseDataTypes; import nl.sense_os.service.constants.SensorData.DataPoint; import nl.sense_os.service.provider.SNTP; import nl.sense_os.service.shared.SensorDataPoint; import nl.sense_os.service.shared.SensorDataPoint.DataType; import nl.sense_os.service.subscription.BaseDataProducer; import nl.sense_os.service.subscription.DataConsumer; import org.json.JSONObject; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.os.SystemClock; import android.util.Log;
package nl.sense_os.service.motion; public class StandardMotionSensor extends BaseDataProducer implements DataConsumer { private static final String TAG = "StandardMotionSensor"; private Context context; private long[] lastSampleTimes = new long[50]; private final List<Sensor> sensors; //private AccelerationFilter accelFilter; //private boolean isFakeLinearRequired ; public StandardMotionSensor(Context context) { this.context = context; sensors = MotionSensorUtils.getAvailableMotionSensors(context); //isFakeLinearRequired = MotionSensorUtils.isFakeLinearRequired( context ); } @Override public boolean isSampleComplete() { // only unregister if all sensors have submitted a new sample int count = 0; boolean complete = false; for (long time : lastSampleTimes) { if (time != 0) { count++; if (count >= sensors.size()) { complete = true; break; } } } return complete; } @Override
public void onNewData(SensorDataPoint dataPoint) {
2
Bernardo-MG/repository-pattern-java
src/test/java/com/wandrell/pattern/test/integration/repository/access/postgresql/springjdbc/ITQueryPostgreSqlSpringJdbcRepository.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.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.AbstractITQuery; 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.postgresql.springjdbc; /** * Integration tests for * {@link com.wandrell.pattern.repository.spring.SpringJdbcRepository * SpringJDBCRepository} implementing {@code AbstractITQuery}, using a * PostgreSQL in-memory database and Spring JDBC. * * @author Bernardo Martínez Garrido * @see com.wandrell.pattern.repository.spring.SpringJdbcRepository * SpringJDBCRepository */ @ContextConfiguration(locations = { TestContextPaths.DEFAULT, PersistenceContextPaths.SPRING_JDBC, RepositoryContextPaths.SPRING_JDBC }) @TestPropertySource(locations = { QueryPropertiesPaths.JDBC_QUERY, RepositoryPropertiesPaths.SPRING_JDBC, TestPropertiesPaths.ENTITY,
PersistenceProviderPropertiesPaths.SPRING_JDBC,
4
ProjectInfinity/ReportRTS
src/main/java/com/nyancraft/reportrts/command/sub/ClaimTicket.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.TicketClaimEvent; import com.nyancraft.reportrts.persistence.DataProvider; import com.nyancraft.reportrts.util.BungeeCord; import com.nyancraft.reportrts.util.Message; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.io.IOException;
package com.nyancraft.reportrts.command.sub; public class ClaimTicket { private static ReportRTS plugin = ReportRTS.getPlugin(); private static DataProvider data = plugin.getDataProvider(); /** * Initial handling of the Claim 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(args.length < 2) return false; if(!RTSPermissions.canClaimTicket(sender)) return true; if(!RTSFunctions.isNumber(args[1])) { sender.sendMessage(Message.errorTicketNaN(args[1])); return true; } int ticketId = Integer.parseInt(args[1]); // The ticket the user is trying to claim is not open. if(!plugin.tickets.containsKey(ticketId)){ sender.sendMessage(Message.ticketNotOpen(ticketId)); return true; } String name = sender.getName(); if(name == null) { sender.sendMessage(Message.error("Name is null! Try again.")); return true; } long timestamp = System.currentTimeMillis() / 1000; switch(data.setTicketStatus(ticketId, (sender instanceof Player) ? ((Player) sender).getUniqueId() : data.getConsole().getUuid(), sender.getName(), 1, false, System.currentTimeMillis() / 1000)) { case -3: // Ticket does not exist. sender.sendMessage(Message.ticketNotExists(ticketId)); return true; case -2: // Ticket status incompatibilities. sender.sendMessage(Message.errorTicketStatus()); return true; case -1: // Username is invalid or does not exist. sender.sendMessage(Message.error("Your user does not exist in the user table and was not successfully created.")); return true; case 0: // No row was affected... sender.sendMessage(Message.error("No entries were affected. Check console for errors.")); return true; case 1: // Everything went swimmingly if case is 1. break; default: sender.sendMessage(Message.error("A invalid result code has occurred.")); return true; } Player player = plugin.getServer().getPlayer(plugin.tickets.get(ticketId).getUUID()); if(player != null) { player.sendMessage(Message.ticketClaimUser(name)); player.sendMessage(Message.ticketText(plugin.tickets.get(ticketId).getMessage())); } plugin.tickets.get(ticketId).setStatus(1); // Workaround for CONSOLE. plugin.tickets.get(ticketId).setStaffUuid((!(sender instanceof Player) ? data.getConsole().getUuid() : ((Player) sender).getUniqueId())); plugin.tickets.get(ticketId).setStaffTime(timestamp); plugin.tickets.get(ticketId).setStaffName(name); try {
BungeeCord.globalNotify(Message.ticketClaim(name, args[1]), ticketId, NotificationType.MODIFICATION);
3
Ctrip-DI/Hue-Ctrip-DI
di-data-service/src/main/java/com/ctrip/di/ganglia/GangliaMetricService.java
[ "@Component\r\npublic class MetricConfigParser {\r\n\t@Value(\"${METRIC_CONFIG_FILE}\")\r\n\tprivate String metricConfigFile;\r\n\r\n\tpublic Clusters getClusters() throws JAXBException {\r\n\t\tJAXBContext jc = JAXBContext.newInstance(Clusters.class);\r\n\t\tUnmarshaller unmarshaller = jc.createUnmarshaller();\r\n...
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Singleton; import javax.xml.bind.JAXBException; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import com.ctrip.di.common.MetricConfigParser; import com.ctrip.di.common.util.UrlUtils; import com.ctrip.di.pojo.gen.Cluster; import com.ctrip.di.pojo.gen.Clusters; import com.ctrip.di.pojo.gen.Metric;
package com.ctrip.di.ganglia; /** * * Ganglia Metric Service: Provide all the metric information from ganglia * @author xgliao * */ @Service @Singleton public class GangliaMetricService { private static Log logger = LogFactory.getLog(GangliaMetricService.class); @Autowired private GangliaHttpParser httpParser; @Autowired private MetricConfigParser configParser; @Value("${GANGLIA_HOST_URL}") private String hostUrl; private Map<String, List<String>> metricMap = new ConcurrentHashMap<String, List<String>>(); private Map<String, List<String>> vimetricMap = new ConcurrentHashMap<String, List<String>>(); private Map<String, List<String>> clusterHostsMap = new ConcurrentHashMap<String, List<String>>(); public List<String> getMetricsByCluster(String cluster) { List<String> metricList = metricMap.get(cluster); if (metricList == null || metricList.isEmpty()) { try { initClusterInfo(false); return metricMap.get(cluster); } catch (Exception e) { logger.error("Ganglia Http Parser Error", e); throw new RuntimeException("Ganglia Http Parser Error", e); } } return metricList; } public List<String> getVIMetricsByCluster(String cluster) { List<String> metricList = vimetricMap.get(cluster); if (metricList == null || metricList.isEmpty()) { try { initVIMap(false); return vimetricMap.get(cluster); } catch (Exception e) { logger.error("Ganglia Http Parser Error", e); throw new RuntimeException("Ganglia Http Parser Error", e); } } return metricList; } public List<String> getHostListByCluster(String cluster) { List<String> hostList = clusterHostsMap.get(cluster); if (hostList == null || hostList.isEmpty()) { try { initClusterInfo(false); return vimetricMap.get(cluster); } catch (Exception e) { logger.error("Ganglia Http Parser Error", e); throw new RuntimeException("Ganglia Http Parser Error", e); } } return hostList; } @Scheduled(fixedDelay = 3600 * 1000) public void start() throws Exception { logger.info("Start Initialize Cluster Information:" + System.currentTimeMillis()); initClusterInfo(true); logger.info("End Initialize Cluster Information:" + System.currentTimeMillis()); logger.info("Start Initialize Very Important Metric Information:" + System.currentTimeMillis()); initVIMap(true); logger.info("End Initialize Very Important Metric Information:" + System.currentTimeMillis()); } private synchronized void initVIMap(boolean force) throws JAXBException { if (vimetricMap.isEmpty() || force) { Clusters clusters = configParser.getClusters();
List<Cluster> clusterList = clusters.getCluster();
2
neva-dev/felix-search-webconsole-plugin
src/main/java/com/neva/felix/webconsole/plugins/search/rest/BundleAssembleServlet.java
[ "public enum MessageType {\n SUCCESS,\n ERROR\n}", "public static void writeMessage(HttpServletResponse response, MessageType type, String text)\n throws IOException {\n writeMessage(response, type, text, Collections.<String, Object>emptyMap());\n}", "public class BundleJar {\n\n private Bund...
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType; import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage; import com.google.common.collect.Lists; import com.neva.felix.webconsole.plugins.search.core.BundleJar; import com.neva.felix.webconsole.plugins.search.core.OsgiExplorer; import com.neva.felix.webconsole.plugins.search.core.SearchMonitor; import com.neva.felix.webconsole.plugins.search.core.bundleassemble.BundleAssembleJob; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.neva.felix.webconsole.plugins.search.rest; public class BundleAssembleServlet extends RestServlet { private static final Logger LOG = LoggerFactory.getLogger(BundleAssembleServlet.class); public static final String ALIAS_NAME = "bundle-assemble"; private final SearchMonitor<BundleAssembleJob> monitor;
private final OsgiExplorer osgiExplorer;
3
czy1121/sdk3rd
ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/media/MoImage.java
[ "public class BitmapResource implements ImageResource {\n public final Bitmap bitmap;\n\n public BitmapResource(Bitmap bitmap) {\n this.bitmap = bitmap;\n }\n\n @Override\n public String toUri() {\n return null;\n }\n\n @Override\n public Bitmap toBitmap() {\n return bit...
import android.graphics.Bitmap; import android.support.annotation.NonNull; import java.io.File; import ezy.sdk3rd.social.share.image.resource.BitmapResource; import ezy.sdk3rd.social.share.image.resource.BytesResource; import ezy.sdk3rd.social.share.image.resource.FileResource; import ezy.sdk3rd.social.share.image.resource.ImageResource; import ezy.sdk3rd.social.share.image.resource.UrlResource;
package ezy.sdk3rd.social.share.media; public class MoImage implements IMediaObject { public ImageResource resource; public MoImage(@NonNull ImageResource resource) { this.resource = resource; } public MoImage(String url) { resource = new UrlResource(url); } public MoImage(File file) { resource = new FileResource(file); } public MoImage(byte[] bytes) {
resource = new BytesResource(bytes);
1
jMotif/SAX
src/test/java/net/seninp/jmotif/sax/datastructures/TestSAXRecords.java
[ "public enum NumerosityReductionStrategy {\n\n /** No reduction at all - all the words going make it into collection. */\n NONE(0),\n\n /** Exact - the strategy based on the exact string match. */\n EXACT(1),\n\n /** Classic - the Lin's and Keogh's MINDIST based strategy. */\n MINDIST(2);\n\n private final i...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import org.junit.Test; import net.seninp.jmotif.sax.NumerosityReductionStrategy; import net.seninp.jmotif.sax.SAXProcessor; import net.seninp.jmotif.sax.TSProcessor; import net.seninp.jmotif.sax.alphabet.NormalAlphabet; import net.seninp.jmotif.sax.datastructure.SAXRecord; import net.seninp.jmotif.sax.datastructure.SAXRecords;
package net.seninp.jmotif.sax.datastructures; /** * Testing SAX records store. * * @author psenin * */ public class TestSAXRecords { private static final String filenameTEK14 = "src/resources/test-data/TEK14.txt"; /** * Test the simple SAX conversion. * * @throws Exception if error occurs. */ @Test public void testProperIndexing() throws Exception { double[] ts1 = TSProcessor.readFileColumn(filenameTEK14, 0, 0); NormalAlphabet na = new NormalAlphabet(); SAXProcessor sp = new SAXProcessor();
SAXRecords res = sp.ts2saxViaWindow(ts1, 400, 6, na.getCuts(3),
5
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/fragment/AllLinesFragment.java
[ "public class OneLineActivity extends AppCompatActivity {\n\n private static final String TAG = OneLineActivity.class.getSimpleName();\n private Toolbar toolbar;\n private ViewPager viewPager;\n private SlidingTabLayout slidingTabLayout;\n\n private int linePosition;\n private Line line;\n\n pr...
import android.app.Activity; import android.support.v4.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import de.greenrobot.event.EventBus; import flying.grub.tamtime.activity.OneLineActivity; import flying.grub.tamtime.adapter.AllLinesAdapter; import flying.grub.tamtime.adapter.DividerItemDecoration; import flying.grub.tamtime.data.Data; import flying.grub.tamtime.data.map.Line; import flying.grub.tamtime.data.update.MessageUpdate; import flying.grub.tamtime.R;
package flying.grub.tamtime.fragment; public class AllLinesFragment extends Fragment { private RecyclerView recyclerView; private AllLinesAdapter adapter; private RecyclerView.LayoutManager layoutManager; private ArrayList<Line> lines; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.view_recycler, container, false); recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); getActivity().setTitle(getString(R.string.all_lines)); RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity()); recyclerView.addItemDecoration(itemDecoration); // specify an adapter (see also next example) lines = Data.getData().getMap().getLines(); adapter = new AllLinesAdapter(lines); recyclerView.setAdapter(adapter); adapter.SetOnItemClickListener(new AllLinesAdapter.OnItemClickListener() { @Override public void onItemClick(View v , int position) { selectitem(position); } }); return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onResume(){ super.onResume(); EventBus.getDefault().register(this); } @Override public void onPause() { EventBus.getDefault().unregister(this); super.onStop(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); } public void selectitem(int i){ Intent intent = new Intent(getActivity(), OneLineActivity.class); Bundle bundle = new Bundle(); bundle.putInt("id", i); intent.putExtras(bundle); startActivity(intent); getActivity().overridePendingTransition(R.anim.slide_from_right, R.anim.fade_scale_out); }
public void onEvent(MessageUpdate event){
5
JAYAndroid/whiteboard
client/src/com/yems/painter/handler/PainterHandler.java
[ "public class Painter extends BasePainter\n\n{\n\n\t@Override\n\tpublic void onCreate(Bundle savedInstanceState)\n\t{\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.painter_main);\n\n\t\t// ³õʼ»¯²¼¾ÖÊÓͼ\n\t\tsetView();\n\t\t// ³õʼ»¯¼àÌýÆ÷\n\t\tinitListener();\n\t\t// ³õʼ»¯²ÎÊý\n\t\tsetVal...
import java.io.File; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import com.yems.painter.Painter; import com.yems.painter.R; import com.yems.painter.activity.PainterPreferences; import com.yems.painter.common.Commons; import com.yems.painter.control.PainterCanvasControl; import com.yems.painter.entity.PainterSettings; import com.yems.painter.task.SaveTask; import com.yems.painter.utils.Utils;
package com.yems.painter.handler; /** * @ClassName: PainterHandler * @Description: »­°åÒµÎñ²Ù×÷Àà * @author lwtx-yems * @date 2015-3-10 ÏÂÎç01:51:10 * */ public class PainterHandler { private Context mContext; /** »­²¼¹ÜÀí¶ÔÏó*/ private PainterCanvasControl mCanvas; /** */ private PainterSettings mSettings; /** */ private Painter mPainter; public PainterHandler(Context context, PainterCanvasControl canvas, PainterSettings settings) { this.mCanvas = canvas; this.mContext = context; this.mSettings = settings; } /** * @return void * @description: ÉèÖû­±Ê¶ÔÏó * @date 2015-3-16 ÏÂÎç10:41:33 * @author: yems */ public void setPainter(Painter painter) { this.mPainter = painter; } /** * ±£´æÍ¼Æ¬ * * @param action ±£´æÍ¼Æ¬µÄͬʱ£¬¸½´øµÄ²Ù×÷ÀàÐÍ£¨È磺´ò¿ª¡¢Í˳öµÈ£© * @param canvas * @param settings */ public void savePicture(int action, PainterCanvasControl canvas, PainterSettings settings) { if (!Utils.getInstance().isStorageAvailable(mContext)) { return; } this.mCanvas = canvas; this.mSettings = settings; final int taskAction = action; new SaveTask(mContext, canvas, settings) { protected void onPostExecute(String pictureName) { Commons.mIsNewFile = false; if (taskAction == Commons.ACTION_SAVE_AND_SHARE) { startShareActivity(pictureName); } if (taskAction == Commons.ACTION_SAVE_AND_OPEN) { startOpenActivity(); } super.onPostExecute(pictureName); if (taskAction == Commons.ACTION_SAVE_AND_EXIT) { ((Painter) mContext).finish(); System.exit(0); } if (taskAction == Commons.ACTION_SAVE_AND_ROTATE) { rotateScreen(mPainter, mSettings); } } }.execute(); } /** * ¿ªÆô·ÖÏí½çÃæ * * @param pictureName * Òª·ÖÏíµÄͼƬÃû³Æ */ public void startShareActivity(String pictureName) { Uri uri = Uri.fromFile(new File(pictureName)); Intent i = new Intent(Intent.ACTION_SEND); i.setType(Commons.PICTURE_MIME); i.putExtra(Intent.EXTRA_STREAM, uri); mContext.startActivity(Intent.createChooser(i, mContext.getString(R.string.share_image_title))); } /** * ¿ªÆô´ò¿ªÎļþµÄ½çÃæ */ public void startOpenActivity() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setDataAndType(Uri.fromFile(new File(Utils.getInstance() .getSaveDir(mContext))), Commons.PICTURE_MIME); ((Painter) mContext).startActivityForResult( Intent.createChooser(intent, mContext.getString(R.string.open_prompt_title)), Commons.REQUEST_OPEN); } /** * ÐýתÆÁÄ»µÄ·½Ïò * * @param activity * @param settings */ public void rotateScreen(Activity activity, PainterSettings settings) { if (activity.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { settings.setOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); Utils.getInstance().saveSettings(activity, settings); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else { settings.setOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); Utils.getInstance().saveSettings(activity, settings); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } /** * @param context * @param settings * @return * @description: ´´½¨·ÖÏí½çÃæ * @date: 2015-3-16 ÉÏÎç11:35:24 * @author£º yems */ public Dialog createDialogShare(Context context, final PainterSettings settings) { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setMessage(R.string.share_prompt); alert.setCancelable(false); alert.setTitle(R.string.share_prompt_title); alert.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { savePicture(Commons.ACTION_SAVE_AND_SHARE, mCanvas, mSettings); } }); alert.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startShareActivity(settings.getLastPicture()); } }); return alert.create(); } /** * @param context * @return * @description: ´´½¨Çå³ýͼÐεĽçÃæ * @date: 2015-3-16 ÉÏÎç11:32:54 * @author£º yems */ public Dialog createDialogClear(Context context) { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setMessage(R.string.clear_bitmap_prompt); alert.setCancelable(false); alert.setTitle(R.string.clear_bitmap_prompt_title); alert.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mPainter.clear(); } }); alert.setNegativeButton(R.string.no, null); return alert.create(); } /** * @return void * @description: ´ò¿ª²ÎÊýÉèÖýçÃæ * @date 2015-3-16 ÏÂÎç10:39:28 * @author: yems */ public void showPreferences() { Intent intent = new Intent();
intent.setClass(mContext, PainterPreferences.class);
2
EsupPortail/esup-papercut
src/main/java/org/esupportail/papercut/services/EsupPaperCutService.java
[ "public class EsupPapercutContext {\n\n\tString papercutContext = \"univ-ville\";\n\t\n String numCommandePrefix = \"EsupPaperCut-\";\n\t\n\tString papercutUserUidAttr = \"uid\";\n\t\n\tString userEmail = \"email\";\n\t\n\tString validatePayboxJustWithRedirection = \"false\";\n\t\n\tString requeteNbTransactions ...
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.esupportail.papercut.config.EsupPapercutContext; import org.esupportail.papercut.dao.PapercutDaoService; import org.esupportail.papercut.domain.PayBoxForm; import org.esupportail.papercut.domain.PayPapercutTransactionLog; import org.esupportail.papercut.domain.PayPapercutTransactionLog.PayMode; import org.esupportail.papercut.domain.UserPapercutInfos; import org.esupportail.papercut.domain.izlypay.IzlyPayCallBack; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Licensed to EsupPortail under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * EsupPortail 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.esupportail.papercut.services; @Service public class EsupPaperCutService { private final Logger log = LoggerFactory.getLogger(getClass()); @Autowired PapercutDaoService papercutDaoService; @Autowired PayBoxService payBoxService; @Autowired IzlyPayService izlyPayService; @Autowired PapercutService papercutService; public void setPayBoxService(PayBoxService payBoxService) { this.payBoxService = payBoxService; } public void setPapercutService(PapercutService papercutService) { this.papercutService = papercutService; } public List<PayMode> getPayModes(EsupPapercutContext context) { List<PayMode> payModes = new ArrayList<PayMode>(); if(context != null) { if(context.getPaybox() != null) { payModes.add(PayMode.PAYBOX); } if(context.getIzlypay() != null) { payModes.add(PayMode.IZLYPAY); } } return payModes; }
public UserPapercutInfos getUserPapercutInfos(EsupPapercutContext context, String uid) {
5
GoogleCloudPlatform/bigquery-data-lineage
src/test/java/com/google/cloud/solutions/datalineage/converter/LineageTagPropagationConverterFactoryTest.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 org.junit.runners.JUnit4; import static com.google.cloud.solutions.datalineage.converter.ProtoJsonConverter.parseAsList; import static com.google.cloud.solutions.datalineage.converter.ProtoJsonConverter.parseJson; import static com.google.common.truth.Truth.assertThat; import com.google.cloud.datacatalog.v1beta1.Tag; import com.google.cloud.solutions.datalineage.model.LineageMessages.CompositeLineage; import com.google.cloud.solutions.datalineage.model.TagsForCatalog; import com.google.cloud.solutions.datalineage.service.DataCatalogService; import com.google.cloud.solutions.datalineage.testing.FakeDataCatalogStub; import com.google.cloud.solutions.datalineage.testing.TestResourceLoader; import com.google.common.collect.ImmutableList; import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith;
/* * 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.converter; @RunWith(JUnit4.class) public final class LineageTagPropagationConverterFactoryTest { @Test public void processor_outputTableMissingInCatalog_empty() throws IOException { FakeDataCatalogStub fakeStub = FakeDataCatalogStub.buildWithTestData( ImmutableList.of("datacatalog-objects/TableA_entry.json", "datacatalog-objects/simple_report_view_entry.json"), ImmutableList.of( "datacatalog-objects/TableA_tags.json", "datacatalog-objects/simple_report_view_tags.json")); LineageTagPropagationConverterFactory propagationConverterFactory = LineageTagPropagationConverterFactory.builder()
.lineage(parseJson(TestResourceLoader.load(
1
Doist/JobSchedulerCompat
library/src/test/java/com/doist/jobschedulercompat/scheduler/alarm/AlarmContentObserverServiceTest.java
[ "public class JobInfo {\n private static final String LOG_TAG = \"JobInfoCompat\";\n\n @IntDef({\n NETWORK_TYPE_NONE,\n NETWORK_TYPE_ANY,\n NETWORK_TYPE_UNMETERED,\n NETWORK_TYPE_NOT_ROAMING,\n NETWORK_TYPE_CELLULAR\n })\n @Retention(RetentionPolicy...
import com.doist.jobschedulercompat.JobInfo; import com.doist.jobschedulercompat.job.JobStatus; import com.doist.jobschedulercompat.job.JobStore; import com.doist.jobschedulercompat.util.DeviceTestUtils; import com.doist.jobschedulercompat.util.JobCreator; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ServiceController; import org.robolectric.annotation.Config; import android.app.Application; import android.content.ContentResolver; import android.net.Uri; import android.os.Build; import androidx.test.core.app.ApplicationProvider; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.isA; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.robolectric.Shadows.shadowOf;
package com.doist.jobschedulercompat.scheduler.alarm; @RunWith(RobolectricTestRunner.class) @Config(sdk = Build.VERSION_CODES.KITKAT) public class AlarmContentObserverServiceTest { private Application application;
private JobStore jobStore;
2
miurahr/tmpotter
src/main/java/org/tmpotter/filters/tmx/TmxFilter.java
[ "@SuppressWarnings(\"serial\")\npublic class Document {\n\n private final ArrayList<String> documentSegments;\n\n public Document() {\n documentSegments = new ArrayList<>();\n }\n\n public Document(List<String> sentences) {\n documentSegments = new ArrayList<>(sentences);\n }\n\n pub...
import org.tmpotter.util.TmxWriter2; import java.io.File; import java.util.HashMap; import java.util.Map; import org.tmpotter.core.Document; import org.tmpotter.core.TmxEntry; import org.tmpotter.filters.FilterContext; import org.tmpotter.filters.IFilter; import org.tmpotter.filters.IParseCallback; import org.tmpotter.util.Language; import org.tmpotter.util.TmxReader2;
/* ************************************************************************* * * TMPotter - Bi-text Aligner/TMX Editor * * Copyright (C) 2016 Hiroshi Miura * * This file is part of TMPotter. * * TMPotter 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. * * TMPotter 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 TMPotter. If not, see http://www.gnu.org/licenses/. * * *************************************************************************/ package org.tmpotter.filters.tmx; /** * TMX import filter. * @author Hiroshi Miura */ public class TmxFilter implements IFilter { private TmxFilter self; /** * Constructor. */ public TmxFilter() { self = this; } /** * Return file format name 'TMX'. * @return format name 'TMX'. */ public String getFileFormatName() { return "TMX"; } /** * Return hint string. * @return hint string. */ public String getHint() { return "TMX file."; } /** * TMX filter read UTF-8 file and not encoding variable. * @return false because UTF-8 encoding fixed. */ public boolean isSourceEncodingVariable() { return false; } /** * TMX filter read UTF-8 file and not encoding variable. * @return false because UTF-8 encoding fixed. */ public boolean isTargetEncodingVariable() { return false; } /** * Return fuzzy mark. * @return mark. */ public String getFuzzyMark() { return ""; } /** * TMX is combined format. * @return true */ public boolean isCombinedFileFormat() { return true; } /** * Check the file is supported with this filter. * @param inFile Source file. * @param config filter's configuration options * @param context processing context * @return true if supported, otherwise false. */ public boolean isFileSupported(File inFile, Map<String, String> config, FilterContext context) { if (inFile.getName().endsWith(".tmx")) { return true; } return false; } /** * Parse file. * @param inFile file to parse * @param config filter's configuration options * @param fc filter context. * @param callback callback for parsed data * @throws Exception when error is happened. */ public void parseFile(File inFile, Map<String, String> config, FilterContext fc, IParseCallback callback) throws Exception { TmxReader2.LoadCallback callbackLoader = new TmxReader2.LoadCallback() { @Override public boolean onEntry(TmxReader2.ParsedTu tu, TmxReader2.ParsedTuv tuvSource, TmxReader2.ParsedTuv tuvTranslation, boolean isParagraphType) { if (tuvSource == null) { return false; } if (tuvTranslation != null) { addTuv(tu, tuvSource, tuvTranslation); } else { for (TmxReader2.ParsedTuv tuv : tu.tuvs) { if (tuv != tuvSource) { addTuv(tu, tuvSource, tuv); } } } return true; } private void addTuv(TmxReader2.ParsedTu tu, TmxReader2.ParsedTuv tuvSource, TmxReader2.ParsedTuv tuvTranslation) { /* changer = StringUtil.nvl(tuvTranslation.changeid, tuvTranslation.creationid, tu.changeid, tu.creationid); changeDate = StringUtil.nvlLong(tuvTranslation.changedate, tuvTranslation.creationdate, tu.changedate, tu.creationdate); creator = StringUtil.nvl(tuvTranslation.creationid, tu.creationid); creationDate = StringUtil.nvlLong(tuvTranslation.creationdate, tu.creationdate); */ callback.addEntry(null, tuvSource.text, tuvTranslation.text, false, tu.note, null, self); } }; TmxReader2 reader = new TmxReader2(); reader.readTmx(inFile, fc.getSourceLang(), fc.getTargetLang(), false, false, callbackLoader); } /** * Parse file. * @param sourceFile source file * @param translateFile translated file * @param config filter's configuration options * @param fc filter context. * @param callback callback for store aligned data * @throws Exception when error is happened. */ @Override public void parseFile(File sourceFile, File translateFile, Map<String, String> config, FilterContext fc, IParseCallback callback) throws Exception { parseFile(sourceFile, config, fc, callback); } @Override public boolean isSaveSupported() { return true; } @Override
public void saveFile(File outFile, Document docOriginal, Document docTranslation,
0
el-groucho/jsRules
src/test/java/org/grouchotools/jsrules/loader/RuleLoaderTest.java
[ "public enum Operator {\n GT {\n @Override\n public Boolean compare(Object left, Object right) throws InvalidParameterException {\n Number leftNumber = getNumber(left);\n Number rightNumber = getNumber(right);\n return leftNumber.doubleValue() > rightNumber.doubleVa...
import org.grouchotools.jsrules.Operator; import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.Rule; import org.grouchotools.jsrules.config.ParamConfig; import org.grouchotools.jsrules.config.ResponseConfig; import org.grouchotools.jsrules.config.RuleConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.RuleLoaderImpl; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.rules.ExpectedException; import org.mockito.InjectMocks; import org.mockito.Mock; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks;
/* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class RuleLoaderTest { @org.junit.Rule public ExpectedException exception= ExpectedException.none(); private final String ruleName = "Left is greater than 10"; private final String leftParameterName = "left"; private final String rightParameterName = "right"; private final Boolean response = true; @InjectMocks private RuleLoaderImpl ruleLoader; @Mock private ParamLoader paramLoader; @Mock private ResponseLoader responseLoader; public RuleLoaderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() throws Exception { initMocks(this); when(paramLoader.load(getLeftParamConfig())). thenReturn(getLeftRuleParameter()); when(paramLoader.load(getRightParamConfig())). thenReturn(getRightRuleParameter()); when(responseLoader.load(getResponseConfig())).thenReturn(response); } @After public void tearDown() { } @Test public void loadFromRuleConfigTest() throws Exception { Rule mockRule = getRule(); RuleConfig ruleConfig = getRuleConfig(); assertEquals(mockRule, ruleLoader.load(ruleConfig)); } @Test public void loadFromRuleConfigInvalidOperatorTest() throws Exception { exception.expect(InvalidConfigException.class); RuleConfig ruleConfig = getRuleConfig(); ruleConfig.setOperator("invalid!"); ruleLoader.load(ruleConfig); } private RuleConfig getRuleConfig() { String operator = "GT"; ResponseConfig responseConfig = getResponseConfig(); RuleConfig ruleConfig = new RuleConfig(ruleName, getLeftParamConfig(), operator, getRightParamConfig(), responseConfig); return ruleConfig; } private ParamConfig getLeftParamConfig() { String leftParameterClass = "Long"; String leftParameterStaticValue = null; ParamConfig leftParamConfig = new ParamConfig(leftParameterName, leftParameterClass, leftParameterStaticValue); return leftParamConfig; } private ParamConfig getRightParamConfig() { String rightParameterClass = "Long"; String rightParameterStaticValue = "10"; ParamConfig rightParamConfig = new ParamConfig(rightParameterName, rightParameterClass, rightParameterStaticValue); return rightParamConfig; } private Rule getRule() { Parameter<Long> leftParameter = getLeftRuleParameter();
Operator operator = Operator.GT;
0
karsany/obridge
obridge-main/src/main/java/org/obridge/generators/EntityObjectGenerator.java
[ "public class OBridgeConfiguration {\n\n public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;\n public static final boolean ADD_ASSERT = false;\n\n private String jdbcUrl;\n private String sourceRoot;\n private String rootPackageName;\n private Packages packages;\n private Loggi...
import org.obridge.util.CodeFormatter; import org.obridge.util.DataSourceProvider; import org.obridge.util.MustacheRunner; import org.obridge.util.OBridgeException; import java.beans.PropertyVetoException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import org.obridge.context.OBridgeConfiguration; import org.obridge.dao.TypeDao; import org.obridge.mappers.PojoMapper; import org.obridge.model.data.TypeAttribute; import org.obridge.model.generator.Pojo;
/* * The MIT License (MIT) * * Copyright (c) 2016 Ferenc Karsany * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.obridge.generators; /** * Created by fkarsany on 2015.01.28.. */ public final class EntityObjectGenerator { private EntityObjectGenerator() { } public static void generate(OBridgeConfiguration c) { try { String packageName = c.getRootPackageName() + "." + c.getPackages().getEntityObjects(); String outputDir = c.getSourceRoot() + "/" + packageName.replace(".", "/") + "/"; TypeDao typeDao = new TypeDao(DataSourceProvider.getDataSource(c.getJdbcUrl())); List<String> types = typeDao.getTypeList(c); for (String typeName : types) { generateEntityObject(packageName, outputDir, typeName, typeDao.getTypeAttributes(typeName, c.getSourceOwner())); } if (types.size() == 0) { generateEntityObject(packageName, outputDir, "Dummy", new ArrayList<>()); } if (OBridgeConfiguration.GENERATE_SOURCE_FOR_PLSQL_TYPES) { List<String> embeddedTypes = typeDao.getEmbeddedTypeList(c.getSourceOwner()); for (String typeName : embeddedTypes) { generateEntityObject(packageName, outputDir, typeName, typeDao.getEmbeddedTypeAttributes(typeName, c.getSourceOwner())); } } } catch (PropertyVetoException | IOException e) { throw new OBridgeException(e); } } private static void generateEntityObject(String packageName, String outputDir, String typeName, List<TypeAttribute> typeAttributes) throws IOException {
Pojo pojo = PojoMapper.typeToPojo(typeName, typeAttributes);
2
yammer/telemetry
telemetry-agent/src/test/java/com/yammer/telemetry/agent/TelemetryTransformerTest.java
[ "public interface ClassInstrumentationHandler {\n boolean transformed(CtClass cc, ClassPool pool);\n}", "public abstract class SubTypeInstrumentationHandler implements ClassInstrumentationHandler {\n private static final Logger LOGGER = Logger.getLogger(SubTypeInstrumentationHandler.class.getName());\n p...
import com.yammer.telemetry.instrumentation.ClassInstrumentationHandler; import com.yammer.telemetry.agent.handlers.SubTypeInstrumentationHandler; import com.yammer.telemetry.test.TransformingClassLoader; import com.yammer.telemetry.instrumentation.TelemetryTransformer; import javassist.*; import org.junit.Test; import java.io.IOException; import static com.yammer.telemetry.agent.TelemetryTransformerTest.ClassUtils.wrapMethod; import static org.junit.Assert.*;
package com.yammer.telemetry.agent; public class TelemetryTransformerTest { @Test public void testUnmodifiedWhenNoHandlersAdded() throws Exception { TelemetryTransformer transformer = new TelemetryTransformer(); assertNull(transformer.transform(getClass().getClassLoader(), "com/yammer/telemetry/agent/test/SimpleBean", null, null, new byte[0])); } @Test public void testUnmodifiedWhenNotHandled() throws Exception { TelemetryTransformer transformer = new TelemetryTransformer(); transformer.addHandler(new ClassInstrumentationHandler() { @Override public boolean transformed(CtClass cc, ClassPool pool) { return false; } }); assertNull(transformer.transform(getClass().getClassLoader(), "com/yammer/telemetry/agent/test/SimpleBean", null, null, new byte[0])); } @Test public void testModifiedWhenHandled() throws Exception { TelemetryTransformer transformer = new TelemetryTransformer(); transformer.addHandler(new ClassInstrumentationHandler() { @Override public boolean transformed(CtClass cc, ClassPool pool) { return true; } }); // Note we didn't actually change anything but claimed we did so expect input & output bytes to match assertArrayEquals(new byte[0], transformer.transform(getClass().getClassLoader(), "com/yammer/telemetry/agent/test/SimpleBean", null, null, new byte[0])); } @Test public void testModificationViaClassLoader() throws Exception { TelemetryTransformer transformer = new TelemetryTransformer();
transformer.addHandler(new SubTypeInstrumentationHandler("com.yammer.telemetry.agent.test.SimpleBean") {
1
rust-keylock/rust-keylock-ui
java/src/main/java/org/rustkeylock/ui/callbacks/ShowEntryCb.java
[ "public interface RklController {\n /**\n * Sets a native callback to the Rust world that can be used to send data to Rust on actions\n * @param consumer\n */\n void setCallback(Consumer<Object> consumer);\n}", "public class ShowEntryController extends BaseController implements RklController, In...
import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import org.astonbitecode.j4rs.api.invocation.NativeCallbackToRustChannelSupport; import org.rustkeylock.controllers.RklController; import org.rustkeylock.controllers.ShowEntryController; import org.rustkeylock.fxcomponents.RklStage; import org.rustkeylock.japi.JavaEntry; import org.rustkeylock.ui.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL;
// Copyright 2019 astonbitecode // This file is part of rust-keylock password manager. // // rust-keylock 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. // // rust-keylock 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 rust-keylock. If not, see <http://www.gnu.org/licenses/>. package org.rustkeylock.ui.callbacks; public class ShowEntryCb extends NativeCallbackToRustChannelSupport { private final Logger logger = LoggerFactory.getLogger(this.getClass());
private RklStage stage;
2
mgilangjanuar/GoSCELE
app/src/main/java/com/mgilangjanuar/dev/goscele/modules/main/view/HomeFragment.java
[ "public abstract class BaseFragment extends Fragment {\n\n @LayoutRes\n public abstract int findLayout();\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View view = inflater.inflate(findLayout(), ...
import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; import com.mgilangjanuar.dev.goscele.R; import com.mgilangjanuar.dev.goscele.base.BaseFragment; import com.mgilangjanuar.dev.goscele.modules.forum.list.view.ForumListActivity; import com.mgilangjanuar.dev.goscele.modules.forum.list.view.ForumSearchActivity; import com.mgilangjanuar.dev.goscele.modules.main.adapter.HomeRecyclerViewAdapter; import com.mgilangjanuar.dev.goscele.modules.main.listener.HomeListener; import com.mgilangjanuar.dev.goscele.modules.main.presenter.HomePresenter; import butterknife.BindView;
package com.mgilangjanuar.dev.goscele.modules.main.view; /** * Created by mgilangjanuar (mgilangjanuar@gmail.com) * * @since 2017 */ public class HomeFragment extends BaseFragment implements HomeListener { @BindView(R.id.toolbar_home) Toolbar toolbar; @BindView(R.id.recycler_view_home) RecyclerView recyclerView; @BindView(R.id.text_status_home) TextView textStatus; @BindView(R.id.swipe_refresh_home) SwipeRefreshLayout swipeRefreshLayout;
HomePresenter presenter = new HomePresenter(this);
5
CrazyBBB/tenhou-visualizer
src/main/java/tenhouvisualizer/app/main/MjlogTreeControl.java
[ "public class Analyzer implements IAnalyzer, SceneContainer {\r\n private final static String[] haiStr = {\r\n \"1m\", \"1m\", \"1m\", \"1m\", \"2m\", \"2m\", \"2m\", \"2m\", \"3m\", \"3m\", \"3m\", \"3m\",\r\n \"4m\", \"4m\", \"4m\", \"4m\", \"赤5m\", \"5m\", \"5m\", \"5m\", \"6m\", \"6m\",...
import javafx.scene.control.TreeView; import tenhouvisualizer.domain.analyzer.Analyzer; import tenhouvisualizer.domain.analyzer.ParseHandler; import tenhouvisualizer.domain.model.Kyoku; import tenhouvisualizer.domain.model.MahjongScene; import tenhouvisualizer.domain.model.Mjlog; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.ByteArrayInputStream; import java.util.List;
package tenhouvisualizer.app.main; public class MjlogTreeControl extends TreeView<Mjlog> { public MjlogTreeControl() { this.setShowRoot(false); } public void showMjlogContent(byte[] xml, int position) { List<Kyoku> scenesList; try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser; saxParser = saxParserFactory.newSAXParser(); Analyzer analyzer = new Analyzer(position);
ParseHandler parseHandler = new ParseHandler(analyzer);
1
blind-coder/SpaceTrader
SpaceTrader/src/main/java/de/anderdonau/spacetrader/FragmentSystemInformation.java
[ "public class CrewMember implements Serializable {\n\tpublic int nameIndex;\n\tpublic int pilot;\n\tpublic int fighter;\n\tpublic int trader;\n\tpublic int engineer;\n\tpublic int curSystem;\n\n\tpublic CrewMember() {\n\t\tnameIndex = 1;\n\t\tpilot = 1;\n\t\tfighter = 1;\n\t\ttrader = 1;\n\t\tengineer = 1;\n\t\tcur...
import de.anderdonau.spacetrader.DataTypes.Politics; import de.anderdonau.spacetrader.DataTypes.Popup; import de.anderdonau.spacetrader.DataTypes.Shields; import de.anderdonau.spacetrader.DataTypes.ShipTypes; import de.anderdonau.spacetrader.DataTypes.SolarSystem; import de.anderdonau.spacetrader.DataTypes.SpecialEvents; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import java.util.Random; import de.anderdonau.spacetrader.DataTypes.CrewMember; import de.anderdonau.spacetrader.DataTypes.MyFragment;
/* * Copyright (c) 2014 Benjamin Schieder * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package de.anderdonau.spacetrader; public class FragmentSystemInformation extends MyFragment { Main main; String[][] NewsPaperNames = {{"* Arsenal", "The Grassroot", "Kick It!"}, /* Anarchy */ {"The Daily Worker", "The People's Voice", "* Proletariat"}, /* Capitalist */ {"Planet News", "* Times", "Interstate Update"}, /* Communist */ {"The Objectivist", "* Market", "The Invisible Hand"}, /* Confederacy */ {"+ Memo", "News From The Board", "Status Report"}, /* Corporate */ {"Pulses", "Binary Stream", "The System Clock"}, /* Cybernetic */ {"The Daily Planet", "* Majority", "Unanimity"}, /* Democracy */ {"The Command", "Leader's Voice", "* Mandate"}, /* Dictatorship */ {"State Tribune", "Motherland News", "Homeland Report"}, /* Fascist */ {"News from the Keep", "The Town Crier", "* Herald"}, /* Feudal */ {"General Report", "+ Dispatch", "* Sentry"}, /* Military */ {"Royal Times", "The Loyal Subject", "The Fanfare"}, /* Monarchy */ {"Pax Humani", "Principle", "* Chorus"}, /* Pacifist */ {"All for One", "Brotherhood", "The People's Syndicate"}, /* Socialist */ {"The Daily Koan", "Haiku", "One Hand Clapping"}, /* Satori */ {"The Future", "Hardware Dispatch", "TechNews"}, /* Technocracy */ {"The Spiritual Advisor", "Church Tidings", "The Temple Tribune"}, /* Theocracy */}; String[][] CannedNews = {{"Riots, Looting Mar Factional Negotiations.", "Communities Seek Consensus.", "Successful Bakunin Day Rally!", "Major Faction Conflict Expected for the Weekend!"}, {"Editorial: Taxes Too High!", "Market Indices Read Record Levels!", "Corporate Profits Up!", "Restrictions on Corporate Freedom Abolished by Courts!"}, {"Party Reports Productivity Increase.", "Counter-Revolutionary Bureaucrats Purged from Party!", "Party: Bold New Future Predicted!", "Politburo Approves New 5-Year Plan!"}, {"States Dispute Natural Resource Rights!", "States Denied Federal Funds over Local Laws!", "Southern States Resist Federal Taxation for Capital Projects!", "States Request Federal Intervention in Citrus Conflict!"}, {"Robot Shortages Predicted for Q4.", "Profitable Quarter Predicted.", "CEO: Corporate Rebranding Progressing.", "Advertising Budgets to Increase."}, {"Olympics: Software Beats Wetware in All Events!", "New Network Protocols To Be Deployed.", "Storage Banks to be Upgraded!", "System Backup Rescheduled."}, {"Local Elections on Schedule!", "Polls: Voter Satisfaction High!", "Campaign Spending Aids Economy!", "Police, Politicians Vow Improvements."}, {"New Palace Planned; Taxes Increase.", "Future Presents More Opportunities for Sacrifice!", "Insurrection Crushed: Rebels Executed!", "Police Powers to Increase!"}, {"Drug Smugglers Sentenced to Death!", "Aliens Required to Carry Visible Identification at All Times!", "Foreign Sabotage Suspected.", "Stricter Immigration Laws Installed."}, {"Farmers Drafted to Defend Lord's Castle!", "Report: Kingdoms Near Flashpoint!", "Baron Ignores Ultimatum!", "War of Succession Threatens!"}, {"Court-Martials Up 2% This Year.", "Editorial: Why Wait to Invade?", "HQ: Invasion Plans Reviewed.", "Weapons Research Increases Kill-Ratio!"}, {"King to Attend Celebrations.", "Queen's Birthday Celebration Ends in Riots!", "King Commissions New Artworks.", "Prince Exiled for Palace Plot!"}, {"Dialog Averts Eastern Conflict! ", "Universal Peace: Is it Possible?", "Editorial: Life in Harmony.", "Polls: Happiness Quotient High! "}, {"Government Promises Increased Welfare Benefits!", "State Denies Food Rationing Required to Prevent Famine.", "'Welfare Actually Boosts Economy,' Minister Says.", "Hoarder Lynched by Angry Mob!"}, {"Millions at Peace.", "Sun Rises.", "Countless Hearts Awaken.", "Serenity Reigns."}, {"New Processor Hits 10 ZettaHerz!", "Nanobot Output Exceeds Expectation.", "Last Human Judge Retires.", "Software Bug Causes Mass Confusion."}, {"High Priest to Hold Special Services.", "Temple Restoration Fund at 81%.", "Sacred Texts on Public Display.", "Dozen Blasphemers Excommunicated!"}}; private GameState gameState; @Override public void onAttach(Activity activity) { super.onAttach(activity); this.main = (Main) activity; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); this.gameState = (GameState) args.getSerializable("gamestate"); final View rootView = inflater.inflate(R.layout.fragment_system_information, container, false); SolarSystem CURSYSTEM = gameState.SolarSystem[gameState.Mercenary[0].curSystem]; CURSYSTEM.visited = true; TextView textView = (TextView) rootView.findViewById(R.id.strSysInfoName); textView.setText(main.SolarSystemName[CURSYSTEM.nameIndex]); textView = (TextView) rootView.findViewById(R.id.strSysInfoSize); textView.setText(main.SystemSize[CURSYSTEM.size]); textView = (TextView) rootView.findViewById(R.id.strSysInfoTechLevel); textView.setText(main.techLevel[CURSYSTEM.techLevel]); textView = (TextView) rootView.findViewById(R.id.strSysInfoGovernment);
textView.setText(Politics.mPolitics[CURSYSTEM.politics].name);
2
keeps/roda-in
src/main/java/org/roda/rodain/core/Constants.java
[ "public class BagitSipCreator extends SimpleSipCreator implements SIPObserver, ISipCreator {\n private static final Logger LOGGER = LoggerFactory.getLogger(BagitSipCreator.class.getName());\n private int countFilesOfZip;\n private int currentSIPsize = 0;\n private int currentSIPadded = 0;\n private int repProc...
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.roda.rodain.core.creation.BagitSipCreator; import org.roda.rodain.core.creation.EarkSip2Creator; import org.roda.rodain.core.creation.EarkSipCreator; import org.roda.rodain.core.creation.HungarianSipCreator; import org.roda.rodain.core.creation.ShallowSipCreator; import org.roda.rodain.core.schema.IPContentType; import org.roda.rodain.core.schema.RepresentationContentType; import com.fasterxml.jackson.annotation.JsonCreator;
public static final String I18N_METADATA_DIFF_FOLDER_DESCRIPTION = "metadata.diffFolder.description"; public static final String I18N_METADATA_DIFF_FOLDER_TITLE = "metadata.diffFolder.title"; public static final String I18N_METADATA_EMPTY_FILE_DESCRIPTION = "metadata.emptyFile.description"; public static final String I18N_METADATA_EMPTY_FILE_TITLE = "metadata.emptyFile.title"; public static final String I18N_METADATA_SAME_FOLDER_DESCRIPTION = "metadata.sameFolder.description"; public static final String I18N_METADATA_SAME_FOLDER_TITLE = "metadata.sameFolder.title"; public static final String I18N_METADATA_SINGLE_FILE_DESCRIPTION = "metadata.singleFile.description"; public static final String I18N_METADATA_SINGLE_FILE_TITLE = "metadata.singleFile.title"; public static final String I18N_METADATA_TEMPLATE_DESCRIPTION = "metadata.template.description"; public static final String I18N_METADATA_TEMPLATE_TITLE = "metadata.template.title"; public static final String I18N_RULECELL_CREATED_ITEM = "RuleCell.createdItem"; public static final String I18N_RULEMODALPANE_ASSOCIATION_METHOD = "RuleModalPane.associationMethod"; public static final String I18N_RULEMODALPANE_CHOOSE_DIRECTORY = "RuleModalPane.chooseDirectory"; public static final String I18N_RULEMODALPANE_CHOOSE_FILE = "RuleModalPane.chooseFile"; public static final String I18N_RULEMODALPANE_METADATA_METHOD = "RuleModalPane.metadataMethod"; public static final String I18N_RULEMODALPANE_METADATA_PATTERN = "RuleModalPane.metadataPattern"; public static final String I18N_RULEMODALPROCESSING_CREATED_PREVIEWS = "RuleModalProcessing.createdPreviews"; public static final String I18N_RULEMODALPROCESSING_CREATING_PREVIEW = "RuleModalProcessing.creatingPreview"; public static final String I18N_RULEMODALPROCESSING_PROCESSED_DIRS_FILES = "RuleModalProcessing.processedDirsFiles"; public static final String I18N_RULEMODALREMOVING_REMOVED_FORMAT = "RuleModalRemoving.removedFormat"; public static final String I18N_RULEMODALREMOVING_TITLE = "RuleModalRemoving.title"; public static final String I18N_SCHEMAPANE_ADD = "SchemaPane.add"; public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_CONTENT = "SchemaPane.confirmNewScheme.content"; public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_HEADER = "SchemaPane.confirmNewScheme.header"; public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_TITLE = "SchemaPane.confirmNewScheme.title"; public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_CONTENT = "SchemaPane.confirmRemove.content"; public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_HEADER = "SchemaPane.confirmRemove.header"; public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_TITLE = "SchemaPane.confirmRemove.title"; public static final String I18N_SCHEMAPANE_CREATE = "SchemaPane.create"; public static final String I18N_SCHEMAPANE_DRAG_HELP = "SchemaPane.dragHelp"; public static final String I18N_SCHEMAPANE_HELP_TITLE = "SchemaPane.help.title"; public static final String I18N_SCHEMAPANE_NEW_NODE = "SchemaPane.newNode"; public static final String I18N_SCHEMAPANE_OR = "SchemaPane.or"; public static final String I18N_SCHEMAPANE_REMOVE = "SchemaPane.remove"; public static final String I18N_SCHEMAPANE_TITLE = "SchemaPane.title"; public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_CONTENT = "SchemaPane.tooManySelected.content"; public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_HEADER = "SchemaPane.tooManySelected.header"; public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_TITLE = "SchemaPane.tooManySelected.title"; public static final String I18N_SIMPLE_SIP_CREATOR_COPYING_DATA = "SimpleSipCreator.copyingData"; public static final String I18N_SIMPLE_SIP_CREATOR_DOCUMENTATION = "SimpleSipCreator.documentation"; public static final String I18N_SIMPLE_SIP_CREATOR_INIT_ZIP = "SimpleSipCreator.initZIP"; public static final String I18N_SIMPLE_SIP_CREATOR_CREATING_STRUCTURE = "SimpleSipCreator.creatingStructure"; public static final String I18N_SIMPLE_SIP_CREATOR_COPYING_METADATA = "SimpleSipCreator.copyingMetadata"; public static final String I18N_SIMPLE_SIP_CREATOR_FINALIZING_SIP = "SimpleSipCreator.finalizingSip"; public static final String I18N_SOURCE_TREE_CELL_REMOVE = "SourceTreeCell.remove"; public static final String I18N_SOURCE_TREE_LOADING_TITLE = "SourceTreeLoading.title"; public static final String I18N_SOURCE_TREE_LOAD_MORE_TITLE = "SourceTreeLoadMore.title"; public static final String I18N_ADD = "add"; public static final String I18N_AND = "and"; public static final String I18N_APPLY = "apply"; public static final String I18N_ASSOCIATE = "associate"; public static final String I18N_BACK = "back"; public static final String I18N_CANCEL = "cancel"; public static final String I18N_CLEAR = "clear"; public static final String I18N_CLOSE = "close"; public static final String I18N_COLLAPSE = "collapse"; public static final String I18N_CONFIRM = "confirm"; public static final String I18N_CONTINUE = "continue"; public static final String I18N_CREATIONMODALPROCESSING_REPRESENTATION = "CreationModalProcessing.representation"; public static final String I18N_DATA = "data"; public static final String I18N_DIRECTORIES = "directories"; public static final String I18N_DIRECTORY = "directory"; public static final String I18N_DOCUMENTATION = "documentation"; public static final String I18N_DONE = "done"; public static final String I18N_ERROR_VALIDATING_METADATA = "errorValidatingMetadata"; public static final String I18N_EXPAND = "expand"; public static final String I18N_EXPORT = "export"; public static final String I18N_FILE = "file"; public static final String I18N_FILES = "files"; public static final String I18N_FOLDERS = "folders"; public static final String I18N_HELP = "help"; public static final String I18N_IGNORE = "ignore"; public static final String I18N_INVALID_METADATA = "invalidMetadata"; public static final String I18N_IP_CONTENT_TYPE = "IPContentType."; public static final String I18N_ITEMS = "items"; public static final String I18N_LOAD = "load"; public static final String I18N_LOADINGPANE_CREATE_ASSOCIATION = "LoadingPane.createAssociation"; public static final String I18N_NAME = "name"; public static final String I18N_REMOVE = "remove"; public static final String I18N_REPRESENTATION_CONTENT_TYPE = "RepresentationContentType."; public static final String I18N_RESTART = "restart"; public static final String I18N_ROOT = "root"; public static final String I18N_SELECTED = "selected"; public static final String I18N_SIP_NAME_STRATEGY = "sipNameStrategy."; public static final String I18N_START = "start"; public static final String I18N_TYPE = "type"; public static final String I18N_VALID_METADATA = "validMetadata"; public static final String I18N_VERSION = "version"; public static final String I18N_RENAME_REPRESENTATION = "RenameModalProcessing.renameRepresentation"; public static final String I18N_RENAME = "rename"; public static final String I18N_RENAME_REPRESENTATION_ALREADY_EXISTS = "RenameModalProcessing.renameAlreadyExists"; public static final String CONF_K_REFERENCE_TRANSFORMER_LIST = "reference.transformer.list[]"; public static final String CONF_K_REFERENCE_TRANSFORMER = "reference.transformer."; /* * ENUMs */ // sip type public enum SipType { EARK(EarkSipCreator.getText(), EarkSipCreator.requiresMETSHeaderInfo(), EarkSipCreator.ipSpecificContentTypes(), EarkSipCreator.representationSpecificContentTypes(), SipNameStrategy.ID, SipNameStrategy.TITLE_ID, SipNameStrategy.TITLE_DATE), EARK2(EarkSip2Creator.getText(), EarkSip2Creator.requiresMETSHeaderInfo(), EarkSip2Creator.ipSpecificContentTypes(), EarkSip2Creator.representationSpecificContentTypes(), SipNameStrategy.ID, SipNameStrategy.TITLE_ID, SipNameStrategy.TITLE_DATE), BAGIT(BagitSipCreator.getText(), BagitSipCreator.requiresMETSHeaderInfo(), BagitSipCreator.ipSpecificContentTypes(), BagitSipCreator.representationSpecificContentTypes(), SipNameStrategy.ID, SipNameStrategy.TITLE_ID, SipNameStrategy.TITLE_DATE), HUNGARIAN(HungarianSipCreator.getText(), HungarianSipCreator.requiresMETSHeaderInfo(), HungarianSipCreator.ipSpecificContentTypes(), HungarianSipCreator.representationSpecificContentTypes(), SipNameStrategy.DATE_TRANSFERRING_SERIALNUMBER), EARK2S(ShallowSipCreator.getText(), ShallowSipCreator.requiresMETSHeaderInfo(), ShallowSipCreator.ipSpecificContentTypes(), ShallowSipCreator.representationSpecificContentTypes(), SipNameStrategy.ID, SipNameStrategy.TITLE_ID, SipNameStrategy.TITLE_DATE); private final String text; private Set<SipNameStrategy> sipNameStrategies; private boolean requiresMETSHeaderInfo; private List<IPContentType> ipContentTypes;
private List<RepresentationContentType> representationContentTypes;
6
lob/lob-java
src/main/java/com/lob/model/USVerification.java
[ "public class APIException extends LobException {\n\n private static final long serialVersionUID = 1L;\n\n @JsonCreator\n public APIException(@JsonProperty(\"error\") final Map<String, Object> error) {\n super((String)error.get(\"message\"), (Integer)error.get(\"status_code\"));\n }\n\n}", "pub...
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.lob.exception.APIException; import com.lob.exception.AuthenticationException; import com.lob.exception.InvalidRequestException; import com.lob.exception.RateLimitException; import com.lob.net.APIResource; import com.lob.net.LobResponse; import com.lob.net.RequestOptions; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;
this.secondaryLine = secondaryLine; this.urbanization = urbanization; this.lastLine = lastLine; this.deliverability = deliverability; this.components = components; this.deliverabilityAnalysis = deliverabilityAnalysis; this.lobConfidenceScore = lobConfidenceScore; this.object = object; } public String getId() { return id; } public String getRecipient() { return recipient; } public String getPrimaryLine() { return primaryLine; } public String getSecondaryLine() { return secondaryLine; } public String getUrbanization() { return urbanization; } public String getLastLine() { return lastLine; } public String getDeliverability() { return deliverability; } public Components getComponents() { return components; } public Deliverability getDeliverabilityAnalysis() { return deliverabilityAnalysis; } public ConfidenceScore getLobConfidenceScore() { return lobConfidenceScore; } public String getObject() { return object; } @Override public String toString() { return "USVerification{" + "id='" + id + '\'' + ", recipient='" + recipient + '\'' + ", primaryLine='" + primaryLine + '\'' + ", secondaryLine='" + secondaryLine + '\'' + ", urbanization='" + urbanization + '\'' + ", lastLine='" + lastLine + '\'' + ", deliverability='" + deliverability + '\'' + ", components=" + components + ", deliverabilityAnalysis=" + deliverabilityAnalysis + ", lobConfidenceScore=" + lobConfidenceScore + '}'; } public static final class RequestBuilder { private Map<String, Object> params = new HashMap<String, Object>(); public RequestBuilder() { } public RequestBuilder setAddress(String address) { params.put("address", address); return this; } public RequestBuilder setRecipient(String recipient) { params.put("recipient", recipient); return this; } public RequestBuilder setPrimaryLine(String primaryLine) { params.put("primary_line", primaryLine); return this; } public RequestBuilder setSecondaryLine(String secondaryLine) { params.put("secondary_line", secondaryLine); return this; } public RequestBuilder setUrbanization(String urbanization) { params.put("urbanization", urbanization); return this; } public RequestBuilder setCity(String city) { params.put("city", city); return this; } public RequestBuilder setState(String state) { params.put("state", state); return this; } public RequestBuilder setZipCode(String zipCode) { params.put("zip_code", zipCode); return this; } public Map<String, Object> build() { return params; }
public LobResponse<USVerification> verify() throws APIException, IOException, AuthenticationException, InvalidRequestException, RateLimitException {
3
wesabe/grendel
src/test/java/com/wesabe/grendel/openpgp/tests/SubKeyTest.java
[ "public enum AsymmetricAlgorithm implements IntegerEquivalent {\n\t/**\n\t * Elgamal (Encrypt-Only)\n\t * \n\t * @see <a href=\"http://en.wikipedia.org/wiki/ElGamal_encryption\">Wikipedia</a>\n\t */\n\tELGAMAL(\t\"ElGamal\",\t\tPublicKeyAlgorithmTags.ELGAMAL_ENCRYPT) {\n\t\t@Override\n\t\tpublic AlgorithmParameterS...
import static org.fest.assertions.Assertions.*; import java.io.FileInputStream; import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import com.google.common.collect.ImmutableList; import com.wesabe.grendel.openpgp.AsymmetricAlgorithm; import com.wesabe.grendel.openpgp.CompressionAlgorithm; import com.wesabe.grendel.openpgp.HashAlgorithm; import com.wesabe.grendel.openpgp.MasterKey; import com.wesabe.grendel.openpgp.SubKey; import com.wesabe.grendel.openpgp.SymmetricAlgorithm;
package com.wesabe.grendel.openpgp.tests; @RunWith(Enclosed.class) public class SubKeyTest { public static class A_Sub_Key { private MasterKey masterKey;
private SubKey key;
4
witwall/sfntly-java
src/main/java/com/google/typography/font/tools/conversion/eot/HdmxEncoder.java
[ "public class Font {\n\n private static final Logger logger =\n Logger.getLogger(Font.class.getCanonicalName());\n\n /**\n * Offsets to specific elements in the underlying data. These offsets are relative to the\n * start of the table or the start of sub-blocks within the table.\n */\n private enum Offs...
import com.google.typography.font.sfntly.Font; import com.google.typography.font.sfntly.Tag; import com.google.typography.font.sfntly.data.WritableFontData; import com.google.typography.font.sfntly.table.core.FontHeaderTable; import com.google.typography.font.sfntly.table.core.HorizontalDeviceMetricsTable; import com.google.typography.font.sfntly.table.core.HorizontalMetricsTable; import com.google.typography.font.sfntly.table.core.MaximumProfileTable;
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.typography.font.tools.conversion.eot; /** * Implementation of compression of CTF horizontal device metrics data, as per * section 5.4 of the MicroType Express spec. * * @author Raph Levien */ public class HdmxEncoder { private static int HEADER_SIZE = 8; private static int RECORD_SIZE = 2; public WritableFontData encode(Font sourceFont) { HorizontalDeviceMetricsTable hdmx = sourceFont.getTable(Tag.hdmx); HorizontalMetricsTable hmtx = sourceFont.getTable(Tag.hmtx);
MaximumProfileTable maxp = sourceFont.getTable(Tag.maxp);
6
fairSIM/fairSIM
org/fairsim/fiji/SimPatternSimulator.java
[ "public class OtfProvider {\n \n // --- internal parameters ----\n\n public enum APPROX_TYPE {\n\tEXPONENTIAL,\n\tSPHERICAL,\n\tNONE\n };\n\n // vals[band][idx], where idx = cycles / cyclesPerMicron\n private Cplx.Float [][] vals\t= null; \n private Cplx.Float [][] valsAtt\t= null; \n priv...
import javax.swing.filechooser.FileNameExtensionFilter; import java.util.Random; import ij.plugin.PlugIn; import ij.ImageStack; import ij.ImagePlus; import ij.IJ; import ij.gui.GenericDialog; import ij.process.ImageProcessor; import org.fairsim.utils.Args; import org.fairsim.sim_algorithm.OtfProvider; import org.fairsim.sim_algorithm.SimUtils; import org.fairsim.utils.Conf; import org.fairsim.utils.Tool; import org.fairsim.linalg.Vec2d; import org.fairsim.linalg.Vec; import org.fairsim.linalg.Cplx; import java.io.File; import javax.swing.JFileChooser;
/* This file is part of Free Analysis and Interactive Reconstruction for Structured Illumination Microscopy (fairSIM). fairSIM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. fairSIM 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 fairSIM. If not, see <http://www.gnu.org/licenses/> */ package org.fairsim.fiji; /** * Small plugin that generate bead surfaces * */ public class SimPatternSimulator implements PlugIn { public void run(String attr) { ImageProcessor ip = IJ.getProcessor(); if ( ip.getWidth() != ip.getHeight() ) { IJ.showMessage("Please use a square image"); return; } if ( IJ.getImage().getType() != ImagePlus.GRAY8 && IJ.getImage().getType() != ImagePlus.GRAY16 && IJ.getImage().getType() != ImagePlus.GRAY32 ) { IJ.showMessage("Please use 8bit, 16bit or float gray scale"); } String imgName = IJ.getImage().getTitle(); // parse the parameters // TODO: This could be done with less code using reflections, but... GenericDialog gd = new GenericDialog("SIM Simulator"); gd.addNumericField("downsample", 4, 0); gd.addNumericField("pixel size (nm)", 80, 3); gd.addNumericField("angles", 3, 0); gd.addNumericField("phases", 3, 0); gd.addNumericField("SIM res. improvement", 1.9, 1); gd.addNumericField("SIM modulation depth", 0.78,2); gd.addNumericField("obj. NA", 1.4, 2); gd.addNumericField("em. wavelength (nm)", 525, 0); gd.addNumericField("photons per input count", 1, 2); gd.addNumericField("camera (offset)", 100, 0); gd.addNumericField("camera (noise)", 2, 0); gd.addNumericField("PRNG seed", 42, 0); gd.showDialog(); if (gd.wasCanceled()) { return; } final int downSample = (int)gd.getNextNumber(); final double pxlSize = gd.getNextNumber(); final int angles = (int)gd.getNextNumber(); final int phases = (int)gd.getNextNumber(); final double simResImpr = gd.getNextNumber()-1; final double simModDepth = gd.getNextNumber(); final double NA = gd.getNextNumber(); final double wavelength = gd.getNextNumber(); final double photons = gd.getNextNumber(); final double bgrOffset = gd.getNextNumber(); final double bgrNoise = gd.getNextNumber(); final int prngSeed = (int)gd.getNextNumber(); final int inputSize = ip.getWidth(); if (inputSize % downSample != 0 ) { IJ.showMessage("image size has to be a multiple of 'downsample'"); } final int outputSize = ip.getWidth()/downSample; Vec2d.Real groundTruth = ImageVector.copy( ip ); Random noisePRNG = new Random(prngSeed*2+123); FairSim_ImageJplugin.setLog(true); // run the simulation DisplayWrapper dwSI = new DisplayWrapper( outputSize, outputSize,imgName+"_simulSIM"); DisplayWrapper dwWF = new DisplayWrapper( outputSize, outputSize,imgName+"_simulWF"); DisplayWrapper dwGT = new DisplayWrapper( inputSize, inputSize,imgName+"_simul_intermediate"); DisplayWrapper dwIL = new DisplayWrapper( inputSize, inputSize,imgName+"_sim_field"); dwSI.setPixelSize( pxlSize ); dwWF.setPixelSize( pxlSize ); dwGT.setPixelSize( pxlSize / downSample ); dwIL.setPixelSize( pxlSize / downSample ); dwGT.addImage( groundTruth, "Ground truth"); // initialize OTF final double cyclPerMicron = 1./(pxlSize/1000. * outputSize); OtfProvider otf = OtfProvider.fromEstimate(NA, wavelength, .7); otf.setPixelSize( cyclPerMicron ); // create wide-field Vec2d.Cplx img = Vec2d.createCplx( groundTruth ); img.copy( groundTruth ); img.fft2d(false); otf.applyOtf( img,0 ); dwGT.addImage( SimUtils.spatial( img ), "Widefield"); // create SIM Vec2d.Cplx sim = Vec2d.createCplx( groundTruth ); Vec2d.Real tmp = Vec2d.createReal( groundTruth ); ImageVector tmp2 = ImageVector.create( outputSize, outputSize ); ImageVector resWF = ImageVector.create( outputSize, outputSize ); final double abbeLimit = 1. / otf.getCutoff(); final double simPttrLen = abbeLimit / simResImpr ; final double k0 = otf.getCutoff()*simResImpr / cyclPerMicron;
Tool.trace(" Abbe (um): "+abbeLimit+" sim spacing (um): "+simPttrLen+" k0 (len): "+k0);
3
Tonius/SimplyJetpacks
src/main/java/tonius/simplyjetpacks/gui/GuiPack.java
[ "@Mod(modid = SimplyJetpacks.MODID, version = SimplyJetpacks.VERSION, dependencies = SimplyJetpacks.DEPENDENCIES, guiFactory = SimplyJetpacks.GUI_FACTORY)\npublic class SimplyJetpacks {\n \n public static final String MODID = \"simplyjetpacks\";\n public static final String VERSION = \"@VERSION@\";\n pu...
import net.minecraft.util.ResourceLocation; import tonius.simplyjetpacks.SimplyJetpacks; import tonius.simplyjetpacks.gui.element.ElementEnergyStoredAdv; import tonius.simplyjetpacks.gui.element.ElementFluidTankAdv; import tonius.simplyjetpacks.network.PacketHandler; import tonius.simplyjetpacks.network.message.MessageModKey; import tonius.simplyjetpacks.setup.ModKey; import tonius.simplyjetpacks.util.SJStringHelper; import cofh.lib.gui.GuiBase; import cofh.lib.gui.element.ElementButton;
package tonius.simplyjetpacks.gui; public class GuiPack extends GuiBase { private final ContainerPack container; public GuiPack(ContainerPack container) {
super(container, new ResourceLocation(SimplyJetpacks.RESOURCE_PREFIX + "textures/gui/pack.png"));
0
Multiplayer-italia/AuthMe-Reloaded
src/main/java/uk/org/whoami/authme/commands/UnregisterCommand.java
[ "public class Utils {\r\n //private Settings settings = Settings.getInstance();\r\n private Player player;\r\n private String currentGroup;\r\n private static Utils singleton;\r\n private String unLoggedGroup = Settings.getUnloggedinGroup;\r\n /* \r\n public Utils(Player player) {\r\n t...
import java.security.NoSuchAlgorithmException; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitScheduler; import uk.org.whoami.authme.ConsoleLogger; import uk.org.whoami.authme.Utils; import uk.org.whoami.authme.cache.auth.PlayerCache; import uk.org.whoami.authme.cache.backup.FileCache; import uk.org.whoami.authme.cache.limbo.LimboCache; import uk.org.whoami.authme.datasource.DataSource; import uk.org.whoami.authme.security.PasswordSecurity; import uk.org.whoami.authme.settings.Messages; import uk.org.whoami.authme.settings.Settings; import uk.org.whoami.authme.task.MessageTask; import uk.org.whoami.authme.task.TimeoutTask;
/* * Copyright 2011 Sebastian Köhler <sebkoehler@whoami.org.uk>. * * 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 uk.org.whoami.authme.commands; public class UnregisterCommand implements CommandExecutor { private Messages m = Messages.getInstance(); //private Settings settings = Settings.getInstance(); private JavaPlugin plugin; private DataSource database; private FileCache playerCache = new FileCache(); public UnregisterCommand(JavaPlugin plugin, DataSource database) { this.plugin = plugin; this.database = database; } @Override public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) { if (!(sender instanceof Player)) { return true; } if (!sender.hasPermission("authme." + label.toLowerCase())) { sender.sendMessage(m._("no_perm")); return true; } Player player = (Player) sender; String name = player.getName().toLowerCase(); if (!PlayerCache.getInstance().isAuthenticated(name)) { player.sendMessage(m._("not_logged_in")); return true; } if (args.length != 1) { player.sendMessage(m._("usage_unreg")); return true; } try { if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash())) { if (!database.removeAuth(name)) { player.sendMessage("error"); return true; } if(Settings.isForcedRegistrationEnabled) { player.getInventory().setArmorContents(new ItemStack[4]); player.getInventory().setContents(new ItemStack[36]); player.saveData(); PlayerCache.getInstance().removePlayer(player.getName().toLowerCase()); LimboCache.getInstance().addLimboPlayer(player); int delay = Settings.getRegistrationTimeout * 20; int interval = Settings.getWarnMessageInterval; BukkitScheduler sched = sender.getServer().getScheduler(); if (delay != 0) {
int id = sched.scheduleSyncDelayedTask(plugin, new TimeoutTask(plugin, name), delay);
7
Keridos/FloodLights
src/main/java/de/keridos/floodlights/FloodLights.java
[ "@SuppressWarnings(\"WeakerAccess\")\npublic class ModCompatibility {\n private static ModCompatibility instance = null;\n\n public static boolean IC2Loaded = false;\n public static boolean BCLoaded = false;\n public static boolean CofhCoreLoaded = false;\n public static boolean NEILoaded = false;\n ...
import de.keridos.floodlights.compatability.ModCompatibility; import de.keridos.floodlights.core.proxy.CommonProxy; import de.keridos.floodlights.handler.ConfigHandler; import de.keridos.floodlights.handler.GuiHandler; import de.keridos.floodlights.handler.PacketHandler; import de.keridos.floodlights.init.ModBlocks; import de.keridos.floodlights.init.ModItems; import de.keridos.floodlights.reference.Reference; import de.keridos.floodlights.util.RandomUtil; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import java.util.Map;
package de.keridos.floodlights; /** * Created by Keridos on 28.02.14. * This Class is the Main Class of the Mod. */ @SuppressWarnings("unused") @Mod.EventBusSubscriber
@Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.VERSION, dependencies = Reference.DEPENDENCIES)
7
Ouyangan/hunt-admin
hunt-service/src/main/java/com/hunt/service/impl/SysRoleServiceImpl.java
[ "public interface SysPermissionMapper {\n //新增\n public Long insert(SysPermission SysPermission);\n\n //更新\n public void update(SysPermission SysPermission);\n\n //通过对象进行查询\n public SysPermission select(SysPermission SysPermission);\n\n //通过id进行查询\n public SysPermission selectById(@Param(\"i...
import com.hunt.dao.SysPermissionMapper; import com.hunt.dao.SysRoleMapper; import com.hunt.dao.SysRolePermissionMapper; import com.hunt.model.dto.PageInfo; import com.hunt.model.dto.SysRoleDto; import com.hunt.model.entity.SysPermission; import com.hunt.model.entity.SysRole; import com.hunt.model.entity.SysRolePermission; import com.hunt.service.SysRoleService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List;
package com.hunt.service.impl; /** * @Author ouyangan * @Date 2016/10/14/14:53 * @Description */ @Service @Transactional public class SysRoleServiceImpl implements SysRoleService { private static Logger log = LoggerFactory.getLogger(SysRoleServiceImpl.class); @Autowired
private SysRoleMapper sysRoleMapper;
1
ZhangFly/WTFSocket_Server_JAVA
test/controller/RegisterController.java
[ "public class ApplicationMsg {\n\n private Integer flag;\n private Integer cmd;\n private Integer errCode;\n private JSONArray params;\n private String version = \"1.0\";\n private String cause = null;\n\n public static ApplicationMsg failure(int errCode, String cause) {\n return new App...
import model.ApplicationMsg; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Controller; import wtf.socket.controller.WTFSocketController; import wtf.socket.exception.WTFSocketException; import wtf.socket.exception.fatal.WTFSocketInvalidSourceException; import wtf.socket.protocol.WTFSocketMsg; import wtf.socket.routing.item.WTFSocketRoutingItem; import wtf.socket.routing.item.WTFSocketRoutingTmpItem; import java.util.List;
package controller; /** * 注册功能 */ @Controller public class RegisterController implements WTFSocketController { @Override public boolean isResponse(WTFSocketMsg msg) {
ApplicationMsg body = msg.getBody(ApplicationMsg.class);
0
jlaw90/Grimja
liblab/src/com/sqrt/liblab/entry/model/GrimModel.java
[ "public class LabFile {\n /**\n * The collection that this LabFile belongs to\n */\n public final LabCollection container;\n /**\n * The names and data for the entries of this LabFile\n */\n public final List<DataSource> entries = new LinkedList<DataSource>();\n private int version = ...
import com.sqrt.liblab.LabFile; import com.sqrt.liblab.entry.LabEntry; import com.sqrt.liblab.threed.Angle; import com.sqrt.liblab.threed.Bounds3; import com.sqrt.liblab.threed.Vector3f; import java.util.LinkedList; import java.util.List;
/* * Copyright (C) 2014 James Lawrence. * * This file is part of LibLab. * * LibLab is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.sqrt.liblab.entry.model; /** * A 3D model */ public class GrimModel extends LabEntry { /** * The geosets of this model */ public final List<Geoset> geosets = new LinkedList<Geoset>(); /** * The hierarchy used for animation */ public final List<ModelNode> hierarchy = new LinkedList<ModelNode>(); /** * The 3d offset of this model */ public Vector3f off; /** * The radius of a bounding sphere? */ public float radius; public GrimModel(LabFile container, String name) { super(container, name); } /** * Returns the 3d bounds of this model * @return the bounds */ public Bounds3 getBounds() { return hierarchy.get(0).getBounds(new Vector3f(0, 0, 0)); } /** * Attempts to locate the ModelNode with the specified name * @param meshName the name of the mesh * @return the located node or null if not found */ public ModelNode findNode(String meshName) { for(ModelNode node: hierarchy) { if(node.name.equalsIgnoreCase(meshName)) return node; if(node.mesh != null && node.mesh.name.equalsIgnoreCase(meshName)) return node; } return null; } public void reset() { for(ModelNode node: hierarchy) { node.animPos = Vector3f.zero;
node.animYaw = node.animRoll = node.animPitch = Angle.zero;
2
hosuaby/example-restful-project
src/test/java/io/hosuaby/restful/tests/config/WebMvcTestsConfig.java
[ "@Component\npublic class PortHolder implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {\n\n private int port;\n\n @Override\n public void onApplicationEvent(\n EmbeddedServletContainerInitializedEvent event) {\n port = event.getEmbeddedServletContainer().getPort()...
import io.hosuaby.restful.PortHolder; import io.hosuaby.restful.domain.Teapot; import io.hosuaby.restful.mappers.TeapotMapper; import io.hosuaby.restful.mappers.TeapotMapperImpl; import io.hosuaby.restful.services.TeapotCommandService; import io.hosuaby.restful.services.TeapotCrudService; import io.hosuaby.restful.services.exceptions.teapots.TeapotNotExistsException; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import java.util.HashSet; import java.util.Set; import static org.mockito.Mockito.*;
package io.hosuaby.restful.tests.config; /** * Configuration for tests of MVC controllers. */ @Configuration @ComponentScan(basePackages = { "io.hosuaby.restful.controllers", "io.hosuaby.restful.domain.validators" }) public class WebMvcTestsConfig { /** Teapot "Mouse" */ private static final Teapot MOUSE = new Teapot( "mouse", "Mouse", "Tefal", Teapot.L0_3); /** Teapot "Einstein" */ private static final Teapot EINSTEIN = new Teapot( "einstein", "Einstein", "Sony", Teapot.L3); /** Teapot "Nemezis" */ private static final Teapot NEMEZIS = new Teapot( "nemezis", "Nemezis", "Philips", Teapot.L10); /** Teapots to return by {@code TeapotCrudService} mock */ private static final Set<Teapot> TEAPOTS = new HashSet<Teapot>() { private static final long serialVersionUID = 1L; { add(MOUSE); add(EINSTEIN); add(NEMEZIS); } }; /** * @return {@link TeapotMapper} implementation. */ @Bean
public TeapotMapper teapotMapper() {
2
AVMf/avmf
src/test/java/org/avmframework/ObjectiveFunctions.java
[ "public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> {\n\n protected double value;\n protected boolean higherIsBetter;\n\n protected boolean haveOptimum = false;\n protected double optimum;\n\n public NumericObjectiveValue(double value, boolean higherIsBetter) {\n this.value = v...
import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.IntegerVariable; import org.avmframework.variable.Variable;
package org.avmframework; public class ObjectiveFunctions { public static ObjectiveFunction flat() { ObjectiveFunction objFun = new ObjectiveFunction() { @Override
protected ObjectiveValue computeObjectiveValue(Vector vector) {
2
echocat/adam
src/main/java/org/echocat/adam/profile/UserProfileMacro.java
[ "public class LocalizationHelper implements DisposableBean {\n\n @Nonnull\n public static final Locale DEFAULT_LOCALE = US;\n\n @Nullable\n private static LocalizationHelper c_instance;\n\n @Nonnull\n public static LocalizationHelper localizationHelper() {\n final LocalizationHelper result ...
import com.atlassian.confluence.content.render.xhtml.ConversionContext; import com.atlassian.confluence.languages.LocaleManager; import com.atlassian.confluence.macro.Macro; import com.atlassian.confluence.macro.MacroExecutionException; import com.atlassian.confluence.security.PermissionManager; import com.atlassian.confluence.user.AuthenticatedUserThreadLocal; import com.atlassian.confluence.user.ConfluenceUser; import com.atlassian.confluence.user.UserAccessor; import com.atlassian.user.User; import org.echocat.adam.localization.LocalizationHelper; import org.echocat.adam.profile.element.ElementRenderer; import org.echocat.adam.view.View; import org.echocat.adam.view.ViewProvider; import org.echocat.jomon.runtime.util.Hints; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.atlassian.confluence.macro.Macro.BodyType.NONE; import static com.atlassian.confluence.renderer.radeox.macros.MacroUtils.defaultVelocityContext; import static com.atlassian.confluence.security.Permission.VIEW; import static com.atlassian.confluence.security.PermissionManager.TARGET_PEOPLE_DIRECTORY; import static com.atlassian.confluence.util.velocity.VelocityUtils.getRenderedTemplate; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static java.lang.Enum.valueOf; import static java.util.regex.Pattern.compile; import static org.apache.commons.lang3.StringUtils.isEmpty; import static org.apache.commons.lang3.StringUtils.uncapitalize; import static org.echocat.adam.profile.element.ElementRenderer.enableUserLinkIfPossible; import static org.echocat.adam.profile.element.ElementRenderer.fullNameTagName; import static org.echocat.jomon.runtime.CollectionUtils.addAll; import static org.echocat.jomon.runtime.StringUtils.split;
/***************************************************************************************** * *** BEGIN LICENSE BLOCK ***** * * echocat Adam, Copyright (c) 2014 echocat * * 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 3.0 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. * * *** END LICENSE BLOCK ***** ****************************************************************************************/ package org.echocat.adam.profile; public class UserProfileMacro implements Macro { @Nonnull protected static final String TEMPLATE_NAME_SUFFIX = ".vm"; @Nonnull protected static final String TEMPLATE_NAME_PREFIX = UserProfileMacro.class.getName().replace('.', '/'); @Nonnull protected static final Pattern EXTRACT_VIEW_NAME_PATTERN = compile("\\$\\$view:([a-zA-Z0-9_\\-]+)\\$\\$"); @Nonnull private final ProfileProvider _profileProvider; @Nonnull private final UserAccessor _userAccessor; @Nonnull private final LocalizationHelper _localizationHelper; @Nonnull
private final ElementRenderer _elementRenderer;
1
Ouyangan/hunt-admin
hunt-service/src/main/java/com/hunt/service/SystemService.java
[ "public class PageInfo {\n private int total;\n private Object rows;\n\n public PageInfo(int total, Object rows) {\n this.total = total;\n this.rows = rows;\n }\n\n @Override\n public String toString() {\n return \"PageInfo{\" +\n \"total=\" + total +\n ...
import com.hunt.model.dto.PageInfo; import com.hunt.model.entity.SysDataGroup; import com.hunt.model.entity.SysDataItem; import com.hunt.model.entity.SysIpForbidden; import com.hunt.model.entity.SysLog; import java.util.List;
package com.hunt.service; /** * @Author: ouyangan * @Date : 2016/10/21 */ public interface SystemService { void forceLogout(long userId); void clearAuthorizationInfoCacheByUserId(long userId); void clearAuthorizationInfoALL(); void clearAuthorizationInfoByRoleId(long roleId); PageInfo selectLogStatus(int page, int rows); PageInfo selectLog(int page, int rows, String s, String order, String method, String url, String param, String result); void insertSysControllerLog(SysLog runningLog); Long insertSysDataGroup(SysDataGroup sysDataGroup); boolean isExistDataGroupName(String name); List<SysDataGroup> selectDataGroupList();
long insertSysDataItem(SysDataItem sysDataItem);
2
google/ftc-object-detection
TFObjectDetector/tfod/src/main/java/com/google/ftcresearch/tfod/detection/RecognizeImageRunnable.java
[ "public class AnnotatedYuvRgbFrame {\n\n private final YuvRgbFrame frame;\n private final List<Recognition> recognitions;\n private final long frameTimeNanos;\n\n public AnnotatedYuvRgbFrame(@NonNull YuvRgbFrame frame, @NonNull List<Recognition> recognitions,\n long frameTimeNanos) ...
import java.util.List; import java.util.Map; import org.tensorflow.lite.Interpreter; import android.graphics.RectF; import android.util.Log; import com.google.ftcresearch.tfod.util.AnnotatedYuvRgbFrame; import com.google.ftcresearch.tfod.util.Recognition; import com.google.ftcresearch.tfod.util.Size; import com.google.ftcresearch.tfod.util.Timer; import com.google.ftcresearch.tfod.util.YuvRgbFrame; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap;
/* * Copyright (C) 2018 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.ftcresearch.tfod.detection; /** * Run a single frame through a TensorFlow Lite interpreter and return the recognitions. * * <p>This runnable is invoked as a series of tasks submitted to an ExecutorService by the frame * manager. This runnable performs all pre- and post-processing work required to transform a raw * image, directly out of a {@link com.google.ftcresearch.tfod.generators.FrameGenerator} into a list of * {@link Recognition}. */ class RecognizeImageRunnable implements Runnable { private static final String TAG = "RecognizeImageRunnable"; // Constants for float model, used to normalize float images to [-1, 1] private static final float IMAGE_MEAN = 128.0f; private static final float IMAGE_STD = 128.0f;
private final AnnotatedYuvRgbFrame annotatedFrame;
0
TGAC/RAMPART
src/main/java/uk/ac/tgac/rampart/stage/analyse/asm/AnalyseAssembliesArgs.java
[ "public class Mecq extends RampartProcess {\n\n private static Logger log = LoggerFactory.getLogger(Mecq.class);\n\n public Mecq(ConanExecutorService ces) {\n this(ces, new Args());\n }\n\n public Mecq(ConanExecutorService ces, Args args) {\n super(ces, args);\n }\n\n\n public Args g...
import org.apache.commons.cli.CommandLine; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import uk.ac.ebi.fgpt.conan.core.process.AbstractProcessArgs; import uk.ac.ebi.fgpt.conan.model.ConanProcess; import uk.ac.ebi.fgpt.conan.model.param.ConanParameter; import uk.ac.ebi.fgpt.conan.model.param.ParamMap; import uk.ac.tgac.conan.core.data.Organism; import uk.ac.tgac.conan.core.util.XmlHelper; import uk.ac.tgac.rampart.stage.Mecq; import uk.ac.tgac.rampart.stage.RampartProcess; import uk.ac.tgac.rampart.stage.RampartStage; import uk.ac.tgac.rampart.stage.RampartStageArgs; import uk.ac.tgac.rampart.stage.analyse.asm.analysers.AssemblyAnalyser; import uk.ac.tgac.rampart.util.SpiFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;
/* * RAMPART - Robust Automatic MultiPle AssembleR Toolkit * Copyright (C) 2015 Daniel Mapleson - TGAC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.tgac.rampart.stage.analyse.asm; /** * Created by maplesod on 15/06/14. */ public abstract class AnalyseAssembliesArgs extends RampartProcess.RampartProcessArgs { private static final String KEY_ELEM_TOOL = "tool"; public static final boolean DEFAULT_RUN_PARALLEL = false;
private SpiFactory<AssemblyAnalyser> assemblyAnalyserFactory;
5
OpenNTF/DomSQL
domsql/eclipse/plugins/com.ibm.domino.domsql.sqlite/src/com/ibm/domino/domsql/sqlite/driver/Database.java
[ "public class DomSQLConnection extends DomSQLObject implements Connection {\r\n\t\r\n private Database db;\r\n private String userName;\r\n\r\n private DomSQLDatabaseMetaData meta;\r\n private boolean autoCommit = true;\r\n private int timeout;\r\n\r\n // Indicates if a transaction was started whi...
import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.ibm.commons.Platform; import com.ibm.commons.util.StringUtil; import com.ibm.domino.domsql.sqlite.driver.jdbc.DomSQLConnection; import com.ibm.domino.domsql.sqlite.driver.jdbc.DomSQLStatement; import com.ibm.domino.domsql.sqlite.driver.jni.DomSQL; import com.ibm.domino.domsql.sqlite.driver.jni.JNIUtils; import com.ibm.domino.domsql.sqlite.driver.jni.NotesAPI; import com.ibm.domino.domsql.sqlite.driver.meta.DatabaseDefinition;
/* * © Copyright IBM Corp. 2010 * * 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.ibm.domino.domsql.sqlite.driver; /** * Holds the definition a pointer to a database. * * @author priand */ public class Database { private String name; private String url; private String domSqlName; private String nsfPath; private long sqliteDb; private long timeout; private long lastAccess; private long designTS; private List<DomSQLConnection> connections = new ArrayList<DomSQLConnection>(); public Database(String name, String url, String nsfPath, String domSqlName) { this.name = name; this.url = url; this.nsfPath = nsfPath; this.domSqlName = domSqlName; this.timeout = Constants.DEFAULT_TIMEOUT; try { int mins = NotesAPI.OSGetEnvironmentInt(Constants.NOTESINI_DOMSQLPORT); if(mins>0) { this.timeout = mins * 60 *1000; // in ms, from minutes } else if(mins<0) { this.timeout = -1; } } catch(Exception e) {} // Use the defaut... } public String getName() { return name; } public long getLastAccess() { return lastAccess; } public void updateLastAccess() { this.lastAccess = System.currentTimeMillis(); } public boolean isExpired(long now) { if(timeout>0) { return lastAccess+timeout<now; } return false; } public String getUrl() { return url; } public String getNsfPath() { return nsfPath; } public String getDomSqlName() { return domSqlName; } public long getSqliteDb() { return sqliteDb; } public synchronized void close() throws SQLException { // Make a copy as closing a connection removes it from the list DomSQLConnection[] c = connections.toArray(new DomSQLConnection[connections.size()]); for(int i=0; i<c.length; i++) { c[i].close(); } // Then close the SQLDB if(sqliteDb!=0) { SQLite.close(sqliteDb); sqliteDb = 0; } } // ============================================================================ // Connection management // ============================================================================ public synchronized void addConnection(DomSQLConnection c) { connections.add(c); } public synchronized void removeConnection(DomSQLConnection c) { connections.remove(c); } // ============================================================================ // Check if the database is outdated // ============================================================================ public boolean refreshIfNecessary() throws SQLException { if(shouldRefresh()) { refresh(); return true; } return false; } public boolean shouldRefresh() throws SQLException { // We currently only check the current database // But we should also check all the referenced databases to be exhautive try { long hdb = Context.get().getDBHandle(null); if(hdb!=0) { long ts = NotesAPI.NSFDbNonDataModifiedTime(hdb); if(ts>designTS) { return true; } } } catch(Throwable t) { Platform.getInstance().log(t); } return false; } public synchronized void refresh() throws SQLException { DefaultContext context = new DefaultContext(); context.setDefaultDbName(nsfPath); try { // If the SQLite database was already initialized, then close it first if(sqliteDb!=0) { SQLite.close(sqliteDb); sqliteDb = 0; } // Read the database definition DatabaseDefinition dbDef = new DatabaseDefinition(nsfPath,domSqlName); // Read the database definition file dbDef.readDomsql(context); // Create the modules for the view table List<String> sql = dbDef.generateInitSql(context); // Read the SQLite file name // It default to a temporary DB String fileName = dbDef.getSqliteFileName(); if(fileName==null) { fileName = ""; //":memory:"; } // Open the sqlite database this.sqliteDb = SQLite.open(fileName);
if(DomSQL.debug.TRACE_DATABASE_LIFECYCLE) {
2
TheCount/jhilbert
src/main/java/jhilbert/Main.java
[ "public class CommandException extends JHilbertException {\n\n\t/**\n\t * Creates a new <code>CommandException</code> with the specified\n\t * detail message.\n\t *\n\t * @param message detail message.\n\t */\n\tpublic CommandException(final String message) {\n\t\tthis(message, null);\n\t}\n\n\t/**\n\t * Creates a ...
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import jhilbert.commands.CommandException; import jhilbert.commands.CommandFactory; import jhilbert.data.DataFactory; import jhilbert.data.Module; import jhilbert.scanners.ScannerException; import jhilbert.scanners.ScannerFactory; import jhilbert.scanners.TokenFeed; import jhilbert.scanners.WikiInputStream; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout;
/* JHilbert, a verifier for collaborative theorem proving Copyright © 2008, 2009, 2011 The JHilbert Authors See the AUTHORS file for the list of JHilbert authors. See the commit logs ("git log") for a list of individual contributions. 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/>. You may contact the author on this Wiki page: http://www.wikiproofs.de/w/index.php?title=User_talk:GrafZahl */ package jhilbert; /** * Main class. */ public final class Main { /** * Version. */ public static final int VERSION = 9; /** * Logger. */ private static final Logger logger; /** * Daemon port. */ private static final int DAEMON_PORT = 3141; /** * MediaWiki API default location. */ private static final String MEDIAWIKI_API = "http://127.0.0.1:80/w/api.php"; /** * Default location for hashstore. */ private static final String HASHSTORE_DEFAULT_PATH = "/var/local/lib/jhilbert/hashstore"; /** * Default socket timeout in milliseconds. */ public static final int DEFAULT_SOCKET_TIMEOUT = 5000; /** * Hashstore location. */ private static String hashstorePath; /** * Is DAEMON? */ private static boolean isDaemon; /** * Daemon socket timeout. */ private static int socketTimeout; /** * Are we reading wiki-format pages from files (--wiki)? */ private static boolean isWiki; /** * Static initialiser. * * Initialises the logger. */ static { BasicConfigurator.configure(new ConsoleAppender( new PatternLayout("%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c - %m%n"))); logger = Logger.getRootLogger(); logger.setLevel(Level.INFO); } /** * Program entry point. * * @param args command line arguments. * * @throws Exception if anything out of the ordinary happens. */ public static void main(String... args) throws Exception { isDaemon = false; socketTimeout = DEFAULT_SOCKET_TIMEOUT; isWiki = false; hashstorePath = null; try { String inputFileName = null; for (String arg: args) { logger.info("Command line argument: " + arg); if (arg.startsWith("-l")) { logger.setLevel(Level.toLevel(arg.substring(2))); } else if (arg.startsWith("-p")) { if (arg.length() > 2) { hashstorePath = arg.substring(2); } else { hashstorePath = HASHSTORE_DEFAULT_PATH; } } else if (arg.equals("-d")) { isDaemon = true; } else if (arg.startsWith("-t")) { try { if (arg.length() > 2) { socketTimeout = Integer.parseInt(arg.substring(2)); } else { throw new NumberFormatException("Empty digit string"); } if (socketTimeout <= 0) throw new NumberFormatException("Positive value required"); } catch (NumberFormatException e) { System.err.println("-t: Invalid timeout specified: " + e.getMessage()); System.exit(1); } } else if (arg.equals("--wiki")) { isWiki = true; } else if (arg.equals("--license")) { showLicense(); } else { inputFileName = arg; } } if (isDaemon == true) { startDaemon(); return; } if (inputFileName == null) { printUsage(); System.exit(1); } if (isWiki) { processWikiFile(inputFileName); } else { processProofModule(inputFileName); } return; } catch (JHilbertException e) { logger.fatal("Exiting due to unrecoverable error", e); System.exit(1); } catch (Exception e) { logger.fatal("Caught unexpected exception"); throw e; } } private static void processWikiFile(String inputFileName) throws IOException, ScannerException, CommandException { if (isInterface(inputFileName)) { logger.info("Processing interface " + inputFileName);
final Module mainInterface = DataFactory.getInstance().createModule(inputFileName);
2
RockinChaos/ItemJoin
src/me/RockinChaos/itemjoin/listeners/triggers/PlayerGuard.java
[ "public class PlayerHandler {\n\t\n\tprivate static HashMap<String, ItemStack[]> craftingItems = new HashMap<String, ItemStack[]>();\n\tprivate static HashMap<String, ItemStack[]> craftingOpenItems = new HashMap<String, ItemStack[]>();\n\tprivate static HashMap<String, ItemStack[]> creativeCraftingItems = new HashM...
import me.RockinChaos.itemjoin.item.ItemUtilities; import me.RockinChaos.itemjoin.item.ItemUtilities.TriggerType; import me.RockinChaos.itemjoin.utils.SchedulerUtils; import me.RockinChaos.itemjoin.utils.ServerUtils; import me.RockinChaos.itemjoin.utils.api.DependAPI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerTeleportEvent; import me.RockinChaos.itemjoin.handlers.PlayerHandler;
/* * ItemJoin * Copyright (C) CraftationGaming <https://www.craftationgaming.com/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.RockinChaos.itemjoin.listeners.triggers; public class PlayerGuard implements Listener { private HashMap < Player, String > playerRegions = new HashMap < Player, String > (); /** * Called on player movement. * Gives and removes any available * custom items upon entering or exiting a region. * * @param event - PlayerMoveEvent */ @EventHandler(ignoreCancelled = true) private void setRegionItems(PlayerMoveEvent event) { final Player player = event.getPlayer(); if (PlayerHandler.isPlayer(player)) { SchedulerUtils.runAsync(() -> { if (PlayerHandler.isEnabled(player, "ALL")) { this.handleRegions(player, player.getLocation(), true); } }); } } /** * Called on player teleport. * Gives and removes any available * custom items upon entering or exiting a region. * * @param event - PlayerTeleportEvent */ @EventHandler(ignoreCancelled = true) private void setRegionItems(PlayerTeleportEvent event) { final Player player = event.getPlayer(); if (PlayerHandler.isPlayer(player)) { if (PlayerHandler.isEnabled(player, "ALL")) { this.handleRegions(player, event.getTo(), false); } } ServerUtils.logDebug("{ItemMap} " + player.getName() + " has performed A REGION trigger by teleporting."); } /** * Handles the checking of WorldGuard regions, * proceeding if the player has entered or exited a new region. * * @param player - The player that has entered or exited a region. */ private void handleRegions(final Player player, final Location location, final boolean async) {
String regions = DependAPI.getDepends(false).getGuard().getRegionAtLocation(location);
5
TeamAmeriFrance/Guide-API
src/main/java/amerifrance/guideapi/gui/GuiHome.java
[ "public class Book {\n\n private static final String GUITEXLOC = \"guideapi:textures/gui/\";\n\n private List<CategoryAbstract> categories = Lists.newArrayList();\n private String title = \"item.GuideBook.name\";\n private String header = title;\n private String itemName = title;\n private String ...
import amerifrance.guideapi.api.impl.Book; import amerifrance.guideapi.api.impl.abstraction.CategoryAbstract; import amerifrance.guideapi.button.ButtonNext; import amerifrance.guideapi.button.ButtonPrev; import amerifrance.guideapi.button.ButtonSearch; import amerifrance.guideapi.network.PacketHandler; import amerifrance.guideapi.network.PacketSyncHome; import amerifrance.guideapi.wrapper.CategoryWrapper; import com.google.common.collect.HashMultimap; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import java.awt.Color; import java.io.IOException;
package amerifrance.guideapi.gui; public class GuiHome extends GuiBase { public ResourceLocation outlineTexture; public ResourceLocation pageTexture; public Book book; public HashMultimap<Integer, CategoryWrapper> categoryWrapperMap = HashMultimap.create(); public ButtonNext buttonNext;
public ButtonPrev buttonPrev;
3
uber-java/tally
example/src/main/java/com/uber/m3/tally/example/PrintStatsReporterExample.java
[ "public interface Counter {\n /**\n * Increment this {@link Counter} by delta.\n * @param delta amount to increment this {@link Counter} by\n */\n void inc(long delta);\n}", "public class ScopeCloseException extends Exception {\n public ScopeCloseException() {\n super();\n }\n\n ...
import com.uber.m3.tally.Counter; import com.uber.m3.tally.ScopeCloseException; import com.uber.m3.util.Duration; import com.uber.m3.tally.Gauge; import com.uber.m3.tally.RootScopeBuilder; import com.uber.m3.tally.Scope; import com.uber.m3.tally.StatsReporter; import com.uber.m3.tally.Timer;
// Copyright (c) 2021 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package com.uber.m3.tally.example; /** * PrintStatsReporterExample usage with a PrintStatsReporter reporting synthetically emitted metrics */ public class PrintStatsReporterExample { public static void main(String[] args) throws InterruptedException { System.out.println("\n-----------\nStarting...\n-----------"); StatsReporter reporter = new PrintStatsReporter(); // Set up rootScope, automatically starting to report every second try (Scope rootScope = new RootScopeBuilder().reporter(reporter).reportEvery(Duration.ofSeconds(1))) { Scope subScope = rootScope.subScope("requests");
Counter exampleCounter = subScope.counter("ticks");
0
Ericliu001/Weather2016
app/src/main/java/com/example/ericliu/weather2016/repo/RemoteWeatherRepo.java
[ "public class MyApplication extends Application {\n\n private static RepoComponent component;\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n RepoComponent repoComponent = DaggerRepoComponent.builder()\n .repoModule(new RepoModule())\n .appModule...
import android.app.Application; import android.util.Log; import com.example.ericliu.weather2016.application.MyApplication; import com.example.ericliu.weather2016.common.NetworkConstants; import com.example.ericliu.weather2016.framework.repository.Repository; import com.example.ericliu.weather2016.framework.repository.RepositoryResult; import com.example.ericliu.weather2016.framework.repository.Specification; import com.example.ericliu.weather2016.model.WeatherResult; import com.example.ericliu.weather2016.model.WeatherSpecification; import com.google.gson.Gson; import java.io.IOException; import java.util.List; import javax.inject.Inject; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;
package com.example.ericliu.weather2016.repo; /** * Created by ericliu on 12/04/2016. */ public class RemoteWeatherRepo implements Repository<WeatherResult> { private static final String TAG = RemoteWeatherRepo.class.getSimpleName(); @Inject Application mApplication; @Inject Gson mGson; @Inject OkHttpClient mOkHttpClient; public RemoteWeatherRepo() { MyApplication.getComponent().inject(this); } @Override
public WeatherResult get(Specification specification) throws IOException {
4
Team254/FRC-2013
src/com/team254/frc2013/auto/ThreeDiscAutoMode.java
[ "public class ResetDriveEncodersCommand extends CommandBase {\n protected void initialize() {\n drive.resetEncoders();\n }\n\n protected void execute() {\n }\n\n protected boolean isFinished() {\n return true;\n }\n\n protected void end() {\n }\n\n protected void interrupted() {\n }\n}", "public c...
import com.team254.frc2013.commands.ResetDriveEncodersCommand; import com.team254.frc2013.commands.ResetGyroCommand; import com.team254.frc2013.commands.RunIntakeCommand; import com.team254.frc2013.commands.SetIntakeDownCommand; import com.team254.frc2013.commands.ShootSequenceCommand; import com.team254.frc2013.commands.ShooterOnCommand; import com.team254.frc2013.commands.ShooterPresetCommand; import com.team254.frc2013.commands.WaitCommand; import com.team254.frc2013.subsystems.Shooter; import edu.wpi.first.wpilibj.command.CommandGroup;
package com.team254.frc2013.auto; /** * Shoots three preloaded discs from the back of the pyramid * * @author jonathan.chang13@gmail.com (Jonathan Chang) */ public class ThreeDiscAutoMode extends CommandGroup { public ThreeDiscAutoMode() { addSequential(new ResetDriveEncodersCommand());
addSequential(new ResetGyroCommand());
1
tastybento/askygrid
src/com/wasteofplastic/askygrid/commands/SkyGridCmd.java
[ "public class ASkyGrid extends JavaPlugin {\n // This plugin\n private static ASkyGrid plugin;\n // The ASkyGrid world\n private static World gridWorld = null;\n private static World netherWorld = null;\n private static World endWorld = null;\n // Player folder file\n private File playersFol...
import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.UUID; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionAttachmentInfo; import com.wasteofplastic.askygrid.ASkyGrid; import com.wasteofplastic.askygrid.GridManager; import com.wasteofplastic.askygrid.Settings; import com.wasteofplastic.askygrid.listeners.PlayerEvents; import com.wasteofplastic.askygrid.util.Util; import com.wasteofplastic.askygrid.util.VaultHelper;
/******************************************************************************* * This file is part of ASkyGrid. * * ASkyGrid 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. * * ASkyGrid 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 ASkyGrid. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package com.wasteofplastic.askygrid.commands; public class SkyGridCmd implements CommandExecutor, TabCompleter { public boolean levelCalcFreeFlag = true; private ASkyGrid plugin; /** * Constructor * * @param plugin * @param players */ public SkyGridCmd(ASkyGrid plugin) { // Plugin instance this.plugin = plugin; } /** * Makes the default home for the player * @param player */ public void newHome(final Player player) { //long time = System.nanoTime(); final UUID playerUUID = player.getUniqueId(); Util.logger(2,"DEBUG: finding spawn location"); Random random = new Random(); long x = (random.nextInt(Settings.spawnDistance*2) - Settings.spawnDistance) + Settings.spawnCenterX; long z = (random.nextInt(Settings.spawnDistance*2) - Settings.spawnDistance) + Settings.spawnCenterZ; Location next = new Location(ASkyGrid.getGridWorld(), x, Settings.spawnHeight, z); // Check world Guard int tries = 0; if (plugin.getWorldGuard() != null && Settings.claim_protectionRange > 0) { while (!plugin.getGguard().canBuild(player, next) && tries < 10) { x = (random.nextInt(Settings.spawnDistance*2) - Settings.spawnDistance) + Settings.spawnCenterX; z = (random.nextInt(Settings.spawnDistance*2) - Settings.spawnDistance) + Settings.spawnCenterZ; next = new Location(ASkyGrid.getGridWorld(), x, Settings.spawnHeight, z); tries++; } if (tries == 10) { plugin.getLogger().warning("Could not find an unclaimed spot for player to spawn. Try increasing spawn distance or move spawn center"); } } Util.logger(2,"DEBUG: found " + next); // Clear any old home locations (they should be clear, but just in case) plugin.getPlayers().clearHomeLocations(playerUUID); // Set the player's island location to this new spot plugin.getPlayers().setHomeLocation(playerUUID, next); // Save the player so that if the server is reset weird things won't happen plugin.getPlayers().save(playerUUID); // Set the biome //BiomesPanel.setIslandBiome(next, schematic.getBiome()); // Teleport to the new home plugin.getGrid().homeTeleport(player); // Reset any inventory, etc. This is done AFTER the teleport because other plugins may switch out inventory based on world plugin.resetPlayer(player); // Reset money if required if (Settings.resetMoney) { resetMoney(player); } // Show fancy titles! // Show fancy titles! if (!Bukkit.getServer().getVersion().contains("(MC: 1.7")) { if (!plugin.myLocale(player.getUniqueId()).gridSubTitle.isEmpty()) { //plugin.getLogger().info("DEBUG: title " + player.getName() + " subtitle {\"text\":\"" + plugin.myLocale(player.getUniqueId()).islandSubTitle + "\", \"color\":\"" + plugin.myLocale(player.getUniqueId()).islandSubTitleColor + "\"}"); plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "title " + player.getName() + " subtitle {\"text\":\"" + plugin.myLocale(player.getUniqueId()).gridSubTitle + "\", \"color\":\"" + plugin.myLocale(player.getUniqueId()).gridSubTitleColor + "\"}"); } if (!plugin.myLocale(player.getUniqueId()).gridTitle.isEmpty()) { //plugin.getLogger().info("DEBUG: title " + player.getName() + " title {\"text\":\"" + plugin.myLocale(player.getUniqueId()).islandTitle + "\", \"color\":\"" + plugin.myLocale(player.getUniqueId()).islandTitleColor + "\"}"); plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "title " + player.getName() + " title {\"text\":\"" + plugin.myLocale(player.getUniqueId()).gridTitle + "\", \"color\":\"" + plugin.myLocale(player.getUniqueId()).gridTitleColor + "\"}"); } if (!plugin.myLocale(player.getUniqueId()).gridDonate.isEmpty() && !plugin.myLocale(player.getUniqueId()).gridURL.isEmpty()) { //plugin.getLogger().info("DEBUG: tellraw " + player.getName() + " {\"text\":\"" + plugin.myLocale(player.getUniqueId()).islandDonate + "\",\"color\":\"" + plugin.myLocale(player.getUniqueId()).islandDonateColor + "\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"" // + plugin.myLocale(player.getUniqueId()).islandURL + "\"}}"); plugin.getServer().dispatchCommand( plugin.getServer().getConsoleSender(), "tellraw " + player.getName() + " {\"text\":\"" + plugin.myLocale(player.getUniqueId()).gridDonate + "\",\"color\":\"" + plugin.myLocale(player.getUniqueId()).gridDonateColor + "\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"" + plugin.myLocale(player.getUniqueId()).gridURL + "\"}}"); } } // Run any commands that need to be run at the start /* if (firstTime) { runCommands(Settings.startCommands, player.getUniqueId()); }*/ // Done - fire event //final IslandNewEvent event = new IslandNewEvent(player,schematic, myIsland); //plugin.getServer().getPluginManager().callEvent(event); //Util.logger(2,"DEBUG: Done! " + (System.nanoTime()- time) * 0.000001); } private void resetMoney(Player player) { if (!Settings.useEconomy) { return; } // Set player's balance in acid island to the starting balance try { // Util.logger(2,"DEBUG: " + player.getName() + " " + // Settings.general_worldName);
if (VaultHelper.econ == null) {
5
Atmosphere/wasync
wasync/src/test/java/org/atmosphere/tests/SSETest.java
[ "public class ClientFactory {\n\n private final static ClientFactory factory = new ClientFactory();\n private final String clientClassName;\n\n public ClientFactory() {\n clientClassName = System.getProperty(\"wasync.client\");\n }\n\n /**\n * Return the default Factory.\n *\n * @r...
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import java.net.ServerSocket; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.asynchttpclient.AsyncHttpClient; import org.atmosphere.cpr.AtmosphereHandler; import org.atmosphere.cpr.AtmosphereResource; import org.atmosphere.cpr.AtmosphereResourceEvent; import org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter; import org.atmosphere.nettosphere.Config; import org.atmosphere.nettosphere.Nettosphere; import org.atmosphere.wasync.ClientFactory; import org.atmosphere.wasync.Event; import org.atmosphere.wasync.Function; import org.atmosphere.wasync.Request; import org.atmosphere.wasync.RequestBuilder; import org.atmosphere.wasync.Socket; import org.atmosphere.wasync.impl.AtmosphereClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
/* * Copyright 2008-2022 Async-IO.org * * 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.atmosphere.tests; /** * @author Sebastian Lövdahl <slovdahl@hibox.fi> */ public class SSETest { private static final Logger logger = LoggerFactory.getLogger(SSETest.class); protected final static String RESUME = "Resume"; protected Nettosphere server; protected String targetUrl; protected int port; protected AsyncHttpClient ahc; protected int findFreePort() throws IOException { ServerSocket socket = null; try { socket = new ServerSocket(0); return socket.getLocalPort(); } finally { if (socket != null) { socket.close(); } } } @AfterMethod(alwaysRun = true) public void tearDownGlobal() throws Exception { if (server != null && server.isStarted()) { server.stop(); ahc.close(); } } @BeforeMethod(alwaysRun = true) public void start() throws IOException { port = findFreePort(); targetUrl = "http://127.0.0.1:" + port; ahc = BaseTest.createDefaultAsyncHttpClient(); } Request.TRANSPORT transport() { return Request.TRANSPORT.SSE; } int statusCode() { return 200; } int notFoundCode() { return 404; } int getCount() { return 5; } @Test(timeOut = 20000) public void closeTest() throws Exception { Config config = new Config.Builder() .port(port) .host("127.0.0.1") .resource("/suspend", new AtmosphereHandler() { private final AtomicBoolean b = new AtomicBoolean(false); @Override public void onRequest(AtmosphereResource r) throws IOException { if (!b.getAndSet(true)) { r.suspend(-1); } else { r.getBroadcaster().broadcast(RESUME); } } @Override public void onStateChange(AtmosphereResourceEvent r) throws IOException { if (!r.isResuming() || !r.isCancelled()) { r.getResource().getResponse().getWriter().print(r.getMessage()); r.getResource().resume(); } } @Override public void destroy() { } }).build(); server = new Nettosphere.Builder().config(config).build(); assertNotNull(server); server.start(); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<String> response = new AtomicReference<String>();
AtmosphereClient client = ClientFactory.getDefault().newClient(AtmosphereClient.class);
6
longkai/catnut
src/org/catnut/plugin/fantasy/Photo.java
[ "public class CatnutApp extends Application {\n\n\tpublic static final String TAG = \"CatnutApp\";\n\n\t/** singleton */\n\tprivate static CatnutApp sApp;\n\t/** http request header for weibo' s access token */\n\tprivate static Map<String, String> sAuthHeaders;\n\n\tprivate RequestQueue mRequestQueue;\n\tprivate S...
import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.provider.BaseColumns; import android.util.Log; import org.catnut.R; import org.catnut.core.CatnutApp; import org.catnut.core.CatnutMetadata; import org.catnut.core.CatnutProcessor; import org.catnut.core.CatnutProvider; import org.catnut.util.Constants; import org.catnut.util.DateTime; import org.json.JSONArray; import org.json.JSONObject;
/* * The MIT License (MIT) * Copyright (c) 2014 longkai * The software shall be used for good, not evil. */ package org.catnut.plugin.fantasy; /** * fantasy * * @author longkai */ public class Photo implements CatnutMetadata<JSONObject, ContentValues> { public static final String TAG = "Photo"; public static final String TABLE = "photos"; public static final String SINGLE = "photo"; public static final String MULTIPLE = "photos"; public static final String LAST_FANTASY_MILLIS = "last_fantasy_millis"; public static final String FEATURE_POPULAR = "popular"; public static final String FEATURE_EDITORS = "editors"; public static final String FEATURE_UPCOMING = "upcoming"; public static final String FEATURE_FRESH_TODAY = "fresh_today"; public static final String FEATURE_FRESH_YESTERDAY = "fresh_yesterday"; public static final String FEATURE_FRESH_WEEK = "fresh_week"; public static final String feature = "feature"; public static final String name = "name"; public static final String width = "width"; public static final String height = "height"; public static final String description = "description"; public static final String image_url = "image_url"; public static final Photo METADATA = new Photo(); private Photo() { } @Override public String ddl() { Log.i(TAG, "create table [photos]..."); StringBuilder ddl = new StringBuilder("CREATE TABLE "); ddl.append(TABLE).append("(") .append(BaseColumns._ID).append(" int primary key,") .append(name).append(" text,") .append(feature).append(" text,") .append(description).append(" text,") .append(image_url).append(" int,") .append(width).append(" int, ") .append(height).append(" int") .append(")"); return ddl.toString(); } public static boolean shouldRefresh() { CatnutApp app = CatnutApp.getTingtingApp(); SharedPreferences pref = app.getPreferences(); return !pref.contains(app.getString(R.string.pref_first_run)) ? true : pref.getBoolean( app.getString(R.string.pref_enable_fantasy), app.getResources().getBoolean(R.bool.default_plugin_status)
) && System.currentTimeMillis() - pref.getLong(LAST_FANTASY_MILLIS, 0) > DateTime.DAY_MILLIS;
5
qubole/presto-kinesis
src/test/java/com/qubole/presto/kinesis/decoder/json/TestRFC2822JsonKinesisFieldDecoder.java
[ "@VisibleForTesting\nstatic final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern(\"EEE MMM dd HH:mm:ss Z yyyy\").withLocale(Locale.ENGLISH).withZoneUTC();", "public static void checkIsNull(Set<KinesisFieldValueProvider> providers, KinesisColumnHandle handle)\n{\n KinesisFieldValueProvider provider = f...
import static com.qubole.presto.kinesis.decoder.json.RFC2822JsonKinesisFieldDecoder.FORMATTER; import static com.qubole.presto.kinesis.decoder.util.DecoderTestUtil.checkIsNull; import static com.qubole.presto.kinesis.decoder.util.DecoderTestUtil.checkValue; import static java.lang.String.format; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import com.qubole.presto.kinesis.decoder.KinesisFieldDecoder; import io.airlift.json.ObjectMapperProvider; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.annotations.Test; import com.qubole.presto.kinesis.KinesisColumnHandle; import com.qubole.presto.kinesis.KinesisFieldValueProvider; import com.facebook.presto.spi.type.BigintType; import com.facebook.presto.spi.type.VarcharType; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap;
/* * 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.qubole.presto.kinesis.decoder.json; public class TestRFC2822JsonKinesisFieldDecoder { private static final Map<String, JsonKinesisFieldDecoder> DECODERS = ImmutableMap.of(KinesisFieldDecoder.DEFAULT_FIELD_DECODER_NAME, new JsonKinesisFieldDecoder(), RFC2822JsonKinesisFieldDecoder.NAME, new RFC2822JsonKinesisFieldDecoder()); private static final ObjectMapperProvider PROVIDER = new ObjectMapperProvider();
private static Map<KinesisColumnHandle, KinesisFieldDecoder<?>> map(List<KinesisColumnHandle> columns)
4
kendzi/kendzi-math
kendzi-straight-skeleton/src/main/java/kendzi/math/geometry/skeleton/debug/display/DisplayLav2.java
[ "abstract public class DisplayObject {\n\n\tabstract public void draw(Graphics2D g2d, EquationDisplay disp, boolean selected);\n\n\tabstract public Object drawObject();\n\n\tabstract public DisplayRectBounds getBounds();\n\n}", "public class DisplayRectBounds {\r\n double minX = Double.MAX_VALUE;\r\n double...
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Stroke; import javax.vecmath.Point2d; import kendzi.math.geometry.debug.DisplayObject; import kendzi.math.geometry.debug.DisplayRectBounds; import kendzi.math.geometry.skeleton.circular.CircularList; import kendzi.math.geometry.skeleton.circular.Vertex; import kendzi.swing.ui.panel.equation.EquationDisplay;
package kendzi.math.geometry.skeleton.debug.display; /** * * @author Tomasz Kędziora (kendzi) */ public class DisplayLav2 extends DisplayObject { private CircularList<Vertex> lav; private Color color; /** * @param LAV * @param pColor */ public DisplayLav2(CircularList<Vertex> lav, Color pColor) { super(); this.lav = lav; this.color = pColor; } @Override
public void draw(Graphics2D g2d, EquationDisplay disp, boolean selected) {
4
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/adapter/HomeAdapter.java
[ "public class OneStopActivity extends AppCompatActivity {\n private Toolbar toolbar;\n private ViewPager viewPager;\n private SlidingTabLayout slidingTabLayout;\n\n private FavoriteStops favoriteStops;\n private FavoriteStopLine favoriteStopLine;\n\n private int stop_zone_id;\n private StopZone...
import android.content.Intent; import android.os.Bundle; import android.support.annotation.UiThread; import android.support.v4.app.FragmentActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.activity.OneStopActivity; import flying.grub.tamtime.data.map.Line; import flying.grub.tamtime.data.persistence.LineStop; import flying.grub.tamtime.data.map.StopZone; import flying.grub.tamtime.layout.FavHomeView; import flying.grub.tamtime.layout.SearchView;
package flying.grub.tamtime.adapter; public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final String TAG = HomeAdapter.class.getSimpleName(); private static final int TYPE_HEADER = 0; private static final int TYPE_ITEM = 1; private static final int TYPE_FOOTER = 2; public OnItemClickListener mItemClickListener; private ArrayList<LineStop> favoriteStopLine; private FragmentActivity context;
private FavHomeView favHomeView;
4
offa/NBCndUnit
src/test/java/bv/offa/netbeans/cnd/unittest/googletest/GoogleTestSuiteStartedHandlerTest.java
[ "public class CndTestSuite extends TestSuite\n{\n private final TestFramework framework;\n \n public CndTestSuite(String name, TestFramework framework)\n {\n super(name);\n this.framework = framework;\n }\n\n \n /**\n * Returns the framework.\n * \n * @return Framewor...
import bv.offa.netbeans.cnd.unittest.api.CndTestSuite; import bv.offa.netbeans.cnd.unittest.api.ManagerAdapter; import bv.offa.netbeans.cnd.unittest.api.TestFramework; import static bv.offa.netbeans.cnd.unittest.testhelper.Helper.checkedMatch; import static bv.offa.netbeans.cnd.unittest.testhelper.Helper.createCurrentTestSuite; import static bv.offa.netbeans.cnd.unittest.testhelper.MockArgumentMatcher.isSuite; import static com.google.common.truth.Truth.assertThat; import java.util.regex.Matcher; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import org.mockito.InOrder; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.netbeans.api.project.Project; import org.netbeans.modules.gsf.testrunner.api.Report; import org.netbeans.modules.gsf.testrunner.api.TestSession; import org.netbeans.modules.gsf.testrunner.api.TestSuite; import org.openide.filesystems.FileUtil; import org.openide.util.Lookup;
/* * NBCndUnit - C/C++ unit tests for NetBeans. * Copyright (C) 2015-2021 offa * * This file is part of NBCndUnit. * * NBCndUnit 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. * * NBCndUnit 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 NBCndUnit. If not, see <http://www.gnu.org/licenses/>. */ package bv.offa.netbeans.cnd.unittest.googletest; @Tag("Test-Framework") @Tag("GoogleTest") public class GoogleTestSuiteStartedHandlerTest { private static final TestFramework FRAMEWORK = TestFramework.GOOGLETEST; private static Project project; private static Report report; private GoogleTestSuiteStartedHandler handler; private TestSession session;
private ManagerAdapter manager;
1
TooTallNate/Java-WebSocket
src/test/java/org/java_websocket/issues/Issue677Test.java
[ "public interface WebSocket {\n\n /**\n * sends the closing handshake. may be send in response to an other handshake.\n *\n * @param code the closing code\n * @param message the closing message\n */\n void close(int code, String message);\n\n /**\n * sends the closing handshake. may be send in res...
import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.framing.CloseFrame; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.junit.Test; import static org.junit.Assert.assertTrue; import java.net.InetSocketAddress; import java.net.URI; import java.util.concurrent.CountDownLatch;
/* * Copyright (c) 2010-2020 Nathan Rajlich * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.issues; public class Issue677Test { CountDownLatch countDownLatch0 = new CountDownLatch(1); CountDownLatch countServerDownLatch = new CountDownLatch(1); @Test public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort();
WebSocketClient webSocket0 = new WebSocketClient(new URI("ws://localhost:" + port)) {
1
daneren2005/Subsonic
app/src/main/java/github/daneren2005/dsub/util/UserUtil.java
[ "public class DownloadService extends Service {\n\tprivate static final String TAG = DownloadService.class.getSimpleName();\n\n\tpublic static final String CMD_PLAY = \"github.daneren2005.dsub.CMD_PLAY\";\n\tpublic static final String CMD_TOGGLEPAUSE = \"github.daneren2005.dsub.CMD_TOGGLEPAUSE\";\n\tpublic static f...
import android.app.Activity; import android.support.v7.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import github.daneren2005.dsub.R; import github.daneren2005.dsub.adapter.SectionAdapter; import github.daneren2005.dsub.domain.User; import github.daneren2005.dsub.fragments.SubsonicFragment; import github.daneren2005.dsub.service.DownloadService; import github.daneren2005.dsub.service.MusicService; import github.daneren2005.dsub.service.MusicServiceFactory; import github.daneren2005.dsub.service.OfflineException; import github.daneren2005.dsub.service.ServerTooOldException; import github.daneren2005.dsub.adapter.SettingsAdapter; import github.daneren2005.dsub.view.UpdateView;
public static void changeEmail(final Activity context, final User user) { View layout = context.getLayoutInflater().inflate(R.layout.change_email, null); final TextView emailView = (TextView) layout.findViewById(R.id.new_email); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.admin_change_email) .setView(layout) .setPositiveButton(R.string.common_save, null) .setNegativeButton(R.string.common_cancel, null) .setCancelable(true); final AlertDialog dialog = builder.create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String email = emailView.getText().toString(); // Don't allow blank emails if ("".equals(email)) { Util.toast(context, R.string.admin_change_email_invalid); return; } new SilentBackgroundTask<Void>(context) { @Override protected Void doInBackground() throws Throwable { MusicService musicService = MusicServiceFactory.getMusicService(context); musicService.changeEmail(user.getUsername(), email, context, null); user.setEmail(email); return null; } @Override protected void done(Void v) { Util.toast(context, context.getResources().getString(R.string.admin_change_email_success, user.getUsername())); } @Override protected void error(Throwable error) { String msg; if (error instanceof OfflineException || error instanceof ServerTooOldException) { msg = getErrorMessage(error); } else { msg = context.getResources().getString(R.string.admin_change_email_error, user.getUsername()); } Util.toast(context, msg); } }.execute(); dialog.dismiss(); } }); } public static void deleteUser(final Context context, final User user, final SectionAdapter adapter) { Util.confirmDialog(context, R.string.common_delete, user.getUsername(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new SilentBackgroundTask<Void>(context) { @Override protected Void doInBackground() throws Throwable { MusicService musicService = MusicServiceFactory.getMusicService(context); musicService.deleteUser(user.getUsername(), context, null); return null; } @Override protected void done(Void v) { if(adapter != null) { adapter.removeItem(user); } Util.toast(context, context.getResources().getString(R.string.admin_delete_user_success, user.getUsername())); } @Override protected void error(Throwable error) { String msg; if (error instanceof OfflineException || error instanceof ServerTooOldException) { msg = getErrorMessage(error); } else { msg = context.getResources().getString(R.string.admin_delete_user_error, user.getUsername()); } Util.toast(context, msg); } }.execute(); } }); } public static void addNewUser(final Activity context, final SubsonicFragment fragment, User sampleUser) { final User user = new User(); for(String role: User.ROLES) { if(role.equals(User.SETTINGS) || role.equals(User.STREAM)) { user.addSetting(role, true); } else { user.addSetting(role, false); } } if(sampleUser != null && sampleUser.getMusicFolderSettings() != null) { for(User.Setting setting: sampleUser.getMusicFolderSettings()) { User.MusicFolderSetting musicFolderSetting = (User.MusicFolderSetting) setting; user.addMusicFolder(musicFolderSetting, true); } } View layout = context.getLayoutInflater().inflate(R.layout.create_user, null); final TextView usernameView = (TextView) layout.findViewById(R.id.username); final TextView emailView = (TextView) layout.findViewById(R.id.email); final TextView passwordView = (TextView) layout.findViewById(R.id.password); final RecyclerView recyclerView = (RecyclerView) layout.findViewById(R.id.settings_list); LinearLayoutManager layoutManager = new LinearLayoutManager(context); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(SettingsAdapter.getSettingsAdapter(context, user, null, true, new SectionAdapter.OnItemClickedListener<User.Setting>() { @Override
public void onItemClicked(UpdateView<User.Setting> updateView, User.Setting item) {
4
HarryXR/SimpleNews
app/src/main/java/com/lauren/simplenews/news/presenter/NewsPresenterImpl.java
[ "public class NewsBean implements Serializable {\n\n /**\n * docid\n */\n public String docid;\n /**\n * 标题\n */\n public String title;\n /**\n * 小内容\n */\n public String digest;\n /**\n * 图片地址\n */\n public String imgsrc;\n /**\n * 来源\n */\n pub...
import com.lauren.simplenews.beans.NewsBean; import com.lauren.simplenews.commons.Urls; import com.lauren.simplenews.news.model.NewsModel; import com.lauren.simplenews.news.model.NewsModelImpl; import com.lauren.simplenews.news.view.NewsView; import com.lauren.simplenews.news.widget.NewsFragment; import com.lauren.simplenews.utils.LogUtils; import java.util.List;
package com.lauren.simplenews.news.presenter; /** * Description : * Author : lauren * Email : lauren.liuling@gmail.com * Blog : http://www.liuling123.com * Date : 15/12/18 */ public class NewsPresenterImpl implements NewsPresenter, NewsModelImpl.OnLoadNewsListListener { private static final String TAG = "NewsPresenterImpl"; private NewsView mNewsView; private NewsModel mNewsModel; public NewsPresenterImpl(NewsView newsView) { this.mNewsView = newsView; this.mNewsModel = new NewsModelImpl(); } @Override public void loadNews(final int type, final int pageIndex) { String url = getUrl(type, pageIndex);
LogUtils.d(TAG, url);
6
kaif-open/kaif-android
app/src/main/java/io/kaif/mobile/service/ServiceModule.java
[ "public class ApiConfiguration {\n\n private String endPoint;\n\n private String clientId;\n\n private String redirectUri;\n\n private String clientSecret;\n\n public ApiConfiguration(String endPoint,\n String clientId,\n String clientSecret,\n String redirectUri) {\n this.endPoint = endPoint...
import android.app.Application; import android.net.ConnectivityManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.kaif.mobile.BuildConfig; import io.kaif.mobile.R; import io.kaif.mobile.config.ApiConfiguration; import io.kaif.mobile.json.ApiResponseDeserializer; import io.kaif.mobile.model.oauth.AccessTokenInfo; import io.kaif.mobile.model.oauth.AccessTokenManager; import io.kaif.mobile.retrofit.RetrofitRetryStaleProxy; import okhttp3.Cache; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers;
package io.kaif.mobile.service; @Module public class ServiceModule { private final Application application; private static final int CACHE_SIZE = 10 * 1024 * 1024; public ServiceModule(Application application) { this.application = application; } @Provides @Singleton public FeedService provideFeedService( @Named("apiRetrofit") RetrofitRetryStaleProxy restAdapter) { return restAdapter.create(FeedService.class); } @Provides @Singleton public AccountService provideAccountService( @Named("apiRetrofit") RetrofitRetryStaleProxy restAdapter) { return restAdapter.create(AccountService.class); } @Provides @Singleton public ZoneService provideZoneService( @Named("apiRetrofit") RetrofitRetryStaleProxy restAdapter) { return restAdapter.create(ZoneService.class); } @Provides @Singleton public VoteService provideVoteService( @Named("apiRetrofit") RetrofitRetryStaleProxy restAdapter) { return restAdapter.create(VoteService.class); } @Provides @Singleton public DebateService provideDebateService( @Named("apiRetrofit") RetrofitRetryStaleProxy restAdapter) { return restAdapter.create(DebateService.class); } @Provides @Singleton public ArticleService provideArticleService( @Named("apiRetrofit") RetrofitRetryStaleProxy restAdapter) { return restAdapter.create(ArticleService.class); } @Provides @Singleton public OauthService provideOauthService(@Named("oauthRetrofit") Retrofit retrofit) { return retrofit.create(OauthService.class); } @Provides @Singleton public Interceptor provideHeaderRequestInterceptor(AccessTokenManager accessTokenManager, ConnectivityManager connectivityManager) { return chain -> {
final AccessTokenInfo accountTokenInfo = accessTokenManager.findAccount();
2
4FunApp/4Fun
client/FourFun/app/src/main/java/com/joker/fourfun/di/component/ActivityComponent.java
[ "@Module\npublic class ActivityModule {\n private AppCompatActivity mActivity;\n\n public ActivityModule(AppCompatActivity appCompatActivity) {\n mActivity = appCompatActivity;\n }\n\n @Provides\n @PerActivity\n AppCompatActivity provideActivity() {\n return mActivity;\n }\n}", ...
import android.support.v7.app.AppCompatActivity; import com.joker.fourfun.di.PerActivity; import com.joker.fourfun.di.module.ActivityModule; import com.joker.fourfun.ui.LoginActivity; import com.joker.fourfun.ui.MainActivity; import com.joker.fourfun.ui.MovieDetailActivity; import com.joker.fourfun.ui.PictureDetailActivity; import com.joker.fourfun.ui.RegisterActivity; import com.joker.fourfun.ui.SplashActivity; import dagger.Component;
package com.joker.fourfun.di.component; /** * Created by joker on 2016/11/28. */ @PerActivity @Component(dependencies = AppComponent.class, modules = ActivityModule.class) public interface ActivityComponent { AppCompatActivity activity(); void inject(SplashActivity activity); void inject(MainActivity activity); void inject(PictureDetailActivity activity); void inject(LoginActivity activity);
void inject(RegisterActivity activity);
5
teivah/TIBreview
src/test/java/com/tibco/exchange/tibreview/processor/resourcerule/CProcessorProxyConfigurationTest.java
[ "public class TIBResource {\n\tprivate String filePath;\n\tprivate String type;\n\t\n\tprivate static final String REQUEST_GET_TYPE = \"/jndi:namedResource/@type\";\n\t\n\tpublic TIBResource(String filePath) throws Exception {\n\t\tthis.filePath = filePath;\n\t\tthis.type = Util.xpathEval(filePath, Constants.RESOUR...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import org.apache.log4j.Logger; import org.junit.Test; import com.tibco.exchange.tibreview.common.TIBResource; import com.tibco.exchange.tibreview.engine.Context; import com.tibco.exchange.tibreview.model.pmd.Violation; import com.tibco.exchange.tibreview.model.rules.Configuration; import com.tibco.exchange.tibreview.model.rules.Resource; import com.tibco.exchange.tibreview.model.rules.Tibrules; import com.tibco.exchange.tibreview.parser.RulesParser;
package com.tibco.exchange.tibreview.processor.resourcerule; public class CProcessorProxyConfigurationTest { private static final Logger LOGGER = Logger.getLogger(CProcessorProxyConfigurationTest.class); @Test public void testCProcessorLDAPConfigurationTest() { TIBResource fileresource; try { fileresource = new TIBResource("src/test/resources/FileResources/ProxyConfigurationResource.httpProxyResource"); fileresource.toString(); LOGGER.info(fileresource.toString()); assertTrue(fileresource.toString().equals("TIBResource [filePath=src/test/resources/FileResources/ProxyConfigurationResource.httpProxyResource, type=httpproxy:ProxyConfiguration]")); Tibrules tibrules= RulesParser.getInstance().parseFile("src/test/resources/FileResources/xml/ProxyConfigurationResource.xml"); Resource resource = tibrules.getResource(); LOGGER.info(resource.getRule().size()); assertEquals(resource.getRule().size(),1); ConfigurationProcessor a = new ConfigurationProcessor();
Configuration Configuracion = resource.getRule().get(0).getConfiguration();
3
indvd00m/java-ascii-render
ascii-render/src/test/java/com/indvd00m/ascii/render/tests/TestOverlay.java
[ "public class Canvas implements ICanvas {\n\n\tpublic static final char NULL_CHAR = '\\0';\n\n\tprotected final int width;\n\tprotected final int height;\n\tprotected final List<StringBuilder> lines;\n\n\t// cache\n\tprotected String cachedText;\n\tprotected String cachedLines;\n\tprotected boolean needUpdateCache ...
import com.indvd00m.ascii.render.Canvas; import com.indvd00m.ascii.render.Render; import com.indvd00m.ascii.render.api.ICanvas; import com.indvd00m.ascii.render.api.IContext; import com.indvd00m.ascii.render.api.IContextBuilder; import com.indvd00m.ascii.render.api.IRender; import com.indvd00m.ascii.render.elements.Dot; import com.indvd00m.ascii.render.elements.Overlay; import com.indvd00m.ascii.render.elements.Rectangle; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock;
package com.indvd00m.ascii.render.tests; /** * @author indvd00m (gotoindvdum[at]gmail[dot]com) * @since 1.4.0 */ public class TestOverlay { @Test public void test01() { IRender render = new Render(); IContextBuilder builder = render.newBuilder(); builder.width(21).height(10);
builder.element(new Rectangle());
8
KeithYokoma/LGTMCamera
app/src/main/java/jp/yokomark/lgtm/app/preference/ui/PreferenceActivity.java
[ "@Module(\n\t\tcomplete = false,\n\t\tlibrary = true\n)\npublic class ActivityModule {\n\tprivate final Activity mActivity;\n\n\tpublic ActivityModule(Activity activity) {\n\t\tmActivity = activity;\n\t}\n\n\t@Provides\n\t@Singleton\n\tObjectGraph provideActivityGraph() {\n\t\tif (mActivity instanceof DaggerFragmen...
import android.os.Bundle; import android.view.MenuItem; import com.anprosit.android.dagger.ActivityModule; import com.anprosit.android.dagger.ui.DaggerActivity; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import jp.yokomark.lgtm.R; import jp.yokomark.lgtm.app.preference.ui.helper.PreferenceListHelper; import jp.yokomark.lgtm.app.preference.ui.helper.PreferenceModule; import jp.yokomark.lgtm.app.preference.ui.helper.options.PreferenceOptionsMenu;
package jp.yokomark.lgtm.app.preference.ui; /** * @author yokomakukeishin * @version 1.0.0 * @since 1.0.0 */ public class PreferenceActivity extends DaggerActivity { public static final String TAG = PreferenceActivity.class.getSimpleName();
@Inject PreferenceListHelper mHelper;
2
beckchr/juel
modules/impl/src/main/java/de/odysseus/el/tree/impl/ast/AstIdentifier.java
[ "public abstract class ELContext {\r\n\tprivate Map<Class<?>, Object> context;\r\n\tprivate Locale locale;\r\n\tprivate boolean resolved;\r\n\r\n\t/**\r\n\t * Returns the context object associated with the given key. The ELContext maintains a\r\n\t * collection of context objects relevant to the evaluation of an ex...
import de.odysseus.el.tree.IdentifierNode; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import javax.el.ELContext; import javax.el.ELException; import javax.el.MethodExpression; import javax.el.MethodInfo; import javax.el.MethodNotFoundException; import javax.el.PropertyNotFoundException; import javax.el.ValueExpression; import javax.el.ValueReference; import de.odysseus.el.misc.LocalMessages; import de.odysseus.el.tree.Bindings;
/* * Copyright 2006-2009 Odysseus Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.odysseus.el.tree.impl.ast; public class AstIdentifier extends AstNode implements IdentifierNode { private final String name; private final int index; private final boolean ignoreReturnType; public AstIdentifier(String name, int index) { this(name, index, false); } public AstIdentifier(String name, int index, boolean ignoreReturnType) { this.name = name; this.index = index; this.ignoreReturnType = ignoreReturnType; } public Class<?> getType(Bindings bindings, ELContext context) {
ValueExpression expression = bindings.getVariable(index);
4
yammer/telemetry
telemetry-agent/src/test/java/com/yammer/telemetry/agent/TelemetryTransformerTest.java
[ "public interface ClassInstrumentationHandler {\n boolean transformed(CtClass cc, ClassPool pool);\n}", "public abstract class SubTypeInstrumentationHandler implements ClassInstrumentationHandler {\n private static final Logger LOGGER = Logger.getLogger(SubTypeInstrumentationHandler.class.getName());\n p...
import com.yammer.telemetry.instrumentation.ClassInstrumentationHandler; import com.yammer.telemetry.agent.handlers.SubTypeInstrumentationHandler; import com.yammer.telemetry.test.TransformingClassLoader; import com.yammer.telemetry.instrumentation.TelemetryTransformer; import javassist.*; import org.junit.Test; import java.io.IOException; import static com.yammer.telemetry.agent.TelemetryTransformerTest.ClassUtils.wrapMethod; import static org.junit.Assert.*;
package com.yammer.telemetry.agent; public class TelemetryTransformerTest { @Test public void testUnmodifiedWhenNoHandlersAdded() throws Exception { TelemetryTransformer transformer = new TelemetryTransformer(); assertNull(transformer.transform(getClass().getClassLoader(), "com/yammer/telemetry/agent/test/SimpleBean", null, null, new byte[0])); } @Test public void testUnmodifiedWhenNotHandled() throws Exception { TelemetryTransformer transformer = new TelemetryTransformer();
transformer.addHandler(new ClassInstrumentationHandler() {
0
Protino/Fad-Flicks
app/src/main/java/com/calgen/prodek/fadflicks/Fragment/GridFragment.java
[ "public class MainActivity extends AppCompatActivity implements GridFragment.ReloadCallback {\n\n //re-enable usage of vectors for devices(API 19 and lower)\n static {\n AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);\n }\n\n public static final String MOVIE_DETAIL_FRAGMENT_TAG = \"M...
import android.content.Context; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import com.calgen.prodek.fadflicks.R; import com.calgen.prodek.fadflicks.activity.MainActivity; import com.calgen.prodek.fadflicks.adapter.GridMovieAdapter; import com.calgen.prodek.fadflicks.api.ApiClient; import com.calgen.prodek.fadflicks.model.Movie; import com.calgen.prodek.fadflicks.model.MovieBundle; import com.calgen.prodek.fadflicks.model.MovieResponse; import com.calgen.prodek.fadflicks.utils.ApplicationConstants; import com.calgen.prodek.fadflicks.utils.Cache; import com.calgen.prodek.fadflicks.utils.Network; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import butterknife.BindString; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import icepick.Icepick; import icepick.State; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;
context = getContext(); if (savedInstanceState == null) { movieList = new ArrayList<>(); } movieAdapter = new GridMovieAdapter(context, movieList); RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(context, getSpanCount()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(movieAdapter); return rootView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (savedInstanceState != null) { hideLoadingLayout(); if (isDataLoadedFromCache && movieList.isEmpty()) showEmptyFavouritesLayout(); if (isInternetOff) showInternetErrorLayout(); return; } if (fragmentDataType.equals(popularData)) { sort_type = context.getString(R.string.sort_type_popular); updateMovieData(); } else if (fragmentDataType.equals(topRatedData)) { sort_type = context.getString(R.string.sort_type_top_rated); updateMovieData(); } else { fetchCacheData(); hideLoadingLayout(); } } @Override public boolean onQueryTextSubmit(String query) { movieAdapter.getFilter().filter(query); return false; } @Override public boolean onQueryTextChange(String newText) { movieAdapter.getFilter().filter(newText); return false; } @OnClick(R.id.try_again) public void onClick() { hideInternetErrorLayout(); ((ReloadCallback) getActivity()).reloadData(); } public interface ReloadCallback { void reloadData(); } private void updateMovieData() { //Check for network connection beforehand showLoadingLayout(); if (Network.isConnected(context)) { fetchData(); isInternetOff = false; } else { isInternetOff = true; showInternetErrorLayout(); hideLoadingLayout(); } } /** * Fetch the movie data from the cache. This is only relevant in case of * favourite movies as of now. */ private void fetchCacheData() { isDataLoadedFromCache = true; HashMap<Integer, Boolean> map = Cache.getFavouriteMovies(context); if (map == null) { showEmptyFavouritesLayout(); return; } List<Integer> favouriteMovieIdList = new ArrayList<>(); for (HashMap.Entry<Integer, Boolean> entry : map.entrySet()) { if (entry.getValue()) { favouriteMovieIdList.add(entry.getKey()); } } List<MovieBundle> movieBundleList; movieList.clear(); movieBundleList = Cache.bulkReadMovieData(context, favouriteMovieIdList); for (MovieBundle movieBundle : movieBundleList) { movieList.add(movieBundle.movie); } if (movieList.isEmpty()) showEmptyFavouritesLayout(); else hideEmptyFavouritesLayout(); initializeFavourites(); movieAdapter.notifyDataSetChanged(); } /** * Retrieves movie data using from tmdb.org using {@link retrofit2.Retrofit} based * api calls. */ private void fetchData() { ApiClient apiClient = new ApiClient().setIsDebug(ApplicationConstants.DEBUG); Call<MovieResponse> call = apiClient.movieInterface().getMovies(sort_type, MIN_VOTE_COUNT); call.enqueue(new Callback<MovieResponse>() { @Override public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) { hideInternetErrorLayout(); movieList.clear(); List<Movie> movies = response.body().getMovies(); for (Movie movie : movies) { movieList.add(movie); } initializeFavourites(); movieAdapter.notifyDataSetChanged(); hideLoadingLayout();
if (MainActivity.twoPane && firstLaunch && fragmentDataType.equals(popularData)) {
0
WebcamStudio/webcamstudio
src/webcamstudio/externals/ProcessRenderer.java
[ "public static int audioFreq = 22050;", "public static int outFMEbe = 1;", "public static String wsDistroWatch() {\n String distro = null;\n Runtime rt = Runtime.getRuntime();\n String distroCmd = \"uname -a\";\n try {\n Process distroProc = rt.exec(distroCmd);\n Tools.sleep(10);\n ...
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.SocketException; import java.net.URL; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import static webcamstudio.WebcamStudio.audioFreq; import static webcamstudio.WebcamStudio.outFMEbe; import static webcamstudio.WebcamStudio.wsDistroWatch; import static webcamstudio.externals.ProcessRenderer.ACTION.OUTPUT; import webcamstudio.media.renderer.Capturer; import webcamstudio.media.renderer.Exporter; import webcamstudio.media.renderer.ProcessExecutor; import webcamstudio.mixers.Frame; import webcamstudio.mixers.MasterMixer; import webcamstudio.streams.SinkFile; import webcamstudio.streams.SinkUDP; import webcamstudio.streams.SourceDVB; import webcamstudio.streams.Stream; import webcamstudio.util.Tools; import webcamstudio.util.Tools.OS;
} break; case KEYINT: if (fme != null) { command = command.replaceAll(Tags.KEYINT.toString(), "" + fme.getKeyInt()); } else { command = command.replaceAll(Tags.KEYINT.toString(), "" + Integer.toString(5*mixer.getRate())); } break; case PORT: if (fme != null && !"".equals(fme.getPort())) { command = command.replaceAll(Tags.PORT.toString(), "" + fme.getPort()); } break; case APORT: command = command.replaceAll(Tags.APORT.toString(), "" + audioPort); break; case CHEIGHT: command = command.replaceAll(Tags.CHEIGHT.toString(), "" + stream.getCaptureHeight()); break; case CWIDTH: command = command.replaceAll(Tags.CWIDTH.toString(), "" + stream.getCaptureWidth()); break; case FILE: if (stream.getFile() != null) { if (Tools.getOS() == OS.WINDOWS) { command = command.replaceAll(Tags.FILE.toString(), "\"" + stream.getFile().getAbsolutePath().replaceAll("\\\\", "\\\\\\\\") + "\""); } else { if (stream.getFile().getAbsolutePath().contains("http")) { command = command.replaceAll(Tags.FILE.toString(), "" + stream.getFile().getAbsolutePath().replace(userHomeDir+"/", "") + ""); } else { String sFile = stream.getFile().getAbsolutePath().replaceAll(" ", "\\ "); if (stream instanceof SinkFile) { sFile = sFile.replaceAll(" ", "_"); } command = command.replaceAll(Tags.FILE.toString(), "" + sFile + ""); } } } break; case OHEIGHT: command = command.replaceAll(Tags.OHEIGHT.toString(), "" + stream.getHeight()); break; case OWIDTH: command = command.replaceAll(Tags.OWIDTH.toString(), "" + stream.getWidth()); break; case RATE: command = command.replaceAll(Tags.RATE.toString(), "" + stream.getRate()); break; case SEEK: command = command.replaceAll(Tags.SEEK.toString(), "" + stream.getSeek()); break; case VPORT: command = command.replaceAll(Tags.VPORT.toString(), "" + videoPort); break; case GSEFFECT: command = command.replaceAll(Tags.GSEFFECT.toString(), "" + stream.getGSEffect()); break; case WEBURL: if (stream.getProtected() && "wanscam".equals(stream.getPtzBrand())) { String soloURL = stream.getWebURL().replace("http://", ""); command = command.replaceAll(Tags.WEBURL.toString(), "\""+"http://"+soloURL+"?user="+stream.getIPUser()+"&pwd="+stream.getIPPwd()+"\""); } if (stream.getProtected()) { String soloURL = stream.getWebURL().replace("http://", ""); command = command.replaceAll(Tags.WEBURL.toString(), "\""+"http://"+stream.getIPUser()+":"+stream.getIPPwd()+"@"+soloURL+"\""); } else { command = command.replaceAll(Tags.WEBURL.toString(), "\""+stream.getWebURL()+"\""); } break; case BW: command = command.replaceAll(Tags.BW.toString(), "" + stream.getDVBBandwidth()); break; case DVBFREQ: command = command.replaceAll(Tags.DVBFREQ.toString(), "" + stream.getDVBFrequency()); break; case DVBCH: command = command.replaceAll(Tags.DVBCH.toString(), "" + stream.getDVBChannelNumber()); break; case FREQ: command = command.replaceAll(Tags.FREQ.toString(), "" + frequency); break; case BITSIZE: command = command.replaceAll(Tags.BITSIZE.toString(), "" + bitSize); break; case CHANNELS: command = command.replaceAll(Tags.CHANNELS.toString(), "" + channels); break; case AUDIOSRC: command = command.replaceAll(Tags.AUDIOSRC.toString(), "" + stream.getAudioSource()); break; case PAUDIOSRC: command = command.replaceAll(Tags.PAUDIOSRC.toString(), "" + audioPulseInput); break; } } return command; }
public Frame getFrame() {
5
adyliu/jafka
src/main/java/io/jafka/consumer/ZookeeperConsumerConnector.java
[ "public class Broker {\n\n /**\n * the global unique broker id\n */\n public final int id;\n\n /**\n * the broker creator (hostname with created time)\n *\n * @see ServerRegister#registerBrokerInZk()\n */\n public final String creatorId;\n\n /**\n * broker hostname\n *...
import com.github.zkclient.IZkChildListener; import com.github.zkclient.IZkStateListener; import com.github.zkclient.ZkClient; import com.github.zkclient.exception.ZkNoNodeException; import com.github.zkclient.exception.ZkNodeExistsException; import io.jafka.api.OffsetRequest; import io.jafka.cluster.Broker; import io.jafka.cluster.Cluster; import io.jafka.cluster.Partition; import io.jafka.common.ConsumerRebalanceFailedException; import io.jafka.common.InvalidConfigException; import io.jafka.producer.serializer.Decoder; import io.jafka.utils.Closer; import io.jafka.utils.KV.StringTuple; import io.jafka.utils.Pool; import io.jafka.utils.Scheduler; import io.jafka.utils.zookeeper.ZkGroupDirs; import io.jafka.utils.zookeeper.ZkGroupTopicDirs; import io.jafka.utils.zookeeper.ZkUtils; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import static java.lang.String.format;
consumerIdString,curBrokerPartitions.size(),topic,curBrokerPartitions,curConsumers.size(),curConsumers ); if (logger.isDebugEnabled()) { StringBuilder buf = new StringBuilder(1024); buf.append("[").append(topic).append("] preassigning details:"); for (int i = 0; i < curConsumers.size(); i++) { final int startPart = nPartsPerConsumer * i + Math.min(i, nConsumersWithExtraPart); final int nParts = nPartsPerConsumer + ((i + 1 > nConsumersWithExtraPart) ? 0 : 1); if (nParts > 0) { for (int m = startPart; m < startPart + nParts; m++) { buf.append("\n ").append(curConsumers.get(i)).append(" ==> ") .append(curBrokerPartitions.get(m)); } } } logger.debug(buf.toString()); } //consumerThreadId=> groupid_consumerid-index (index from count) for (String consumerThreadId : e.getValue()) { final int myConsumerPosition = curConsumers.indexOf(consumerThreadId); assert (myConsumerPosition >= 0); final int startPart = nPartsPerConsumer * myConsumerPosition + Math.min(myConsumerPosition, nConsumersWithExtraPart); final int nParts = nPartsPerConsumer + ((myConsumerPosition + 1 > nConsumersWithExtraPart) ? 0 : 1); /* * Range-partition the sorted partitions to consumers for better locality. * The first few consumers pick up an extra partition, if any. */ if (nParts <= 0) { logger.warn("No broker partition of topic {} for consumer {}, {} partitions and {} consumers",topic,consumerThreadId,// curBrokerPartitions.size(),curConsumers.size()); } else { for (int i = startPart; i < startPart + nParts; i++) { String brokerPartition = curBrokerPartitions.get(i); logger.info("[" + consumerThreadId + "] ==> " + brokerPartition + " claimming"); addPartitionTopicInfo(currentTopicRegistry, topicDirs, brokerPartition, topic, consumerThreadId); // record the partition ownership decision partitionOwnershipDecision.put(new StringTuple(topic, brokerPartition), consumerThreadId); } } } } // /* * move the partition ownership here, since that can be used to indicate a truly * successful rebalancing attempt A rebalancing attempt is completed successfully * only after the fetchers have been started correctly */ if (reflectPartitionOwnershipDecision(partitionOwnershipDecision)) { logger.debug("Updating the cache"); logger.debug("Partitions per topic cache " + brokerPartitionsPerTopicMap); logger.debug("Consumers per topic cache " + consumersPerTopicMap); topicRegistry = currentTopicRegistry; updateFetcher(cluster, messagesStreams); return true; } else { return false; } //////////////////////////// } private void updateFetcher(Cluster cluster, Map<String, List<MessageStream<T>>> messagesStreams2) { if (fetcher != null) { List<PartitionTopicInfo> allPartitionInfos = new ArrayList<PartitionTopicInfo>(); for (Pool<Partition, PartitionTopicInfo> p : topicRegistry.values()) { allPartitionInfos.addAll(p.values()); } fetcher.startConnections(allPartitionInfos, cluster, messagesStreams2); } } private boolean reflectPartitionOwnershipDecision(Map<StringTuple, String> partitionOwnershipDecision) { final List<StringTuple> successfullyOwnerdPartitions = new ArrayList<StringTuple>(); int hasPartitionOwnershipFailed = 0; for (Map.Entry<StringTuple, String> e : partitionOwnershipDecision.entrySet()) { final String topic = e.getKey().k; final String brokerPartition = e.getKey().v; final String consumerThreadId = e.getValue(); final ZkGroupTopicDirs topicDirs = new ZkGroupTopicDirs(group, topic); final String partitionOwnerPath = topicDirs.consumerOwnerDir + "/" + brokerPartition; try { ZkUtils.createEphemeralPathExpectConflict(zkClient, partitionOwnerPath, consumerThreadId); successfullyOwnerdPartitions.add(new StringTuple(topic, brokerPartition)); } catch (ZkNodeExistsException e2) { logger.warn(format("[%s] waiting [%s] to release => %s",// consumerThreadId,// ZkUtils.readDataMaybeNull(zkClient, partitionOwnerPath),// brokerPartition)); hasPartitionOwnershipFailed++; } } // if (hasPartitionOwnershipFailed > 0) { for (StringTuple topicAndPartition : successfullyOwnerdPartitions) { deletePartitionOwnershipFromZK(topicAndPartition.k, topicAndPartition.v); } return false; } return true; } private void addPartitionTopicInfo(Pool<String, Pool<Partition, PartitionTopicInfo>> currentTopicRegistry, ZkGroupTopicDirs topicDirs, String brokerPartition, String topic, String consumerThreadId) { Partition partition = Partition.parse(brokerPartition); Pool<Partition, PartitionTopicInfo> partTopicInfoMap = currentTopicRegistry.get(topic); final String znode = topicDirs.consumerOffsetDir + "/" + partition.getName(); String offsetString = ZkUtils.readDataMaybeNull(zkClient, znode); // If first time starting a consumer, set the initial offset based on the config long offset; if (offsetString == null) { if (OffsetRequest.SMALLES_TIME_STRING.equals(config.getAutoOffsetReset())) { offset = earliestOrLatestOffset(topic, partition.brokerId, partition.partId, OffsetRequest.EARLIES_TTIME); } else if (OffsetRequest.LARGEST_TIME_STRING.equals(config.getAutoOffsetReset())) { offset = earliestOrLatestOffset(topic, partition.brokerId, partition.partId, OffsetRequest.LATES_TTIME); } else {
throw new InvalidConfigException("Wrong value in autoOffsetReset in ConsumerConfig");
2
dotcool/coolreader
src/com/dotcool/reader/service/UpdateService.java
[ "public class Constants {\n\n\t// public static final String BaseURL = \"http://www.baka-tsuki.org/project/\";\n\tpublic static final String BASE_URL_HTTPS = \"http://fiction.icoolxue.com/index.php\";\n\tpublic static final String BASE_URL = \"http://fiction.icoolxue.com/index.php\";\n\tpublic static final String B...
import java.util.ArrayList; import java.util.Date; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Binder; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import com.dotcool.reader.Constants; import com.dotcool.reader.LNReaderApplication; import com.dotcool.reader.callback.CallbackEventData; import com.dotcool.reader.callback.ICallbackNotifier; import com.dotcool.reader.dao.NovelsDao; import com.dotcool.reader.model.PageModel; import com.dotcool.reader.model.UpdateInfoModel; import com.dotcool.reader.model.UpdateType; import com.dotcool.view.MainTabActivity;
package com.dotcool.reader.service; public class UpdateService extends Service { private final IBinder mBinder = new MyBinder(); public boolean force = false; public final static String TAG = UpdateService.class.toString(); private static boolean isRunning;
public ICallbackNotifier notifier;
3
loklak/loklak_server
src/org/loklak/api/search/InstagramProfileScraper.java
[ "public class JSONObject {\n /**\n * JSONObject.NULL is equivalent to the value that JavaScript calls null,\n * whilst Java's null is equivalent to the value that JavaScript calls\n * undefined.\n */\n private static final class Null {\n\n /**\n * There is only intended to be a ...
import org.loklak.data.DAO; import org.loklak.harvester.BaseScraper; import org.loklak.harvester.Post; import org.loklak.server.BaseUserRole; import java.io.BufferedReader; import java.io.IOException; import java.net.URISyntaxException; import java.util.Map; import org.apache.http.client.utils.URIBuilder; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONObject; import org.json.JSONArray; import org.jsoup.Jsoup; import org.jsoup.nodes.Document;
/** * Instagram Profile Scraper * Copyright 08.08.2016 by Jigyasa Grover, @jig08 * * 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 program in the file lgpl21.txt * If not, see <http://www.gnu.org/licenses/>. */ package org.loklak.api.search; public class InstagramProfileScraper extends BaseScraper { private static final long serialVersionUID = -3360416757176406604L; /** * instaJsonData is a Pattern object which will be used to match the required pattern * with the extracted elements from html page */ private Pattern instaJsonData = Pattern.compile("(\\{\"config\").*(\\});"); /** * Constructor to set baseUrl and scraperName in the super(Base-Interface) for * current Search-Scrapper */ public InstagramProfileScraper() { super(); this.baseUrl = "https://www.instagram.com/"; this.scraperName = "instagram"; } /** * Constructor to set the given query and map _extra * @param _extra * A map with key and value as string * @param _query * _query in form for string value */ public InstagramProfileScraper(String _query, Map<String, String> _extra) { this(); this.setExtra(_extra); this.query = _query; } /** * Constructor to map the given _extra param with key and value as String */ public InstagramProfileScraper(Map<String, String> _extra) { this(); this.setExtra(_extra); } /** * Constructor to set String query * @param query as string */ public InstagramProfileScraper(String _query) { this(); this.query = _query; } /** * Method to get api path of the Instagram Profile Scraper * @return api endpoint of Instagram Profile Scraper in form of String */ @Override public String getAPIPath() { return "/api/instagramprofilescraper.json"; } @Override public BaseUserRole getMinimalBaseUserRole() { return BaseUserRole.ANONYMOUS; } /** * @return null when asked for the default permissions * of the given base user role in form of JSONObject */ @Override public JSONObject getDefaultPermissions(BaseUserRole baseUserRole) { return null; } /** * Method to generate url for search using URIBuilder * @return URL in string format */ protected String prepareSearchUrl(String type) { URIBuilder url = null; try { url = new URIBuilder(this.baseUrl + this.query); } catch (URISyntaxException e) { DAO.log("Invalid Url: baseUrl = " + this.baseUrl + ", mid-URL = " + midUrl + "query = " + this.query + "type = " + type); return ""; } return url.toString(); } /** * Method to set the "profile" key with value of query if the "profile" key is empty/null * and set the "query" key with value of query */ protected void setParam() { if("".equals(this.getExtraValue("profile"))) { this.setExtraValue("profile", this.query); } this.setExtraValue("query", this.query); } /** * Method to scrape the given url with key as "profile_posts" * @return instaObj as a Post object */ protected Post scrape(BufferedReader br, String type, String url) { Post instaObj = new Post(true); this.putData(instaObj, "profile_posts", this.scrapeInstagram(br, url)); return instaObj; } /** * Method to match the given pattern with extracted elements of html page * and parse the result for the posts on the given instagram page * @return instaProfile as a JSONArray object containing all posts and details of viewer */
public JSONArray scrapeInstagram(BufferedReader br, String url) {
1
martino2k6/StoreBox
storebox-lib/src/main/java/net/orange_box/storebox/StoreBoxInvocationHandler.java
[ "public interface StoreBoxTypeAdapter<F, T> {\n \n StoreType getStoreType();\n \n T getDefaultValue();\n\n T adaptForPreferences(F value);\n\n F adaptFromPreferences(T value);\n}", "public enum PreferencesMode {\n\n /**\n * Default.\n * \n * @see android.content.Context#MODE_PRIVA...
import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.preference.PreferenceManager; import android.util.TypedValue; import net.orange_box.storebox.adapters.StoreBoxTypeAdapter; import net.orange_box.storebox.annotations.method.ClearMethod; import net.orange_box.storebox.annotations.method.DefaultValue; import net.orange_box.storebox.annotations.method.KeyByResource; import net.orange_box.storebox.annotations.method.KeyByString; import net.orange_box.storebox.annotations.method.RemoveMethod; import net.orange_box.storebox.annotations.method.TypeAdapter; import net.orange_box.storebox.annotations.method.RegisterChangeListenerMethod; import net.orange_box.storebox.annotations.method.UnregisterChangeListenerMethod; import net.orange_box.storebox.annotations.option.SaveOption; import net.orange_box.storebox.enums.PreferencesMode; import net.orange_box.storebox.enums.PreferencesType; import net.orange_box.storebox.enums.SaveMode; import net.orange_box.storebox.handlers.ChangeListenerMethodHandler; import net.orange_box.storebox.handlers.MethodHandler; import net.orange_box.storebox.utils.MethodUtils; import net.orange_box.storebox.utils.PreferenceUtils; import net.orange_box.storebox.utils.TypeUtils; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.Locale;
/* * Copyright 2015 Martin Bella * * 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.orange_box.storebox; /** * This is where the magic happens... */ @SuppressLint("CommitPrefEdits") class StoreBoxInvocationHandler implements InvocationHandler { private static final Method OBJECT_EQUALS = MethodUtils.getObjectMethod("equals", Object.class); private static final Method OBJECT_HASHCODE = MethodUtils.getObjectMethod("hashCode"); private static final Method OBJECT_TOSTRING = MethodUtils.getObjectMethod("toString"); private final SharedPreferences prefs; private final SharedPreferences.Editor editor; private final Resources res; private final SaveMode saveMode; private final MethodHandler mChangesHandler; private int hashCode; public StoreBoxInvocationHandler( Context context, PreferencesType preferencesType, String openNameValue, PreferencesMode preferencesMode, SaveMode saveMode) { switch (preferencesType) { case ACTIVITY: prefs = ((Activity) context).getPreferences( preferencesMode.value()); break; case FILE: prefs = context.getSharedPreferences( openNameValue, preferencesMode.value()); break; case DEFAULT_SHARED: default: prefs = PreferenceManager.getDefaultSharedPreferences(context); } editor = prefs.edit(); res = context.getResources(); this.saveMode = saveMode; mChangesHandler = new ChangeListenerMethodHandler(prefs); } @Override public Object invoke( Object proxy, Method method, Object... args) throws Throwable { /* * Find the key for the preference from the method's annotation, or * whether it's a remove method, else we try to forward the method to * the SharedPreferences or Editor implementations. */ final String key; final boolean isRemove; final boolean isClear; final boolean isChange; if (method.isAnnotationPresent(KeyByString.class)) { key = method.getAnnotation(KeyByString.class).value(); isRemove = method.isAnnotationPresent(RemoveMethod.class); isClear = false; isChange = MethodUtils.areAnyAnnotationsPresent( method, RegisterChangeListenerMethod.class, UnregisterChangeListenerMethod.class); } else if (method.isAnnotationPresent(KeyByResource.class)) { key = res.getString( method.getAnnotation(KeyByResource.class).value()); isRemove = method.isAnnotationPresent(RemoveMethod.class); isClear = false; isChange = MethodUtils.areAnyAnnotationsPresent( method, RegisterChangeListenerMethod.class, UnregisterChangeListenerMethod.class); } else if (method.isAnnotationPresent(RemoveMethod.class)) { key = MethodUtils.getKeyForRemove(res, args); isRemove = true; isClear = false; isChange = false; } else if (method.isAnnotationPresent(ClearMethod.class)) { key = null; isRemove = false; isClear = true; isChange = false; } else { // handle Object's equals/hashCode/toString if (method.equals(OBJECT_EQUALS)) { return internalEquals(proxy, args[0]); } else if (method.equals(OBJECT_HASHCODE)) { return internalHashCode(); } else if (method.equals(OBJECT_TOSTRING)) { return toString(); } // can we forward the method to the SharedPreferences? try { final Method prefsMethod = prefs.getClass().getDeclaredMethod( method.getName(), method.getParameterTypes()); return prefsMethod.invoke(prefs, args); } catch (NoSuchMethodException e) { // NOP } // can we forward the method to the Editor? try { final Method editorMethod = editor.getClass().getDeclaredMethod( method.getName(), method.getParameterTypes()); return editorMethod.invoke(editor, args); } catch (NoSuchMethodException e) { // NOP } // fail fast, rather than ignoring the method invocation throw new UnsupportedOperationException(String.format( Locale.ENGLISH, "Failed to invoke %1$s method, " + "perhaps the %2$s or %3$s annotation is missing?", method.getName(), KeyByString.class.getSimpleName(), KeyByResource.class.getSimpleName())); } /* * Find out based on the method return type whether it's a get or set * operation. We could provide a further annotation for get/set methods, * but we can infer this reasonably easily. */ final Class<?> returnType = method.getReturnType(); if (isRemove) { editor.remove(key); } else if (isClear) { editor.clear(); } else if (isChange) { return mChangesHandler.handleInvocation(key, proxy, method, args); } else if ( returnType == Void.TYPE || returnType == method.getDeclaringClass() || returnType == SharedPreferences.Editor.class) { /* * Set. * * Argument types are boxed for us, so we only need to check one * variant and we also need to find out what type to store the * value under, */
final StoreBoxTypeAdapter adapter = TypeUtils.getTypeAdapter(
8
filosganga/geogson
core/src/test/java/com/github/filosganga/geogson/gson/FeatureAdapterTest.java
[ "public final class FeatureUtils {\n\n public static Feature featureWithId(String id) {\n return Feature.builder().withGeometry(Point.from(12.3, 45.3)).withId(id).build();\n }\n\n public static Feature featureWithGeometry(Geometry<?> geometry) {\n return Feature.builder().withGeometry(Point.f...
import com.github.filosganga.geogson.gson.utils.FeatureUtils; import com.github.filosganga.geogson.gson.utils.JsonUtils; import com.github.filosganga.geogson.model.Feature; import com.github.filosganga.geogson.model.Point; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static com.github.filosganga.geogson.model.Matchers.emptyMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is;
package com.github.filosganga.geogson.gson; public class FeatureAdapterTest { private Gson toTest; @Before public void initToTest() { toTest = new GsonBuilder().registerTypeAdapterFactory(new GeometryAdapterFactory()).create(); } @Test public void shouldHandleFeaturesWithId() {
Feature feature = FeatureUtils.featureWithId("testid");
2
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/command/CommandModifyAbilities.java
[ "public class AbilityHelpers {\n\n /**\n * This value is synced with {@link GeneralConfig#maxPlayerAbilities} from the server.\n * This is to ensure that clients can not hack around the ability limit.\n */\n public static int maxPlayerAbilitiesClient = -1;\n\n public static final int[] RARITY_C...
import com.mojang.brigadier.Command; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.minecraft.command.CommandSource; import net.minecraft.command.Commands; import net.minecraft.command.arguments.EntityArgument; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.util.Util; import net.minecraft.util.text.TranslationTextComponent; import org.cyclops.cyclopscore.command.argument.ArgumentTypeEnum; import org.cyclops.everlastingabilities.ability.AbilityHelpers; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.api.capability.IMutableAbilityStore; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; import org.cyclops.everlastingabilities.command.argument.ArgumentTypeAbility;
package org.cyclops.everlastingabilities.command; /** * Command for modifying abilities to players. * @author rubensworks */ public class CommandModifyAbilities implements Command<CommandSource> { private final boolean checkAbility; private final boolean checkLevel; public CommandModifyAbilities(boolean checkAbility, boolean checkLevel) { this.checkAbility = checkAbility; this.checkLevel = checkLevel; } @Override public int run(CommandContext<CommandSource> context) throws CommandSyntaxException { ServerPlayerEntity sender = context.getSource().asPlayer(); Action action = ArgumentTypeEnum.getValue(context, "action", Action.class); ServerPlayerEntity player = EntityArgument.getPlayer(context, "player"); IMutableAbilityStore abilityStore = player.getCapability(MutableAbilityStoreConfig.CAPABILITY).orElse(null); if (action == Action.LIST) { sender.sendMessage(abilityStore.getTextComponent(), Util.DUMMY_UUID); } else { if (!this.checkAbility) { throw new SimpleCommandExceptionType(new TranslationTextComponent( "chat.everlastingabilities.command.invalidAbility", "null")).create(); } // Determine the ability IAbilityType abilityType = context.getArgument("ability", IAbilityType.class); // Determine level to add or remove int level = this.checkLevel ? context.getArgument("level", Integer.class) : 1; if (action == Action.ADD) { level = Math.max(1, Math.min(abilityType.getMaxLevelInfinitySafe(), level)); Ability ability = new Ability(abilityType, level); Ability addedAbility = AbilityHelpers.addPlayerAbility(player, ability, true, false); Ability newAbility = abilityStore.getAbility(abilityType); sender.sendMessage(new TranslationTextComponent("chat.everlastingabilities.command.addedAbility", addedAbility, newAbility), Util.DUMMY_UUID); } else { level = Math.max(1, level); Ability ability = new Ability(abilityType, level); Ability removedAbility = AbilityHelpers.removePlayerAbility(player, ability, true, false); Ability newAbility = abilityStore.getAbility(abilityType); sender.sendMessage(new TranslationTextComponent("chat.everlastingabilities.command.removedAbility", removedAbility, newAbility), Util.DUMMY_UUID); } } return 0; } public static LiteralArgumentBuilder<CommandSource> make() { return Commands.literal("abilities") .requires((commandSource) -> commandSource.hasPermissionLevel(2)) .then(Commands.argument("action", new ArgumentTypeEnum<>(Action.class)) .then(Commands.argument("player", EntityArgument.player()) .executes(new CommandModifyAbilities(false, false))
.then(Commands.argument("ability", new ArgumentTypeAbility())
5
bretthshelley/Maven-IIB9-Plug-In
src/main/java/ch/sbb/maven/plugins/iib/utils/SkipUtil.java
[ "@Mojo(name = \"apply-bar-overrides\", defaultPhase = LifecyclePhase.PROCESS_CLASSES)\npublic class ApplyBarOverridesMojo extends AbstractMojo {\n\n\n /**\n * Whether the applybaroverride command should be executed or not\n */\n @Parameter(property = \"applyBarOverrides\", defaultValue = \"true\", req...
import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.regex.Pattern; import ch.sbb.maven.plugins.iib.mojos.ApplyBarOverridesMojo; import ch.sbb.maven.plugins.iib.mojos.DeployBarMojo; import ch.sbb.maven.plugins.iib.mojos.InitializeBarBuildWorkspaceMojo; import ch.sbb.maven.plugins.iib.mojos.MqsiDeployMojo; import ch.sbb.maven.plugins.iib.mojos.PackageBarMojo; import ch.sbb.maven.plugins.iib.mojos.PrepareBarBuildWorkspaceMojo; import ch.sbb.maven.plugins.iib.mojos.ValidateBarBuildWorkspaceMojo; import ch.sbb.maven.plugins.iib.mojos.ValidateClassloaderApproachMojo;
/* * Copyright (C) Schweizerische Bundesbahnen SBB, 2015. */ package ch.sbb.maven.plugins.iib.utils; /** * * * * @author Brett (user_vorname user_nachname) * @version $Id: $ * @since pom_version, 2015 */ public class SkipUtil { @SuppressWarnings("rawtypes") static LinkedHashMap<Class, String> classGoalMap = new LinkedHashMap<Class, String>(); List<String> skipGoals = new ArrayList<String>(); String skipToGoal = null; static { classGoalMap.put(InitializeBarBuildWorkspaceMojo.class, "initialize"); classGoalMap.put(PrepareBarBuildWorkspaceMojo.class, "generate-resources"); classGoalMap.put(ValidateBarBuildWorkspaceMojo.class, "process-resources"); classGoalMap.put(PackageBarMojo.class, "compile"); classGoalMap.put(String.class, "test-compile");
classGoalMap.put(ApplyBarOverridesMojo.class, "process-classes");
0
FedUni/caliko
caliko-visualisation/src/main/java/au/edu/federation/caliko/visualisation/FabrikLine2D.java
[ "public class FabrikBone2D implements FabrikBone<Vec2f,FabrikJoint2D>\r\n{\r\n\t/**\r\n\t * mJoint\tThe joint attached to this FabrikBone2D.\r\n\t * <p>\r\n\t * Each bone has a single FabrikJoint2D which controls the angle to which the bone is\r\n\t * constrained with regard to the previous (i.e. earlier / closer t...
import au.edu.federation.caliko.FabrikBone2D; import au.edu.federation.caliko.FabrikChain2D; import au.edu.federation.caliko.FabrikChain2D.BaseboneConstraintType2D; import au.edu.federation.caliko.FabrikJoint2D.ConstraintCoordinateSystem; import au.edu.federation.caliko.FabrikStructure2D; import au.edu.federation.utils.Colour4f; import au.edu.federation.utils.Mat4f; import au.edu.federation.utils.Utils; import au.edu.federation.utils.Vec2f;
package au.edu.federation.caliko.visualisation; /** * A static class used to draw a 2D lines to represent FabrikBone2D, FabrikChain2D or FabrickStructure2D objects. * <p> * These draw methods are only provided to assist with prototyping and debugging. * <p> * The GLSL shaders used to draw the lines require a minimum OpenGL version of 3.3 (i.e. GLSL #version 330). * * @author Al Lansley * @version 0.6 - 02/08/2016 */ public class FabrikLine2D { /** Anticlockwise constraint lines will be drawn in red at full opacity. */ private static final Colour4f ANTICLOCKWISE_CONSTRAINT_COLOUR = new Colour4f(1.0f, 0.0f, 0.0f, 1.0f); /** Clockwise constraint lines will be drawn in blue at full opacity. */ private static final Colour4f CLOCKWISE_CONSTRAINT_COLOUR = new Colour4f(0.0f, 0.0f, 1.0f, 1.0f); /** A static Line2D object used to draw all lines. */ private static Line2D line = new Line2D(); /** A point to draw the 2D target if chains use embedded targets. */ private static Point2D point = new Point2D(); // ---------- FabrikBone2D Drawing Methods ---------- /** * Draw this bone as a line. * <p> * The line will be drawn in the colour and line width as taken from the bone. * * @param bone The bone to draw. * @param mvpMatrix The ModelViewProjection matrix with which to draw the line * @see FabrikBone2D#setColour(Colour4f) * @see FabrikBone2D#setLineWidth(float) * @see Mat4f#createOrthographicProjectionMatrix(float, float, float, float, float, float) */ public static void draw(FabrikBone2D bone, Mat4f mvpMatrix) { line.draw(bone.getStartLocation(), bone.getEndLocation(), bone.getColour(), bone.getLineWidth(), mvpMatrix); } /** * Draw this bone as a line using a specific line width. * <p> * The line will be drawn in the colour as taken from the bone. * * @param bone The bone the draw. * @param lineWidth The width of the line to draw . * @param mvpMatrix The ModelViewProjection matrix with which to draw the line. * @see FabrikBone2D#setColour(Colour4f) * @see Mat4f#createOrthographicProjectionMatrix(float, float, float, float, float, float) */ public static void draw(FabrikBone2D bone, float lineWidth, Mat4f mvpMatrix) { FabrikLine2D.line.draw(bone.getStartLocation(), bone.getEndLocation(), bone.getColour(), lineWidth, mvpMatrix); } /** * Draw this bone as a line using a specific colour and line width. * * @param bone The bone the draw. * @param colour The colour of the line to draw. * @param lineWidth The width of the line to draw. * @param mvpMatrix The ModelViewProjection matrix with which to draw the line. * @see Mat4f#createOrthographicProjectionMatrix(float, float, float, float, float, float) */ public void draw(FabrikBone2D bone, Colour4f colour, float lineWidth, Mat4f mvpMatrix) { FabrikLine2D.line.draw(bone.getStartLocation(), bone.getEndLocation(), colour, lineWidth, mvpMatrix); } // ---------- FabrikChain2D Drawing Methods ---------- /** * Draw the provided IK chain as a series of lines using the colour and line width properties of each bone. * * @param chain The chain to draw. * @param mvpMatrix The ModelViewProjection matrix with which to draw this chain. * @see Mat4f#createOrthographicProjectionMatrix(float, float, float, float, float, float) */ public static void draw(FabrikChain2D chain, Mat4f mvpMatrix) { int numBones = chain.getNumBones(); for (int loop = 0; loop < numBones; ++loop) { draw(chain.getBone(loop), mvpMatrix); } // Chain has an embedded target? Draw it. if ( chain.getEmbeddedTargetMode() ) { point.draw(chain.getEmbeddedTarget(), Utils.YELLOW, 4.0f, mvpMatrix); } } /** * Draw a FabrikChain2D as a series of lines. * <p> * Each line is drawn using the specified line width, with the colour taken from the bone's * {@link FabrikBone2D#mColour} property. * * @param chain The FabrikChain2D object to draw. * @param lineWidth The width of the line used to draw each bone in the chain. * @param mvpMatrix The ModelViewProjection matrix with which to draw the chain. */ public static void draw(FabrikChain2D chain, float lineWidth, Mat4f mvpMatrix) { int numBones = chain.getNumBones(); for (int loop = 0; loop < numBones; ++loop) { FabrikLine2D.draw(chain.getBone(loop), lineWidth, mvpMatrix); } // Chain has an embedded target? Draw it. if ( chain.getEmbeddedTargetMode() ) { point.draw(chain.getEmbeddedTarget(), Utils.YELLOW, 4.0f, mvpMatrix); } } /** * Draw the constraint angles for each bone in an IK chain. * <p> * Line length values must be at least 1.0f otherwise an IllegalArgumentException is thrown. * Line widths may commonly be between 1.0f and 32.0f, values outside of this range may result in unspecified behaviour. * * @param chain The chain to draw the constraint angle lines for * @param lineLength The length of the constraint lines to be drawn * @param lineWidth The width of the constrain lines to be drawn * @param mvpMatrix The ModelViewProjection matrix used to draw our geometry * @see Mat4f#createOrthographicProjectionMatrix(float, float, float, float, float, float) */ public static void drawChainConstraintAngles(FabrikChain2D chain, float lineLength, float lineWidth, Mat4f mvpMatrix) { // Sanity checking if (lineLength < 1.0f) { throw new IllegalArgumentException("Constraint line length must be at least 1.0f"); } // Loop over all bones in the chain int numBones = chain.getNumBones(); for (int loop = 0; loop < numBones; ++loop) { // If we're working on the base bone... if (loop == 0) { // ...and if the base bone is constrained... BaseboneConstraintType2D constraintType = chain.getBaseboneConstraintType(); if (constraintType != BaseboneConstraintType2D.NONE) { // If the basebone constraint type LOCAL_ABSOLUTE i.e. a direction in the host bone's local space...
Vec2f baseboneConstraintUV;
8
fralalonde/iostream
src/test/java/ca/rbon/iostream/channel/filter/CipherFilterTest.java
[ "public class IOUtils {\n // NOTE: This class is focused on InputStream, OutputStream, Reader and\n // Writer. Each method should take at least one of these as a parameter,\n // or return one of them.\n\n /**\n * The default buffer size ({@value}) to use in copy methods.\n */\n public static ...
import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import ca.rbon.iostream.utils.IOUtils; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import ca.rbon.iostream.IO; import ca.rbon.iostream.wrap.BufferedReaderOf; import ca.rbon.iostream.wrap.InputStreamOf; import ca.rbon.iostream.wrap.OutputStreamOf; import ca.rbon.iostream.wrap.PrintWriterOf; import static java.nio.charset.StandardCharsets.UTF_8;
package ca.rbon.iostream.channel.filter; public class CipherFilterTest { static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5PADDING"; final String s = "Using IoStream for encryption"; // SECRETS final String key = "Bar12345Bar12345"; final String initVector = "RandomInitVector"; Cipher outCipher; Cipher inCipher; @Before public void init() throws Exception { // OUTPUT IvParameterSpec inIV = new IvParameterSpec(initVector.getBytes(UTF_8)); SecretKeySpec outSkeySpec = new SecretKeySpec(key.getBytes(UTF_8), "AES"); outCipher = Cipher.getInstance(AES_CBC_PKCS5PADDING); outCipher.init(Cipher.ENCRYPT_MODE, outSkeySpec, inIV); // INPUT IvParameterSpec outIv = new IvParameterSpec(initVector.getBytes(UTF_8)); SecretKeySpec inSkeySpec = new SecretKeySpec(key.getBytes(UTF_8), "AES"); inCipher = Cipher.getInstance(AES_CBC_PKCS5PADDING); inCipher.init(Cipher.DECRYPT_MODE, inSkeySpec, outIv); } @Test public void bytesCipher() throws Exception { OutputStreamOf<byte[]> encryptedBytes = IO.bytes().cipher(outCipher).outputStream(); encryptedBytes.write(s.getBytes()); encryptedBytes.close(); OutputStreamOf<byte[]> bytes = IO.bytes().outputStream(); InputStreamOf<byte[]> in = IO.bytes(encryptedBytes.getInner()).cipher(inCipher).inputStream();
IOUtils.copy(in, bytes);
0
hlavki/g-suite-identity-sync
services/facade/src/main/java/eu/hlavki/identity/services/rest/service/GoogleSettingsService.java
[ "public interface GSuiteDirectoryService {\n\n /**\n * Retrieve all groups for a member.\n *\n * @param userKey The userKey can be the user's primary email address, the user's alias email address, a\n * group's primary email address, a group's email alias, or the user's unique id.\n * @return...
import eu.hlavki.identity.services.google.GSuiteDirectoryService; import eu.hlavki.identity.services.google.ResourceNotFoundException; import eu.hlavki.identity.services.google.config.Configuration; import eu.hlavki.identity.services.google.model.GroupMembership; import eu.hlavki.identity.services.rest.model.ServiceAccount; import eu.hlavki.identity.services.rest.model.GoogleSettingsData; import eu.hlavki.identity.services.rest.model.UserInfo; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package eu.hlavki.identity.services.rest.service; @Path("google/settings") public class GoogleSettingsService { private static final Logger LOG = LoggerFactory.getLogger(GoogleSettingsService.class); @Context private OidcClientTokenContext oidcContext; private final Configuration googleConfig; private final eu.hlavki.identity.services.rest.config.Configuration config; private final GSuiteDirectoryService gsuiteDirService; public GoogleSettingsService(Configuration googleConfig, GSuiteDirectoryService gsuiteDirService, eu.hlavki.identity.services.rest.config.Configuration config) { this.googleConfig = googleConfig; this.gsuiteDirService = gsuiteDirService; this.config = config; } @GET public GoogleSettingsData getSettings() { String domain = googleConfig.getGSuiteDomain(); UserInfo userInfo = new UserInfo(oidcContext.getUserInfo().getName(), oidcContext.getUserInfo().getEmail()); return new GoogleSettingsData(domain, userInfo); } @PUT @Path("service-account") public void configureServiceAccount(@NotNull @Valid ServiceAccount serviceAccount) { String privateKey = serviceAccount.getPrivateKey() .replace("-----BEGIN PRIVATE KEY-----\n", "") .replace("-----END PRIVATE KEY-----", "") .replace("\n", ""); String me = oidcContext.getUserInfo().getSubject(); googleConfig.setServiceAccount(serviceAccount.getClientEmail(), privateKey, me, serviceAccount.getTokenUri()); String adminGroup = config.getAdminGroup() + "@" + gsuiteDirService.getDomainName(); try {
GroupMembership admins = gsuiteDirService.getGroupMembers(adminGroup);
3
garfieldon757/video_management_system
src/com/adp/dao/impl/UserDAOImpl.java
[ "public interface UserDAO {\r\n\t\r\n\tpublic void testDaoAspect();\r\n\tpublic void fuck(int a, String s);\r\n\tpublic void addUser(User user);\r\n\tpublic User getUserByEmail(String email);\r\n\tpublic User getUserByID(int userID);\r\n\tpublic Role getRole(int roleID);\r\n\tpublic AuthorizationList findAuthList(i...
import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.junit.Test; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.adp.dao.UserDAO; import com.adp.model.AuthorizationList; import com.adp.model.AuthorizationRoleRelation; import com.adp.model.DaoFunctionUpdateDetail; import com.adp.model.FunctionLog; import com.adp.model.Role; import com.adp.model.User; import com.adp.model.Video; import com.adp.model.VideoCategory;
package com.adp.dao.impl; @Repository("ud") @Transactional public class UserDAOImpl implements UserDAO{ @PersistenceContext(name="un") private EntityManager em ; @Override public void testDaoAspect(){ System.out.println("This is userDAOIpml.testDaoAspect()."); return ; } @Override public void fuck(int a, String s) { System.out.println(a); System.out.println(s); return ; } @Override public void addUser(User user) { // TODO Auto-generated method stub em.persist(user); } @Override public User getUserByEmail(String email) { // TODO Auto-generated method stub String jpql = "select u from User u where u.email=:email"; List<User> resultList = em.createQuery(jpql).setParameter("email", email).getResultList(); User user = resultList.get(0); return user; } @Override public User getUserByID(int userID) { // TODO Auto-generated method stub String jpql = "select u from User u where u.userID=:userID"; List<User> resultList = em.createQuery(jpql).setParameter("userID", userID).getResultList(); User user = null; if (resultList.size() != 0){ user = resultList.get(0); } return user; } @Override
public Role getRole(int roleID) {
5
vsite-hr/hive
src/main/java/hr/vsite/hive/dao/PostgresDao.java
[ "public class Sensor implements Comparable<Sensor> {\n\n\t/** Hive's ID of this Sensor */\n\tpublic UUID getId() { return id; }\n\tpublic void setId(UUID id) { this.id = id; }\n\t\n\t/** Sensor's own ID */\n\tpublic String getDeviceId() { return deviceId; }\n\tpublic void setDeviceId(String deviceId) { this.deviceI...
import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import javax.inject.Inject; import hr.vsite.hive.sensors.Sensor; import hr.vsite.hive.sensors.SensorFilter; import hr.vsite.hive.ticks.CounterTick; import hr.vsite.hive.ticks.Tick; import hr.vsite.hive.ticks.TickFilter; import hr.vsite.hive.ticks.ToggleTick; import hr.vsite.hive.ticks.ValueTick; import hr.vsite.hive.ticks.ValueTickFilter;
} } private void modify(Sensor sensor) { try (PreparedStatement statement = getConn().prepareStatement("UPDATE sensors SET sensor_name = ? WHERE sensor_id = ?", Statement.RETURN_GENERATED_KEYS)) { statement.setString(1, sensor.getName()); statement.execute(); try (ResultSet resultSet = statement.getGeneratedKeys()) { if (!resultSet.next()) throw new RuntimeException("Unable to update sensor " + sensor); sensor.setLastModified(resultSet.getTimestamp("sensor_last_modified").toInstant()); } } catch (SQLException e) { throw new RuntimeException("Unable to modify sensor " + sensor, e); } } private Sensor sensorFromResultSet(ResultSet resultSet) { Sensor sensor = new Sensor(); try { sensor.setId(UUID.class.cast(resultSet.getObject("sensor_id"))); sensor.setDeviceId(resultSet.getString("sensor_device_id")); sensor.setName(resultSet.getString("sensor_name")); sensor.setLastModified(resultSet.getTimestamp("sensor_last_modified").toInstant()); } catch (SQLException e) { throw new RuntimeException("Unable to resolve sensor from result set", e); } return sensor; } @Override public void delete(Sensor sensor) { // TODO throw new UnsupportedOperationException(); } @Override public Sensor findSensorById(UUID id) { try (PreparedStatement statement = getConn().prepareStatement("SELECT * FROM sensors WHERE sensor_id = ?")) { statement.setObject(1, id); statement.execute(); try (ResultSet resultSet = statement.getResultSet()) { return resultSet.next() ? sensorFromResultSet(resultSet) : null; } } catch (SQLException e) { throw new RuntimeException("Unable to find sensor with id " + id, e); } } @Override public Sensor findSensorByDeviceId(String deviceId) { try (PreparedStatement statement = getConn().prepareStatement("SELECT * FROM sensors WHERE sensor_device_id = ?")) { statement.setString(1, deviceId); statement.execute(); try (ResultSet resultSet = statement.getResultSet()) { return resultSet.next() ? sensorFromResultSet(resultSet) : null; } } catch (SQLException e) { throw new RuntimeException("Unable to find sensor with device id " + deviceId, e); } } @Override public List<Sensor> listSensors(SensorFilter filter, int count, int offset) { List<Sensor> sensors = new ArrayList<Sensor>(count); StringBuilder queryBuilder = new StringBuilder(1000); queryBuilder.append("SELECT * FROM sensors WHERE true"); if (filter.getName() != null) queryBuilder.append(" AND lower(sensor_name) LIKE '%' || lower(?) || '%'"); queryBuilder.append(" LIMIT ? OFFSET ?"); try (PreparedStatement statement = getConn().prepareStatement(queryBuilder.toString())) { int index = 0; if (filter.getName() != null) statement.setString(++index, filter.getName()); statement.setInt(++index, count); statement.setInt(++index, offset); statement.execute(); try (ResultSet resultSet = statement.getResultSet()) { while(resultSet.next()) sensors.add(sensorFromResultSet(resultSet)); } } catch (SQLException e) { throw new RuntimeException("Unable to list sensors", e); } return sensors; } @Override public void persist(ValueTick tick) { try (PreparedStatement statement = getConn().prepareStatement("INSERT INTO ticks_value (tick_created_time, tick_sensor_ordinal, sensor_id, tick_type, tick_value) VALUES (?, ?, ?, ?::tick_type, ?)", Statement.RETURN_GENERATED_KEYS)) { statement.setTimestamp(1, tick.getCreatedTime() != null ? Timestamp.from(tick.getCreatedTime()) : null); if (tick.getSensorOrdinal() == null) statement.setNull(2, Types.INTEGER); else statement.setInt(2, tick.getSensorOrdinal()); statement.setObject(3, tick.getSensor().getId()); statement.setString(4, tick.getType().toString()); statement.setInt(5, tick.getValue()); statement.execute(); try (ResultSet resultSet = statement.getGeneratedKeys()) { if (!resultSet.next()) throw new RuntimeException("Unable to insert new value tick into db!"); tick.setId(UUID.class.cast(resultSet.getObject("tick_id"))); tick.setReceivedTime(resultSet.getTimestamp("tick_received_time").toInstant()); Integer metaOrdinal = resultSet.getInt("tick_meta_ordinal"); if (!resultSet.wasNull()) tick.setMetaOrdinal(metaOrdinal); } } catch (SQLException e) { throw new RuntimeException("Unable to create new value tick", e); } } @Override public void persist(CounterTick tick) { // TODO throw new UnsupportedOperationException(); } @Override
public void persist(ToggleTick tick) {
5
novarto-oss/sane-dbc
sane-dbc-examples/src/test/java/com/novarto/sanedbc/examples/MapExample1.java
[ "public class SyncDbInterpreter\n{\n private final Try0<Connection, SQLException> ds;\n\n /**\n * Construct an interpreter, given a piece of code which knows how to spawn connections, e.g. a Data Source, Connection Pool,\n * Driver Manager, etc.\n * @param ds - the data source, which can spawn con...
import com.novarto.sanedbc.core.interpreter.SyncDbInterpreter; import com.novarto.sanedbc.core.ops.EffectOp; import com.novarto.sanedbc.core.ops.SelectOp; import com.novarto.sanedbc.core.ops.UpdateOp; import fj.Unit; import fj.control.db.DB; import fj.data.Option; import org.junit.Test; import java.sql.DriverManager; import static com.novarto.sanedbc.core.ops.DbOps.unique; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package com.novarto.sanedbc.examples; public class MapExample1 { public static class User { public final String user; public final String hash; public User(String user, String hash) { this.user = user; this.hash = hash; } } public static class UserDB {
public static final DB<Unit> CREATE_USER_TABLE = new EffectOp(
1
AURIN/online-whatif
src/main/java/au/org/aurin/wif/impl/AsyncProjectServiceImpl.java
[ "@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE, \nreason = \"Spatial DataStore creation failed!\")\npublic class DataStoreCreationException extends Exception {\n\n /** The Constant serialVersionUID. */\n private static final long serialVersionUID = 1124576769564144835L;\n\n /**\n * Instantiates a new ...
import java.io.IOException; import java.util.HashSet; import java.util.concurrent.Future; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import org.geotools.feature.FeatureCollection; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Service; import au.org.aurin.wif.config.GeoServerConfig; import au.org.aurin.wif.config.WifConfig; import au.org.aurin.wif.exception.config.WifInvalidConfigException; import au.org.aurin.wif.exception.io.DataStoreCreationException; import au.org.aurin.wif.exception.io.DataStoreUnavailableException; import au.org.aurin.wif.exception.io.MiddlewarePersistentException; import au.org.aurin.wif.exception.io.ShapeFile2PostGISCreationException; import au.org.aurin.wif.exception.io.WifIOException; import au.org.aurin.wif.exception.validate.InvalidFFNameException; import au.org.aurin.wif.exception.validate.InvalidLabelException; import au.org.aurin.wif.exception.validate.WifInvalidInputException; import au.org.aurin.wif.io.DataStoreToPostgisExporter; import au.org.aurin.wif.io.GeodataFinder; import au.org.aurin.wif.io.PostgisToDataStoreExporter; import au.org.aurin.wif.model.WifProject; import au.org.aurin.wif.model.suitability.SuitabilityConfig; import au.org.aurin.wif.repo.impl.CouchWifProjectDao; import au.org.aurin.wif.svc.AllocationLUService; import au.org.aurin.wif.svc.AsyncProjectService; import au.org.aurin.wif.svc.WifKeys; import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
package au.org.aurin.wif.impl; /** * The Class AsyncProjectServiceImpl. */ @Service @Qualifier("asyncProjectService") public class AsyncProjectServiceImpl implements AsyncProjectService { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 213432423433L; /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory .getLogger(AsyncProjectServiceImpl.class); /** The geoserver publisher. */ @Autowired private GeoServerRESTPublisher geoserverPublisher; /** The postgis to data store exporter. */ @Autowired private PostgisToDataStoreExporter postgisToDataStoreExporter; /** The geoserver config. */ @Autowired private GeoServerConfig geoserverConfig; /** The wif config. */ @Resource private WifConfig wifConfig; /** The validator crs. */ @Resource private ValidatorCRS validatorCRS; /** The wif project dao. */ @Autowired private CouchWifProjectDao wifProjectDao; /** The exporter. */ @Autowired private DataStoreToPostgisExporter exporter; /** The geodata finder. */ @Autowired private GeodataFinder geodataFinder; /** The validator crs. */ @Resource private ValidatorUAZ validatorUAZ; @Resource private AllocationLUService allocationLUService; /** * Inits the. */ @PostConstruct public void init() {
LOGGER.trace("Initializing version: " + WifKeys.WIF_KEY_VERSION);
5
oSoc14/Artoria
app/src/main/java/be/artoria/belfortapp/mixare/plugin/remoteobjects/RemoteDataHandler.java
[ "public class POI {\n\n\n private static final int BOAT = 0;\n private static final int CIVIL = 1;\n private static final int RELIGIOUS = 2;\n private static final int TOWER = 3;\n private static final int THEATRE = 4;\n private static final int CASTLE = 5;\n private static final int...
import be.artoria.belfortapp.mixare.lib.marker.Marker; import be.artoria.belfortapp.mixare.lib.marker.draw.ParcelableProperty; import be.artoria.belfortapp.mixare.lib.marker.draw.PrimitiveProperty; import be.artoria.belfortapp.mixare.lib.service.IDataHandlerService; import be.artoria.belfortapp.mixare.plugin.PluginLoader; import be.artoria.belfortapp.mixare.plugin.PluginNotFoundException; import android.os.RemoteException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.json.JSONException; import be.artoria.belfortapp.app.POI; import be.artoria.belfortapp.mixare.data.DataHandler; import be.artoria.belfortapp.mixare.data.convert.DataProcessor; import be.artoria.belfortapp.mixare.lib.marker.InitialMarkerData;
/* * Copyright (C) 2012- Peer internet solutions & Finalist IT Group * * This file is part of be.artoria.belfortapp.mixare. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/> */ package be.artoria.belfortapp.mixare.plugin.remoteobjects; public class RemoteDataHandler extends DataHandler implements DataProcessor { private String dataHandlerName; private IDataHandlerService iDataHandlerService; public String getDataHandlerName() { return dataHandlerName; } public RemoteDataHandler(IDataHandlerService iDataHandlerService) { this.iDataHandlerService = iDataHandlerService; } public void buildDataHandler(){ try { this.dataHandlerName = iDataHandlerService.build(); } catch (RemoteException e) { throw new PluginNotFoundException(e); } } public String[] getUrlMatch() { try { return iDataHandlerService.getUrlMatch(dataHandlerName); } catch (RemoteException e) { throw new PluginNotFoundException(e); } } public String[] getDataMatch() { try { return iDataHandlerService.getDataMatch(dataHandlerName); } catch (RemoteException e) { throw new PluginNotFoundException(e); } } @Override public boolean matchesRequiredType(String type) { //TODO: change the datasource so that it can have more types, // so that plugins can also have a required type return true; }
public List<Marker> load(List<POI> rawData, int taskId, int colour) {
4