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 |
|---|---|---|---|---|---|---|
goshippo/shippo-java-client | src/main/java/com/shippo/model/Batch.java | [
"public class APIConnectionException extends ShippoException {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic APIConnectionException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic APIConnectionException(String message, Throwable e) {\n\t\tsuper(message, e);\n\t}\n\n}",
"public class AP... | import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import com.google.gson.annotations.SerializedName;
import com.shippo.exception.APIConnectionException;
import com.shippo.exception.APIException;
import com.shippo.exception.AuthenticationException;
import com.shippo.exception.InvalidRequestException;
import com.shippo.net.APIResource;
import com.shippo.util.HttpUtil; | package com.shippo.model;
/**
* Represents <code>/batches</code> endpoint documented at
* https://goshippo.com/docs/reference#batches
*/
public final class Batch extends APIResource {
@SerializedName("object_id")
private String id;
@SerializedName("object_owner")
private String owner;
public static enum BatchStatus {
VALIDATING, VALID, INVALID, PURCHASING, PURCHASED
}
@SerializedName("status")
private BatchStatus status;
@SerializedName("object_created")
private Date created;
@SerializedName("object_updated")
private Date updated;
@SerializedName("metadata")
private String metadata;
@SerializedName("default_carrier_account")
private String defaultCarrierAccount;
@SerializedName("default_servicelevel_token")
private String defaultServiceLevelToken;
@SerializedName("label_filetype")
private LabelFileType labelFileType;
public static class BatchShipmentCollection {
private int count;
private String next;
private String previous;
@SerializedName("results")
private BatchShipment[] shipments;
@Override
public String toString() {
return "BatchShipmentCollection [next=" + next + ", shipments=" + Arrays.toString(shipments) + "]";
}
public String getNext() {
return next;
}
public String getPrevious() {
return previous;
}
public BatchShipment[] getShipments() {
return shipments;
}
public int getCount() {
return count;
}
}
@SerializedName("batch_shipments")
private BatchShipmentCollection batchShipments;
@SerializedName("label_url")
private String[] labelURLs;
public static class Counts {
@SerializedName("creation_succeeded")
private int creationSucceeded;
@SerializedName("creation_failed")
private int creationFailed;
@SerializedName("purchase_succeeded")
private int purchaseSucceeded;
@SerializedName("purchase_failed")
private int purchaseFailed;
@Override
public String toString() {
return "Counts [creationSucceeded=" + creationSucceeded + ", creationFailed=" + creationFailed
+ ", purchaseSucceeded=" + purchaseSucceeded + ", purchaseFailed=" + purchaseFailed + "]";
}
public int getCreationSucceeded() {
return creationSucceeded;
}
public int getCreationFailed() {
return creationFailed;
}
public int getPurchaseSucceeded() {
return purchaseSucceeded;
}
public int getPurchaseFailed() {
return purchaseFailed;
}
}
@SerializedName("object_results")
private Counts objectResults;
@Override
public String toString() {
return "Batch [id=" + id + ", owner=" + owner + ", status=" + status + ", created=" + created + ", updated="
+ updated + ", metadata=" + metadata + ", defaultCarrierAccount=" + defaultCarrierAccount
+ ", defaultServiceLevelToken=" + defaultServiceLevelToken + ", labelFileType=" + labelFileType
+ ", batchShipments=" + batchShipments + ", labelURLs=" + Arrays.toString(labelURLs)
+ ", objectResults=" + objectResults + "]";
}
private static class BatchCollection {
private String next;
@SerializedName("results")
private Batch[] array;
}
/**
* Get all batches created in the account.
*
* @return Array of Batch object
*/
public static Batch[] all() throws AuthenticationException, InvalidRequestException, APIConnectionException,
APIException, UnsupportedEncodingException, MalformedURLException {
List<Batch> all_batches = new ArrayList<Batch>();
Map<String, String> params = new HashMap<String, String>();
while (true) {
Map<String, Object> reqParams = new HashMap<String, Object>(params);
BatchCollection coll = request(RequestMethod.GET, classURL(Batch.class), reqParams, BatchCollection.class,
null);
if (coll.array.length == 0) {
break;
}
all_batches.addAll(Arrays.asList(coll.array));
if (coll.next == null) {
break;
} | params = HttpUtil.queryToParams(new URL(coll.next).getQuery()); | 5 |
futurice/vor | vor-android/mobile/src/main/java/com/futurice/vor/fragment/CardsNowFragment.java | [
"public class Cards {\n\n /**\n * 3D printing card\n * @param file the file in base64\n * @param context the context\n * @return the 3d printing topic\n */\n public static ITopic printer3d(String file, Context context) {\n final Topic topic = new Topic(\"3D Printing\", 110, context,... | import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import com.reactivecascade.i.CallOrigin;
import com.futurice.vor.Cards;
import com.futurice.vor.Config;
import com.futurice.vor.R;
import com.futurice.vor.VorApplication;
import com.futurice.vor.adapter.TopicListAdapter;
import com.futurice.vor.card.ITopic;
import com.futurice.vor.utils.SharedPreferencesManager;
import com.futurice.vor.utils.BeaconLocationManager;
import com.futurice.vor.utils.VorUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import io.socket.client.Socket;
import static com.reactivecascade.Async.UI;
import static com.futurice.vor.Constants.*;
import static com.google.android.youtube.player.YouTubeStandalonePlayer.createVideoIntent; | package com.futurice.vor.fragment;
public class CardsNowFragment extends BaseVorFragment {
private static final String TAG = CardsNowFragment.class.getSimpleName();
Socket mSocket;
ExpandableListView mElv;
String mGreatShotUrl;
SharedPreferences mTestSP;
SharedPreferences mFoodSP;
SharedPreferences mPoolSP;
SharedPreferences mPoolVideoSP;
SharedPreferences m3dPrinterSP;
OnSharedPreferenceChangeListener mTestCardListener = this::addCard;
OnSharedPreferenceChangeListener mFoodCardListener = this::addCard;
OnSharedPreferenceChangeListener mPoolCardListener = this::addCard;
OnSharedPreferenceChangeListener mPoolVideoCardListener = this::addCard;
OnSharedPreferenceChangeListener m3dPrinterCardListener = this::addCard;
ExpandableListView.OnGroupClickListener greatShotListener = (parent, v, groupPosition, id) -> {
if (id == 340) { // ID of the great shot
startActivity(createVideoIntent(
getActivity(),
Config.YOUTUBE_API_KEY,
VorUtils.extractYouTubeVideoId(mGreatShotUrl),
0,
true,
true));
parent.collapseGroup(groupPosition);
return true;
}
return false;
};
public CardsNowFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSocket = VorApplication.getSocket();
mTestSP = getActivity().getSharedPreferences(TEST_KEY, Context.MODE_PRIVATE);
mFoodSP = getActivity().getSharedPreferences(FOOD_KEY, Context.MODE_PRIVATE);
mPoolSP = getActivity().getSharedPreferences(POOL_KEY, Context.MODE_PRIVATE);
mPoolVideoSP = getActivity().getSharedPreferences(POOL_KEY, Context.MODE_PRIVATE);
m3dPrinterSP = getActivity().getSharedPreferences(PRINTER_3D_KEY, Context.MODE_PRIVATE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cards_now, container, false);
initViewsAndAdapters();
initListView();
RelativeLayout emptyView = (RelativeLayout) inflater.inflate(R.layout.no_cards_view, null);
ExpandableListView expandableListView = getExpandableListView();
setEmptyExpandableListView(getActivity(), emptyView);
FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.now_cards_list);
frameLayout.addView(expandableListView);
mSocket.on(EVENT_INIT, args -> {
UI.execute(() -> {
JSONObject jsonObject = (JSONObject) args[0];
try {
JSONArray jsonArray = jsonObject.getJSONArray(INIT_BEACONS_KEY);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject beacon = (JSONObject) jsonArray.get(i);
String identifier = beacon.getString(ID_KEY);
int floor = beacon.getInt(FLOOR_KEY);
float x = (float) beacon.getDouble(LOCATION_X_KEY);
float y = (float) beacon.getDouble(LOCATION_Y_KEY);
BeaconLocationManager bm = VorApplication.getBeaconLocationManager();
bm.addBeacon(identifier, floor, x, y, getContext());
}
// Start the manager.
VorApplication.getBeaconLocationManager().resume();
// Initialize cards.
JSONArray cardsArray = jsonObject.getJSONArray(INIT_MESSAGES_KEY);
setupInitialView(cardsArray);
} catch (JSONException e) {
e.printStackTrace();
}
});
});
mSocket.emit(EVENT_INIT); // Requests latest messages
initTopicsAndCards(
createPreBuiltTopics(),
getSourceTopicModel(),
getTopicListAdapter());
filterModel();
return view;
}
@Override
public void onResume() {
super.onResume();
mTestSP.registerOnSharedPreferenceChangeListener(mTestCardListener);
mFoodSP.registerOnSharedPreferenceChangeListener(mFoodCardListener);
mPoolSP.registerOnSharedPreferenceChangeListener(mPoolCardListener);
mPoolVideoSP.registerOnSharedPreferenceChangeListener(mPoolVideoCardListener);
m3dPrinterSP.registerOnSharedPreferenceChangeListener(m3dPrinterCardListener);
}
@Override
public void onPause() {
super.onPause();
mTestSP.unregisterOnSharedPreferenceChangeListener(mTestCardListener);
mFoodSP.unregisterOnSharedPreferenceChangeListener(mFoodCardListener);
mPoolSP.unregisterOnSharedPreferenceChangeListener(mPoolCardListener);
mPoolVideoSP.unregisterOnSharedPreferenceChangeListener(mPoolVideoCardListener);
m3dPrinterSP.unregisterOnSharedPreferenceChangeListener(m3dPrinterCardListener);
}
protected void initViewsAndAdapters() {
mElv = new ExpandableListView(getActivity());
setExpandableListView(mElv);
TopicListAdapter tla = new TopicListAdapter(getSourceTopicModel(), "NowCardsListAdapter");
setTopicListAdapter(tla);
}
private void setupInitialView(JSONArray jsonArray) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (!jsonObject.has(TYPE_KEY)) {
continue; // Not a valid card if doesn't have type
}
Context context = VorApplication.getStaticContext(); | List<ITopic> cards = getSourceTopicModel(); | 4 |
Terracotta-OSS/offheap-store | src/test/java/org/terracotta/offheapstore/WriteLockedOffHeapClockCacheIT.java | [
"public class WriteLockedOffHeapClockCache<K, V> extends AbstractOffHeapClockCache<K, V> {\n\n private final Lock lock = new ReentrantLock();\n\n public WriteLockedOffHeapClockCache(PageSource source, StorageEngine<? super K, ? super V> storageEngine) {\n super(source, storageEngine);\n }\n\n public WriteLoc... | import org.terracotta.offheapstore.WriteLockedOffHeapClockCache;
import java.util.concurrent.ConcurrentMap;
import org.junit.Test;
import org.terracotta.offheapstore.buffersource.HeapBufferSource;
import org.terracotta.offheapstore.buffersource.OffHeapBufferSource;
import org.terracotta.offheapstore.paging.PageSource;
import org.terracotta.offheapstore.paging.PhantomReferenceLimitedPageSource;
import org.terracotta.offheapstore.paging.UnlimitedPageSource;
import org.terracotta.offheapstore.paging.UpfrontAllocatingPageSource;
import org.terracotta.offheapstore.storage.IntegerStorageEngine;
import org.terracotta.offheapstore.storage.OffHeapBufferHalfStorageEngine;
import org.terracotta.offheapstore.storage.SplitStorageEngine;
import org.terracotta.offheapstore.storage.portability.ByteArrayPortability;
import org.terracotta.offheapstore.util.Generator;
import static org.terracotta.offheapstore.util.Generator.BAD_GENERATOR;
import static org.terracotta.offheapstore.util.Generator.GOOD_GENERATOR;
import org.terracotta.offheapstore.util.Generator.SpecialInteger;
import org.terracotta.offheapstore.util.MemoryUnit;
import org.terracotta.offheapstore.util.ParallelParameterized;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.core.Is.is;
import static org.junit.Assume.assumeThat;
import org.junit.runner.RunWith; | /*
* Copyright 2015 Terracotta, Inc., a Software AG company.
*
* 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.terracotta.offheapstore;
@RunWith(ParallelParameterized.class)
public class WriteLockedOffHeapClockCacheIT extends AbstractConcurrentOffHeapMapIT {
@ParallelParameterized.Parameters(name = "generator={0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[] {GOOD_GENERATOR}, new Object[] {BAD_GENERATOR});
}
public WriteLockedOffHeapClockCacheIT(Generator generator) {
super(generator);
}
@Test
public void testCacheEviction() {
assumeThat(generator, is(GOOD_GENERATOR));
CapacityLimitedIntegerStorageEngineFactory factory = new CapacityLimitedIntegerStorageEngineFactory();
CacheTestRoutines.testCacheEviction(new WriteLockedOffHeapClockCache<>(new UnlimitedPageSource(new OffHeapBufferSource()), factory
.newInstance(), 1), factory);
}
@Test
public void testCacheEvictionDueToTableResizeFailure() {
assumeThat(generator, is(GOOD_GENERATOR));
for (int i = 1; i < 100; i++) {
CacheTestRoutines.testCacheEvictionMinimal(new WriteLockedOffHeapClockCache<>(new PhantomReferenceLimitedPageSource(16 * i), new SplitStorageEngine<>(new IntegerStorageEngine(), new IntegerStorageEngine()), 1));
}
}
@Test
public void testCacheEvictionThreshold() {
CacheTestRoutines.testCacheEvictionThreshold(createOffHeapBufferMap(new PhantomReferenceLimitedPageSource(4 * 1024)));
}
@Test
public void testCacheFillBehavior() { | CacheTestRoutines.testFillBehavior(createOffHeapBufferMap(new UpfrontAllocatingPageSource(new HeapBufferSource(), MemoryUnit.KILOBYTES.toBytes(8), MemoryUnit.KILOBYTES.toBytes(8)))); | 3 |
karsany/obridge | obridge-main/src/main/java/org/obridge/generators/ProcedureContextGenerator.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.List;
import org.apache.commons.io.FileUtils;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.dao.ProcedureDao;
import org.obridge.mappers.PojoMapper;
import org.obridge.model.data.Procedure;
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 ProcedureContextGenerator {
private ProcedureContextGenerator() {
}
public static void generate(OBridgeConfiguration c) {
try {
String packageName = c.getRootPackageName() + "." + c.getPackages().getProcedureContextObjects();
String objectPackage = c.getRootPackageName() + "." + c.getPackages().getEntityObjects();
String outputDir = c.getSourceRoot() + "/" + packageName.replace(".", "/") + "/";
| ProcedureDao procedureDao = new ProcedureDao(DataSourceProvider.getDataSource(c.getJdbcUrl())); | 1 |
sooola/V2EX-Android | app/src/main/java/com/sola/v2ex_android/ui/NodeFragment.java | [
"public class NodeInfo {\n /**\n * id : 300\n * name : programmer\n * url : http://www.v2ex.com/go/programmer\n * title : 程序员\n * title_alternative : Programmer\n * topics : 13616\n * stars : 2688\n * header : While code monkeys are not eating bananas, they're coding.\n * foot... | import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.sola.v2ex_android.R;
import com.sola.v2ex_android.model.NodeInfo;
import com.sola.v2ex_android.network.V2exService;
import com.sola.v2ex_android.ui.base.BaseSwipeRefreshFragment;
import com.sola.v2ex_android.util.LogUtil;
import com.sola.v2ex_android.util.NodeDataUtil;
import com.sola.v2ex_android.util.ToastUtil;
import com.zzhoujay.richtext.RichText;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers; | package com.sola.v2ex_android.ui;
/**
* 主页 - 节点
* Created by wei on 2016/10/27.
*/
public class NodeFragment extends BaseSwipeRefreshFragment {
private String[] mTechnologyGroupTitle = new String[] { "程序员", "Python", "iDev", "Android","Linux" ,"node.js"};
private String[] mCreativeGroupTitle = new String[] { "分享创造", "设计", "奇思妙想"};
private String[] mFunGroupTitle = new String[] { "分享发现", "电子游戏", "电影" , "旅行"};
private String[] mCoolGroupTitle = new String[] { "酷工作", "求职", "职场话题"};
private String[] mTransactionGroupTitle = new String[] { "二手交易", "物物交换", "免费赠送" , "域名"};
private boolean mIsFirst = true;
public static NodeFragment newInstance() {
return new NodeFragment();
}
@BindView(R.id.ll_root)
LinearLayout mContentLl;
Observer<List<NodeInfo>> observer = new Observer<List<NodeInfo>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) { | LogUtil.d("UserDetialActivity", "e" + e.toString()); | 3 |
kefik/MsPacMan-vs-Ghosts-AI | PacMan-vs-Ghosts-Agents/src/game/controllers/pacman/examples/RandomPacMan.java | [
"public class PacManSimulator {\n\t\n\tpublic static class GameConfig {\n\t\t\n\t\tpublic int seed = -1;\n\t\t\n\t\t/**\n\t\t * Whether POWER PILLS should be present within the environment.\n\t\t */\n\t\tpublic boolean powerPillsEnabled = true;\n\t\t\n\t\t/**\n\t\t * Total percentage of PILLS present within the lev... | import game.PacManSimulator;
import game.controllers.ghosts.game.GameGhosts;
import game.controllers.pacman.PacManHijackController;
import game.core.G;
import game.core.Game; | package game.controllers.pacman.examples;
public final class RandomPacMan extends PacManHijackController
{
@Override | public void tick(Game game, long timeDue) { | 4 |
samtingleff/jchronic | src/main/java/com/mdimension/jchronic/handlers/SRPHandler.java | [
"public class Chronic {\n public static final String VERSION = \"0.2.3\";\n\n private Chronic() {\n // DO NOTHING\n }\n\n public static Span parse(String text) {\n return Chronic.parse(text, new Options());\n }\n\n /**\n * Parses a string containing a natural language date or time. If the parser\n *... | import java.util.List;
import com.mdimension.jchronic.Chronic;
import com.mdimension.jchronic.Options;
import com.mdimension.jchronic.repeaters.Repeater;
import com.mdimension.jchronic.tags.Pointer;
import com.mdimension.jchronic.tags.Scalar;
import com.mdimension.jchronic.utils.Span;
import com.mdimension.jchronic.utils.Token; | package com.mdimension.jchronic.handlers;
public class SRPHandler implements IHandler {
public Span handle(List<Token> tokens, Span span, Options options) { | int distance = tokens.get(0).getTag(Scalar.class).getType().intValue(); | 4 |
xbynet/crawler | crawler-core/src/test/java/net/xby1993/crawler/QiushibaikeCrawler.java | [
"public abstract class Processor implements Closeable{\n\tprivate FileDownloader fileDownloader=null;\n\tprivate Spider spider=null;\n\t\n\tpublic abstract void process(Response resp);\n\t\n\tpublic boolean download(Request req,String savePath){\n\t\treturn fileDownloader.download(req, savePath);\n\t}\n\tpublic boo... | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.github.xbynet.crawler.Processor;
import com.github.xbynet.crawler.Response;
import com.github.xbynet.crawler.Site;
import com.github.xbynet.crawler.Spider;
import com.github.xbynet.crawler.parser.JsoupParser; | package net.xby1993.crawler;
public class QiushibaikeCrawler extends Processor{
@Override | public void process(Response resp) { | 1 |
flyersa/MuninMX | src/com/clavain/workers/ServiceCheckInspector.java | [
"public class ReturnServiceCheck {\n private Integer returnValue;\n private List<String> output;\n private Integer user_id;\n private Integer cid;\n private Integer checktime;\n private Integer downTimeConfirmedAt;\n private Integer lastDownTimeConfirm;\n private String checktype;\n priva... | import com.clavain.checks.ReturnServiceCheck;
import static com.clavain.utils.Checks.isServiceCheckDown;
import static com.clavain.utils.Checks.removeCheckFromProcessingList;
import static com.clavain.utils.Checks.addDownTimeToDb;
import static com.clavain.alerts.Methods.*;
import static com.clavain.utils.Generic.getUnixtime;
import static com.clavain.muninmxcd.logger;
import static com.clavain.muninmxcd.p; | /*
* MuninMX
* Written by Enrico Kern, kern@clavain.com
* www.clavain.com
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.clavain.workers;
/**
*
* @author enricokern
*/
public class ServiceCheckInspector implements Runnable {
private ReturnServiceCheck sc;
private int notificationruns = 0;
@Override
public void run() {
logger.info("ServiceCheckInspector for failed check: " + sc.getCid() + " spawned. Will take care of notifications and ongoing check control");
boolean keepMeRunning = true;
boolean isCheckDown;
boolean waiting = false;
int cycle = 0;
while(keepMeRunning)
{
try
{
// initial notification?
if(notificationruns == 0)
{
// instant?
if(sc.getNotifydown() == 0)
{
sendNotifications(sc);
notificationruns++;
}
else
{
// convert to seconds
int waitTime = sc.getNotifydown() * 60;
// time already passed?
int waitTimeUnix = sc.getDownTimeConfirmedAt() + waitTime;
if(getUnixtime() > waitTimeUnix)
{
logger.info("[ServiceCheckInspector "+sc.getCid()+"] Waittime already passed. Sending notifications NOW");
sendNotifications(sc);
notificationruns++;
}
else
{
// wait for it
logger.info("[ServiceCheckInspector "+sc.getCid()+"] Notifydown set to: " + sc.getNotifydown() + " minutes. Waiting and rechecking...");
int curTime = getUnixtime();
while(curTime < waitTimeUnix)
{
Thread.sleep(10000);
curTime = getUnixtime();
}
// check if its down
logger.info("[ServiceCheckInspector "+sc.getCid()+"] " + sc.getNotifydown() + " Minutes for NotifyDown passed. Verifying if check is stil critical");
isCheckDown = isServiceCheckDown(sc);
if(isCheckDown)
{
sendNotifications(sc);
notificationruns++;
}
else
{
logger.info("[ServiceCheckInspector "+sc.getCid()+"] " + sc.getNotifydown() + " Minutes for NotifyDown passed. Check is FINE. not sending notifications");
keepMeRunning = false;
addDownTimeToDb(sc.getCid(), sc.getDownTimeConfirmedAt(), getUnixtime()); | removeCheckFromProcessingList(sc.getCid()); | 2 |
groupon/vertx-memcache | src/main/java/com/groupon/vertx/memcache/command/MemcacheCommand.java | [
"public class MemcacheException extends RuntimeException {\n private static final long serialVersionUID = -386882705199382789L;\n\n public MemcacheException(String message) {\n super(message);\n }\n}",
"public class MemcacheCommandResponse {\n private final JsendStatus status;\n private fina... | import io.vertx.core.Handler;
import com.groupon.vertx.memcache.MemcacheException;
import com.groupon.vertx.memcache.client.response.MemcacheCommandResponse;
import com.groupon.vertx.memcache.parser.DeleteLineParser;
import com.groupon.vertx.memcache.parser.LineParser;
import com.groupon.vertx.memcache.parser.LineParserType;
import com.groupon.vertx.memcache.parser.ModifyLineParser;
import com.groupon.vertx.memcache.parser.RetrieveLineParser;
import com.groupon.vertx.memcache.parser.StoreLineParser;
import com.groupon.vertx.memcache.parser.TouchLineParser;
import com.groupon.vertx.utils.Logger; | /**
* Copyright 2014 Groupon.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.groupon.vertx.memcache.command;
/**
* This class encapsulates the information necessary to send a command to the
* Memcache server.
*
* @author Stuart Siegrist (fsiegrist at groupon dot com)
* @since 1.0.0
*/
public class MemcacheCommand {
private static final Logger log = Logger.getLogger(MemcacheCommand.class);
private MemcacheCommandType type;
private String key;
private String value;
private Integer expires;
private LineParser parser;
private Handler<MemcacheCommandResponse> commandResponseHandler;
/**
* A helper method for manually building a command.
*
* @param type - An enum for the command type.
* @param key - A String containing the key.
* @param value - The String value to be sent using the command.
* @param expires - An integer with the seconds before expiration.
*/
public MemcacheCommand(MemcacheCommandType type, String key, String value, Integer expires) {
if (type == null || key == null) {
log.warn("initMemcacheCommand", "failure", new String[]{"reason"}, "Invalid command format");
throw new IllegalArgumentException("Invalid command format");
}
setLineParser(type.getLineParserType());
this.type = type;
this.key = key;
this.value = value;
this.expires = expires;
}
/**
* The MemcacheCommandType enum which represents the command type being sent to Memcache.
*
* @return - A MemcacheCommandType representing the current command.
*/
public MemcacheCommandType getType() {
return type;
}
/**
* The String name for the command.
*
* @return - A String containing the name for the Memcache command.
*/
public String getCommand() {
return type.getCommand();
}
/**
* The key for inserting, updating, or deleting an object in the store.
*
* @return - A String containing the key.
*/
public String getKey() {
return key;
}
/**
* The value to be stored or updated in the store.
*
* @return - A String containing the value.
*/
public String getValue() {
return value;
}
/**
* The number of seconds for updating the expiration of a key.
*
* @return - An integer representing the number of seconds before a key expires.
*/
public Integer getExpires() {
return expires;
}
/**
* Calling this method will execute the handler associate with this command. If no
* handler is specified the response will be ignored.
*
* @param response - The Memcache response for this command.
*/
public void setResponse(MemcacheCommandResponse response) {
if (commandResponseHandler != null) {
commandResponseHandler.handle(response);
} else {
log.trace("setResponse", "missingHandler");
}
}
/**
* This handler will be executed when the response has been received from Memcache.
*
* @param handler - A handler for the JsonObject Memcache response.
*/
public void commandResponseHandler(Handler<MemcacheCommandResponse> handler) {
this.commandResponseHandler = handler;
}
/**
* This is the parser for processing the current response for this command.
*
* @return - The currently initialized line parser.
*/
public LineParser getLineParser() {
return parser;
}
/**
* This initializes the line parser for processing the response for this command.
*
* @param lineParserType - The type of line parser to create.
*/
private void setLineParser(LineParserType lineParserType) {
switch (lineParserType) {
case RETRIEVE:
parser = new RetrieveLineParser();
break;
case STORE:
parser = new StoreLineParser();
break;
case MODIFY:
parser = new ModifyLineParser();
break;
case DELETE:
parser = new DeleteLineParser();
break;
case TOUCH:
parser = new TouchLineParser();
break;
default: | throw new MemcacheException("Unable to initialize line parser."); | 0 |
Nilhcem/droidcontn-2016 | app/src/main/java/com/nilhcem/droidcontn/core/dagger/AppGraph.java | [
"@DebugLog\npublic class BootReceiver extends BroadcastReceiver {\n\n public static void enable(Context context) {\n setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_ENABLED);\n }\n\n public static void disable(Context context) {\n setActivationState(context, PackageManager.... | import com.nilhcem.droidcontn.receiver.BootReceiver;
import com.nilhcem.droidcontn.ui.drawer.DrawerActivity;
import com.nilhcem.droidcontn.ui.schedule.day.ScheduleDayFragment;
import com.nilhcem.droidcontn.ui.schedule.pager.SchedulePagerFragment;
import com.nilhcem.droidcontn.ui.sessions.details.SessionDetailsActivity;
import com.nilhcem.droidcontn.ui.sessions.list.SessionsListActivity;
import com.nilhcem.droidcontn.ui.settings.SettingsFragment;
import com.nilhcem.droidcontn.ui.speakers.details.SpeakerDetailsDialogFragment;
import com.nilhcem.droidcontn.ui.speakers.list.SpeakersListFragment; | package com.nilhcem.droidcontn.core.dagger;
/**
* A common interface implemented by both the internal and production flavored components.
*/
public interface AppGraph {
void inject(DrawerActivity activity);
void inject(SchedulePagerFragment fragment);
void inject(ScheduleDayFragment fragment);
| void inject(SessionsListActivity activity); | 5 |
OpenNMS/jrobin | src/test/java/org/jrobin/test/JRobinRRATimePeriodTest.java | [
"public class ArcDef implements ConsolFuns {\n\t/**\n\t * array of valid consolidation function names\n\t */\n\tpublic static final String CONSOL_FUNS[] = {CF_AVERAGE, CF_MAX, CF_MIN, CF_LAST};\n\n\tprivate String consolFun;\n\tprivate double xff;\n\tprivate int steps, rows;\n\n\t/**\n\t * Creates new archive defin... | import java.util.Random;
import org.jrobin.core.ArcDef;
import org.jrobin.core.RrdBackendFactory;
import org.jrobin.core.RrdDb;
import org.jrobin.core.RrdDef;
import org.jrobin.core.Sample;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; | /*******************************************************************************
* Copyright (c) 2001-2005 Sasa Markovic and Ciaran Treanor.
* Copyright (c) 2011 The OpenNMS Group, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*******************************************************************************/
package org.jrobin.test;
public class JRobinRRATimePeriodTest {
RrdDb m_db = null;
Random m_random = new Random();
@BeforeClass
public static void beforeClass() throws Exception {
if (!RrdBackendFactory.isInstanceCreated()) {
RrdBackendFactory.setDefaultFactory("FILE");
}
}
@Test
public void testRRATimePeriod() throws Exception { | RrdDef def = new RrdDef("target/test.jrb"); | 3 |
KorAP/Koral | src/main/java/de/ids_mannheim/korap/query/serialize/AnnisQueryProcessor.java | [
"public enum KoralFrame {\n\n SUCCEDS(\"succeeds\"), SUCCEDS_DIRECTLY(\"succeedsDirectly\"), OVERLAPS_RIGHT(\"overlapsRight\"), \n ALIGNS_RIGHT(\"alignsRight\"), IS_WITHIN(\"isWithin\"), STARTS_WITH(\"startsWith\"), \n MATCHES(\"matches\"), ALIGNS_LEFT(\"alignsLeft\"), IS_AROUND(\"isAround\"), ENDS_WITH(\"... | import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.antlr.v4.parse.ANTLRParser.throwsSpec_return;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.ids_mannheim.korap.query.object.KoralFrame;
import de.ids_mannheim.korap.query.object.KoralMatchOperator;
import de.ids_mannheim.korap.query.object.KoralOperation;
import de.ids_mannheim.korap.query.object.KoralTermGroupRelation;
import de.ids_mannheim.korap.query.object.KoralType;
import de.ids_mannheim.korap.query.parse.annis.AqlLexer;
import de.ids_mannheim.korap.query.parse.annis.AqlParser;
import de.ids_mannheim.korap.query.serialize.util.Antlr4DescriptiveErrorListener;
import de.ids_mannheim.korap.query.serialize.util.KoralException;
import de.ids_mannheim.korap.query.serialize.util.KoralObjectGenerator;
import de.ids_mannheim.korap.query.serialize.util.StatusCodes; | package de.ids_mannheim.korap.query.serialize;
/**
* Processor class for ANNIS QL queries. This class uses an ANTLR v4
* grammar
* for query parsing, it therefore extends
* {@link Antlr4AbstractQueryProcessor}.
* The parser object is inherited from the parent class and
* instantiated in {@link #parseAnnisQuery(String)} as an
* {@link AqlParser}.
*
* @see http://annis-tools.org/aql.html
*
* @author Joachim Bingel (bingel@ids-mannheim.de)
* @author Eliza Margaretha (margaretha@ids-mannheim.de)
* @version 0.3.0
* @since 0.1.0
*/
public class AnnisQueryProcessor extends Antlr4AbstractQueryProcessor {
private static final boolean DEBUG = false;
private static Logger log = LoggerFactory
.getLogger(AnnisQueryProcessor.class);
/**
* Flag that indicates whether token fields or meta fields are
* currently
* being processed
*/
boolean inMeta = false;
/**
* Keeps track of operands that are to be integrated into yet
* uncreated
* objects.
*/
LinkedList<Map<String, Object>> operandStack = new LinkedList<Map<String, Object>>();
/**
* Keeps track of explicitly (by #-var definition) or implicitly
* (number
* as reference) introduced entities (for later reference by
* #-operator)
*/
Map<String, Map<String, Object>> nodeVariables = new HashMap<String, Map<String, Object>>();
/**
* Keeps track of explicitly (by #-var definition) or implicitly
* (number
* as reference) introduced entities (for later reference by
* #-operator)s
*/
Map<ParseTree, String> nodes2refs = new HashMap<ParseTree, String>();
/**
* Counter for variable definitions.
*/
Integer variableCount = 1;
/**
* Marks the currently active token in order to know where to add
* flags
* (might already have been taken away from token stack).
*/
Map<String, Object> curToken = new HashMap<String, Object>();
/**
* Keeps track of operands lists that are to be serialised in an
* inverted
* order (e.g. the IN() operator) compared to their AST
* representation.
*/
private LinkedList<ArrayList<Object>> invertedOperandsLists = new LinkedList<ArrayList<Object>>();
/**
* Keeps track of operation:class numbers.
*/
int classCounter = 1;
/**
* Keeps track of numers of relations processed (important when
* dealing
* with multiple predications).
*/
int relationCounter = 0;
/**
* Keeps track of references to nodes that are operands of groups
* (e.g.
* tree relations). Those nodes appear on the top level of the
* parse tree
* but are to be integrated into the AqlTree at a later point
* (namely as
* operands of the respective group). Therefore, store references
* to these
* nodes here and exclude the operands from being written into the
* query
* map individually.
*/
private int totalRelationCount = 0;
/**
* Keeps a record of reference-class-mapping, i.e. which 'class'
* has been
* assigned to which #n reference. This is important when
* introducing
* koral:reference spans to refer back to previously established
* classes for
* entities.
*/
private Map<String, Integer> refClassMapping = new HashMap<String, Integer>();
/**
* Keeps a record of unary relations on spans/tokens.
*/
private Map<String, ArrayList<ParseTree>> unaryRelations = new HashMap<String, ArrayList<ParseTree>>();
/**
* Keeps track of the number of references to a node/token by
* means of #n.
* E.g. in the query <tt>tok="x" & tok="y" & tok="z" & #1 . #2 &
* #2 . #3</tt>,
* the 2nd token ("y") is referenced twice, the others once.
*/
private Map<String, Integer> nodeReferencesTotal = new HashMap<String, Integer>();
/**
* Keeps track of the number of references to a node/token that
* have
* already been processed.
*/
private Map<String, Integer> nodeReferencesProcessed = new HashMap<String, Integer>();
/**
* Keeps track of queued relations. Relations sometimes cannot be
* processed
* directly, namely in case it does not share any operands with
* the
* previous relation. Then wait until a relation with a shared
* operand has
* been processed.
*/
private LinkedList<ParseTree> queuedRelations = new LinkedList<ParseTree>();
/**
* For some objects, it may be decided in the initial scan
* ({@link #processAndTopExpr(ParseTree)} that they need to be
* wrapped in a
* class operation when retrieved later. This map stores this
* information.
* More precisely, it stores for every node in the tree which
* class ID its
* derived KoralQuery object will receive.
*/
private Map<ParseTree, Integer> objectsToWrapInClass = new HashMap<ParseTree, Integer>();
public AnnisQueryProcessor (String query) { | KoralObjectGenerator.setQueryProcessor(this); | 7 |
heroku/heroku.jar | heroku-api/src/main/java/com/heroku/api/request/team/TeamAppCreate.java | [
"public class App implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n String id;\n String name;\n Domain domain_name;\n String created_at;\n App.Owner owner;\n String web_url;\n App.Stack stack;\n String requested_stack;\n String git_url;\n String buil... | import com.heroku.api.App;
import com.heroku.api.Heroku;
import com.heroku.api.TeamApp;
import com.heroku.api.exception.RequestFailedException;
import com.heroku.api.http.Http;
import com.heroku.api.request.Request;
import com.heroku.api.request.RequestConfig;
import java.util.Collections;
import java.util.Map;
import static com.heroku.api.parser.Json.parse; | package com.heroku.api.request.team;
/**
* TODO: Javadoc
*
* @author Naaman Newbold
*/
public class TeamAppCreate implements Request<TeamApp> {
private final RequestConfig config;
public TeamAppCreate(TeamApp app) {
RequestConfig builder = new RequestConfig();
builder = builder.with(Heroku.RequestKey.Team, app.getTeam().getName());
builder = (app.getName() != null) ? builder.with(Heroku.RequestKey.AppName, app.getName()) : builder;
builder = (app.getStack() != null) ? builder.with(Heroku.RequestKey.Stack, app.getStack().getName()) : builder;
config = builder;
}
@Override
public Http.Method getHttpMethod() {
return Http.Method.POST;
}
@Override
public String getEndpoint() {
return Heroku.Resource.TeamAppsAll.value;
}
@Override
public boolean hasBody() {
return true;
}
@Override
public String getBody() {
return config.asJson();
}
@Override
public Map<String,Object> getBodyAsMap() {
return config.asMap();
}
@Override
public Http.Accept getResponseType() {
return Http.Accept.JSON;
}
@Override
public Map<String, String> getHeaders() {
return Collections.emptyMap();
}
@Override
public TeamApp getResponse(byte[] in, int code, Map<String,String> responseHeaders) {
if (code == Http.Status.CREATED.statusCode)
return parse(in, getClass());
else if (code == Http.Status.ACCEPTED.statusCode)
return parse(in, getClass());
else | throw new RequestFailedException("Failed to create team app", code, in); | 3 |
aw20/MongoWorkBench | src/org/aw20/mongoworkbench/eclipse/view/MSystemJavaScript.java | [
"public class EventWorkBenchManager extends Object {\n\tprivate static EventWorkBenchManager thisInst;\n\t\n\tpublic static synchronized EventWorkBenchManager getInst(){\n\t\tif ( thisInst == null )\n\t\t\tthisInst = new EventWorkBenchManager();\n\n\t\treturn thisInst;\n\t}\n\n\tprivate Set<EventWorkBenchListener>\... | import java.io.IOException;
import org.aw20.mongoworkbench.EventWorkBenchManager;
import org.aw20.mongoworkbench.MongoCommandListener;
import org.aw20.mongoworkbench.MongoFactory;
import org.aw20.mongoworkbench.command.MongoCommand;
import org.aw20.mongoworkbench.command.SystemJavaScriptReadCommand;
import org.aw20.mongoworkbench.command.SystemJavaScriptValidateCommand;
import org.aw20.mongoworkbench.command.SystemJavaScriptWriteCommand;
import org.aw20.util.MSwtUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text; | /*
* MongoWorkBench is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* Free Software Foundation,version 3.
*
* MongoWorkBench is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* If not, see http://www.gnu.org/licenses/
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with any of the JARS listed in the README.txt (or a modified version of
* (that library), containing parts covered by the terms of that JAR, the
* licensors of this Program grant you additional permission to convey the
* resulting work.
*
* https://github.com/aw20/MongoWorkBench
*
* April 2013
*/
package org.aw20.mongoworkbench.eclipse.view;
public class MSystemJavaScript extends MAbstractView implements MongoCommandListener {
private Text textBox;
private String HELPURL = "http://docs.mongodb.org/manual/tutorial/store-javascript-function-on-server/";
private Button btnValidate, btnSave;
private SystemJavaScriptReadCommand readCommand;
public MSystemJavaScript() {
MongoFactory.getInst().registerListener(this);
}
public void dispose() {
MongoFactory.getInst().deregisterListener(this);
super.dispose();
}
public void init2() {
parent.setLayout(new GridLayout(3, false));
textBox = MSwtUtil.createText(parent);
GridData gd_text = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
gd_text.widthHint = 438;
textBox.setLayoutData(gd_text);
Label urlLabel = new Label(parent, SWT.NONE);
urlLabel.setText("url");
urlLabel.setText(HELPURL);
urlLabel.setToolTipText("click here to visit the MongoDB documentation");
urlLabel.setCursor( new Cursor( parent.getDisplay(), SWT.CURSOR_HAND ) );
urlLabel.addMouseListener(new MouseListener() {
@Override
public void mouseDoubleClick(MouseEvent e) {}
@Override
public void mouseDown(MouseEvent e) {}
@Override
public void mouseUp(MouseEvent e) {
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(HELPURL));
} catch (IOException e1) {}
}
});
btnValidate = new Button(parent, SWT.NONE);
btnValidate.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1));
btnValidate.setText("validate");
btnValidate.setEnabled(false);
btnValidate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onValidate();
}
});
btnSave = new Button(parent, SWT.NONE);
btnSave.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
btnSave.setText("save");
btnSave.setEnabled(false);
btnSave.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onSave();
}
});
}
private void onValidate() {
try { | MongoCommand mcmd = new SystemJavaScriptValidateCommand(readCommand.getJSName(), textBox.getText()); | 3 |
pangliang/MirServer-Netty | LoginServer/src/main/java/com/zhaoxiaodan/mirserver/loginserver/LoginServer.java | [
"public class DB {\n\n\tprivate static SessionFactory ourSessionFactory;\n\tprivate static ServiceRegistry serviceRegistry;\n\n\tpublic static void init() throws Exception {\n\t\tConfiguration configuration = new Configuration();\n\t\tconfiguration.configure();\n\n\t\tserviceRegistry = new StandardServiceRegistryB... | import com.zhaoxiaodan.mirserver.db.DB;
import com.zhaoxiaodan.mirserver.loginserver.handlers.LoginHandler;
import com.zhaoxiaodan.mirserver.network.PacketDispatcher;
import com.zhaoxiaodan.mirserver.network.debug.ExceptionHandler;
import com.zhaoxiaodan.mirserver.network.decoder.ClientPacketBit6Decoder;
import com.zhaoxiaodan.mirserver.network.decoder.ClientPacketDecoder;
import com.zhaoxiaodan.mirserver.network.encoder.ServerPacketBit6Encoder;
import com.zhaoxiaodan.mirserver.network.encoder.ServerPacketEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler; | package com.zhaoxiaodan.mirserver.loginserver;
public class LoginServer {
public static final int REQUEST_MAX_FRAME_LENGTH = 1024; // 封包每一帧的最大大小
public static final int DEFAULT_LOGIN_GATE_PORT = 7000; // 登录网关默认端口号
private int port;
public LoginServer(int port) {
this.port = port == 0? DEFAULT_LOGIN_GATE_PORT : port;
}
public void run() throws Exception {
// db init
DB.init();
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(10);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(
//解码
// new MyLoggingHandler(MyLoggingHandler.Type.Read),
new DelimiterBasedFrameDecoder(REQUEST_MAX_FRAME_LENGTH, false, Unpooled.wrappedBuffer(new byte[]{'!'})), | new ClientPacketBit6Decoder(), | 4 |
IceReaper/DesktopAdventuresToolkit | src/net/eiveo/Unpacker.java | [
"public class SNDS {\r\n\tpublic List<Sound> sounds = new ArrayList<>();\r\n\t\r\n\tpublic static SNDS read(SmartByteBuffer data, boolean isYoda, File root) throws Exception {\r\n\t\tSNDS instance = new SNDS();\r\n\t\t\r\n\t\tint length = data.getInt();\r\n\t\tint lengthStart = data.position();\r\n\r\n\t\tshort num... | import java.awt.Color;
import java.io.File;
import net.eiveo.original.sections.SNDS;
import net.eiveo.original.sections.TILE;
import net.eiveo.original.sections.todo.not_converted_yet.ZONE;
import net.eiveo.structured.Palette;
import net.eiveo.structured.Sound;
import net.eiveo.structured.Tile;
import net.eiveo.structured.Zone;
import net.eiveo.utils.Image;
| package net.eiveo;
public class Unpacker {
public static void unpack(File container, File executable) throws Exception {
// Step 1: Read
net.eiveo.original.Game originalGame = net.eiveo.original.Game.read(container, executable);
// Step 2: Convert
net.eiveo.structured.Game structuredGame = new net.eiveo.structured.Game();
// Palette
structuredGame.palette = new Palette();
for (int i = 10; i < 256 - 10; i++) {
structuredGame.palette.colors[i] = new Color(
originalGame.palette[i * 4 + 2] & 0xff,
originalGame.palette[i * 4 + 1] & 0xff,
originalGame.palette[i * 4 + 0] & 0xff,
255
).getRGB();
}
// Splash Image
structuredGame.splashImage = Image.indexedToImage(originalGame.container.STUP.image, structuredGame.palette, 9 * 32, 9 * 32, false);
// Sounds
for (SNDS.Sound oldSound : originalGame.container.SNDS.sounds) {
if (oldSound.data != null) {
Sound sound = new Sound();
sound.name = oldSound.name.toLowerCase();
sound.data = oldSound.data;
structuredGame.sounds.put(sound.name, sound);
}
}
// Tiles and items.
for (short tileId = 0; tileId < originalGame.container.TILE.tiles.size(); tileId++) {
TILE.Tile originalTile = originalGame.container.TILE.tiles.get(tileId);
Tile tile = new Tile();
tile.id = "" + tileId;
if (originalGame.container.TNAM.names.containsKey(tileId)) {
tile.name = originalGame.container.TNAM.names.get(tileId);
}
tile.type = Mapping.getType("tile.type", originalTile.type >> 1);
// TODO split non-tile related stuff like weapon, item, npc.
tile.subtype = Mapping.getType("tile.subtype-" + tile.type, originalTile.subtype);
tile.image = Image.indexedToImage(originalTile.image, structuredGame.palette, 32, 32, (originalTile.type & 0b1) == 1);
structuredGame.tiles.put(tile.id, tile);
}
// TODO how is linked which item is which weapon? Possibly using the tileId...
// Characters and Weapons.
/*for (short characterId : originalGame.container.CHAR.ICHA.keySet()) {
// TODO frames.
ICHA icha = originalGame.container.CHAR.ICHA.get(characterId);
short weaponOrSoundId = originalGame.container.CHWP.weaponOrSoundId.get(characterId);
short healthOrUnk = originalGame.container.CHWP.healthOrUnk.get(characterId);
short damage = originalGame.container.CAUX.damage.get(characterId);
if (icha.type.equals("weapon")) {
String sound = originalGame.container.SNDS.sounds.get(weaponOrSoundId);
sound = new File(sound.substring(0, sound.lastIndexOf("."))).getName().toLowerCase();
Weapon weapon = new Weapon();
weapon.id = "" + characterId;
weapon.name = icha.name;
weapon.sound = sound;
weapon.damage = damage < 1 ? null : damage;
weapon.type = icha.subtype;
// TODO healthOrUnk?
// TODO where is ammo?
structuredGame.weapons.add(weapon);
} else {
Character character = new Character();
character.id = "" + characterId;
character.name = icha.name;
character.type = icha.subtype;
if (icha.type.equals("npc")) {
character.damage = damage < 1 ? null : damage;
character.health = healthOrUnk < 1 ? null : healthOrUnk;
if (weaponOrSoundId != -1) {
character.weapon = originalGame.container.CHAR.ICHA.get(weaponOrSoundId).name;
}
}
structuredGame.characters.add(character);
}
}
// Puzzles
for (short puzzleId : originalGame.container.PUZ2.IPUZ.keySet()) {
IPUZ ipuz = originalGame.container.PUZ2.IPUZ.get(puzzleId);
String name = originalGame.isYoda ? "" : originalGame.container.PNAM.names.get(puzzleId);
// TODO write puzzle
//System.out.println(puzzleId + "\t" + ipuz.type + " : " + ipuz.unk1 + "\t" + ipuz.texts[0] + "\n\t\t" + ipuz.texts[1] + "\n\t\t" + ipuz.texts[2] + "\n\t\t" + ipuz.texts[3]);
}*/
// TODO here goes the other stuff, as zone has to go last!
for (short zoneId = 0; zoneId < originalGame.container.ZONE.zones.size(); zoneId++) {
| ZONE.Zone originalZone = originalGame.container.ZONE.zones.get(zoneId);
| 6 |
onepf/OPFPush | samples/pushchat/src/main/java/org/onepf/pushchat/PushChatApplication.java | [
"public final class OPFPush {\n\n private static volatile OPFPushHelper helper;\n\n private OPFPush() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Returns the {@link org.onepf.opfpush.OPFPushHelper} instance.\n *\n * @return The {@link org.onepf.opfpush.OPFPushHelper... | import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import org.onepf.opfpush.OPFPush;
import org.onepf.opfpush.adm.ADMProvider;
import org.onepf.opfpush.configuration.Configuration;
import org.onepf.opfpush.gcm.GCMProvider;
import org.onepf.opfpush.nokia.NokiaNotificationsProvider;
import org.onepf.opfutils.OPFLog;
import org.onepf.pushchat.listener.PushEventListener;
import org.onepf.pushchat.utils.UuidGenerator; | /*
* Copyright 2012-2015 One Platform Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onepf.pushchat;
/**
* @author Roman Savin
* @since 29.04.2015
*/
public class PushChatApplication extends Application {
private static final String GCM_SENDER_ID = "707033278505";
private static final String NOKIA_SENDER_ID = "pushsample";
private String uuid;
private RefWatcher refWatcher;
@Override
public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
OPFLog.setEnabled(BuildConfig.DEBUG, true);
OPFLog.logMethod();
uuid = UuidGenerator.generateUuid(this);
OPFLog.i("Generated uuid : %s", uuid);
final Configuration.Builder configBuilder = new Configuration.Builder()
.addProviders(
new GCMProvider(this, GCM_SENDER_ID),
new ADMProvider(this),
new NokiaNotificationsProvider(this, NOKIA_SENDER_ID)
)
.setSelectSystemPreferred(true)
.setEventListener(new PushEventListener());
| OPFPush.init(this, configBuilder.build()); | 0 |
matthewcmead/sleet | src/main/java/sleet/generators/time/TimeDependentSequenceIdGenerator.java | [
"public class SleetException extends Exception {\n\n /**\n * generated by eclipse\n */\n private static final long serialVersionUID = -404982431470350032L;\n\n public SleetException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public SleetException(String message) {\n super(mes... | import java.util.List;
import java.util.Properties;
import sleet.SleetException;
import sleet.generators.GeneratorConfigException;
import sleet.generators.GeneratorSessionException;
import sleet.generators.IdGenerator;
import sleet.id.LongId;
import sleet.id.LongIdType;
import sleet.id.TimeIdType;
import sleet.state.IdState; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sleet.generators.time;
public class TimeDependentSequenceIdGenerator implements IdGenerator<LongIdType> {
public static final String BITS_IN_SEQUENCE_KEY = "sequence.bits.in.sequence.value";
private int bits = -1;
private long maxSequenceValue = -1;
private long lastTimeValue = -1;
private long sequenceValue = 0;
@Override
public void beginIdSession(Properties config) throws SleetException {
if (this.maxSequenceValue != -1) { | throw new GeneratorSessionException("Session was already started. Stop session by calling endIdSession() then start session by calling beginIdSession()"); | 2 |
senseobservationsystems/sense-android-library | sense-android-library/src/nl/sense_os/service/ambience/LoudnessSensor.java | [
"public class SensePrefs {\r\n /**\r\n * Keys for the authentication-related preferences of the Sense Platform\r\n */\r\n public static class Auth {\r\n /**\r\n * Key for login preference for session cookie.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n ... | import java.util.ArrayList;
import java.util.Iterator;
import nl.sense_os.service.R;
import nl.sense_os.service.constants.SenseDataTypes;
import nl.sense_os.service.constants.SensePrefs;
import nl.sense_os.service.constants.SensePrefs.SensorSpecifics;
import nl.sense_os.service.constants.SensorData.DataPoint;
import nl.sense_os.service.constants.SensorData.SensorNames;
import nl.sense_os.service.provider.SNTP;
import nl.sense_os.service.shared.SensorDataPoint;
import nl.sense_os.service.subscription.BaseDataProducer;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log; | package nl.sense_os.service.ambience;
/**
* Helper class for {@link NoiseSensor}. Scales the measured sound level measurement according to
* the highest and lowest sound levels that have been recorded.
*
* @author Pim Nijdam <pim@sense-os.nl>
*/
public class LoudnessSensor extends BaseDataProducer {
private class TimestampValueTuple {
long timestamp;
double value;
TimestampValueTuple(long timestamp, double value) {
this.timestamp = timestamp;
this.value = value;
}
};
//private static final String TAG = "Loudness sensor";
private static final float DEFAULT_TOTAL_SILENCE = Float.MAX_VALUE;
private static final float DEFAULT_LOUDEST = Float.MIN_VALUE;
private final long AVERAGING_PERIOD;
private static final long DEFAULT_AVERAGING_PERIOD = 10 * 60 * 1000;
private static final double MIN_LOUDNESS_DYNAMIC = 10;
private Context context;
private ArrayList<TimestampValueTuple> window = new ArrayList<LoudnessSensor.TimestampValueTuple>();
private double totalSilence;
private double loudest;
private boolean filled = false;
protected LoudnessSensor(Context context) {
this.context = context;
AVERAGING_PERIOD = DEFAULT_AVERAGING_PERIOD;
//restore silence
SharedPreferences sensorSpecifics = context.getSharedPreferences(SensePrefs.SENSOR_SPECIFICS,
Context.MODE_PRIVATE);
totalSilence = sensorSpecifics.getFloat(SensorSpecifics.Loudness.TOTAL_SILENCE, DEFAULT_TOTAL_SILENCE);
loudest = sensorSpecifics.getFloat(SensorSpecifics.Loudness.LOUDEST, DEFAULT_LOUDEST);
Log.v("Sense Loudness","Loudest " + loudest + ", total silence " + totalSilence);
}
private static LoudnessSensor instance = null;
public static LoudnessSensor getInstance(Context context) {
if(instance == null) {
instance = new LoudnessSensor(context);
}
return instance;
}
public void onNewNoise(long ms, double dB) {
addNoiseInDb(ms, dB);
// double value = relativeLoudnessOf(dB);
// Log.v(TAG, "new noise value " + dB + ", loudness: " + value);
if (filled) {
double l = loudness();
if (loudest - totalSilence > MIN_LOUDNESS_DYNAMIC)
sendSensorValue(l, ms);
}
}
private void addNoiseInDb(long timestamp, double dB) {
// TODO: should we calculate something like phon or sone to better fit
// perceived volume by humans?
if (dB == 0)
return; //discard 0
window.add(new TimestampValueTuple(timestamp, dB));
if (timestamp - window.get(0).timestamp > AVERAGING_PERIOD)
filled = true;
}
private double loudness() {
long startTime = SNTP.getInstance().getTime() - AVERAGING_PERIOD;
// remove old values and average over past period
// average over past period
double meanSum = 0;
int values = 0;
Iterator<TimestampValueTuple> iter = window.iterator();
while (iter.hasNext()) {
TimestampValueTuple tuple = iter.next();
if (tuple.timestamp < startTime)
iter.remove();
else {
meanSum += Math.pow(10, tuple.value / 20);
values += 1;
}
}
double mean = 20 * Math.log(meanSum / values) / Math.log(10);
if (mean < totalSilence)
setLowestEver(mean);
if (mean > loudest)
setHighestEver(mean);
// make relative
if (loudest - totalSilence > 0)
return (mean - totalSilence) / (loudest - totalSilence) * 10;
else
return 5;
}
private void setLowestEver(double lowest) {
totalSilence = lowest;
Editor sensorSpecifics = context.getSharedPreferences(SensePrefs.SENSOR_SPECIFICS,
Context.MODE_PRIVATE).edit();
sensorSpecifics.putFloat(SensorSpecifics.Loudness.TOTAL_SILENCE, (float)totalSilence);
sensorSpecifics.commit();
}
private void setHighestEver(double highest) {
loudest = highest;
Editor sensorSpecifics = context.getSharedPreferences(SensePrefs.SENSOR_SPECIFICS,
Context.MODE_PRIVATE).edit();
sensorSpecifics.putFloat(SensorSpecifics.Loudness.LOUDEST, (float)loudest);
sensorSpecifics.commit();
}
private void sendSensorValue(double value, long ms) {
this.notifySubscribers();
SensorDataPoint dataPoint = new SensorDataPoint(value); | dataPoint.sensorName = SensorNames.LOUDNESS; | 3 |
tonikolaba/MrTower | src/al/artofsoul/ndihma/StateManger.java | [
"public static PllakaFusha LoadMap(String mapName) {\n\tPllakaFusha grid = new PllakaFusha();\n\ttry {\n\t\tBufferedReader br = new BufferedReader(new FileReader(mapName));\n\t\tString data = br.readLine();\n\t\tfor (int i = 0; i < grid.getPllakaWide(); i++) {\n\t\t\tfor (int j = 0; j < grid.getPllakaHigh(); j++) {... | import static al.artofsoul.ndihma.Leveler.LoadMap;
import al.artofsoul.data.Editor;
import al.artofsoul.data.Game;
import al.artofsoul.data.MainMenu;
import al.artofsoul.data.PllakaFusha; | package al.artofsoul.ndihma;
public class StateManger {
public static enum GameState {
MAINMENU, GAME, EDITOR
}
public static GameState gameState = GameState.MAINMENU;
public static MainMenu mainMenu;
public static Game game; | public static Editor editor; | 1 |
kihira/Tails | src/main/java/uk/kihira/gltf/GltfLoader.java | [
"public class Animation {\n private final ArrayList<Channel> channels;\n\n private FloatBuffer interpolatedValues; // todo per channel instead?\n private float currentAnimTime;\n\n public Animation(ArrayList<Channel> channels) {\n this.channels = channels;\n interpolatedValues = BufferUtil... | import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.renderer.texture.NativeImage;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.io.FilenameUtils;
import org.lwjgl.BufferUtils;
import uk.kihira.gltf.animation.Animation;
import uk.kihira.gltf.animation.AnimationPath;
import uk.kihira.gltf.animation.Channel;
import uk.kihira.gltf.animation.Sampler;
import uk.kihira.gltf.spec.Accessor;
import uk.kihira.gltf.spec.BufferView;
import uk.kihira.gltf.spec.MeshPrimitive;
import uk.kihira.tails.common.ByteBufferInputStream;
import uk.kihira.tails.common.Tails;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap; | package uk.kihira.gltf;
public class GltfLoader {
private static final Gson gson = new Gson();
private static final int JSON_CHUNK = 0x4E4F534A;
private static final int BIN_CHUNK = 0x004E4942;
// Temp cache values | private static final ArrayList<Accessor> accessors = new ArrayList<>(); | 4 |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/expressions/BitvectorExpression.java | [
"public abstract class Expression<E> extends AbstractPrintable {\n \n \n public static final int QUOTE_IDENTIFIERS = 1;\n public static final int INCLUDE_VARIABLE_TYPE = 2;\n public static final int INCLUDE_BOUND_DECL_TYPE = 4;\n public static final int SIMPLE_PROP_OPERATORS = 8;\n \n public static final in... | import gov.nasa.jpf.constraints.api.Expression;
import gov.nasa.jpf.constraints.api.ExpressionVisitor;
import gov.nasa.jpf.constraints.api.Valuation;
import gov.nasa.jpf.constraints.api.Variable;
import gov.nasa.jpf.constraints.types.BVIntegerType;
import gov.nasa.jpf.constraints.types.Type;
import gov.nasa.jpf.constraints.types.TypeContext;
import java.io.IOException;
import java.util.Collection; | /*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may obtain a
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package gov.nasa.jpf.constraints.expressions;
public class BitvectorExpression<E>
extends AbstractExpression<E> {
public static Expression<?> createCompatible(Expression<?> left,
BitvectorOperator op, Expression<?> right, TypeContext types) {
Type<?> lt = left.getType(), rt = right.getType();
Type<?> superType = types.mostSpecificSupertype(left.getType(), right.getType());
if(!(superType instanceof BVIntegerType))
throw new IllegalArgumentException();
Expression<?> l = (superType.equals(lt)) ? left : CastExpression.create(left, superType);
Expression<?> r = (superType.equals(rt)) ? right : CastExpression.create(right, superType);
return create(l, op, r);
}
public static <E> BitvectorExpression<E> create(Expression<E> left, BitvectorOperator op, Expression<?> right) {
BVIntegerType<E> type = (BVIntegerType<E>)left.getType();
Expression<E> r = right.requireAs(type);
return new BitvectorExpression<E>(left, op, r);
}
private final BitvectorOperator op;
private final Expression<E> left;
private final Expression<E> right;
public BitvectorExpression(Expression<E> left, BitvectorOperator op, Expression<E> right) {
this.op = op;
this.left = left;
this.right = right;
}
@Override
public E evaluate(Valuation values) {
E lv = left.evaluate(values);
E rv = right.evaluate(values);
BVIntegerType<E> type = (BVIntegerType<E>)getType();
switch(op) {
case AND:
return type.and(lv, rv);
case OR:
return type.or(lv, rv);
case XOR:
return type.xor(lv, rv);
case SHIFTL:
return type.shiftLeft(lv, rv);
case SHIFTR:
return type.shiftRight(lv, rv);
case SHIFTUR:
return type.shiftRightUnsigned(lv, rv);
default:
throw new IllegalStateException("Unknown bitvector operator " + op);
}
}
@Override
public void collectFreeVariables(Collection<? super Variable<?>> variables) {
left.collectFreeVariables(variables);
right.collectFreeVariables(variables);
}
@Override | public <R, D> R accept(ExpressionVisitor<R, D> visitor, D data) { | 1 |
Daskiworks/ghwatch | app/src/main/java/com/daskiworks/ghwatch/backend/WatchedRepositoriesService.java | [
"public class Utils {\n\n public static final long MILLIS_SECOND = 1000L;\n public static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;\n public static final long MILLIS_HOUR = 60 * MILLIS_MINUTE;\n public static final long MILLIS_DAY = 24 * MILLIS_HOUR;\n\n /**\n * Get Vibrator if available in system.\n ... | import com.daskiworks.ghwatch.model.BaseViewData;
import com.daskiworks.ghwatch.model.LoadingStatus;
import com.daskiworks.ghwatch.model.Repository;
import com.daskiworks.ghwatch.model.WatchedRepositories;
import com.daskiworks.ghwatch.model.WatchedRepositoriesViewData;
import cz.msebera.android.httpclient.auth.AuthenticationException;
import java.io.File;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.net.NoRouteToHostException;
import java.net.URISyntaxException;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.util.Log;
import com.daskiworks.ghwatch.Utils;
import com.daskiworks.ghwatch.auth.AuthenticationManager;
import com.daskiworks.ghwatch.backend.RemoteSystemClient.Response; | /*
* Copyright 2014 contributors as indicated by the @authors tag.
*
* 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.daskiworks.ghwatch.backend;
/**
* Service used to work with watched repositories.
*
* @author Vlastimil Elias <vlastimil.elias@worldonline.cz>
*/
public class WatchedRepositoriesService {
private static final String TAG = "WatchedRepositoriesServ";
/**
* URL to load notifications from.
*/
private static final String URL_NOTIFICATIONS = GHConstants.URL_BASE + "/user/subscriptions";
/**
* Name of file where data are persisted.
*/
private static final String fileName = "WatchedRepositories.td";
/**
* Reload from server is forced automatically if data in persistent store are older than this timeout [millis]
*/
private static final long FORCE_VIEW_RELOAD_AFTER = 12 * Utils.MILLIS_HOUR;
private Context context;
private File persistFile;
private AuthenticationManager authenticationManager;
/**
* Create service.
*
* @param context this service runs in
*/
public WatchedRepositoriesService(Context context) {
this.context = context;
persistFile = context.getFileStreamPath(fileName);
this.authenticationManager = AuthenticationManager.getInstance();
}
/**
* Get watched repositories for view.
*
* @param reloadStrategy if data should be reloaded from server
* @return view data
*/
public WatchedRepositoriesViewData getWatchedRepositoriesForView(ViewDataReloadStrategy reloadStrategy) {
WatchedRepositoriesViewData nswd = new WatchedRepositoriesViewData();
WatchedRepositories ns = null;
synchronized (TAG) {
WatchedRepositories oldNs = Utils.readFromStore(TAG, context, persistFile);
// user from store if possible, apply timeout of data from store
if (reloadStrategy == ViewDataReloadStrategy.IF_TIMED_OUT) {
ns = oldNs;
if (ns != null && ns.getLastFullUpdateTimestamp() < (System.currentTimeMillis() - FORCE_VIEW_RELOAD_AFTER))
ns = null;
} else if (reloadStrategy == ViewDataReloadStrategy.NEVER) {
ns = oldNs;
}
// read from server
try {
if (ns == null && reloadStrategy != ViewDataReloadStrategy.NEVER) {
ns = readFromServer(URL_NOTIFICATIONS);
if (ns != null) {
Utils.writeToStore(TAG, context, persistFile, ns);
}
}
} catch (InvalidObjectException e) {
nswd.loadingStatus = LoadingStatus.DATA_ERROR;
Log.w(TAG, "Watched Repositories loading failed due to data format problem: " + e.getMessage(), e);
} catch (NoRouteToHostException e) {
nswd.loadingStatus = LoadingStatus.CONN_UNAVAILABLE;
Log.d(TAG, "Watched Repositories loading failed due to connection not available.");
} catch (AuthenticationException e) {
nswd.loadingStatus = LoadingStatus.AUTH_ERROR;
Log.d(TAG, "Watched Repositories loading failed due to authentication problem: " + e.getMessage());
} catch (IOException e) {
nswd.loadingStatus = LoadingStatus.CONN_ERROR;
Log.w(TAG, "Watched Repositories loading failed due to connection problem: " + e.getMessage());
} catch (JSONException e) {
nswd.loadingStatus = LoadingStatus.DATA_ERROR;
Log.w(TAG, "Watched Repositories loading failed due to data format problem: " + e.getMessage());
} catch (Exception e) {
nswd.loadingStatus = LoadingStatus.UNKNOWN_ERROR;
Log.e(TAG, "Watched Repositories loading failed due to: " + e.getMessage(), e);
}
// Show content from store because we are unable to read new one but want to show something
if (ns == null)
ns = oldNs;
nswd.repositories = ns;
return nswd;
}
}
/**
* @param id of repository to unwatch
* @return view data with result of call
*/ | public BaseViewData unwatchRepository(long id) { | 3 |
kbase/kb_sdk | src/java/us/kbase/mobu/initializer/test/DockerClientServerTester.java | [
"public class ModuleInitializer {\n\tpublic static final String DEFAULT_LANGUAGE = \"python\";\n\n\tprivate String moduleName;\n\tprivate String userName;\n\tprivate String language;\n\tprivate boolean verbose;\n\tprivate File dir;\n\t\n\tprivate static String[] subdirs = {\"data\",\n\t\t\t\t\t\t\t\t\t\t\"scripts\"... | import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import us.kbase.auth.AuthToken;
import us.kbase.common.service.ServerException;
import us.kbase.common.service.UObject;
import us.kbase.mobu.initializer.ModuleInitializer;
import us.kbase.mobu.installer.ClientInstaller;
import us.kbase.mobu.tester.ModuleTester;
import us.kbase.mobu.util.ProcessHelper;
import us.kbase.mobu.util.TextUtils;
import us.kbase.scripts.test.TestConfigHelper;
import us.kbase.scripts.test.TypeGeneratorTest; | "#BEGIN_HEADER\n" +
"#END_HEADER\n" +
"\n" +
" #BEGIN_CONSTRUCTOR\n" +
" #END_CONSTRUCTOR\n" +
"\n" +
" #BEGIN run_test\n" +
" $return = $input;\n" +
" #END run_test\n" +
"\n" +
" #BEGIN throw_error\n" +
" die $input;\n" +
" #END throw_error\n";
File implFile = new File(moduleDir, "lib/" + moduleName + "/" +
moduleName + "Impl.pm");
init("perl", moduleName, implFile, implInit);
return moduleDir;
}
protected File initJava(String moduleName) throws Exception {
File moduleDir = new File(moduleName);
String implInit = "" +
"//BEGIN_HEADER\n" +
"//END_HEADER\n" +
"\n" +
" //BEGIN_CLASS_HEADER\n" +
" //END_CLASS_HEADER\n" +
"\n" +
" //BEGIN_CONSTRUCTOR\n" +
" //END_CONSTRUCTOR\n" +
"\n" +
" //BEGIN run_test\n" +
" returnVal = input;\n" +
" //END run_test\n" +
"\n" +
" //BEGIN throw_error\n" +
" throw new Exception(input);\n" +
" //END throw_error\n";
File implFile = new File(moduleDir, "lib/src/" + moduleName.toLowerCase() + "/" +
moduleName + "Server.java");
init("java", moduleName, implFile, implInit);
return moduleDir;
}
protected File initPython(String moduleName) throws Exception {
File moduleDir = new File(moduleName);
String implInit = "" +
"#BEGIN_HEADER\n" +
"#END_HEADER\n" +
"\n" +
" #BEGIN_CLASS_HEADER\n" +
" #END_CLASS_HEADER\n" +
"\n" +
" #BEGIN_CONSTRUCTOR\n" +
" #END_CONSTRUCTOR\n" +
"\n" +
" #BEGIN run_test\n" +
" returnVal = input\n" +
" #END run_test\n" +
"\n" +
" #BEGIN throw_error\n" +
" raise ValueError(input)\n" +
" #END throw_error\n";
File implFile = new File(moduleDir, "lib/" + moduleName + "/" +
moduleName + "Impl.py");
init("python", moduleName, implFile, implInit);
return moduleDir;
}
public static void correctDockerfile(File moduleDir) throws Exception {
File buildXmlFile = new File("build.xml");
File sdkSubFolder = new File(moduleDir, "kb_sdk");
File sdkDistSubFolder = new File(sdkSubFolder, "dist");
FileUtils.copyFile(buildXmlFile, new File(sdkSubFolder, buildXmlFile.getName()));
File sdkJarFile = new File("dist/kbase_module_builder2.jar");
FileUtils.copyFile(sdkJarFile, new File(sdkDistSubFolder, sdkJarFile.getName()));
File jarDepsFile = new File("JAR_DEPS");
FileUtils.copyFile(jarDepsFile, new File(sdkSubFolder, jarDepsFile.getName()));
File makeFile = new File("Makefile");
FileUtils.copyFile(makeFile, new File(sdkSubFolder, makeFile.getName()));
File dockerFile = new File(moduleDir, "Dockerfile");
String dockerText = FileUtils.readFileToString(dockerFile);
dockerText = dockerText.replace("COPY ./ /kb/module", "" +
"COPY ./ /kb/module\n" +
"RUN . /kb/dev_container/user-env.sh && \\\n" +
" cd /kb/dev_container/modules/jars && \\\n" +
" git pull && make && make deploy && \\\n" +
" rm /kb/dev_container/bin/kb-sdk && \\\n" +
" rm /kb/deployment/bin/kb-sdk && \\\n" +
" cd /kb/dev_container/modules/kb_sdk && \\\n" +
" cp -r /kb/module/kb_sdk/* ./ && \\\n" +
" make deploy && echo \"" + new Date(startingTime) + "\"");
FileUtils.writeStringToFile(dockerFile, dockerText);
}
protected static String prepareDockerImage(File moduleDir,
AuthToken token) throws Exception {
String moduleName = moduleDir.getName();
correctDockerfile(moduleDir);
File testCfgFile = new File(moduleDir, "test_local/test.cfg");
String testCfgText = ""+
"test_token=" + token.getToken() + "\n" +
"kbase_endpoint=" + TestConfigHelper.getKBaseEndpoint() + "\n" +
"auth_service_url=" + TestConfigHelper.getAuthServiceUrl() + "\n" +
"auth_service_url_allow_insecure=" +
TestConfigHelper.getAuthServiceUrlInsecure() + "\n";
FileUtils.writeStringToFile(testCfgFile, testCfgText);
File tlDir = new File(moduleDir, "test_local");
File workDir = new File(tlDir, "workdir");
workDir.mkdir();
File tokenFile = new File(workDir, "token");
FileWriter fw = new FileWriter(tokenFile);
try {
fw.write(token.getToken());
} finally {
fw.close();
}
File runDockerSh = new File(tlDir, "run_docker.sh");
ProcessHelper.cmd("chmod", "+x", runDockerSh.getCanonicalPath()).exec(tlDir);
String imageName = "test/" + moduleName.toLowerCase() + ":latest"; | if (!ModuleTester.buildNewDockerImageWithCleanup(moduleDir, tlDir, runDockerSh, | 2 |
mp911de/spinach | src/main/java/biz/paluch/spinach/cluster/QueueListenerFactory.java | [
"public class DisqueClient extends AbstractRedisClient {\n\n private final static DisqueURI EMPTY_DISQUE_URI = new DisqueURI();\n private final DisqueURI disqueURI;\n\n protected DisqueClient(ClientResources clientResources, DisqueURI disqueURI) {\n\n super(clientResources);\n\n assertNotNull... | import rx.Observable;
import rx.Scheduler;
import rx.schedulers.Schedulers;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import com.lambdaworks.redis.codec.RedisCodec;
import com.lambdaworks.redis.internal.LettuceAssert;
import biz.paluch.spinach.DisqueClient;
import biz.paluch.spinach.DisqueURI;
import biz.paluch.spinach.api.DisqueConnection;
import biz.paluch.spinach.api.Job;
import biz.paluch.spinach.cluster.QueueListener.LocalityAwareConnection;
import biz.paluch.spinach.impl.SocketAddressSupplier;
import biz.paluch.spinach.impl.SocketAddressSupplierFactory; | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package biz.paluch.spinach.cluster;
/**
* Cluster-aware Job listener. This listener emits {@link biz.paluch.spinach.api.Job jobs} by listening on one or multiple
* queues by using an observable subject. Instances are designed to be long-living objects. A {@link QueueListenerFactory} can
* keep track of the originating cluster node. If the majority of received jobs originate from a node to which the client is not
* connected to, the {@link QueueListenerFactory} tries to switch the server to minimize latency.
*
* @author Mark Paluch
*/
public class QueueListenerFactory<K, V> {
public static final int DEFAULT_TIMEOUT = 10;
public static final TimeUnit DEFAULT_TIMEOUT_UNIT = TimeUnit.MILLISECONDS;
public static final int DEFAULT_COUNT = 1;
private final Scheduler scheduler;
private final DisqueClient disqueClient;
private final boolean sharedClient;
private final DisqueURI disqueURI;
private final RedisCodec<K, V> codec;
private final List<QueueListener<K, V>> resources = new CopyOnWriteArrayList<>();
private final K[] queues;
/**
* @param scheduler the scheduler for blocking operations, must not be {@literal null}
* @param disqueURI the URI, must not be {@literal null}
* @param codec use this codec to encode/decode keys and values, must not be {@literal null}
* @param queues queue names to listen on, must not be {@literal null} and not empty
*/
protected QueueListenerFactory(Scheduler scheduler, DisqueURI disqueURI, RedisCodec<K, V> codec, K[] queues) {
this(null, scheduler, disqueURI, codec, queues);
}
/**
* @param disqueClient a shared client instance. Creates a new client instance if {@literal null}
* @param scheduler the scheduler for blocking operations, must not be {@literal null}
* @param disqueURI the URI, must not be {@literal null}
* @param codec use this codec to encode/decode keys and values, must not be {@literal null}
* @param queues queue names to listen on, must not be {@literal null} and not empty
*/
protected QueueListenerFactory(DisqueClient disqueClient, Scheduler scheduler, DisqueURI disqueURI, RedisCodec<K, V> codec,
K[] queues) {
LettuceAssert.notNull(scheduler, "Scheduler must not be null");
LettuceAssert.notNull(disqueURI, "DisqueURI must not be null");
LettuceAssert.notNull(codec, "RedisCodec must not be null");
LettuceAssert.isTrue(queues != null && queues.length > 0, "Queues must not be empty");
if (disqueClient != null) {
sharedClient = true;
this.disqueClient = disqueClient;
} else {
sharedClient = false;
this.disqueClient = DisqueClient.create();
}
this.disqueURI = disqueURI;
this.codec = codec;
this.queues = queues;
this.scheduler = scheduler;
}
/**
* Create a new {@link QueueListenerFactory}. The default {@link Schedulers#io()} scheduler is used for listener
* notification and I/O operations.
*
* @param disqueURI the DisqueURI
* @param codec use this codec to encode/decode keys and values, must note be {@literal null}
* @param queues the queue names
* @param <K> Key type
* @param <V> Value type
* @return a new instance of {@link QueueListenerFactory}
*/
public static <K, V> QueueListenerFactory<K, V> create(DisqueURI disqueURI, RedisCodec<K, V> codec, K... queues) {
return new QueueListenerFactory<K, V>(Schedulers.io(), disqueURI, codec, queues);
}
/**
* Create a new {@link QueueListenerFactory}. The provided {@code scheduler} is used for listener notification and I/O
* operations.
*
* @param scheduler a scheduler from rxjava for I/O operations
* @param disqueURI the DisqueURI
* @param codec use this codec to encode/decode keys and values, must note be {@literal null}
* @param queues the queue names
* @param <K> Key type
* @param <V> Value type
* @return a new instance of {@link QueueListenerFactory}
*/
public static <K, V> QueueListenerFactory<K, V> create(Scheduler scheduler, DisqueURI disqueURI, RedisCodec<K, V> codec,
K... queues) {
return new QueueListenerFactory<K, V>(scheduler, disqueURI, codec, queues);
}
/**
* Create a new {@link QueueListenerFactory}. The provided {@code scheduler} is used for listener notification and I/O
* operations.
*
* @param disqueClient a shared client instance for reuse
* @param scheduler a scheduler from rxjava for I/O operations, must not be {@literal null}
* @param disqueURI the DisqueURI
* @param codec use this codec to encode/decode keys and values, must note be {@literal null}
* @param queues the queue names
* @param <K> Key type
* @param <V> Value type
* @return a new instance of {@link QueueListenerFactory}
*/
public static <K, V> QueueListenerFactory<K, V> create(DisqueClient disqueClient, Scheduler scheduler, DisqueURI disqueURI,
RedisCodec<K, V> codec, K... queues) {
return new QueueListenerFactory<K, V>(disqueClient, scheduler, disqueURI, codec, queues);
}
/**
* Get jobs from the specified queues. By default COUNT is 1, so just one job will be returned. A default TIMEOUT of 10
* MILLISECONDS is used to enable graceful connection shutdown.
* <p>
* When there are jobs in more than one of the queues, the command guarantees to return jobs in the order the queues are
* specified. If COUNT allows more jobs to be returned, queues are scanned again and again in the same order popping more
* elements.
* </p>
* <p>
* The {@link Observable} emits {@link Job} objects as soon as a job is received from Disque. The terminal event is emitted
* as soon as the {@link rx.Subscriber subscriber} unsubscribes from the {@link Observable}.
* </p>
*
* @return an Observable that emits {@link Job} elements until the subscriber terminates the subscription
*/
public Observable<Job<K, V>> getjobs() {
return new GetJobsBuilder().getjobs();
}
/**
* Get jobs from the specified queues.
*
* <p>
* When there are jobs in more than one of the queues, the command guarantees to return jobs in the order the queues are
* specified. If COUNT allows more jobs to be returned, queues are scanned again and again in the same order popping more
* elements.
* </p>
* <p>
* The {@link Observable} emits {@link Job} objects as soon as a job is received from Disque. The terminal event is emitted
* as soon as the {@link rx.Subscriber subscriber} unsubscribes from the {@link Observable}.
* </p>
*
* @param timeout timeout to wait
* @param timeUnit timeout unit
* @param count count of jobs to return
* @return an Observable that emits {@link Job} elements until the subscriber terminates the subscription
*/
public Observable<Job<K, V>> getjobs(long timeout, TimeUnit timeUnit, long count) {
return new GetJobsBuilder().getjobs(timeout, timeUnit, count);
}
private QueueListener<K, V> newOnSubscribe(long timeout, TimeUnit timeUnit, long count) {
Supplier<LocalityAwareConnection<K, V>> connectionSupplier = createDisqueConnectionSupplier();
QueueListener<K, V> onSubscribe = new QueueListener<K, V>(scheduler, connectionSupplier,
GetJobsArgs.create(timeout, timeUnit, count, queues));
resources.add(onSubscribe);
return onSubscribe;
}
/**
* Create a new GetJobsBuilder with enabled locality tracking.
* <p>
* Locality tracking records statistics about the creating node of a job. If the majority of received jobs originate from a
* different node, the client should consider moving off the current node to the node which created the jobs. This makes a
* good use of locality.
* </p>
*
* @return the LocalityTrackingGetJobsBuilder.
*/
public LocalityTrackingGetJobsBuilder withLocalityTracking() {
return new LocalityTrackingGetJobsBuilder();
}
private Supplier<LocalityAwareConnection<K, V>> createDisqueConnectionSupplier() {
return new Supplier<LocalityAwareConnection<K, V>>() {
@Override
public LocalityAwareConnection<K, V> get() {
final NodeIdAwareSocketAddressSupplier socketAddressSupplier = createSocketAddressSupplier();
DisqueConnection<K, V> connection = disqueClient.connect(codec, disqueURI, new SocketAddressSupplierFactory() {
@Override | public SocketAddressSupplier newSupplier(DisqueURI disqueURI) { | 5 |
sandflow/regxmllib | src/main/java/com/sandflow/smpte/regxml/XMLSchemaBuilder.java | [
"@XmlAccessorType(XmlAccessType.NONE)\npublic class CharacterTypeDefinition extends Definition {\n\npublic CharacterTypeDefinition() { }\n\n @Override\n public void accept(DefinitionVisitor visitor) throws DefinitionVisitor.VisitorException {\n visitor.visit(this);\n }\n\n}",
"@XmlAccessorType(Xml... | import com.sandflow.smpte.klv.exceptions.KLVException;
import com.sandflow.smpte.regxml.dict.DefinitionResolver;
import com.sandflow.smpte.regxml.dict.MetaDictionary;
import com.sandflow.smpte.regxml.dict.definitions.CharacterTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.ClassDefinition;
import com.sandflow.smpte.regxml.dict.definitions.Definition;
import com.sandflow.smpte.regxml.dict.definitions.EnumerationTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.ExtendibleEnumerationTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.FixedArrayTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.FloatTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.IndirectTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.IntegerTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.LensSerialFloatTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.OpaqueTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.PropertyAliasDefinition;
import com.sandflow.smpte.regxml.dict.definitions.PropertyDefinition;
import com.sandflow.smpte.regxml.dict.definitions.RecordTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.RenameTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.SetTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.StreamTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.StringTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.StrongReferenceTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.VariableArrayTypeDefinition;
import com.sandflow.smpte.regxml.dict.definitions.WeakReferenceTypeDefinition;
import com.sandflow.smpte.util.AUID;
import com.sandflow.smpte.util.UL;
import com.sandflow.util.events.BasicEvent;
import com.sandflow.util.events.Event;
import com.sandflow.util.events.EventHandler;
import java.io.IOException;
import java.net.URI;
import java.security.InvalidParameterException;
import java.util.HashMap;
import java.util.Set;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException; | /*
* Copyright (c) 2014, Pierre-Anthony Lemieux (pal@sandflow.com)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.sandflow.smpte.regxml;
/**
* Generates XML Schemas from RegXML dictionaries according to the Model Mapping
* Rules specified in SMPTE ST 2001-1. These XML Schemas can be used to validate
* RegXML fragments, including those generated using
* {@link com.sandflow.smpte.regxml.FragmentBuilder}
*/
public class XMLSchemaBuilder {
private final static Logger LOG = Logger.getLogger(XMLSchemaBuilder.class.getName());
public static final String REGXML_NS = "http://sandflow.com/ns/SMPTEST2001-1/baseline";
private final static String XMLNS_NS = "http://www.w3.org/2000/xmlns/";
private static final String XSD_NS = "http://www.w3.org/2001/XMLSchema";
private static final String XLINK_NS = "http://www.w3.org/1999/xlink";
private static final String XLINK_LOC = "http://www.w3.org/1999/xlink.xsd";
private static final AUID AUID_AUID = new AUID(UL.fromDotValue("06.0E.2B.34.01.04.01.01.01.03.01.00.00.00.00.00"));
private static final AUID UUID_AUID = new AUID(UL.fromDotValue("06.0E.2B.34.01.04.01.01.01.03.03.00.00.00.00.00"));
private static final AUID DateStruct_AUID = new AUID(UL.fromDotValue("06.0E.2B.34.01.04.01.01.03.01.05.00.00.00.00.00"));
private static final AUID PackageID_AUID = new AUID(UL.fromDotValue("06.0E.2B.34.01.04.01.01.01.03.02.00.00.00.00.00"));
private static final AUID Rational_AUID = new AUID(UL.fromDotValue("06.0E.2B.34.01.04.01.01.03.01.01.00.00.00.00.00"));
private static final AUID TimeStruct_AUID = new AUID(UL.fromDotValue("06.0E.2B.34.01.04.01.01.03.01.06.00.00.00.00.00"));
private static final AUID TimeStamp_AUID = new AUID(UL.fromDotValue("06.0E.2B.34.01.04.01.01.03.01.07.00.00.00.00.00"));
private static final AUID VersionType_AUID = new AUID(UL.fromDotValue("06.0E.2B.34.01.04.01.01.03.01.03.00.00.00.00.00"));
private static final AUID ObjectClass_AUID = new AUID(UL.fromDotValue("06.0E.2B.34.01.01.01.02.06.01.01.04.01.01.00.00"));
private static final AUID ByteOrder_AUID = new AUID(UL.fromDotValue("06.0E.2B.34.01.01.01.01.03.01.02.01.02.00.00.00"));
private static final AUID InstanceID_AUID = new AUID(UL.fromURN("urn:smpte:ul:060e2b34.01010101.01011502.00000000"));
private DefinitionResolver resolver;
private final NamespacePrefixMapper prefixes = new NamespacePrefixMapper();
private final EventHandler evthandler;
/**
* Defines the events returned by this class
*/
public static enum EventCodes {
/**
* Raised when a type definition is not found.
*/
UNKNOWN_TYPE(Event.Severity.ERROR);
public final Event.Severity severity;
private EventCodes(Event.Severity severity) {
this.severity = severity;
}
}
/**
* All events raised by this class are instances of this class.
*/
public static class SchemaEvent extends BasicEvent {
final String reason;
final String where;
public SchemaEvent(EventCodes kind, String reason) {
this(kind, reason, null);
}
public SchemaEvent(EventCodes kind, String reason, String where) {
super(kind.severity, kind, reason + (where != null ? " at " + where : ""));
this.reason = reason;
this.where = where;
}
public String getReason() {
return reason;
}
public String getWhere() {
return where;
}
}
void addInformativeComment(Element element, String comment) {
element.appendChild(element.getOwnerDocument().createComment(comment));
}
void handleEvent(SchemaEvent evt) throws RuleException {
if (evthandler != null) {
if (!evthandler.handle(evt) || evt.getSeverity() == Event.Severity.FATAL) {
/* die on FATAL events or if requested by the handler */
throw new RuleException(evt.getMessage());
}
} else if (evt.getSeverity() == Event.Severity.ERROR
|| evt.getSeverity() == Event.Severity.FATAL) {
/* if no event handler was provided, die on FATAL and ERROR events */
throw new RuleException(evt.getMessage());
}
}
/**
* Creates an XMLSchemaBuilder that can be used to generate XML Schemas for
* any metadictionary covered by the resolver. The caller can optionally
* provide an EventHandler to receive notifications of events encountered in
* the process.
*
* @param resolver Collection of Metadictionary definitions, typically a
* {@link com.sandflow.smpte.regxml.dict.MetaDictionaryCollection}
* @param handler Event handler provided by the caller. May be null.
*/
public XMLSchemaBuilder(DefinitionResolver resolver, EventHandler handler) {
if (resolver == null) {
throw new InvalidParameterException("A resolver must be provided");
}
this.resolver = resolver;
this.evthandler = handler;
}
/**
* Creates an XMLSchemaBuilder that can be used to generate XML Schemas for
* any metadictionary covered by the resolver.
*
* @deprecated Replaced by
* {@link #XMLSchemaBuilder(com.sandflow.smpte.regxml.dict.DefinitionResolver, com.sandflow.util.events.EventHandler) }
* This constructor does not allow the caller to provide an event handler,
* and instead uses java.util.logging to output events.
*
* @param resolver Collection of Metadictionary definitions, typically a
* {@link com.sandflow.smpte.regxml.dict.MetaDictionaryCollection}
*/
public XMLSchemaBuilder(DefinitionResolver resolver) {
this(resolver,
new EventHandler() {
@Override
public boolean handle(Event evt) {
switch (evt.getSeverity()) {
case ERROR:
case FATAL:
LOG.severe(evt.getMessage());
break;
case INFO:
LOG.info(evt.getMessage());
break;
case WARN:
LOG.warning(evt.getMessage());
}
return true;
}
}
);
}
private String createQName(URI uri, String name) {
return this.prefixes.getPrefixOrCreate(uri) + ":" + name;
}
/**
* Generates a single XML Schema document from a single Metadictionary. A
* definition from the latter may reference a definition from another
* Metadictionary, i.e. in a different namespace, as long as this second
* Metadictionary can be resolved by the {@link DefinitionResolver} provided
* a creation-time.
*
* @param dict Metadictionary for which an XML Schema will be generated.
*
* @return XML Schema document
*
* @throws javax.xml.parsers.ParserConfigurationException
* @throws com.sandflow.smpte.klv.exceptions.KLVException
* @throws com.sandflow.smpte.regxml.XMLSchemaBuilder.RuleException
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
*/
public Document fromDictionary(MetaDictionary dict) throws ParserConfigurationException, KLVException, RuleException, SAXException, IOException {
/* reset namespace prefixes */
this.prefixes.clear();
/* create the DOM from the STD_DECL template */
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
doc.setXmlStandalone(true);
Element schema = doc.createElementNS(XSD_NS, "xs:schema");
schema.setAttribute("targetNamespace", dict.getSchemeURI().toString());
schema.setAttributeNS(XMLNS_NS, "xmlns:reg", REGXML_NS);
schema.setAttributeNS(XMLNS_NS, "xmlns:xlink", XLINK_NS);
schema.setAttribute("elementFormDefault", "qualified");
schema.setAttribute("attributeFormDefault", "unqualified");
doc.appendChild(schema);
Element importelem = doc.createElementNS(XSD_NS, "xs:import");
importelem.setAttribute("namespace", XLINK_NS);
importelem.setAttribute("schemaLocation", XLINK_LOC);
doc.getDocumentElement().appendChild(importelem);
importelem = doc.createElementNS(XSD_NS, "xs:import");
importelem.setAttribute("namespace", REGXML_NS);
doc.getDocumentElement().appendChild(importelem);
for (Definition definition : dict.getDefinitions()) {
if (definition instanceof ClassDefinition) {
applyRule4(doc.getDocumentElement(), (ClassDefinition) definition);
} else if (definition.getClass() == PropertyDefinition.class) {
applyRule5(doc.getDocumentElement(), (PropertyDefinition) definition);
} else if (definition.getClass() == PropertyAliasDefinition.class) {
/* need to supress alias declaration since they use the same symbol and AUID as parent */
} else {
applyRule6(doc.getDocumentElement(), definition);
}
}
/* hack to clean-up namespace prefixes */
for (URI uri : prefixes.getURIs()) {
doc.getDocumentElement().setAttributeNS(
XMLNS_NS,
"xmlns:" + prefixes.getPrefixOrCreate(uri),
uri.toString()
);
if (!uri.equals(dict.getSchemeURI())) {
importelem = doc.createElementNS(XSD_NS, "xs:import");
importelem.setAttribute("namespace", uri.toString());
doc.getDocumentElement().insertBefore(importelem, doc.getDocumentElement().getFirstChild());
}
}
return doc;
}
void applyRule4(Element root, ClassDefinition definition) throws RuleException {
/*
<element name=”{name}” [abstract=”true”]?>
<complexType>
<complexContent>
<all>
Apply rule 4.1
</all>
[<attribute ref=”reg:uid” use=”required”/>]?
<attribute ref="reg:path" use="optional"/>
</complexContent>
</complexType>
</element>
*/
Element element = root.getOwnerDocument().createElementNS(XSD_NS, "xs:element");
element.setAttribute("name", definition.getSymbol());
if (!definition.isConcrete()) {
element.setAttribute("abstract", "true");
}
root.appendChild(element);
Element complexType = root.getOwnerDocument().createElementNS(XSD_NS, "xs:complexType");
element.appendChild(complexType);
Element all = root.getOwnerDocument().createElementNS(XSD_NS, "xs:all");
complexType.appendChild(all);
boolean hasUID = false;
ClassDefinition cdef = definition;
while (cdef != null) {
for (AUID auid : resolver.getMembersOf(cdef)) {
PropertyDefinition pdef
= (PropertyDefinition) resolver.getDefinition(auid);
element = root.getOwnerDocument().createElementNS(XSD_NS, "xs:element");
element.setAttribute("ref", createQName(pdef.getNamespace(), pdef.getSymbol()));
if (pdef.isOptional() || pdef.getIdentification().equals(ObjectClass_AUID)) {
element.setAttribute("minOccurs", "0");
}
/* NOTE: require reg:uid only if the object has one property
with IsUniqueIdentifier */
hasUID |= pdef.isUniqueIdentifier();
all.appendChild(element);
}
if (cdef.getParentClass() != null) {
cdef = (ClassDefinition) resolver.getDefinition(cdef.getParentClass());
} else {
cdef = null;
}
}
Element attribute = null;
/* @reg:uid */
if (hasUID) {
attribute = root.getOwnerDocument().createElementNS(XSD_NS, "xs:attribute");
attribute.setAttribute("ref", "reg:uid");
attribute.setAttribute("use", "required");
complexType.appendChild(attribute);
}
/* @reg:path */
attribute = root.getOwnerDocument().createElementNS(XSD_NS, "xs:attribute");
attribute.setAttribute("ref", "reg:path");
attribute.setAttribute("use", "optional");
complexType.appendChild(attribute);
}
void applyRule5(Element root, PropertyDefinition definition) throws RuleException {
Element elem = root.getOwnerDocument().createElementNS(XSD_NS, "xs:element");
elem.setAttribute("name", definition.getSymbol());
if (definition.getIdentification().equals(ByteOrder_AUID)) {
/* rule 5.1 */
elem.setAttribute("type", "reg:ByteOrderType");
} else {
Definition typedef = resolver.getDefinition(definition.getType());
if (typedef == null) {
throw new RuleException(
String.format(
"Type UL does not resolve at Element %s ",
definition.getIdentification().toString()
)
);
}
elem.setAttribute("type", createQName(typedef.getNamespace(), typedef.getSymbol()));
}
root.appendChild(elem);
}
void applyRule6(Element element, Definition definition) throws RuleException {
if (definition instanceof CharacterTypeDefinition) {
applyRule6_1(element, (CharacterTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof EnumerationTypeDefinition) {
applyRule6_2(element, (EnumerationTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof ExtendibleEnumerationTypeDefinition) {
applyRule6_3(element, (ExtendibleEnumerationTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof FixedArrayTypeDefinition) {
applyRule6_4(element, (FixedArrayTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof IndirectTypeDefinition) {
applyRule6_5(element, (IndirectTypeDefinition) definition);
} else if (definition instanceof IntegerTypeDefinition) {
applyRule6_6(element, (IntegerTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof OpaqueTypeDefinition) {
applyRule6_7(element, (OpaqueTypeDefinition) definition);
} else if (definition instanceof RecordTypeDefinition) {
applyRule6_8(element, (RecordTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof RenameTypeDefinition) {
applyRule6_9(element, (RenameTypeDefinition) definition);
/* need to check if rename type works */
applyRule6Sub2(element, definition);
} else if (definition instanceof SetTypeDefinition) {
applyRule6_10(element, (SetTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof StreamTypeDefinition) {
applyRule6_11(element, (StreamTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof StringTypeDefinition) {
applyRule6_12(element, (StringTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof StrongReferenceTypeDefinition) {
applyRule6_13(element, (StrongReferenceTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof VariableArrayTypeDefinition) {
applyRule6_14(element, (VariableArrayTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof WeakReferenceTypeDefinition) {
applyRule6_15(element, (WeakReferenceTypeDefinition) definition);
applyRule6Sub2(element, definition);
} else if (definition instanceof FloatTypeDefinition) {
applyRule6_alpha(element, (FloatTypeDefinition) definition);
applyRule6Sub2(element, definition);
| } else if (definition instanceof LensSerialFloatTypeDefinition) { | 1 |
Niels-NTG/FTLAV | src/main/java/net/ntg/ftl/FTLAdventureVisualiser.java | [
"public class Profile {\n\n\tprivate Stats stats;\n\n\tpublic Profile() {\n\t}\n\n\tpublic void setHeaderAlpha( int n ) {\n\t}\n\n\tpublic void setStats( Stats stats ) {\n\t\tthis.stats = stats;\n\t}\n\tpublic Stats getStats() {\n\t\treturn stats;\n\t}\n\n}",
"public class SectorDot {\n\tprivate final String sect... | import net.blerf.ftl.model.Profile;
import net.blerf.ftl.model.sectortree.SectorDot;
import net.blerf.ftl.parser.DataManager;
import net.blerf.ftl.parser.DefaultDataManager;
import net.blerf.ftl.parser.SavedGameParser;
import net.ntg.ftl.ui.FTLFrame;
import net.vhati.modmanager.core.FTLUtilities;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.JDOMException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.xml.bind.JAXBException;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.prefs.Preferences; | package net.ntg.ftl;
public class FTLAdventureVisualiser {
private static final Logger log = LogManager.getLogger(FTLAdventureVisualiser.class);
public static final String APP_NAME = "FTL Adventure Visualiser";
public static final int APP_VERSION = 3;
private static final Preferences prefs = Preferences.userNodeForPackage(net.ntg.ftl.FTLAdventureVisualiser.class);
private static final String FTL_DAT_PATH = "ftlDatsPath";
private static final String FTL_CONTINUE_PATH = "ftlContinuePath";
private static final String FTL_PROFILE_PATH = "ftlProfilePath";
private static final String FTL_AE_PROFILE_PATH = "ftlAEProfilePath";
public static File gameStateFile;
// public static File profileFile;
public static File aeProfileFile;
public static SavedGameParser.SavedGameState gameState = null;
public static SavedGameParser.ShipState shipState = null;
public static SavedGameParser.ShipState nearbyShipState = null;
public static List<SavedGameParser.CrewState> playerCrewState;
public static List<SavedGameParser.CrewState> enemyCrewState;
public static SavedGameParser.EnvironmentState environmentState = null; | public static ArrayList<SectorDot> sectorArray = new ArrayList<>(); | 1 |
mapsforge/mapsforge | mapsforge-samples-awt/src/main/java/org/mapsforge/samples/awt/Samples.java | [
"public class BoundingBox implements Serializable {\n private static final long serialVersionUID = 1L;\n\n /**\n * Creates a new BoundingBox from a comma-separated string of coordinates in the order minLat, minLon, maxLat,\n * maxLon. All coordinate values must be in degrees.\n *\n * @param bo... | import org.mapsforge.core.graphics.GraphicFactory;
import org.mapsforge.core.model.BoundingBox;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.model.MapPosition;
import org.mapsforge.core.model.Point;
import org.mapsforge.core.util.LatLongUtils;
import org.mapsforge.core.util.Parameters;
import org.mapsforge.map.awt.graphics.AwtGraphicFactory;
import org.mapsforge.map.awt.util.AwtUtil;
import org.mapsforge.map.awt.util.JavaPreferences;
import org.mapsforge.map.awt.view.MapView;
import org.mapsforge.map.datastore.MapDataStore;
import org.mapsforge.map.datastore.MultiMapDataStore;
import org.mapsforge.map.layer.Layers;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.debug.TileCoordinatesLayer;
import org.mapsforge.map.layer.debug.TileGridLayer;
import org.mapsforge.map.layer.download.TileDownloadLayer;
import org.mapsforge.map.layer.download.tilesource.OpenStreetMapMapnik;
import org.mapsforge.map.layer.download.tilesource.TileSource;
import org.mapsforge.map.layer.hills.DiffuseLightShadingAlgorithm;
import org.mapsforge.map.layer.hills.HillsRenderConfig;
import org.mapsforge.map.layer.hills.MemoryCachingHgtReaderTileSource;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.model.IMapViewPosition;
import org.mapsforge.map.model.Model;
import org.mapsforge.map.model.common.PreferencesFacade;
import org.mapsforge.map.reader.MapFile;
import org.mapsforge.map.rendertheme.InternalRenderTheme;
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.prefs.Preferences; | /*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2014 Christian Pesch
* Copyright 2014 Ludwig M Brinckmann
* Copyright 2014-2022 devemux86
* Copyright 2017 usrusr
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.samples.awt;
public final class Samples {
private static final GraphicFactory GRAPHIC_FACTORY = AwtGraphicFactory.INSTANCE;
private static final boolean SHOW_DEBUG_LAYERS = false;
private static final boolean SHOW_RASTER_MAP = false;
private static final String MESSAGE = "Are you sure you want to exit the application?";
private static final String TITLE = "Confirm close";
/**
* Starts the {@code Samples}.
*
* @param args command line args: expects the map files as multiple parameters
* with possible SRTM hgt folder as 1st argument.
*/
public static void main(String[] args) {
// Square frame buffer
Parameters.SQUARE_FRAME_BUFFER = false;
HillsRenderConfig hillsCfg = null;
File demFolder = getDemFolder(args);
if (demFolder != null) {
MemoryCachingHgtReaderTileSource tileSource = new MemoryCachingHgtReaderTileSource(demFolder, new DiffuseLightShadingAlgorithm(), AwtGraphicFactory.INSTANCE);
tileSource.setEnableInterpolationOverlap(true);
hillsCfg = new HillsRenderConfig(tileSource);
hillsCfg.indexOnThread();
args = Arrays.copyOfRange(args, 1, args.length);
}
List<File> mapFiles = SHOW_RASTER_MAP ? null : getMapFiles(args);
final MapView mapView = createMapView();
final BoundingBox boundingBox = addLayers(mapView, mapFiles, hillsCfg);
final PreferencesFacade preferencesFacade = new JavaPreferences(Preferences.userNodeForPackage(Samples.class));
final JFrame frame = new JFrame();
frame.setTitle("Mapsforge Samples");
frame.add(mapView);
frame.pack();
frame.setSize(1024, 768);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(frame, MESSAGE, TITLE, JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
mapView.getModel().save(preferencesFacade);
mapView.destroyAll();
AwtGraphicFactory.clearResourceMemoryCache();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
@Override
public void windowOpened(WindowEvent e) {
final Model model = mapView.getModel();
model.init(preferencesFacade);
if (model.mapViewPosition.getZoomLevel() == 0 || !boundingBox.contains(model.mapViewPosition.getCenter())) {
byte zoomLevel = LatLongUtils.zoomForBounds(model.mapViewDimension.getDimension(), boundingBox, model.displayModel.getTileSize());
model.mapViewPosition.setMapPosition(new MapPosition(boundingBox.getCenterPoint(), zoomLevel));
}
}
});
frame.setVisible(true);
}
private static BoundingBox addLayers(MapView mapView, List<File> mapFiles, HillsRenderConfig hillsRenderConfig) {
Layers layers = mapView.getLayerManager().getLayers();
int tileSize = SHOW_RASTER_MAP ? 256 : 512;
// Tile cache
TileCache tileCache = AwtUtil.createTileCache(
tileSize,
mapView.getModel().frameBufferModel.getOverdrawFactor(),
1024,
new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()));
final BoundingBox boundingBox;
if (SHOW_RASTER_MAP) {
// Raster
mapView.getModel().displayModel.setFixedTileSize(tileSize);
OpenStreetMapMapnik tileSource = OpenStreetMapMapnik.INSTANCE;
tileSource.setUserAgent("mapsforge-samples-awt");
TileDownloadLayer tileDownloadLayer = createTileDownloadLayer(tileCache, mapView.getModel().mapViewPosition, tileSource);
layers.add(tileDownloadLayer);
tileDownloadLayer.start();
mapView.setZoomLevelMin(tileSource.getZoomLevelMin());
mapView.setZoomLevelMax(tileSource.getZoomLevelMax());
boundingBox = new BoundingBox(LatLongUtils.LATITUDE_MIN, LatLongUtils.LONGITUDE_MIN, LatLongUtils.LATITUDE_MAX, LatLongUtils.LONGITUDE_MAX);
} else {
// Vector
mapView.getModel().displayModel.setFixedTileSize(tileSize);
MultiMapDataStore mapDataStore = new MultiMapDataStore(MultiMapDataStore.DataPolicy.RETURN_ALL);
for (File file : mapFiles) {
mapDataStore.addMapDataStore(new MapFile(file), false, false);
}
TileRendererLayer tileRendererLayer = createTileRendererLayer(tileCache, mapDataStore, mapView.getModel().mapViewPosition, hillsRenderConfig);
layers.add(tileRendererLayer);
boundingBox = mapDataStore.boundingBox();
}
// Debug
if (SHOW_DEBUG_LAYERS) {
layers.add(new TileGridLayer(GRAPHIC_FACTORY, mapView.getModel().displayModel));
layers.add(new TileCoordinatesLayer(GRAPHIC_FACTORY, mapView.getModel().displayModel));
}
return boundingBox;
}
private static MapView createMapView() {
MapView mapView = new MapView();
mapView.getMapScaleBar().setVisible(true);
if (SHOW_DEBUG_LAYERS) {
mapView.getFpsCounter().setVisible(true);
}
return mapView;
}
@SuppressWarnings("unused")
private static TileDownloadLayer createTileDownloadLayer(TileCache tileCache, IMapViewPosition mapViewPosition, TileSource tileSource) {
return new TileDownloadLayer(tileCache, mapViewPosition, tileSource, GRAPHIC_FACTORY) {
@Override
public boolean onTap(LatLong tapLatLong, Point layerXY, Point tapXY) {
System.out.println("Tap on: " + tapLatLong);
return true;
}
};
}
private static TileRendererLayer createTileRendererLayer(TileCache tileCache, MapDataStore mapDataStore, IMapViewPosition mapViewPosition, HillsRenderConfig hillsRenderConfig) {
TileRendererLayer tileRendererLayer = new TileRendererLayer(tileCache, mapDataStore, mapViewPosition, false, true, false, GRAPHIC_FACTORY, hillsRenderConfig) {
@Override
public boolean onTap(LatLong tapLatLong, Point layerXY, Point tapXY) {
System.out.println("Tap on: " + tapLatLong);
return true;
}
}; | tileRendererLayer.setXmlRenderTheme(InternalRenderTheme.DEFAULT); | 6 |
mikolajmitura/java-properties-to-json | src/main/java/pl/jalokim/propertiestojson/resolvers/primitives/string/TextToElementsResolver.java | [
"public static final String EMPTY_STRING = \"\";",
"public static final String SIMPLE_ARRAY_DELIMITER = \",\";",
"public static boolean hasJsonArraySignature(String propertyValue) {\n return hasJsonSignature(propertyValue.trim(), ARRAY_START_SIGN, ARRAY_END_SIGN);\n}",
"public static boolean isValidJsonObj... | import static java.lang.String.join;
import static pl.jalokim.propertiestojson.Constants.EMPTY_STRING;
import static pl.jalokim.propertiestojson.Constants.SIMPLE_ARRAY_DELIMITER;
import static pl.jalokim.propertiestojson.resolvers.primitives.utils.JsonObjectHelper.hasJsonArraySignature;
import static pl.jalokim.propertiestojson.resolvers.primitives.utils.JsonObjectHelper.isValidJsonObjectOrArray;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import pl.jalokim.propertiestojson.resolvers.PrimitiveJsonTypesResolver; | package pl.jalokim.propertiestojson.resolvers.primitives.string;
public class TextToElementsResolver implements TextToConcreteObjectResolver<List<?>> {
private final String arrayElementSeparator;
private final boolean resolveTypeOfEachElement;
public TextToElementsResolver() {
this(true);
}
public TextToElementsResolver(boolean resolveTypeOfEachElement) {
this(resolveTypeOfEachElement, SIMPLE_ARRAY_DELIMITER);
}
public TextToElementsResolver(boolean resolveTypeOfEachElement, String arrayElementSeparator) {
this.resolveTypeOfEachElement = resolveTypeOfEachElement;
this.arrayElementSeparator = arrayElementSeparator;
}
@Override
@SuppressWarnings("PMD.AvoidReassigningParameters")
public Optional<List<?>> returnObjectWhenCanBeResolved(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, String propertyValue, String propertyKey) {
if (isSimpleArray(propertyValue) && !isValidJsonObjectOrArray(propertyValue)) {
if (hasJsonArraySignature(propertyValue)) {
propertyValue = propertyValue | .replaceAll("]\\s*$", EMPTY_STRING) | 0 |
xSAVIKx/openweathermap-java-api | api-examples/src/main/java/org/openweathermap/api/example/DailyForecastExample.java | [
"public interface DataWeatherClient extends WeatherClient {\n\n CurrentWeather getCurrentWeather(CurrentWeatherOneLocationQuery query);\n\n List<CurrentWeather> getCurrentWeather(CurrentWeatherMultipleLocationsQuery query);\n\n ForecastInformation<HourlyForecast> getForecastInformation(HourlyForecastQuery ... | import org.openweathermap.api.DataWeatherClient;
import org.openweathermap.api.UrlConnectionDataWeatherClient;
import org.openweathermap.api.model.forecast.ForecastInformation;
import org.openweathermap.api.model.forecast.daily.DailyForecast;
import org.openweathermap.api.query.Language;
import org.openweathermap.api.query.QueryBuilderPicker;
import org.openweathermap.api.query.UnitFormat;
import org.openweathermap.api.query.forecast.daily.ByCityName; | /*
* Copyright 2021, Yurii Serhiichuk
*
* 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.openweathermap.api.example;
public class DailyForecastExample {
private static final String API_KEY = System.getenv("OPENWEATHERMAP_API_KEY");
public static void main(String[] args) { | DataWeatherClient client = new UrlConnectionDataWeatherClient(API_KEY); | 1 |
MCBans/MCBans | src/main/java/com/mcbans/plugin/commands/BaseCommand.java | [
"public class IPTools {\n public static boolean validIP(String playerIP){\n if(playerIP==null)\n return false;\n return playerIP.matches(\"^([0-9]{1,3})\\\\.([0-9]{1,3})\\\\.([0-9]{1,3})\\\\.([0-9]{1,3})$\");\n }\n public static boolean validBanIP(String playerIP){\n if(playerIP==null)\n retur... | import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.mcbans.utils.IPTools;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.mcbans.plugin.ConfigurationManager;
import com.mcbans.plugin.MCBans;
import com.mcbans.plugin.exception.CommandException;
import com.mcbans.plugin.util.Util;
import static com.mcbans.plugin.I18n.localize; | package com.mcbans.plugin.commands;
public abstract class BaseCommand {
// Set this class
protected MCBans plugin;
protected ConfigurationManager config;
protected CommandSender sender;
protected String command=null;
// Needs init
protected List<String> args = new ArrayList<String>();
// Sender
protected Player senderPlayer = null;
protected String senderName = null;
protected String senderUUID = null;
// Set this class if banning (needs init)
protected String target = null;
protected String targetIP = null;
protected String targetUUID = null;
// Set extend class constructor (Command property)
protected String name = null;
protected int argLength = 0;
protected String usage = null;
protected boolean bePlayer = false;
protected boolean banning = false;
public boolean run(final MCBans plugin, final CommandSender sender, final String cmd, final String[] preArgs) {
if (name == null){
Util.message(sender, "&cThis command has not been loaded properly.");
return true;
}
// init command
init();
this.plugin = plugin;
this.config = plugin.getConfigs();
this.sender = sender;
this.command = cmd;
// Sort args
for (String arg : preArgs)
args.add(arg);
// Check args size
if (argLength > args.size()){
//sendUsage();
Util.message(sender, ChatColor.RED + localize("formatError"));
return true;
}
// Check sender is player
if (bePlayer && !(sender instanceof Player)){
Util.message(sender, "&cThis command cannot be executed from the console.");
return true;
}
if (sender instanceof Player){
senderPlayer = (Player)sender;
senderName = senderPlayer.getName();
senderUUID = senderPlayer.getUniqueId().toString().replaceAll("-", "");
}
// Check permission
if (!permission(sender)){
Util.message(sender, ChatColor.RED + localize("permissionDenied"));
//plugin.log(senderName + " has tried the command [" + command + "]!"); // maybe not needs command logger. Craftbukkit added this.
//plugin.broadcastPlayer(sender, "&cYou don't have permission to use this!");
return true;
}
// set banning information
if (banning && args.size() > 0){
// target = args.remove(0); // Don't touch args here
target = args.get(0).trim();
// get targetIP if available
final Player targetPlayer = MCBans.getPlayer(plugin, target);
if (targetPlayer != null && targetPlayer.isOnline()){
InetSocketAddress socket = targetPlayer.getAddress();
//Not all IPs are successfully resolved
//This prevents players from being unbannable/kickable in this rare case
if(socket.isUnresolved()) {
targetIP = null;
} else {
targetIP = socket.getAddress().getHostAddress();
}
}
// check isValid player name
if (!Util.isValidName(target)){
if(Util.isValidUUID(target)){
targetUUID = target;
target = null;
}else{
if(IPTools.validBanIP(target)){
targetIP = target;
}else{
Util.message(sender, ChatColor.RED + localize("invalidName"));
return true;
}
}
}
System.out.println("target: "+target);
System.out.println("targetUUID: "+targetUUID);
}
// Exec
try {
check();
execute(); | } catch (CommandException ex) { | 3 |
emina/kodkod | src/kodkod/engine/Evaluator.java | [
"public abstract class Expression extends Node {\n\t\n\t/** The universal relation: contains all atoms in a {@link kodkod.instance.Universe universe of discourse}. */\n\tpublic static final Expression UNIV = new ConstantExpression(\"univ\", 1);\n\t\n\t/** The identity relation: maps all atoms in a {@link kodkod.in... | import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.IntExpression;
import kodkod.engine.bool.BooleanMatrix;
import kodkod.engine.bool.Int;
import kodkod.engine.config.Options;
import kodkod.engine.fol2sat.Translator;
import kodkod.instance.Instance;
import kodkod.instance.TupleSet; | /*
* Kodkod -- Copyright (c) 2005-present, Emina Torlak
*
* 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 kodkod.engine;
/**
* An evaluator for relational formulas and expressions with
* respect to a given {@link kodkod.instance.Instance instance}
* and {@link kodkod.engine.config.Options options}.
*
* <p><b>Note: </b> you may observe surprising (though correct)
* evaluator behavior if you do not use the same set of integer
* options (i.e. {@link kodkod.engine.config.Options#intEncoding() intEncoding} and {@link kodkod.engine.config.Options#bitwidth() bitwidth}
* when evaluating and solving a formula. For example, suppose that
* that an Instance i is a solution to a formula f found using options o.
* If you create an evaluator e such that e.instance = i, but e.options
* is an Options object with different integer settings than o,
* e.evaluate(f) may return false. </p>
*
* @specfield options: Options
* @specfield instance: Instance
* @author Emina Torlak
*/
public final class Evaluator {
private final Instance instance;
private final Options options;
/**
* Constructs a new Evaluator for the given instance, using a
* default Options object.
* @ensures this.instance' = instance && this.options' = new Options()
* @throws NullPointerException instance = null
*/
public Evaluator(Instance instance) {
this(instance, new Options());
}
/**
* Constructs a new Evaluator for the given instance and options
* @ensures this.instance' = instance && this.options' = options
* @throws NullPointerException instance = null || options = null
*/
public Evaluator(Instance instance, Options options) {
if (instance==null || options==null) throw new NullPointerException();
this.instance = instance;
this.options = options;
}
/**
* Returns the Options object used by this evaluator.
* @return this.options
*/
public Options options() { return options; }
/**
* Returns this.instance. Any modifications to the returned object
* will be reflected in the behavior of the evaluate methods.
*
* @return this.instance
*/
public Instance instance() { return instance; }
/**
* Evaluates the specified formula with respect to the relation-tuple mappings
* given by this.instance and using this.options.
* @return true if formula is true with respect to this.instance and this.options;
* otherwise returns false
* @throws kodkod.engine.fol2sat.HigherOrderDeclException the formula contains a higher order declaration
* @throws kodkod.engine.fol2sat.UnboundLeafException the formula contains an undeclared variable or
* a relation not mapped by this.instance
*/
public boolean evaluate(Formula formula){
if (formula == null) throw new NullPointerException("formula");
return (Translator.evaluate(formula, instance, options)).booleanValue();
}
/**
* Evaluates the specified expression with respect to the relation-tuple mappings
* given by this.instance and using this.options.
* @return {@link kodkod.instance.TupleSet set} of tuples to which the expression evaluates given the
* mappings in this.instance and the options in this.options.
* @throws kodkod.engine.fol2sat.HigherOrderDeclException the expression contains a higher order declaration
* @throws kodkod.engine.fol2sat.UnboundLeafException the expression contains an undeclared variable or
* a relation not mapped by this.instance
*/
public TupleSet evaluate(Expression expression){
if (expression == null) throw new NullPointerException("expression");
final BooleanMatrix sol = Translator.evaluate(expression,instance,options);
return instance.universe().factory().setOf(expression.arity(), sol.denseIndices());
}
/**
* Evaluates the specified int expression with respect to the relation-tuple mappings
* given by this.instance and using this.options.
* @return the integer to which the expression evaluates given the
* mappings in this.instance and the options in this.options.
* @throws kodkod.engine.fol2sat.HigherOrderDeclException intExpr contains a higher order declaration
* @throws kodkod.engine.fol2sat.UnboundLeafException intExpr contains an undeclared variable or
* a relation not mapped by this.instance
*/ | public int evaluate(IntExpression intExpr) { | 1 |
dbuschman7/mongoFS | src/test/java/com/mongodb/MongoFileExpirationTest.java | [
"public final class LoremIpsum {\n\n private static final String TEXT_FILE = \"./src/test/resources/loremIpsum.txt\";\n\n private LoremIpsum() {\n // hidden\n }\n\n public static File getFile() throws IOException {\n File file = new File(TEXT_FILE);\n if (!file.exists()) {\n ... | import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import me.lightspeed7.mongofs.LoremIpsum;
import me.lightspeed7.mongofs.MongoFileCursor;
import me.lightspeed7.mongofs.MongoFileStore;
import me.lightspeed7.mongofs.MongoFileStoreConfig;
import me.lightspeed7.mongofs.MongoFileWriter;
import me.lightspeed7.mongofs.MongoTestConfig;
import me.lightspeed7.mongofs.util.TimeMachine;
import org.junit.BeforeClass;
import org.junit.Test; | package com.mongodb;
public class MongoFileExpirationTest {
private static final String DB_NAME = "MongoFSTest-expiration";
| private static MongoFileStore store; | 2 |
sumeetchhetri/gatf | alldep-jar/src/main/java/com/gatf/executor/distributed/DistributedGatfTester.java | [
"public class AcceptanceTestContext {\r\n\r\n\tprivate Logger logger = Logger.getLogger(AcceptanceTestContext.class.getSimpleName());\r\n\t\r\n\tpublic final static String\r\n\t PROP_SOAP_ACTION_11 = \"SOAPAction\",\r\n\t PROP_SOAP_ACTION_12 = \"action=\",\r\n\t PROP_CONTENT_TYPE = \"Content-Type\",\r\n\t ... | import com.gatf.executor.core.AcceptanceTestContext;
import com.gatf.executor.core.TestCase;
import com.gatf.executor.distributed.DistributedAcceptanceContext.Command;
import com.gatf.executor.report.ReportHandler;
import com.gatf.executor.report.RuntimeReportUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
| /*
Copyright 2013-2019, Sumeet Chhetri
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.gatf.executor.distributed;
public class DistributedGatfTester {
private static final Logger logger = Logger.getLogger(DistributedGatfTester.class.getSimpleName());
public static class DistributedConnection {
private Socket sock;
private String node;
private Output oos = null;
private Input ois = null;
public String toString()
{
return node;
}
}
public DistributedConnection distributeContext(String node, AcceptanceTestContext context, List<Object[]> testdata)
{
Socket client = null;
DistributedConnection conn = null;
try {
logger.info("Connecting to node " + node);
int port = 9567;
if(node.indexOf("@")!=-1) {
try {
String sp = node.substring(node.indexOf("@")+1);
node = node.substring(0, node.indexOf("@"));
port = Integer.parseInt(sp);
} catch (Exception e) {
logger.info("Invalid port number specified for distributed listener, defaulting to 9567");
}
}
client = new Socket(node, port);
DistributedAcceptanceContext disContext = context.getDistributedContext(node, testdata);
Output oos = new Output(client.getOutputStream());
Input ois = new Input(client.getInputStream());
logger.info("Sending GATF configuration to node " + node);
oos.writeInt(Command.CONFIG_SHARE_REQ.ordinal());
DistributedAcceptanceContext.ser(oos, disContext);
oos.flush();
logger.info("Sent GATF configuration to node " + node);
Command command = Command.values()[ois.readInt()];
if(command==Command.CONFIG_SHARE_RES) {
conn = new DistributedConnection();
conn.sock = client;
conn.node = node;
conn.ois = ois;
conn.oos = oos;
logger.info("Sending GATF configuration Successful to node " + node);
} else {
logger.info("Sending GATF configuration Failed to node " + node);
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Sending GATF configuration Failed to node " + node);
if(client!=null)
{
try {
client.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return conn;
}
| public FutureTask<DistributedTestStatus> distributeTests(List<TestCase> simTestCases,
| 1 |
SoyaLeaf/CalendarII | app/src/main/java/top/soyask/calendarii/utils/MonthUtils.java | [
"public class EventDao {\n public static final String EVENT = \"EVENT\";\n\n private DBUtils mDBUtils;\n private WeakReference<Context> mContext;\n private static EventDao mEventDao;\n\n private EventDao(DBUtils dBUtils, Context context) {\n this.mDBUtils = dBUtils;\n this.mContext = ne... | import android.support.annotation.NonNull;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import top.soyask.calendarii.database.dao.EventDao;
import top.soyask.calendarii.entity.Birthday;
import top.soyask.calendarii.entity.Day;
import top.soyask.calendarii.entity.Event;
import top.soyask.calendarii.entity.LunarDay;
import top.soyask.calendarii.global.GlobalData; | package top.soyask.calendarii.utils;
/**
* Created by mxf on 2017/10/29.
*/
public class MonthUtils {
private static final String DATE_SP = "-";
/**
* 判断是否有大年三十
*
* @param calendar
* @return
*/
public static final String checkNextDayIsChuxi(Calendar calendar) {
Calendar next = Calendar.getInstance();
next.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
next.add(Calendar.DATE, 1);
LunarDay lunarDay = LunarUtils.getLunar(next);
String lunar = lunarDay.getLunarDate();
String lunarHoliday = HolidayUtils.getHolidayOfLunar(lunar);
if ("除夕".equals(lunarHoliday)) {
return null;
}
return "除夕";
}
public static final LunarDay getLunar(Calendar calendar) {
LunarDay lunarDay = LunarUtils.getLunar(calendar);
setHoliday(calendar, lunarDay);
setSolar(calendar, lunarDay);
setEra(lunarDay);
setZodiac(lunarDay);
setLunarHoliday(calendar, lunarDay);
return lunarDay;
}
private static void setSolar(Calendar calendar, LunarDay lunarDay) {
String solar = SolarUtils.getSolar(calendar);
lunarDay.setSolar(solar);
}
private static void setHoliday(Calendar calendar, LunarDay lunarDay) {
String holidayOfMonth = getHolidayOfMonth(calendar);
lunarDay.setHoliday(holidayOfMonth);
}
private static void setLunarHoliday(Calendar calendar, LunarDay lunarDay) {
String lunarHoliday = getLunarHoliday(calendar, lunarDay);
if (lunarHoliday != null) {
lunarDay.setHoliday(lunarHoliday);
}
}
private static void setZodiac(LunarDay lunarDay) {
String zodiac = EraUtils.getYearForTwelveZodiac(lunarDay.getYear());
lunarDay.setZodiac(zodiac);
}
private static void setEra(LunarDay lunarDay) {
String branches = EraUtils.getYearForEarthlyBranches(lunarDay.getYear());
String stems = EraUtils.getYearForHeavenlyStems(lunarDay.getYear());
lunarDay.setEra(stems + branches);
}
private static String getLunarHoliday(Calendar calendar, LunarDay lunarDay) {
String lunar = lunarDay.getLunarDate();
String lunarHoliday = HolidayUtils.getHolidayOfLunar(lunar);
if ("除夕".equals(lunarHoliday)) {
lunarHoliday = checkNextDayIsChuxi(calendar);
}
return lunarHoliday;
}
private static String getHolidayOfMonth(Calendar calendar) {
String holidayOfMonth = HolidayUtils.getHolidayOfMonth(calendar);
if (holidayOfMonth != null && holidayOfMonth.length() > 4) {
holidayOfMonth = holidayOfMonth.substring(0, 4);
}
return holidayOfMonth;
}
@NonNull
public static Day generateDay(Calendar calendar, EventDao eventDao) {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
boolean isToday = isToday(dayOfMonth, year, month);
LunarDay lunarDay = MonthUtils.getLunar(calendar);
Day day = new Day(year, month, lunarDay, isToday, dayOfMonth, dayOfWeek);
setBirthday(month, dayOfMonth, lunarDay, day);
setHoliday(year, month, dayOfMonth, day);
setEvent(eventDao, day);
return day;
}
private static void setHoliday(int year, int month, int dayOfMonth, Day day) {
String str = new StringBuilder()
.append(year)
.append(DATE_SP)
.append(month)
.append(DATE_SP)
.append(dayOfMonth)
.toString();
day.setHoliday(GlobalData.HOLIDAY.contains(str));
day.setWorkday(GlobalData.WORKDAY.contains(str));
}
private static void setBirthday(int month, int dayOfMonth, LunarDay lunarDay, Day day) { | List<Birthday> birthday0 = GlobalData.BIRTHDAY.get(lunarDay.getLunarDate()); | 1 |
peterfuture/dttv-android | dttv/dttv-samples/src/main/java/dttv/app/widget/AudioUIFragment.java | [
"public interface I_OnMyKey {\r\n public void myOnKeyDown(int keyCode);\r\n}\r",
"public class Constant {\n\n public final static String EXTRA_MESSAGE = \"com.example.simpleplayer.MESSAGE\";\n public final static String FILE_MSG = \"dttp.app.media.URL\";\n public final static String FILE_TYPE = \"dttp... | import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import dttv.app.R;
import dttv.app.impl.I_OnMyKey;
import dttv.app.utils.Constant;
import dttv.app.utils.MusicUtils;
import dttv.app.utils.PlayerUtil;
import dttv.app.utils.SettingUtil;
| package dttv.app.widget;
@SuppressLint("NewApi")
public class AudioUIFragment extends Fragment implements I_OnMyKey, OnClickListener {
static final String TAG = "AudioUIFragment";
View rootView;
ListView audio_listview;
private Cursor mCursor;
//private SimpleCursorAdapter adapter;*/
private int currentPosition;
private List<String> playList;
private int trick_seek = 0;
SettingUtil settingUtil;
public AudioUIFragment() {
// TODO Auto-generated constructor stub
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.dt_audio_ui_fragment, container, false);
settingUtil = new SettingUtil(getActivity());
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
initViews();
initListener();
initFillData();
}
private void initViews() {
audio_listview = (ListView) rootView.findViewById(R.id.audio_listview);
}
private void initListener() {
audio_listview.setOnItemClickListener(new ListItemClickListener());
}
@Override
public void onResume() {
// TODO Auto-generated method stub
/*if(MediaPlayer!=null)
MediaPlayer.start();*/
super.onResume();
}
private class ListItemClickListener implements OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> ad, View v, int position,
long arg3) {
// TODO Auto-generated method stub
/*dt_play_bar_lay.setVisibility(View.VISIBLE);
//String uri = ad.getChildAt(position);
currentPosition = position;
playSong(currentPosition);*/
String uri = playList.get(position);
String name = ((TextView) v.findViewById(R.id.media_row_name)).getText().toString();
Toast.makeText(getActivity(), name, 1).show();
| PlayerUtil.getInstance().beginToPlayer(getActivity(), uri, name, Constant.LOCAL_AUDIO);
| 1 |
Doist/JobSchedulerCompat | library/src/test/java/com/doist/jobschedulercompat/scheduler/alarm/AlarmJobServiceTest.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 com.doist.jobschedulercompat.util.ShadowNetworkInfo;
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.net.Uri;
import android.os.Build;
import java.util.concurrent.TimeUnit;
import androidx.test.core.app.ApplicationProvider;
import static org.junit.Assert.assertEquals;
import static org.robolectric.Shadows.shadowOf; | package com.doist.jobschedulercompat.scheduler.alarm;
@RunWith(RobolectricTestRunner.class)
@Config(sdk = Build.VERSION_CODES.KITKAT, shadows = {ShadowNetworkInfo.class})
public class AlarmJobServiceTest {
private static final long DELAY_MS = 500;
private static final long LATENCY_MS = TimeUnit.HOURS.toMillis(1);
private Application application;
private JobStore jobStore;
private ServiceController<AlarmJobService> service;
@Before
public void setup() {
application = ApplicationProvider.getApplicationContext();
jobStore = JobStore.get(application);
service = Robolectric.buildService(AlarmJobService.class).create();
}
@After
public void teardown() {
JobCreator.interruptJobs();
synchronized (JobStore.LOCK) {
jobStore.clear();
}
}
@Test
public void testJobRuns() { | DeviceTestUtils.setDeviceIdle(application, true); | 3 |
zhanjiashu/ZhihuDialyM | app/src/main/java/io/gitcafe/zhanjiashu/newzhihudialy/fragment/DialyFragment.java | [
"public abstract class BaseRcvAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {\n\n private static final String TAG = \"BaseRcyAdaper\";\n\n protected final Context mContext;\n protected final LayoutInflater mLayoutInflater;\n protected List<T> mData;\n\n @LayoutRes\n private int ... | import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import butterknife.ButterKnife;
import butterknife.InjectView;
import io.gitcafe.zhanjiashu.common.adapter.BaseRcvAdapter;
import io.gitcafe.zhanjiashu.newzhihudialy.R;
import io.gitcafe.zhanjiashu.newzhihudialy.adapter.StoriesAdapter;
import io.gitcafe.zhanjiashu.newzhihudialy.model.DialyEntity;
import io.gitcafe.zhanjiashu.newzhihudialy.model.DialyType;
import io.gitcafe.zhanjiashu.newzhihudialy.model.StoryEntity;
import io.gitcafe.zhanjiashu.newzhihudialy.task.FetchDialyTask;
import io.gitcafe.zhanjiashu.newzhihudialy.task.FetchTask;
import io.gitcafe.zhanjiashu.newzhihudialy.activity.DetailActivity;
import io.gitcafe.zhanjiashu.common.util.LogUtil; | package io.gitcafe.zhanjiashu.newzhihudialy.fragment;
/**
* A simple {@link Fragment} subclass.
*/
public class DialyFragment extends Fragment {
private final String TAG = getClass().getSimpleName();
public static final String KEY_BEFORE_DATE = "beforeDate";
public static final String KEY_DIALY_TYPE = "dialyType";
@InjectView(R.id.rcv_stories)
RecyclerView mStoriesRcv;
@InjectView(R.id.srl_refresh)
SwipeRefreshLayout mRefreshLayout;
private StoriesAdapter mStoriesAdapter;
private String mBeforeDate;
private int mDialyType;
public static DialyFragment newInstance(String beforeDate, int dialyType) {
if (beforeDate == null) {
throw new IllegalArgumentException("The args value can not be null");
}
Bundle args = new Bundle();
args.putString(KEY_BEFORE_DATE, beforeDate);
args.putInt(KEY_DIALY_TYPE, dialyType);
DialyFragment fragment = new DialyFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Bundle args = getArguments();
if (args != null) {
mBeforeDate = args.getString(KEY_BEFORE_DATE);
mDialyType = args.getInt(KEY_DIALY_TYPE);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dialy, container, false);
ButterKnife.inject(this, view);
setupView();
return view;
}
private void setupView() {
mRefreshLayout.setColorSchemeResources(R.color.material_colorAccent);
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
fetchDialy(mBeforeDate, mDialyType, true);
}
});
mStoriesRcv.setLayoutManager(new LinearLayoutManager(getActivity()));
mStoriesRcv.setItemAnimator(new DefaultItemAnimator());
if (mDialyType == DialyType.PICK_DIALY) {
mStoriesAdapter = new StoriesAdapter(getActivity(), new ArrayList<StoryEntity>(), false);
} else {
mStoriesAdapter = new StoriesAdapter(getActivity(), new ArrayList<StoryEntity>(), true);
}
mStoriesRcv.setAdapter(mStoriesAdapter);
mStoriesAdapter.setOnItemClickListener(new BaseRcvAdapter.OnItemClickListener<StoryEntity>() {
@Override
public void onItemClick(View view, int position, StoryEntity entity) {
int storyId = entity.getId();
DetailActivity.startBy(getActivity(), storyId);
}
});
fetchDialy(mBeforeDate, mDialyType, false);
}
private void fetchDialy(String beforeDate, int dialyType, boolean isRefresh) {
boolean fetchFromNetworkFirst = false;
boolean cacheOnDisk = true;
if (isRefresh || dialyType == DialyType.LATEST_DIALY) {
fetchFromNetworkFirst = true;
}
if (dialyType == DialyType.PICK_DIALY) {
fetchFromNetworkFirst = true;
cacheOnDisk = false;
}
FetchTask<DialyEntity> task;
task = new FetchDialyTask(getActivity(), mBeforeDate, fetchFromNetworkFirst, cacheOnDisk); | LogUtil.d(TAG, dialyType + " -> " + fetchFromNetworkFirst + " ->> " + cacheOnDisk); | 8 |
MyGrades/mygrades-app | app/src/main/java/de/mygrades/view/activity/SelectUniversityActivity.java | [
"public class Rule {\n\n private Long ruleId;\n /** Not-null value. */\n private String name;\n private String semesterFormat;\n private String semesterPattern;\n private Integer semesterStartSummer;\n private Integer semesterStartWinter;\n private Double gradeFactor;\n private java.util.... | import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.animator.RefactoredDefaultItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.event.EventBus;
import de.mygrades.R;
import de.mygrades.database.dao.Rule;
import de.mygrades.database.dao.University;
import de.mygrades.main.MainServiceHelper;
import de.mygrades.main.events.ErrorEvent;
import de.mygrades.main.events.UniversityEvent;
import de.mygrades.view.adapter.UniversitiesAdapter;
import de.mygrades.view.adapter.dataprovider.UniversitiesDataProvider;
import de.mygrades.view.adapter.model.RuleItem;
import de.mygrades.view.adapter.model.UniversityItem; | package de.mygrades.view.activity;
/**
* Activity which shows all universities.
* The user can select a university to be forwarded to the LoginActivity.
*/
public class SelectUniversityActivity extends AppCompatActivity {
private static final String SAVED_STATE_EXPANDABLE_ITEM_MANAGER = "RecyclerViewExpandableItemManager";
private RecyclerView rvUniversities;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter wrappedAdapter;
private RecyclerViewExpandableItemManager recyclerViewExpandableItemManager;
private UniversitiesAdapter universitiesAdapter;
private UniversitiesDataProvider dataProvider;
private static final String ERROR_TYPE_STATE = "error_type_state";
private MainServiceHelper mainServiceHelper;
public SelectUniversityActivity() { }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_university);
mainServiceHelper = new MainServiceHelper(this);
// init toolbar
initToolbar();
// init recycler view
initRecyclerView(savedInstanceState);
// register event bus
EventBus.getDefault().register(this);
// restore instance state
if (savedInstanceState != null) {
String error = savedInstanceState.getString(ERROR_TYPE_STATE);
if (error != null) {
universitiesAdapter.showError(ErrorEvent.ErrorType.valueOf(error));
}
}
// get all published universities from the database
mainServiceHelper.getUniversitiesFromDatabase(true);
}
@Override
protected void onResume() {
super.onResume();
// get all published universities from server
mainServiceHelper.getUniversities(true);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save error state
ErrorEvent.ErrorType actErrorType = universitiesAdapter.getActErrorType();
if (actErrorType != null) {
outState.putString(ERROR_TYPE_STATE, actErrorType.name());
}
}
/**
* Initialize the toolbar.
*/
private void initToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
}
/**
* Initialize the recycler view and set the adapter.
*/
private void initRecyclerView(Bundle savedInstanceState) {
// restore state if necessary
final Parcelable eimSavedState = (savedInstanceState != null) ? savedInstanceState.getParcelable(SAVED_STATE_EXPANDABLE_ITEM_MANAGER) : null;
recyclerViewExpandableItemManager = new RecyclerViewExpandableItemManager(eimSavedState);
// create data provider
dataProvider = new UniversitiesDataProvider();
// create adapter
universitiesAdapter = new UniversitiesAdapter(this, dataProvider, recyclerViewExpandableItemManager);
wrappedAdapter = recyclerViewExpandableItemManager.createWrappedAdapter(universitiesAdapter);
// set animation stuff
final GeneralItemAnimator animator = new RefactoredDefaultItemAnimator();
animator.setSupportsChangeAnimations(false);
// init recycler view
layoutManager = new LinearLayoutManager(this);
rvUniversities = (RecyclerView) findViewById(R.id.rv_universities);
rvUniversities.setLayoutManager(layoutManager);
rvUniversities.setAdapter(wrappedAdapter);
rvUniversities.setItemAnimator(animator);
rvUniversities.setHasFixedSize(false);
// attach recycler view to item manager, necessary for touch listeners
recyclerViewExpandableItemManager.attachRecyclerView(rvUniversities);
}
/**
* Add new universities to the adapter.
* If the adapter is empty, an indeterminate progress animation will be shown continuously.
*
* @param universities list of new universities which should be added
*/
private void addUniversities(List<University> universities) {
if (universities.size() > 0) {
universitiesAdapter.showError(null);
universitiesAdapter.showFooter();
}
List<UniversityItem> universityItems = new ArrayList<>();
for(University university : universities) {
UniversityItem universityItem = new UniversityItem(university.getUniversityId());
universityItem.setName(university.getName());
universityItem.setUniversityId(university.getUniversityId());
for (Rule rule : university.getRules()) { | RuleItem ruleData = new RuleItem(rule.getRuleId()); | 7 |
fp7-netide/IDE | plugins/eu.netide.parameters/src/parameters/impl/ParametersPackageImpl.java | [
"public enum AtomicType implements Enumerator {\n\t/**\n\t * The '<em><b>String</b></em>' literal object.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @see #STRING_VALUE\n\t * @generated\n\t * @ordered\n\t */\n\tSTRING(0, \"String\", \"String\"),\n\n\t/**\n\t * The '<em><b>Integer</b></em>' liter... | import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.impl.EPackageImpl;
import parameters.AtomicType;
import parameters.BasicType;
import parameters.CompositeType;
import parameters.Constraint;
import parameters.Parameter;
import parameters.ParameterSpecification;
import parameters.ParametersFactory;
import parameters.ParametersPackage;
import parameters.Type; | /**
*/
package parameters.impl;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Package</b>.
* <!-- end-user-doc -->
* @generated
*/
public class ParametersPackageImpl extends EPackageImpl implements ParametersPackage {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass parameterEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass parameterSpecificationEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass typeEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass compositeTypeEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass basicTypeEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass constraintEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EEnum atomicTypeEEnum = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
* package URI value.
* <p>Note: the correct way to create the package is via the static
* factory method {@link #init init()}, which also performs
* initialization of the package, or returns the registered package,
* if one already exists.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see parameters.ParametersPackage#eNS_URI
* @see #init()
* @generated
*/
private ParametersPackageImpl() {
super(eNS_URI, ParametersFactory.eINSTANCE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
*
* <p>This method is used to initialize {@link ParametersPackage#eINSTANCE} when that field is accessed.
* Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static ParametersPackage init() {
if (isInited) return (ParametersPackage)EPackage.Registry.INSTANCE.getEPackage(ParametersPackage.eNS_URI);
// Obtain or create and register package
ParametersPackageImpl theParametersPackage = (ParametersPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof ParametersPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new ParametersPackageImpl());
isInited = true;
// Create package meta-data objects
theParametersPackage.createPackageContents();
// Initialize created meta-data
theParametersPackage.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theParametersPackage.freeze();
// Update the registry and return the package
EPackage.Registry.INSTANCE.put(ParametersPackage.eNS_URI, theParametersPackage);
return theParametersPackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getParameter() {
return parameterEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getParameter_Name() {
return (EAttribute)parameterEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getParameter_Type() {
return (EReference)parameterEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getParameterSpecification() {
return parameterSpecificationEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getParameterSpecification_Types() {
return (EReference)parameterSpecificationEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getParameterSpecification_Parameters() {
return (EReference)parameterSpecificationEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getType() {
return typeEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getType_Name() {
return (EAttribute)typeEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getType_Constraints() {
return (EReference)typeEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getCompositeType() {
return compositeTypeEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getCompositeType_Innertypes() {
return (EReference)compositeTypeEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getBasicType() {
return basicTypeEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getBasicType_Atomictype() {
return (EAttribute)basicTypeEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getConstraint() {
return constraintEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getConstraint_Constraint() {
return (EAttribute)constraintEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EEnum getAtomicType() {
return atomicTypeEEnum;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ParametersFactory getParametersFactory() {
return (ParametersFactory)getEFactoryInstance();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents() {
if (isCreated) return;
isCreated = true;
// Create classes and their features
parameterEClass = createEClass(PARAMETER);
createEAttribute(parameterEClass, PARAMETER__NAME);
createEReference(parameterEClass, PARAMETER__TYPE);
parameterSpecificationEClass = createEClass(PARAMETER_SPECIFICATION);
createEReference(parameterSpecificationEClass, PARAMETER_SPECIFICATION__TYPES);
createEReference(parameterSpecificationEClass, PARAMETER_SPECIFICATION__PARAMETERS);
typeEClass = createEClass(TYPE);
createEAttribute(typeEClass, TYPE__NAME);
createEReference(typeEClass, TYPE__CONSTRAINTS);
compositeTypeEClass = createEClass(COMPOSITE_TYPE);
createEReference(compositeTypeEClass, COMPOSITE_TYPE__INNERTYPES);
basicTypeEClass = createEClass(BASIC_TYPE);
createEAttribute(basicTypeEClass, BASIC_TYPE__ATOMICTYPE);
constraintEClass = createEClass(CONSTRAINT);
createEAttribute(constraintEClass, CONSTRAINT__CONSTRAINT);
// Create enums
atomicTypeEEnum = createEEnum(ATOMIC_TYPE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void initializePackageContents() {
if (isInitialized) return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Create type parameters
// Set bounds for type parameters
// Add supertypes to classes
compositeTypeEClass.getESuperTypes().add(this.getType());
basicTypeEClass.getESuperTypes().add(this.getType());
// Initialize classes, features, and operations; add parameters
initEClass(parameterEClass, Parameter.class, "Parameter", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getParameter_Name(), ecorePackage.getEString(), "name", null, 0, 1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getParameter_Type(), this.getType(), null, "type", null, 1, 1, Parameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(parameterSpecificationEClass, ParameterSpecification.class, "ParameterSpecification", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getParameterSpecification_Types(), this.getType(), null, "types", null, 0, -1, ParameterSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getParameterSpecification_Parameters(), this.getParameter(), null, "parameters", null, 0, -1, ParameterSpecification.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(typeEClass, Type.class, "Type", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getType_Name(), ecorePackage.getEString(), "name", null, 0, 1, Type.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getType_Constraints(), this.getConstraint(), null, "constraints", null, 0, -1, Type.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
| initEClass(compositeTypeEClass, CompositeType.class, "CompositeType", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); | 2 |
binarybird/Redress-Disassembler | src/main/java/redress/abi/generic/AbstractText.java | [
"public class Capstone {\n\n protected static abstract class OpInfo {};\n protected static abstract class UnionOpInfo extends Structure {};\n\n public static class UnionArch extends Union {\n public static class ByValue extends UnionArch implements Union.ByValue {};\n\n public Arm.UnionOpInfo arm;\n pub... | import capstone.Capstone;
import redress.abi.generic.visitors.AbstractContainerVisitor;
import redress.abi.generic.visitors.AbstractStructureVisitor;
import redress.memory.address.AbstractAddress;
import redress.memory.data.AbstractData;
import redress.memory.data.QWord;
import redress.util.B;
import java.nio.ByteOrder;
import java.util.HashSet;
import java.util.LinkedList; | package redress.abi.generic;
/**
* Created by jamesrichardson on 2/23/16.
*/
public abstract class AbstractText implements IContainer {
protected final LinkedList<IStructure> children = new LinkedList<>();
protected final IStructure parent;
protected IContainer previousSibling;
protected IContainer nextSibling;
protected AbstractAddress beginAddress;
protected AbstractAddress endAddress;
protected final HashSet<String> comment = new HashSet<>(); | protected final Capstone.CsInsn instruction; | 0 |
marcelothebuilder/webpedidos | src/main/java/com/github/marcelothebuilder/webpedidos/controller/CadastroClienteBean.java | [
"public class EnderecoAlteradoEvent {\n\n\tprivate Endereco endereco;\n\tprivate boolean novo;\n\n\tpublic EnderecoAlteradoEvent() {\n\t}\n\n\tpublic EnderecoAlteradoEvent(Endereco endereco) {\n\t\tthis();\n\t\tthis.setEndereco(endereco);\n\t}\n\n\tpublic EnderecoAlteradoEvent(Endereco endereco, boolean novo) {\n\t... | import java.io.Serializable;
import java.util.List;
import javax.enterprise.event.Observes;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.PersistenceException;
import com.github.marcelothebuilder.webpedidos.controller.events.EnderecoAlteradoEvent;
import com.github.marcelothebuilder.webpedidos.model.cliente.Cliente;
import com.github.marcelothebuilder.webpedidos.model.cliente.TipoPessoa;
import com.github.marcelothebuilder.webpedidos.model.endereco.Endereco;
import com.github.marcelothebuilder.webpedidos.repository.Clientes;
import com.github.marcelothebuilder.webpedidos.service.NegocioException; | package com.github.marcelothebuilder.webpedidos.controller;
@Named
@ViewScoped
public class CadastroClienteBean implements Serializable {
private static final long serialVersionUID = 1L;
private @Inject Cliente cliente; | private @Inject Clientes clientes; | 4 |
bingoogolapple/Android-Training | SmartBulb/src/com/bingoogol/smartbulb/ui/SplashActivity.java | [
"public class Config {\n\tprivate static final String TAG = \"Config\";\n\tprivate String deviceType = \"googol\";\n\n\t/**\n\t * 异步认证用户\n\t * \n\t * @param lightCallback\n\t * 操作灯泡的回调接口\n\t */\n\tpublic void createUser(LightCallback lightCallback) {\n\t\tfinal LightHandler lightHandler = new LightHandle... | import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import com.bingoogol.smartbulb.R;
import com.bingoogol.smartbulb.engine.Config;
import com.bingoogol.smartbulb.engine.HueRestClient;
import com.bingoogol.smartbulb.engine.LightHandler.LightCallback;
import com.bingoogol.smartbulb.ui.sub.LinkButtonDialog;
import com.bingoogol.smartbulb.ui.sub.SetWifiDialog;
import com.bingoogol.smartbulb.util.ConnectivityUtil;
import com.bingoogol.smartbulb.util.Constants;
import com.bingoogol.smartbulb.util.Logger;
import com.bingoogol.smartbulb.util.ToastUtil; | package com.bingoogol.smartbulb.ui;
/**
* 欢迎界面,在这个界面认证用户
*
* @author 王浩 bingoogol@sina.com
*/
public class SplashActivity extends GenericActivity {
private static final String TAG = "SplashActivity";
private Config config = new Config();
private ProgressDialog pd;
private LightCallback lightCallback = new LightCallback() {
@Override
public void pressLinkBtn() {
Logger.i(TAG, "打开按钮对话框");
pd.dismiss();
new LinkButtonDialog(SplashActivity.this).show();
}
@Override
public void wifiError() {
Logger.i(TAG, "打开wifi对话框");
pd.dismiss();
new SetWifiDialog(SplashActivity.this).show();
}
@Override
public void onSuccess(Object obj) {
pd.dismiss();
app.addSp("username", (String) obj);
openMainActivity();
}
@Override
public void onFailure() {
ToastUtil.makeText(app, R.string.auth_failure);
pd.dismiss();
auth();
}
@Override
public void unauthorized() {
Logger.e(TAG, "用户名失效");
pd.dismiss();
app.addSp("username", "");
auth();
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { | if (requestCode == Constants.activity.OPEN_WIFI_SETTINGS) { | 6 |
daneren2005/Subsonic | app/src/main/java/github/daneren2005/dsub/util/UpdateHelper.java | [
"public class DownloadFile implements BufferFile {\n private static final String TAG = DownloadFile.class.getSimpleName();\n private static final int MAX_FAILURES = 5;\n private final Context context;\n private final MusicDirectory.Entry song;\n private final File partialFile;\n private final File... | import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.RatingBar;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import github.daneren2005.dsub.R;
import github.daneren2005.dsub.domain.Artist;
import github.daneren2005.dsub.domain.MusicDirectory;
import github.daneren2005.dsub.domain.MusicDirectory.Entry;
import github.daneren2005.dsub.fragments.SubsonicFragment;
import github.daneren2005.dsub.service.DownloadFile;
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.view.UpdateView; | /*
This file is part of Subsonic.
Subsonic 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.
Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2015 (C) Scott Jackson
*/
package github.daneren2005.dsub.util;
public final class UpdateHelper {
private static final String TAG = UpdateHelper.class.getSimpleName();
public static void toggleStarred(Context context, Entry entry) {
toggleStarred(context, entry, null);
}
public static void toggleStarred(final Context context, final Entry entry, final OnStarChange onStarChange) {
toggleStarred(context, Arrays.asList(entry), onStarChange);
}
public static void toggleStarred(Context context, List<Entry> entries) {
toggleStarred(context, entries, null);
}
public static void toggleStarred(final Context context, final List<Entry> entries, final OnStarChange onStarChange) {
if(entries.isEmpty()) {
return;
}
final Entry firstEntry = entries.get(0);
final boolean starred = !firstEntry.isStarred();
for(Entry entry: entries) {
entry.setStarred(starred);
}
if(onStarChange != null) {
onStarChange.entries = entries;
onStarChange.starChange(starred);
}
new SilentBackgroundTask<Void>(context) {
@Override
protected Void doInBackground() throws Throwable { | MusicService musicService = MusicServiceFactory.getMusicService(context); | 3 |
programingjd/okserver | src/samples/java/info/jdavid/ok/server/samples/EchoHttpServer.java | [
"@SuppressWarnings({ \"WeakerAccess\" })\npublic class RequestHandlerChain extends AbstractRequestHandler {\n\n public static void main(final String[] args) {\n cmd(args);\n }\n\n @SuppressWarnings(\"UnusedReturnValue\")\n static HttpServer cmd(final String[] args) {\n //final String[] args = new String[]... | import javax.annotation.Nullable;
import info.jdavid.ok.server.RequestHandlerChain;
import info.jdavid.ok.server.handler.RegexHandler;
import info.jdavid.ok.server.handler.Request;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import info.jdavid.ok.server.HttpServer;
import info.jdavid.ok.server.Response;
import info.jdavid.ok.server.StatusLines;
import okio.Buffer;
import okio.BufferedSource; | package info.jdavid.ok.server.samples;
@SuppressWarnings("WeakerAccess")
public class EchoHttpServer {
private final HttpServer mServer;
public EchoHttpServer() {
this(8080);
}
public EchoHttpServer(final int port) {
mServer = new HttpServer().
requestHandler(new RequestHandlerChain().add(new EchoHandler())).
port(port);
}
public void start() {
mServer.start();
}
@SuppressWarnings("unused")
public void stop() {
mServer.shutdown();
}
public static void main(final String[] args) {
new EchoHttpServer().start();
}
private static Response.Builder echo(@Nullable final Buffer requestBody, @Nullable final MediaType mime) { | if (requestBody == null) return new Response.Builder().statusLine(StatusLines.OK).noBody(); | 5 |
recommenders/rival | rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/ranksys/RanksysRecommenderRunner.java | [
"public class TemporalDataModel<U, I> extends DataModel<U, I> implements TemporalDataModelIF<U, I> {\n\n /**\n * The map with the timestamps between users and items.\n */\n protected Map<U, Map<I, Set<Long>>> userItemTimestamps;\n\n /**\n * Default constructor.\n */\n public TemporalData... | import es.uam.eps.ir.ranksys.core.Recommendation;
import es.uam.eps.ir.ranksys.core.preference.ConcatPreferenceData;
import es.uam.eps.ir.ranksys.core.preference.PreferenceData;
import es.uam.eps.ir.ranksys.core.preference.SimplePreferenceData;
import es.uam.eps.ir.ranksys.fast.index.FastItemIndex;
import es.uam.eps.ir.ranksys.fast.index.FastUserIndex;
import es.uam.eps.ir.ranksys.fast.index.SimpleFastItemIndex;
import es.uam.eps.ir.ranksys.fast.index.SimpleFastUserIndex;
import es.uam.eps.ir.ranksys.fast.preference.FastPreferenceData;
import es.uam.eps.ir.ranksys.fast.preference.SimpleFastPreferenceData;
import es.uam.eps.ir.ranksys.mf.Factorization;
import es.uam.eps.ir.ranksys.mf.Factorizer;
import es.uam.eps.ir.ranksys.nn.item.neighborhood.ItemNeighborhood;
import es.uam.eps.ir.ranksys.nn.item.neighborhood.TopKItemNeighborhood;
import es.uam.eps.ir.ranksys.nn.item.sim.ItemSimilarity;
import es.uam.eps.ir.ranksys.nn.user.neighborhood.TopKUserNeighborhood;
import es.uam.eps.ir.ranksys.nn.user.neighborhood.UserNeighborhood;
import es.uam.eps.ir.ranksys.nn.user.sim.UserSimilarity;
import es.uam.eps.ir.ranksys.rec.Recommender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.DoubleUnaryOperator;
import net.recommenders.rival.core.TemporalDataModel;
import net.recommenders.rival.core.TemporalDataModelIF;
import net.recommenders.rival.recommend.frameworks.AbstractRunner;
import net.recommenders.rival.recommend.frameworks.RecommendationRunner;
import net.recommenders.rival.recommend.frameworks.RecommenderIO;
import net.recommenders.rival.recommend.frameworks.exceptions.RecommenderException;
import org.ranksys.core.util.tuples.Tuple2od;
import org.ranksys.formats.index.ItemsReader;
import org.ranksys.formats.index.UsersReader;
import org.ranksys.formats.parsing.Parsers;
import org.ranksys.formats.preference.SimpleRatingPreferencesReader; | /*
* Copyright 2017 recommenders.net.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.recommenders.rival.recommend.frameworks.ranksys;
/**
* A runner for RankSys-based recommenders.
*
* @author <a href="http://github.com/abellogin">Alejandro</a>
*/
public class RanksysRecommenderRunner extends AbstractRunner<Long, Long> {
public static final double DEFAULT_ALPHA = 1.0;
public static final double DEFAULT_LAMBDA = 0.1;
public static final int DEFAULT_Q = 1;
/**
* Default constructor.
*
* @param props the properties.
*/
public RanksysRecommenderRunner(final Properties props) {
super(props);
}
@Override | public TemporalDataModelIF<Long, Long> run(final RUN_OPTIONS opts) throws RecommenderException, IOException { | 5 |
bgandon/killbill-simple-tax-plugin | src/test/java/org/killbill/billing/plugin/simpletax/util/TestInvoiceHelpers.java | [
"@Nonnull\npublic static BigDecimal amountWithAdjustments(@Nonnull InvoiceItem item,\n @Nonnull Multimap<UUID, InvoiceItem> allAdjustments) {\n Iterable<InvoiceItem> adjustments = allAdjustments.get(item.getId());\n BigDecimal amount = sumItems(adjustments);\n if (item.getAmount() != null) {\n ... | import static com.google.common.collect.Lists.newArrayList;
import static java.math.BigDecimal.ONE;
import static java.math.BigDecimal.TEN;
import static java.math.BigDecimal.ZERO;
import static java.math.BigDecimal.valueOf;
import static java.util.Arrays.asList;
import static org.killbill.billing.plugin.simpletax.util.InvoiceHelpers.amountWithAdjustments;
import static org.killbill.billing.plugin.simpletax.util.InvoiceHelpers.sumAmounts;
import static org.killbill.billing.plugin.simpletax.util.InvoiceHelpers.sumItems;
import static org.killbill.billing.test.helpers.TestUtil.assertEqualsIgnoreScale;
import java.math.BigDecimal;
import java.util.UUID;
import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.test.helpers.InvoiceItemBuilder;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap; | /*
* Copyright 2015 Benjamin Gandon
*
* 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.killbill.billing.plugin.simpletax.util;
/**
* Tests for {@link InvoiceHelpers}.
*
* @author Benjamin Gandon
*/
@SuppressWarnings("javadoc")
public class TestInvoiceHelpers {
private static final BigDecimal NINE = valueOf(9L);
private static final BigDecimal ELEVEN = valueOf(11L);
private static final BigDecimal EIGHTTEEN = valueOf(18L);
private InvoiceItem itemA, itemB, itemC, itemD;
@BeforeClass
public void init() {
itemA = new InvoiceItemBuilder()//
.withAmount(TEN)//
.build();
itemB = new InvoiceItemBuilder()//
.withAmount(null)//
.build();
itemC = new InvoiceItemBuilder()//
.withAmount(ONE)//
.build();
itemD = new InvoiceItemBuilder()//
.withAmount(ONE.negate())//
.build();
}
/** Helper assert that ignores {@linkplain BigDecimal#scale() scales}. */
private static void assertEquals(BigDecimal actual, BigDecimal expected) {
assertEqualsIgnoreScale(actual, expected);
}
@Test(groups = "fast", expectedExceptions = IllegalAccessException.class)
public void shouldBeAbstractClass() throws Exception {
InvoiceHelpers.class.getDeclaredConstructor().newInstance();
}
@Test(groups = "fast")
public void sumItemsShouldReturnZeroForNullInput() {
// Expect
assertEquals(sumItems(null), ZERO);
}
@Test(groups = "fast", expectedExceptions = NullPointerException.class)
public void sumItemsShouldThrowNPEOnNullItem() {
// Expect NPE
sumItems(newArrayList(itemA, null, itemB));
}
@Test(groups = "fast")
public void sumItemsShouldSumPositiveItems() {
// Given
Iterable<InvoiceItem> items = newArrayList(itemA, itemB, itemC);
// Expect
assertEquals(sumItems(items), ELEVEN);
}
@Test(groups = "fast")
public void sumItemsShouldSumNegativeItems() {
// Given
Iterable<InvoiceItem> items = newArrayList(itemA, itemB, itemD);
// Expect
assertEquals(sumItems(items), NINE);
}
/** Shortcut for {@link ImmutableMultimap#of(Object, Object)} */
private static <K, V> Multimap<K, V> multimap(K k1, V v1) {
return ImmutableMultimap.of(k1, v1);
}
@Test(groups = "fast")
public void amountWithAdjustmentsShouldIgnoreInexistentAdjustments() {
// Given
Multimap<UUID, InvoiceItem> adjustments = multimap(itemC.getId(), itemD);
// Expect | assertEquals(amountWithAdjustments(itemA, adjustments), TEN); | 0 |
boaglio/spring-boot-greendogdelivery-casadocodigo | src/main/java/com/boaglio/casadocodigo/greendogdelivery/controller/PedidoController.java | [
"@Entity\npublic class Cliente {\n\n\t@Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\n @NotNull\n @Length(min=2, max=30,message=\"O tamanho do nome deve ser entre {min} e {max} caracteres\")\n\tprivate String nome;\n\n @NotNull\n @Length(min=2, max=300,message=\"O tam... | import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.boaglio.casadocodigo.greendogdelivery.domain.Cliente;
import com.boaglio.casadocodigo.greendogdelivery.domain.Item;
import com.boaglio.casadocodigo.greendogdelivery.domain.Pedido;
import com.boaglio.casadocodigo.greendogdelivery.repository.ClienteRepository;
import com.boaglio.casadocodigo.greendogdelivery.repository.ItemRepository;
import com.boaglio.casadocodigo.greendogdelivery.repository.PedidoRepository;
import com.boaglio.casadocodigo.greendogdelivery.service.AtualizaEstoque; |
package com.boaglio.casadocodigo.greendogdelivery.controller;
@Controller
@RequestMapping("/pedidos")
public class PedidoController {
private final AtualizaEstoque atualizaEstoque;
private final PedidoRepository pedidoRepository;
private final ItemRepository itemRepository;
private final ClienteRepository clienteRepository;
private final String ITEM_URI = "pedidos/";
public PedidoController(PedidoRepository pedidoRepository,ItemRepository itemRepository,ClienteRepository clienteRepository,AtualizaEstoque atualizaEstoque) {
this.pedidoRepository = pedidoRepository;
this.itemRepository = itemRepository;
this.clienteRepository = clienteRepository;
this.atualizaEstoque = atualizaEstoque;
}
@GetMapping("/")
public ModelAndView list() { | Iterable<Pedido> pedidos = this.pedidoRepository.findAll(); | 2 |
zetbaitsu/CodePolitan | app/src/main/java/id/zelory/codepolitan/controller/TagController.java | [
"public abstract class BenihController<P extends BenihController.Presenter>\n{\n protected P presenter;\n\n public BenihController(P presenter)\n {\n this.presenter = presenter;\n Timber.tag(getClass().getSimpleName());\n }\n\n public abstract void saveState(Bundle bundle);\n\n publi... | import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import id.zelory.benih.controller.BenihController;
import id.zelory.benih.util.BenihScheduler;
import id.zelory.benih.util.BenihWorker;
import id.zelory.codepolitan.controller.event.ErrorEvent;
import id.zelory.codepolitan.data.model.Tag;
import id.zelory.codepolitan.data.api.CodePolitanApi;
import id.zelory.codepolitan.data.database.DataBaseHelper;
import rx.Observable;
import timber.log.Timber; | /*
* Copyright (c) 2015 Zelory.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package id.zelory.codepolitan.controller;
/**
* Created on : August 6, 2015
* Author : zetbaitsu
* Name : Zetra
* Email : zetra@mail.ugm.ac.id
* GitHub : https://github.com/zetbaitsu
* LinkedIn : https://id.linkedin.com/in/zetbaitsu
*/
public class TagController extends BenihController<TagController.Presenter>
{
private List<Tag> tags;
private List<Tag> popularTags;
public TagController(Presenter presenter)
{
super(presenter);
}
public void loadTags(int page)
{
presenter.showLoading();
CodePolitanApi.pluck()
.getApi()
.getTags(page)
.compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))
.flatMap(articleListResponse -> Observable.from(articleListResponse.getResult()))
.map(tag -> {
tag.setFollowed(DataBaseHelper.pluck().isFollowed(tag));
return tag;
})
.toList()
.subscribe(tags -> {
BenihWorker.pluck()
.doInNewThread(() -> {
if (page == 1)
{
this.tags = tags;
} else
{
this.tags.addAll(tags);
}
})
.subscribe(o -> {
if (presenter != null)
{
presenter.showPopularTags(tags);
}
});
if (presenter != null)
{
presenter.dismissLoading();
}
}, throwable -> {
if (presenter != null)
{
Timber.d(throwable.getMessage()); | presenter.showError(new Throwable(ErrorEvent.LOAD_LIST_TAG)); | 3 |
WillemJiang/acmeair | acmeair-booking-service/src/test/java/com/acmeair/web/FlightsRESTTest.java | [
"@SpringBootApplication(scanBasePackages = \"com.acmeair.web\")\npublic class FlightRestTestApplication extends SpringBootServletInitializer {\n\n protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {\n\n return builder.sources(FlightRestTestApplication.class);\n }\n\n @Ov... | import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.FlightRestTestApplication;
import com.acmeair.entities.Flight;
import com.acmeair.morphia.entities.FlightImpl;
import com.acmeair.service.BookingService;
import com.acmeair.service.FlightService;
import com.acmeair.service.UserService;
import com.acmeair.web.dto.FlightInfo;
import com.acmeair.web.dto.TripFlightOptions;
import com.acmeair.web.dto.TripLegInfo;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when; | package com.acmeair.web;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = FlightRestTestApplication.class)
@ActiveProfiles({"test", "dev"})
public class FlightsRESTTest {
@MockBean
private UserService customerService;
@MockBean
private FlightService flightService;
@MockBean
private BookingService bookingService;
@Autowired
private TestRestTemplate restTemplate;
private final Calendar calendar = Calendar.getInstance();
private Flight departFlight;
private Flight returnFlight;
@Before
public void setUp() throws Exception {
FixtureFactoryLoader.loadTemplates("com.acmeair.flight.templates");
| departFlight = Fixture.from(FlightImpl.class).gimme("valid"); | 2 |
naomiHauret/OdysseeDesMaths | core/src/com/odysseedesmaths/minigames/coffeePlumbing/PipesScreen.java | [
"public class Musique {\n private static Music currentMusic = null;\n private static String currentFile = null;\n private static int volume;\n\n private Musique() {}\n\n public static Music getCurrent() {\n return currentMusic;\n }\n\n public static void setCurrent(String fileName) {\n ... | import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.odysseedesmaths.Musique;
import com.odysseedesmaths.minigames.coffeePlumbing.Sprite.KoffeeMeter;
import com.odysseedesmaths.minigames.coffeePlumbing.Sprite.Vanne;
import com.odysseedesmaths.minigames.coffeePlumbing.map.CoffeeLevel;
import com.odysseedesmaths.minigames.coffeePlumbing.map.OrthogonalTiledMapRendererWithKoffee;
import java.util.Iterator; | package com.odysseedesmaths.minigames.coffeePlumbing;
public class PipesScreen implements Screen {
private CoffeePlumbing minigame;
private OrthographicCamera camera;
private Viewport viewport;
private int width, height;
private CoffeeLevel level;
private Stage stage;
private OrthogonalTiledMapRendererWithKoffee mapRenderer; //TODO: mettre cette classe en static
public PipesScreen(final CoffeePlumbing game, String map){
minigame = game;
width = Gdx.graphics.getWidth()/2;
height = Gdx.graphics.getHeight()/2;
camera = new OrthographicCamera();
viewport = new StretchViewport(width,height,camera);
stage = new Stage(viewport);
level = new CoffeeLevel(map);
mapRenderer = new OrthogonalTiledMapRendererWithKoffee(level.get_map());
init();
}
public void init(){
level.buildLevel(); | Iterator<Vanne> itVanne = level.get_vannes().iterator(); | 2 |
nichbar/Aequorea | app/src/main/java/nich/work/aequorea/ui/activitiy/AuthorActivity.java | [
"public class Constants {\n public static final String AUTHOR = \"author\";\n public static final String TAG = \"tag\";\n public static final String ARTICLE_ID = \"article_id\";\n public static final String AUTHOR_ID = \"author_id\";\n public static final String TAG_ID = \"tag_id\";\n public stati... | import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import nich.work.aequorea.R;
import nich.work.aequorea.common.Constants;
import nich.work.aequorea.common.utils.DisplayUtils;
import nich.work.aequorea.common.utils.ImageHelper;
import nich.work.aequorea.common.utils.ThemeHelper;
import nich.work.aequorea.model.SimpleArticleListModel;
import nich.work.aequorea.model.entity.Author;
import nich.work.aequorea.model.entity.Data;
import nich.work.aequorea.presenter.AuthorPresenter;
import nich.work.aequorea.ui.adapter.SimpleArticleListAdapter; | package nich.work.aequorea.ui.activitiy;
public class AuthorActivity extends SimpleArticleListActivity {
private boolean mIsAuthorDetailShowing = true;
private static final int ANIMATE_SHOW = 1;
private static final int ANIMATE_HIDE = 0;
private Author mAuthor;
@BindView(R.id.tv_introduction)
protected TextView mIntroductionTv;
@BindView(R.id.tv_article_count)
protected TextView mArticleCountTv;
@BindView(R.id.iv_author)
protected ImageView mAuthorIv;
@BindView(R.id.container_collapsing_toolbar)
protected CollapsingToolbarLayout mCollapsingToolbarLayout;
@BindView(R.id.appbar)
protected AppBarLayout mAppBar;
private AppBarLayout.OnOffsetChangedListener mOffsetListener = new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (verticalOffset >= -15) {
showAuthorDetail();
} else {
hideAuthorDetail();
}
}
};
@Override
protected int getContentViewId() {
return R.layout.activity_author;
}
@Override
protected void initModel() {
mModel = new SimpleArticleListModel();
mModel.setId((int) getIntent().getLongExtra(Constants.AUTHOR_ID, 0));
if (getIntent().getExtras() != null) {
mAuthor = (Author) getIntent().getExtras().get(Constants.AUTHOR);
}
}
@Override
protected void initView() {
ButterKnife.bind(this);
mToolbar.setNavigationIcon(R.drawable.icon_ab_back_material);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
mCollapsingToolbarLayout.setTitle(" ");
mCoordinatorLayout.setPadding(0, DisplayUtils.getStatusBarHeight(getResources()), 0, 0);
mAdapter = new SimpleArticleListAdapter(this, null);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addOnScrollListener(mScrollListener);
mAppBar.addOnOffsetChangedListener(mOffsetListener);
if (mAuthor != null) {
updateAuthorImg(mAuthor);
}
setStatusBarStyle();
}
@Override
protected void initPresenter() { | mPresenter = new AuthorPresenter(); | 7 |
gugemichael/nesty | core/src/main/java/org/nesty/core/server/rest/controller/ControllerMethodDescriptor.java | [
"public class ControllerParamsNotMatchException extends Exception {\n\n public ControllerParamsNotMatchException(String msg) {\n super(msg);\n }\n}",
"public class ControllerParamsParsedException extends Exception {\n\n public ControllerParamsParsedException(String msg) {\n super(msg);\n ... | import org.nesty.commons.annotations.Header;
import org.nesty.commons.annotations.PathVariable;
import org.nesty.commons.annotations.RequestBody;
import org.nesty.commons.annotations.RequestParam;
import org.nesty.commons.exception.ControllerParamsNotMatchException;
import org.nesty.commons.exception.ControllerParamsParsedException;
import org.nesty.commons.exception.SerializeException;
import org.nesty.commons.utils.SerializeUtils;
import org.nesty.core.server.rest.HttpContext;
import org.nesty.core.server.rest.HttpSession;
import org.nesty.core.server.rest.URLResource;
import org.nesty.core.server.rest.controller.ControllerMethodDescriptor.MethodParams.AnnotationType;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; | package org.nesty.core.server.rest.controller;
/**
* controller method descriptor include annotation params
* <p>
* Author : Michael
* Date : March 07, 2016
*/
public class ControllerMethodDescriptor {
// method
private Method method;
// method param include param class type and param annotation
private MethodParams[] params;
// target instance
private Object target;
public ControllerMethodDescriptor(String URI, ControllerClassDescriptor clazz, Method method) {
this.method = method;
String key, value;
Annotation[][] annotations = method.getParameterAnnotations();
Class<?>[] paramsTypes = method.getParameterTypes();
int total = paramsTypes.length;
this.params = new MethodParams[total];
// TODO : ugly code here !! messy
//
for (int i = 0; i != total; i++) {
if (paramsTypes[i] == HttpSession.class) {
params[i] = new MethodParams(null, HttpSession.class);
params[i].annotationType = AnnotationType.HTTP_SESSION;
} else {
params[i] = new MethodParams(annotations[i][0], paramsTypes[i]);
if (params[i].annotation instanceof Header) {
params[i].annotationType = AnnotationType.HEADER;
} else if (params[i].annotation instanceof RequestParam) {
params[i].annotationType = AnnotationType.REQUEST_PARAM;
} else if (params[i].annotation instanceof RequestBody) {
params[i].annotationType = AnnotationType.REQUEST_BODY;
} else if (params[i].annotation instanceof PathVariable) {
params[i].annotationType = AnnotationType.PATH_VARIABLE;
String name = ((PathVariable) params[i].annotation).value();
// findout the index of correspond variable
String[] pathVariable = URI.split("/");
int index = 0;
for (String path : pathVariable) {
if (path == null || path.isEmpty())
continue; | if (path.charAt(0) == URLResource.VARIABLE && path.length() > 2) { | 6 |
iostackproject/SDGen | src/com/ibm/generation/user/MotifDataGenerator.java | [
"public abstract class AbstractChunkCharacterization implements Serializable, Cloneable{\n\t\n\tprivate static final long serialVersionUID = 1L;\n\t/*Size of the chunk during the scan process*/\n\tprotected int size = 0; \n\t/*Amount of non unique data of this chunk across a dataset*/\n\tprotected int deduplicatedD... | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import com.ibm.characterization.AbstractChunkCharacterization;
import com.ibm.characterization.Histogram;
import com.ibm.characterization.IntegersHistogram;
import com.ibm.characterization.user.MotifChunkCharacterization;
import com.ibm.generation.AbstractDataGenerator; | /*
* Copyright (C) 2014 Raul Gracia-Tinedo
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see http://www.gnu.org/licenses/.
*/
package com.ibm.generation.user;
/**
*
*/
public class MotifDataGenerator extends AbstractDataGenerator{
public static int DEFAULT_MOTIF_BUFFER_SIZE = 268;
private static int MAX_CHUNK_SIZE = DEFAULT_MOTIF_BUFFER_SIZE;
private static final int MIN_NUM_SYMBOLS = 8;
private static final int NUM_REPETITIONS_BUFFER = 1000;
private double uniqueness;
| private MotifChunkCharacterization myChunk = null; | 3 |
Condroidapp/android | Condroid/src/main/java/cz/quinix/condroid/ui/activities/WelcomeActivity.java | [
"public abstract class AListenedAsyncTask<Progress, Result> extends RoboAsyncTask<Result> {\r\n\r\n\t@Inject\r\n\tprivate Provider<Context> contextProvider;\r\n\r\n\tprivate ITaskListener listener;\r\n\r\n\tprivate Result results;\r\n\r\n\tpublic AListenedAsyncTask(ITaskListener listener) {\r\n\t\tsuper(listener.ge... | import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.github.rtyley.android.sherlock.roboguice.activity.RoboSherlockFragmentActivity;
import com.google.inject.Inject;
import java.util.List;
import cz.quinix.condroid.R;
import cz.quinix.condroid.abstracts.AListenedAsyncTask;
import cz.quinix.condroid.abstracts.ITaskListener;
import cz.quinix.condroid.database.DataProvider;
import cz.quinix.condroid.database.DatabaseLoader;
import cz.quinix.condroid.loader.ConventionLoader;
import cz.quinix.condroid.model.Convention;
import cz.quinix.condroid.ui.adapters.EventAdapter;
import cz.quinix.condroid.ui.dataLoading.Downloader;
import roboguice.inject.InjectView;
| package cz.quinix.condroid.ui.activities;
public class WelcomeActivity extends RoboSherlockFragmentActivity implements ITaskListener {
@Inject
private DataProvider database;
@InjectView(R.id.pbEvents)
private ProgressBar progressBar;
@InjectView(R.id.lEventSelector)
private ListView listView;
@InjectView(R.id.layProgressEvents)
private LinearLayout layProgressEvents;
@InjectView(R.id.layEventSelector)
private LinearLayout layEventSelector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.setProperty("org.joda.time.DateTimeZone.Provider",
"cz.quinix.condroid.FastJodaTimeZoneProvider");
this.setContentView(R.layout.welcome);
this.load();
}
private void load() {
layEventSelector.setVisibility(View.GONE);
layProgressEvents.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
boolean force = this.getIntent().getBooleanExtra("force", false);
if (database.hasData() && !force) {
Log.d(this.getClass().getName(), "Screen goto: Annotation list");
this.startProgramActivity();
return;
}
ConventionLoader task = new ConventionLoader(this);
task.execute();
}
@Override
public void onTaskCompleted(AListenedAsyncTask<?, ?> task) {
if (task instanceof ConventionLoader) {
this.onEventsLoaded(((ConventionLoader) task).getResults());
} else if (task instanceof DatabaseLoader) {
this.showMessage();
this.startProgramActivity();
} else {
throw new IllegalArgumentException("Instance of " + task.getClass().getName() + " is not supported in this handler.");
}
}
private void showMessage() {
if (!database.getCon().getMessage().equals("")) {
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setTitle(database.getCon().getName());
ab.setMessage(database.getCon().getMessage());
ab.setCancelable(true);
ab.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
ab.create().show();
}
}
private void onEventsLoaded(final List<Convention> results) {
EventAdapter adapter = new EventAdapter(this, results);
listView.setAdapter(adapter);
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Convention item = results.get(position);
| Downloader loader = new Downloader(WelcomeActivity.this, item);
| 7 |
brwe/es-token-plugin | src/main/java/org/elasticsearch/script/pmml/VectorScriptFactory.java | [
"public class TokenPlugin extends Plugin implements ScriptPlugin, ActionPlugin, SearchPlugin, IngestPlugin {\n\n private final Settings settings;\n private final boolean transportClientMode;\n private final IngestAnalysisService ingestAnalysisService;\n\n public TokenPlugin(Settings settings) {\n ... | import org.elasticsearch.search.lookup.LeafIndexLookup;
import java.util.Map;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.plugin.TokenPlugin;
import org.elasticsearch.script.AbstractSearchScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.NativeScriptFactory;
import org.elasticsearch.ml.modelinput.DataSource;
import org.elasticsearch.ml.modelinput.EsDataSource;
import org.elasticsearch.ml.modelinput.VectorRangesToVector;
import org.elasticsearch.ml.modelinput.VectorRangesToVectorJSON;
import org.elasticsearch.search.lookup.LeafDocLookup; | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.script.pmml;
/**
* Can read json def and return sparse vectors with tfs.
*/
public class VectorScriptFactory implements NativeScriptFactory {
public static final String NAME = "doc_to_vector";
public VectorScriptFactory() {
}
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) {
if (params == null || params.containsKey("spec") == false) {
throw new IllegalArgumentException("the spec parameter is required");
}
Map<String, Object> spec = XContentMapValues.nodeMapValue(params.get("spec"), "spec");
// TODO: Add caching mechanism
VectorRangesToVector features = new VectorRangesToVectorJSON(spec);
return new VectorizerScript(features);
}
@Override
public boolean needsScores() {
// TODO: can we reliably know if a vectorizer script does not make use of _score
return false;
}
@Override
public String getName() {
return NAME;
}
public static class VectorizerScript extends AbstractSearchScript {
private final VectorRangesToVector features;
private DataSource dataSource;
/**
* Factory that is registered in
* {@link TokenPlugin#onModule(org.elasticsearch.script.ScriptModule)}
* method when the plugin is loaded.
*/
private VectorizerScript(VectorRangesToVector features) {
this.features = features; | dataSource = new EsDataSource() { | 2 |
msoute/vertx-deploy-tools | vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/service/DefaultDeployService.java | [
"public class DefaultRequestExecutor extends RequestExecutor {\n\n public DefaultRequestExecutor(Log log, Integer requestTimeout, Integer port, String authToken) {\n super(log, requestTimeout, port, authToken);\n }\n\n\n private AwsState executeRequest(final HttpPost postRequest) throws MojoExecutio... | import nl.jpoint.maven.vertx.executor.DefaultRequestExecutor;
import nl.jpoint.maven.vertx.mojo.DeployConfiguration;
import nl.jpoint.maven.vertx.request.DeployRequest;
import nl.jpoint.maven.vertx.request.Request;
import nl.jpoint.maven.vertx.utils.InstanceUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import java.util.List; | package nl.jpoint.maven.vertx.service;
public class DefaultDeployService extends DeployService {
private final DeployConfiguration activeConfiguration;
private final Integer port;
private final Integer requestTimeout;
public DefaultDeployService(DeployConfiguration activeConfiguration, final Integer port, final Integer requestTimeout, Log log) {
super(log);
this.activeConfiguration = activeConfiguration;
this.port = port;
this.requestTimeout = requestTimeout;
}
public void deploy(List<Request> deployModuleRequests, List<Request> deployArtifactRequests, List<Request> deployConfigRequests) throws MojoFailureException, MojoExecutionException {
DeployRequest deployRequest = new DeployRequest.Builder()
.withModules(deployModuleRequests)
.withArtifacts(deployArtifactRequests)
.withConfigs(activeConfiguration.isDeployConfig() ? deployConfigRequests : null)
.withElb(activeConfiguration.useElbStatusCheck())
.withRestart(activeConfiguration.doRestart())
.build();
final DefaultRequestExecutor executor = new DefaultRequestExecutor(getLog(), requestTimeout, port, activeConfiguration.getAuthToken());
getLog().info("Constructed deploy request with '" + deployConfigRequests.size() + "' configs, '" + deployArtifactRequests.size() + "' artifacts and '" + deployModuleRequests.size() + "' modules");
getLog().info("Executing deploy request, waiting for Vert.x to respond.... (this might take some time)");
getLog().debug("Sending request -> " + deployRequest.toJson(true));
| if (activeConfiguration.getHosts().stream().anyMatch(host -> !InstanceUtils.isReachable(host, port, host, getLog()))) { | 4 |
kevinmmarlow/Dreamer | volley/src/main/java/com/android/fancyblurdemo/volley/toolbox/JsonArrayRequest.java | [
"public class NetworkResponse {\n /**\n * Creates a new network response.\n * @param statusCode the HTTP status code\n * @param data Response body\n * @param headers Headers returned with this response, or null for none\n * @param notModified True if the server returned a 304 and the data was... | import com.android.fancyblurdemo.volley.NetworkResponse;
import com.android.fancyblurdemo.volley.ParseError;
import com.android.fancyblurdemo.volley.Response;
import com.android.fancyblurdemo.volley.Response.ErrorListener;
import com.android.fancyblurdemo.volley.Response.Listener;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.UnsupportedEncodingException; | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.fancyblurdemo.volley.toolbox;
/**
* A request for retrieving a {@link org.json.JSONArray} response body at a given URL.
*/
public class JsonArrayRequest extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* @param url URL to fetch the JSON from
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
super(Method.GET, url, null, listener, errorListener);
}
@Override | protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { | 2 |
ccol002/DiscreteMaths | src/discretemaths/examples/BasicPropositional.java | [
"public static Proof hyp(Form... forms) throws InvalidRuleException\n{\n\tProof pf = new Proof();\n\t\t\n\tfor (Form p:forms){\n\t\tif (!p.isWellFormed())\n\t\t\tthrow new InvalidRuleException(\"Malformed formula: \" + p);\n\t\tpf.proof.add(p);\n\t\tpf.reasons.add(new Hyp());\n\t\tpf.depths.add(pf.depth);\n\t}\n\tr... | import static discretemaths.Proof.hyp;
import static discretemaths.forms.Form.$;
import static discretemaths.forms.Form.and;
import static discretemaths.forms.Form.implies;
import static discretemaths.forms.Form.not;
import discretemaths.Proof;
import discretemaths.forms.Form; | package discretemaths.examples;
public class BasicPropositional {
public static void main(String[] args)throws Exception {
| Form f = and($("A"),and($("C"),$("B")));//A ^ (C ^ B) | 1 |
snowhow/cordova-plugin-gpstrack | src/android/org/java_websocket/WebSocketImpl.java | [
"public abstract class Draft {\n\n\t/**\n\t * Enum which represents the states a handshake may be in\n\t */\n\tpublic enum HandshakeState {\n\t\t/** Handshake matched this Draft successfully */\n\t\tMATCHED,\n\t\t/** Handshake is does not match this Draft */\n\t\tNOT_MATCHED\n\t}\n\t/**\n\t * Enum which represents ... | import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft.CloseHandshakeType;
import org.java_websocket.drafts.Draft.HandshakeState;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.exceptions.IncompleteHandshakeException;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.exceptions.InvalidHandshakeException;
import org.java_websocket.exceptions.WebsocketNotConnectedException;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.framing.Framedata;
import org.java_websocket.framing.Framedata.Opcode;
import org.java_websocket.framing.PingFrame;
import org.java_websocket.handshake.*;
import org.java_websocket.server.WebSocketServer.WebSocketWorker;
import org.java_websocket.util.Charsetfunctions;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SelectionKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; | /*
* Copyright (c) 2010-2017 Nathan Rajlich
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.java_websocket;
/**
* Represents one end (client or server) of a single WebSocketImpl connection.
* Takes care of the "handshake" phase, then allows for easy sending of
* text frames, and receiving frames through an event-based model.
*/
public class WebSocketImpl implements WebSocket {
public static int RCVBUF = 16384;
/**
* Activate debug mode for additional infos
*/
public static boolean DEBUG = false; // must be final in the future in order to take advantage of VM optimization
/**
* Queue of buffers that need to be sent to the client.
*/
public final BlockingQueue<ByteBuffer> outQueue;
/**
* Queue of buffers that need to be processed
*/
public final BlockingQueue<ByteBuffer> inQueue;
/**
* The listener to notify of WebSocket events.
*/
private final WebSocketListener wsl;
public SelectionKey key;
/**
* the possibly wrapped channel object whose selection is controlled by {@link #key}
*/
public ByteChannel channel;
/**
* Helper variable meant to store the thread which ( exclusively ) triggers this objects decode method.
**/
public volatile WebSocketWorker workerThread; // TODO reset worker?
/**
* When true no further frames may be submitted to be sent
*/
private volatile boolean flushandclosestate = false;
/**
* The current state of the connection
*/
private READYSTATE readystate = READYSTATE.NOT_YET_CONNECTED;
/**
* A list of drafts available for this websocket
*/ | private List<Draft> knownDrafts; | 0 |
romelo333/notenoughwands1.8.8 | src/main/java/romelo333/notenoughwands/setup/ClientProxy.java | [
"public class ConfigSetup {\n public static String CATEGORY_GENERAL = \"general\";\n public static String CATEGORY_WANDS = \"wandsettings\";\n public static String CATEGORY_MOVINGBLACKLIST = \"movingblacklist\";\n public static String CATEGORY_CAPTUREBLACKLIST = \"captureblacklist\";\n\n public stati... | import mcjty.lib.setup.DefaultClientProxy;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import romelo333.notenoughwands.ConfigSetup;
import romelo333.notenoughwands.Items.GenericWand;
import romelo333.notenoughwands.KeyBindings;
import romelo333.notenoughwands.KeyInputHandler;
import romelo333.notenoughwands.network.NEWPacketHandler;
import romelo333.notenoughwands.network.PacketGetProtectedBlocksAroundPlayer; | package romelo333.notenoughwands.setup;
public class ClientProxy extends DefaultClientProxy {
@Override
public void preInit(FMLPreInitializationEvent e) {
super.preInit(e);
MinecraftForge.EVENT_BUS.register(this);
}
@Override
public void init(FMLInitializationEvent e) {
super.init(e);
MinecraftForge.EVENT_BUS.register(new KeyInputHandler());
KeyBindings.init();
}
@SubscribeEvent
public void renderWorldLastEvent(RenderWorldLastEvent evt) {
Minecraft mc = Minecraft.getMinecraft();
EntityPlayerSP p = mc.player;
ItemStack heldItem = p.getHeldItem(EnumHand.MAIN_HAND);
if (heldItem.isEmpty()) {
return;
} | if (heldItem.getItem() instanceof GenericWand) { | 1 |
kevinKaiF/cango | cango-instance/src/main/java/com/bella/cango/instance/mysql/store/KafkaMysqlStore.java | [
"public class CangoInstanceCache {\n private static final ConcurrentHashMap<String, MysqlInstance> mysqlInstanceMap = new ConcurrentHashMap<>();\n private static final ConcurrentHashMap<String, OracleInstance> oracleInstanceMap = new ConcurrentHashMap<>();\n\n public static void addOracleInstance(String ke... | import com.alibaba.otter.canal.instance.manager.model.CanalParameter;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.position.Position;
import com.alibaba.otter.canal.store.AbstractCanalStoreScavenge;
import com.alibaba.otter.canal.store.CanalEventStore;
import com.alibaba.otter.canal.store.CanalStoreException;
import com.alibaba.otter.canal.store.CanalStoreScavenge;
import com.alibaba.otter.canal.store.model.Event;
import com.alibaba.otter.canal.store.model.Events;
import com.bella.cango.instance.cache.CangoInstanceCache;
import com.bella.cango.dto.CangoMsgDto;
import com.bella.cango.dto.ColumnDto;
import com.bella.cango.enums.EventType;
import com.bella.cango.instance.mysql.MysqlInstance;
import com.bella.cango.instance.mysql.MysqlParameter;
import com.bella.cango.message.producer.KafkaProducer;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit; | package com.bella.cango.instance.mysql.store;
/**
* The type Kafka mysql store.
*/
public class KafkaMysqlStore extends AbstractCanalStoreScavenge implements CanalEventStore<Event>, CanalStoreScavenge {
private static final Logger LOGGER = LoggerFactory.getLogger(KafkaMysqlStore.class);
private static KafkaProducer kafkaProducer;
protected MysqlParameter parameters;
protected String dbHost;
protected int dbPort;
public KafkaMysqlStore(CanalParameter parameters) {
this.parameters = (MysqlParameter) parameters;
initKafkaService();
if (parameters != null) {
List<InetSocketAddress> inetSocketAddresses = parameters.getDbAddresses();
if (CollectionUtils.isNotEmpty(inetSocketAddresses)) {
this.dbHost = inetSocketAddresses.get(0).getHostName();
this.dbPort = inetSocketAddresses.get(0).getPort();
} else {
LOGGER.error("host cannot null");
}
}
}
private void initKafkaService() {
if (kafkaProducer == null) {
synchronized (KafkaMysqlStore.class) {
if (kafkaProducer == null) {
kafkaProducer = KafkaProducer.KafkaProducerHolder.getInstance();
}
}
}
}
@Override
public void cleanAll() throws CanalStoreException {
}
@Override
public void cleanUntil(Position position) throws CanalStoreException {
}
@Override
public void ack(Position position) throws CanalStoreException {
}
@Override
public void put(List<Event> list) throws InterruptedException, CanalStoreException {
if (CollectionUtils.isNotEmpty(list)) {
for (Event event : list) {
CanalEntry.Entry entry = event.getEntry();
try {
CanalEntry.RowChange rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
CanalEntry.EventType eventType = rowChange.getEventType();
if (eventType == CanalEntry.EventType.INSERT || eventType == CanalEntry.EventType.UPDATE || eventType == CanalEntry.EventType.DELETE) {
List<CanalEntry.RowData> rowDatas = rowChange.getRowDatasList();
for (CanalEntry.RowData rowData : rowDatas) {
sendKafkaMsg(rowData, entry, eventType);
}
}
} catch (InvalidProtocolBufferException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
/**
* Send kafka msg.
*
* @param rowData the row data
* @param entry the entry
* @param eventType the event type
*/
private void sendKafkaMsg(CanalEntry.RowData rowData, CanalEntry.Entry entry, CanalEntry.EventType eventType) {
String schemaName = entry.getHeader().getSchemaName();
String tableName = entry.getHeader().getTableName();
String key = parameters.getCanalName();
String executeTime = "";
try {
executeTime = new DateTime(entry.getHeader().getExecuteTime()).toString("yyyy-MM-dd HH:mm:ss");
} catch (Exception e) {
executeTime = "";
}
LOGGER.info("mysqlInstance receive data,KEY:{}, EventType:{}, dbName:{}, tableName:{}, time:{}",
key,
eventType,
schemaName,
tableName,
executeTime);
| MysqlInstance mysqlInstance = CangoInstanceCache.getMysqlInstance(key); | 0 |
Lambda-3/DiscourseSimplification | src/main/java/org/lambda3/text/simplification/discourse/runner/discourse_tree/extraction/rules/PreAttributionExtractor.java | [
"public enum Relation {\n\n UNKNOWN,\n\n // Coordinations\n UNKNOWN_COORDINATION, // the default for coordination\n CONTRAST,\n CAUSE_C,\n RESULT_C,\n LIST,\n DISJUNCTION,\n TEMPORAL_AFTER_C,\n TEMPORAL_BEFORE_C,\n\n // Subordinations\n UNKNOWN_SUBORDINATION, // the default for s... | import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeExtractionUtils;
import org.lambda3.text.simplification.discourse.utils.words.WordsUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import edu.stanford.nlp.ling.Word;
import edu.stanford.nlp.trees.tregex.TregexMatcher;
import edu.stanford.nlp.trees.tregex.TregexPattern;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.Relation;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.Extraction;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.ExtractionRule;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.model.Leaf;
import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeException; | /*
* ==========================License-Start=============================
* DiscourseSimplification : SubordinationPostISAExtractor2
*
* Copyright © 2017 Lambda³
*
* GNU General Public License 3
* 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/.
* ==========================License-End==============================
*/
package org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.rules;
/**
*
*/
public class PreAttributionExtractor extends ExtractionRule {
@Override | public Optional<Extraction> extract(Leaf leaf) throws ParseTreeException { | 1 |
mvmn/gp2srv | src/main/java/x/mvmn/gp2srv/web/servlets/CameraChoiceFilter.java | [
"public interface CameraProvider {\n\n\tpublic GP2Camera getCamera();\n\n\tpublic boolean hasCamera();\n\n\tpublic void setCamera(GP2Camera camera);\n}",
"public class TemplateEngine {\n\n\tpublic static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = \"/x/mvmn/gp2srv/web/templates/\";\n\n\tprivate final Veloci... | import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import x.mvmn.gp2srv.camera.CameraProvider;
import x.mvmn.gp2srv.web.service.velocity.TemplateEngine;
import x.mvmn.gp2srv.web.service.velocity.VelocityContextService;
import x.mvmn.jlibgphoto2.impl.CameraDetectorImpl;
import x.mvmn.jlibgphoto2.impl.GP2CameraImpl;
import x.mvmn.jlibgphoto2.impl.GP2PortInfoList;
import x.mvmn.jlibgphoto2.impl.GP2PortInfoList.GP2PortInfo;
import x.mvmn.lang.util.Provider;
import x.mvmn.log.api.Logger; | package x.mvmn.gp2srv.web.servlets;
public class CameraChoiceFilter extends AbstractGP2Servlet implements Filter {
private static final long serialVersionUID = 1827967172388376853L;
private final CameraProvider camProvider;
public CameraChoiceFilter(final CameraProvider camProvider, final VelocityContextService velocityContextService, | final Provider<TemplateEngine> templateEngineProvider, final Logger logger) { | 1 |
zhaoyangzhou/RXJava | app/src/main/java/com/example/app/rxjava/module/main/model/ChartModel.java | [
"public class AppApplication extends Application {\n\n /*网络是否连接*/\n public static boolean isNetConnect;/*网络连接状态监听*/\n private ConnectionReceiver connectionReceiver = new ConnectionReceiver();\n public static AppApplication APP_APPLICATION;\n\n //刷新广播监听\n public static final String REFRESH_ACTION =... | import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.example.app.rxjava.AppApplication;
import com.example.app.rxjava.R;
import com.example.app.rxjava.base.BaseModel;
import com.example.app.rxjava.base.ResultsDeserializer;
import com.example.app.rxjava.base.converter.html.HtmlConverterFactory;
import com.example.app.rxjava.bean.weather.WeatherListData;
import com.example.app.rxjava.module.main.model.ia.ChartIA;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.Map;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
import rx.functions.Func1; | package com.example.app.rxjava.module.main.model;
/**
* Created by Administrator on 2016/2/29.
*/
public class ChartModel extends BaseModel implements ChartIA {
private static final String ENDPOINT = "http://m.xueka.com";
private final Service mService;
public ChartModel() {
// 适配器
Retrofit mRetrofit = getRetrofitBuilder()
.baseUrl(ENDPOINT)
.addConverterFactory(HtmlConverterFactory.create())
.build();
// 服务
mService = mRetrofit.create(Service.class);
}
@Override
public Observable<LineData> getServerData(int count, float range) {
mService.getData().flatMap(new Func1<String, Observable<?>>() {
@Override
public Observable<?> call(String data) {
Log.e("result", data);
return null;
}
});
ArrayList<String> xVals = new ArrayList<String>();
for (int i = 0; i < count; i++) {
xVals.add((i) + "");
}
ArrayList<Entry> yVals = new ArrayList<Entry>();
for (int i = 0; i < count; i++) {
float mult = (range + 1);
float val = (float) (Math.random() * mult) + 3;// + (float)
// ((mult *
// 0.1) / 10);
yVals.add(new Entry(val, i));
}
// create a dataset and give it a type
LineDataSet set1 = new LineDataSet(yVals, "DataSet 1");
// set1.setFillAlpha(110);
// set1.setFillColor(Color.RED);
// set the line to be drawn like this "- - - - - -"
set1.enableDashedLine(10f, 5f, 0f);
set1.enableDashedHighlightLine(10f, 5f, 0f);
set1.setColor(Color.BLACK);
set1.setCircleColor(Color.BLACK);
set1.setLineWidth(1f);
set1.setCircleRadius(3f);
set1.setDrawCircleHole(false);
set1.setValueTextSize(9f); | Drawable drawable = ContextCompat.getDrawable(AppApplication.getInstance(), R.drawable.fade_red); | 0 |
heroku/heroku.jar | heroku-api/src/main/java/com/heroku/api/request/app/AppInfo.java | [
"public class App implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n String id;\n String name;\n Domain domain_name;\n String created_at;\n App.Owner owner;\n String web_url;\n App.Stack stack;\n String requested_stack;\n String git_url;\n String buil... | import com.heroku.api.App;
import com.heroku.api.Heroku;
import com.heroku.api.exception.RequestFailedException;
import com.heroku.api.http.Http;
import com.heroku.api.http.HttpUtil;
import com.heroku.api.request.Request;
import com.heroku.api.request.RequestConfig;
import java.util.Collections;
import java.util.Map;
import static com.heroku.api.http.HttpUtil.noBody;
import static com.heroku.api.parser.Json.parse; | package com.heroku.api.request.app;
/**
* TODO: Javadoc
*
* @author Naaman Newbold
*/
public class AppInfo implements Request<App> {
private final RequestConfig config;
public AppInfo(String appName) {
this.config = new RequestConfig().app(appName);
}
@Override
public Http.Method getHttpMethod() {
return Http.Method.GET;
}
@Override
public String getEndpoint() { | return Heroku.Resource.App.format(config.getAppName()); | 1 |
tomayac/rest-describe-and-compile | src/com/google/code/apis/rest/client/Tree/ResponseItem.java | [
"public class GuiFactory implements WindowResizeListener {\r\n private static DockPanel blockScreen;\r\n public static Strings strings;\r\n public static Notifications notifications; \r\n private DockPanel dockPanel;\r\n public static final String restCompile = \"restCompile\";\r\n public static final String... | import java.util.Vector;
import com.google.code.apis.rest.client.GUI.GuiFactory;
import com.google.code.apis.rest.client.GUI.SettingsDialog;
import com.google.code.apis.rest.client.Util.SyntaxHighlighter;
import com.google.code.apis.rest.client.Wadl.MethodNode;
import com.google.code.apis.rest.client.Wadl.ResponseNode;
import com.google.code.apis.rest.client.Wadl.WadlXml;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;
| package com.google.code.apis.rest.client.Tree;
public class ResponseItem extends Composite {
public ResponseItem(final MethodNode method, final TreeItem methodTreeItem) {
HorizontalPanel containerPanel = new HorizontalPanel();
| HTML response = new HTML(SyntaxHighlighter.highlight("<" + WadlXml.responseNode + ">"));
| 5 |
assist-group/assist-mcommerce-sdk-android | sdk/src/main/java/ru/assisttech/sdk/processor/AssistTokenPayProcessor.java | [
"public class AssistMerchant {\n\n private String id;\n private String login;\n private String password;\n\n public AssistMerchant(String id) {\n this.id = id;\n }\n\n public AssistMerchant(String id, String login, String password) {\n this.id = id;\n this.login = login;\n ... | import android.content.Context;
import android.util.Log;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import ru.assisttech.sdk.AssistMerchant;
import ru.assisttech.sdk.AssistPaymentData;
import ru.assisttech.sdk.AssistResult;
import ru.assisttech.sdk.FieldName;
import ru.assisttech.sdk.network.AssistNetworkEngine;
import ru.assisttech.sdk.network.HttpResponse;
import ru.assisttech.sdk.storage.AssistTransaction; | package ru.assisttech.sdk.processor;
public class AssistTokenPayProcessor extends AssistBaseProcessor {
public static final String TAG = AssistTokenPayProcessor.class.getSimpleName();
private static final String UTF8 = "UTF-8";
String type;
public AssistTokenPayProcessor(Context context, AssistProcessorEnvironment environment, String type) {
super(context, environment);
this.type = type;
}
@Override
protected void run() {
super.run();
try {
getNetEngine().postRequest(getURL(),
new NetworkConnectionErrorListener(),
new TokenPayResponseParser(),
buildRequest()
);
} catch (Exception e) {
if (hasListener()) {
getListener().onError(AssistTransaction.UNREGISTERED_ID, e.getMessage());
}
finish();
}
}
@Override
protected void terminate() {
getNetEngine().stopTasks();
}
/**
* Web request assembling (HTTP protocol, URL encoded pairs)
*/
String buildRequest() throws Exception {
| AssistPaymentData data = getEnvironment().getData(); | 1 |
MindscapeHQ/raygun4java | core/src/test/java/com/mindscapehq/raygun4java/core/handlers/requestfilters/RaygunDuplicateErrorFilterTest.java | [
"public class RaygunDuplicateErrorFilter implements IRaygunOnBeforeSend, IRaygunOnAfterSend {\n\n private Map<Throwable, Throwable> sentErrors = new WeakHashMap<Throwable, Throwable>();\n\n /**\n * @param message to check if the error has already been sent\n * @return message\n */\n public Rayg... | import com.mindscapehq.raygun4java.core.handlers.requestfilters.RaygunDuplicateErrorFilter;
import com.mindscapehq.raygun4java.core.handlers.requestfilters.RaygunDuplicateErrorFilterFactory;
import com.mindscapehq.raygun4java.core.messages.RaygunErrorMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunMessage;
import com.mindscapehq.raygun4java.core.messages.RaygunMessageDetails;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*; | package com.mindscapehq.raygun4java.core.handlers.requestfilters;
public class RaygunDuplicateErrorFilterTest {
@Test
public void shouldFilterSameException() {
RaygunDuplicateErrorFilter filter = new RaygunDuplicateErrorFilter();
Exception exception = new Exception();
RaygunMessage message = new RaygunMessage();
RaygunMessageDetails details = new RaygunMessageDetails();
RaygunErrorMessage error = new RaygunErrorMessage(exception);
details.setError(error);
message.setDetails(details);
assertEquals(message, filter.onBeforeSend(null, message)); // not filtered first time
filter.onAfterSend(null, message);
message = new RaygunMessage();
details = new RaygunMessageDetails();
error = new RaygunErrorMessage(exception);
details.setError(error);
message.setDetails(details);
assertNull(filter.onBeforeSend(null, message)); // filtered second time
message = new RaygunMessage();
details = new RaygunMessageDetails();
error = new RaygunErrorMessage(new Exception()); // different exception
details.setError(error);
message.setDetails(details);
assertEquals(message, filter.onBeforeSend(null, message)); // not filtered
}
@Test
public void shouldReturnSameInstanceFromCreateFactoryFunction() { | RaygunDuplicateErrorFilterFactory factory = new RaygunDuplicateErrorFilterFactory(); | 1 |
msoute/vertx-deploy-tools | vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/handler/RestDeployStatusHandler.java | [
"@JsonIgnoreProperties(ignoreUnknown = true)\npublic class DeployRequest {\n private final UUID id = UUID.randomUUID();\n private final List<DeployApplicationRequest> modules;\n private final List<DeployConfigRequest> configs;\n private final List<DeployArtifactRequest> artifacts;\n private final boo... | import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import nl.jpoint.vertx.deploy.agent.request.DeployRequest;
import nl.jpoint.vertx.deploy.agent.request.DeployState;
import nl.jpoint.vertx.deploy.agent.service.AwsService;
import nl.jpoint.vertx.deploy.agent.service.DeployApplicationService;
import nl.jpoint.vertx.deploy.agent.util.ApplicationDeployState;
import nl.jpoint.vertx.deploy.agent.util.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package nl.jpoint.vertx.deploy.agent.handler;
public class RestDeployStatusHandler implements Handler<RoutingContext> {
private static final Logger LOG = LoggerFactory.getLogger(RestDeployStatusHandler.class);
private final AwsService deployAwsService; | private final DeployApplicationService deployApplicationService; | 3 |
ThreeTen/threetenbp | src/main/java/org/threeten/bp/Instant.java | [
"public final class DateTimeFormatter {\n\n //-----------------------------------------------------------------------\n /**\n * Returns the ISO date formatter that prints/parses a date without an offset,\n * such as '2011-12-03'.\n * <p>\n * This returns an immutable formatter capable of print... | import static org.threeten.bp.LocalTime.SECONDS_PER_DAY;
import static org.threeten.bp.LocalTime.SECONDS_PER_HOUR;
import static org.threeten.bp.LocalTime.SECONDS_PER_MINUTE;
import static org.threeten.bp.temporal.ChronoField.INSTANT_SECONDS;
import static org.threeten.bp.temporal.ChronoField.MICRO_OF_SECOND;
import static org.threeten.bp.temporal.ChronoField.MILLI_OF_SECOND;
import static org.threeten.bp.temporal.ChronoField.NANO_OF_SECOND;
import static org.threeten.bp.temporal.ChronoUnit.DAYS;
import static org.threeten.bp.temporal.ChronoUnit.NANOS;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectStreamException;
import java.io.Serializable;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.format.DateTimeParseException;
import org.threeten.bp.jdk8.DefaultInterfaceTemporalAccessor;
import org.threeten.bp.jdk8.Jdk8Methods;
import org.threeten.bp.temporal.ChronoField;
import org.threeten.bp.temporal.ChronoUnit;
import org.threeten.bp.temporal.Temporal;
import org.threeten.bp.temporal.TemporalAccessor;
import org.threeten.bp.temporal.TemporalAdjuster;
import org.threeten.bp.temporal.TemporalAmount;
import org.threeten.bp.temporal.TemporalField;
import org.threeten.bp.temporal.TemporalQueries;
import org.threeten.bp.temporal.TemporalQuery;
import org.threeten.bp.temporal.TemporalUnit;
import org.threeten.bp.temporal.UnsupportedTemporalTypeException;
import org.threeten.bp.temporal.ValueRange; | /*
* Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.threeten.bp;
/**
* An instantaneous point on the time-line.
* <p>
* This class models a single instantaneous point on the time-line.
* This might be used to record event time-stamps in the application.
* <p>
* For practicality, the instant is stored with some constraints.
* The measurable time-line is restricted to the number of seconds that can be held
* in a {@code long}. This is greater than the current estimated age of the universe.
* The instant is stored to nanosecond resolution.
* <p>
* The range of an instant requires the storage of a number larger than a {@code long}.
* To achieve this, the class stores a {@code long} representing epoch-seconds and an
* {@code int} representing nanosecond-of-second, which will always be between 0 and 999,999,999.
* The epoch-seconds are measured from the standard Java epoch of {@code 1970-01-01T00:00:00Z}
* where instants after the epoch have positive values, and earlier instants have negative values.
* For both the epoch-second and nanosecond parts, a larger value is always later on the time-line
* than a smaller value.
*
* <h3>Time-scale</h3>
* <p>
* The length of the solar day is the standard way that humans measure time.
* This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds,
* forming a 86400 second day.
* <p>
* Modern timekeeping is based on atomic clocks which precisely define an SI second
* relative to the transitions of a Caesium atom. The length of an SI second was defined
* to be very close to the 86400th fraction of a day.
* <p>
* Unfortunately, as the Earth rotates the length of the day varies.
* In addition, over time the average length of the day is getting longer as the Earth slows.
* As a result, the length of a solar day in 2012 is slightly longer than 86400 SI seconds.
* The actual length of any given day and the amount by which the Earth is slowing
* are not predictable and can only be determined by measurement.
* The UT1 time-scale captures the accurate length of day, but is only available some
* time after the day has completed.
* <p>
* The UTC time-scale is a standard approach to bundle up all the additional fractions
* of a second from UT1 into whole seconds, known as <i>leap-seconds</i>.
* A leap-second may be added or removed depending on the Earth's rotational changes.
* As such, UTC permits a day to have 86399 SI seconds or 86401 SI seconds where
* necessary in order to keep the day aligned with the Sun.
* <p>
* The modern UTC time-scale was introduced in 1972, introducing the concept of whole leap-seconds.
* Between 1958 and 1972, the definition of UTC was complex, with minor sub-second leaps and
* alterations to the length of the notional second. As of 2012, discussions are underway
* to change the definition of UTC again, with the potential to remove leap seconds or
* introduce other changes.
* <p>
* Given the complexity of accurate timekeeping described above, this Java API defines
* its own time-scale with a simplification. The Java time-scale is defined as follows:
* <p><ul>
* <li>midday will always be exactly as defined by the agreed international civil time</li>
* <li>other times during the day will be broadly in line with the agreed international civil time</li>
* <li>the day will be divided into exactly 86400 subdivisions, referred to as "seconds"</li>
* <li>the Java "second" may differ from an SI second</li>
* </ul><p>
* Agreed international civil time is the base time-scale agreed by international convention,
* which in 2012 is UTC (with leap-seconds).
* <p>
* In 2012, the definition of the Java time-scale is the same as UTC for all days except
* those where a leap-second occurs. On days where a leap-second does occur, the time-scale
* effectively eliminates the leap-second, maintaining the fiction of 86400 seconds in the day.
* <p>
* The main benefit of always dividing the day into 86400 subdivisions is that it matches the
* expectations of most users of the API. The alternative is to force every user to understand
* what a leap second is and to force them to have special logic to handle them.
* Most applications do not have access to a clock that is accurate enough to record leap-seconds.
* Most applications also do not have a problem with a second being a very small amount longer or
* shorter than a real SI second during a leap-second.
* <p>
* If an application does have access to an accurate clock that reports leap-seconds, then the
* recommended technique to implement the Java time-scale is to use the UTC-SLS convention.
* <a href="https://www.cl.cam.ac.uk/~mgk25/time/utc-sls/">UTC-SLS</a> effectively smoothes the
* leap-second over the last 1000 seconds of the day, making each of the last 1000 "seconds"
* 1/1000th longer or shorter than a real SI second.
* <p>
* One final problem is the definition of the agreed international civil time before the
* introduction of modern UTC in 1972. This includes the Java epoch of {@code 1970-01-01}.
* It is intended that instants before 1972 be interpreted based on the solar day divided
* into 86400 subdivisions.
* <p>
* The Java time-scale is used by all date-time classes.
* This includes {@code Instant}, {@code LocalDate}, {@code LocalTime}, {@code OffsetDateTime},
* {@code ZonedDateTime} and {@code Duration}.
*
* <h3>Specification for implementors</h3>
* This class is immutable and thread-safe.
*/
public final class Instant
extends DefaultInterfaceTemporalAccessor
implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable {
/**
* Constant for the 1970-01-01T00:00:00Z epoch instant.
*/
public static final Instant EPOCH = new Instant(0, 0);
/**
* The minimum supported epoch second.
*/
private static final long MIN_SECOND = -31557014167219200L;
/**
* The maximum supported epoch second.
*/
private static final long MAX_SECOND = 31556889864403199L;
/**
* The minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'.
* This could be used by an application as a "far past" instant.
* <p>
* This is one year earlier than the minimum {@code LocalDateTime}.
* This provides sufficient values to handle the range of {@code ZoneOffset}
* which affect the instant in addition to the local date-time.
* The value is also chosen such that the value of the year fits in
* an {@code int}.
*/
public static final Instant MIN = Instant.ofEpochSecond(MIN_SECOND, 0);
/**
* The maximum supported {@code Instant}, '1000000000-12-31T23:59:59.999999999Z'.
* This could be used by an application as a "far future" instant.
* <p>
* This is one year later than the maximum {@code LocalDateTime}.
* This provides sufficient values to handle the range of {@code ZoneOffset}
* which affect the instant in addition to the local date-time.
* The value is also chosen such that the value of the year fits in
* an {@code int}.
*/
public static final Instant MAX = Instant.ofEpochSecond(MAX_SECOND, 999999999);
/**
* Simulate JDK 8 method reference Instant::from.
*/
public static final TemporalQuery<Instant> FROM = new TemporalQuery<Instant>() {
@Override
public Instant queryFrom(TemporalAccessor temporal) {
return Instant.from(temporal);
}
};
/**
* Serialization version.
*/
private static final long serialVersionUID = -665713676816604388L;
/**
* Constant for nanos per second.
*/
private static final int NANOS_PER_SECOND = 1000000000;
/**
* Constant for nanos per milli.
*/
private static final int NANOS_PER_MILLI = 1000000;
/**
* Constant for millis per sec.
*/
private static final long MILLIS_PER_SEC = 1000;
/**
* The number of seconds from the epoch of 1970-01-01T00:00:00Z.
*/
private final long seconds;
/**
* The number of nanoseconds, later along the time-line, from the seconds field.
* This is always positive, and never exceeds 999,999,999.
*/
private final int nanos;
//-----------------------------------------------------------------------
/**
* Obtains the current instant from the system clock.
* <p>
* This will query the {@link Clock#systemUTC() system UTC clock} to
* obtain the current instant.
* <p>
* Using this method will prevent the ability to use an alternate time-source for
* testing because the clock is effectively hard-coded.
*
* @return the current instant using the system clock, not null
*/
public static Instant now() {
return Clock.systemUTC().instant();
}
/**
* Obtains the current instant from the specified clock.
* <p>
* This will query the specified clock to obtain the current time.
* <p>
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@link Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current instant, not null
*/
public static Instant now(Clock clock) {
Jdk8Methods.requireNonNull(clock, "clock");
return clock.instant();
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} using seconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The nanosecond field is set to zero.
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z
* @return an instant, not null
* @throws DateTimeException if the instant exceeds the maximum or minimum instant
*/
public static Instant ofEpochSecond(long epochSecond) {
return create(epochSecond, 0);
}
/**
* Obtains an instance of {@code Instant} using seconds from the
* epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second.
* <p>
* This method allows an arbitrary number of nanoseconds to be passed in.
* The factory will alter the values of the second and nanosecond in order
* to ensure that the stored nanosecond is in the range 0 to 999,999,999.
* For example, the following will result in the exactly the same instant:
* <pre>
* Instant.ofSeconds(3, 1);
* Instant.ofSeconds(4, -999_999_999);
* Instant.ofSeconds(2, 1000_000_001);
* </pre>
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z
* @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative
* @return an instant, not null
* @throws DateTimeException if the instant exceeds the maximum or minimum instant
* @throws ArithmeticException if numeric overflow occurs
*/
public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) {
long secs = Jdk8Methods.safeAdd(epochSecond, Jdk8Methods.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
int nos = Jdk8Methods.floorMod(nanoAdjustment, NANOS_PER_SECOND);
return create(secs, nos);
}
/**
* Obtains an instance of {@code Instant} using milliseconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The seconds and nanoseconds are extracted from the specified milliseconds.
*
* @param epochMilli the number of milliseconds from 1970-01-01T00:00:00Z
* @return an instant, not null
* @throws DateTimeException if the instant exceeds the maximum or minimum instant
*/
public static Instant ofEpochMilli(long epochMilli) {
long secs = Jdk8Methods.floorDiv(epochMilli, 1000);
int mos = Jdk8Methods.floorMod(epochMilli, 1000);
return create(secs, mos * NANOS_PER_MILLI);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} from a temporal object.
* <p>
* A {@code TemporalAccessor} represents some form of date and time information.
* This factory converts the arbitrary temporal object to an instance of {@code Instant}.
* <p>
* The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
* and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
* allowing it to be used as a query via method reference, {@code Instant::from}.
*
* @param temporal the temporal object to convert, not null
* @return the instant, not null
* @throws DateTimeException if unable to convert to an {@code Instant}
*/
public static Instant from(TemporalAccessor temporal) {
try {
long instantSecs = temporal.getLong(INSTANT_SECONDS);
int nanoOfSecond = temporal.get(NANO_OF_SECOND);
return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
} catch (DateTimeException ex) {
throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " +
temporal + ", type " + temporal.getClass().getName(), ex);
}
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} from a text string such as
* {@code 2007-12-23T10:15:30.000Z}.
* <p>
* The string must represent a valid instant in UTC and is parsed using
* {@link DateTimeFormatter#ISO_INSTANT}.
*
* @param text the text to parse, not null
* @return the parsed instant, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static Instant parse(final CharSequence text) {
return DateTimeFormatter.ISO_INSTANT.parse(text, Instant.FROM);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} using seconds and nanoseconds.
*
* @param seconds the length of the duration in seconds
* @param nanoOfSecond the nano-of-second, from 0 to 999,999,999
* @throws DateTimeException if the instant exceeds the maximum or minimum instant
*/
private static Instant create(long seconds, int nanoOfSecond) {
if ((seconds | nanoOfSecond) == 0) {
return EPOCH;
}
if (seconds < MIN_SECOND || seconds > MAX_SECOND) {
throw new DateTimeException("Instant exceeds minimum or maximum instant");
}
return new Instant(seconds, nanoOfSecond);
}
/**
* Constructs an instance of {@code Instant} using seconds from the epoch of
* 1970-01-01T00:00:00Z and nanosecond fraction of second.
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z
* @param nanos the nanoseconds within the second, must be positive
*/
private Instant(long epochSecond, int nanos) {
super();
this.seconds = epochSecond;
this.nanos = nanos;
}
//-----------------------------------------------------------------------
/**
* Checks if the specified field is supported.
* <p>
* This checks if this instant can be queried for the specified field.
* If false, then calling the {@link #range(TemporalField) range} and
* {@link #get(TemporalField) get} methods will throw an exception.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The supported fields are:
* <ul>
* <li>{@code NANO_OF_SECOND}
* <li>{@code MICRO_OF_SECOND}
* <li>{@code MILLI_OF_SECOND}
* <li>{@code INSTANT_SECONDS}
* </ul>
* All other {@code ChronoField} instances will return false.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
* passing {@code this} as the argument.
* Whether the field is supported is determined by the field.
*
* @param field the field to check, null returns false
* @return true if the field is supported on this instant, false if not
*/
@Override
public boolean isSupported(TemporalField field) {
if (field instanceof ChronoField) {
return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND;
}
return field != null && field.isSupportedBy(this);
}
@Override | public boolean isSupported(TemporalUnit unit) { | 8 |
Polidea/android-hierarchy-viewer | hierarchyviewer/src/main/java/com/polidea/hierarchyviewer/internal/logic/SystemLayoutParamsConverter.java | [
"public class FrameLayoutParamsModelInfo extends ViewGroupMarginLayoutParamsModelInfo {\n\n interface Metadata {\n\n String GRAVITY = \"gravity\";\n }\n\n @SerializedName(Metadata.GRAVITY)\n int gravity;\n\n @Override\n public void setDataFromLayoutParams(ViewGroup.LayoutParams viewGroupLay... | import android.support.v7.widget.LinearLayoutCompat;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.polidea.hierarchyviewer.internal.model.layoutparams.FrameLayoutParamsModelInfo;
import com.polidea.hierarchyviewer.internal.model.layoutparams.LinearLayoutCompatParamsModelInfo;
import com.polidea.hierarchyviewer.internal.model.layoutparams.LinearLayoutParamsModelInfo;
import com.polidea.hierarchyviewer.internal.model.layoutparams.RelativeLayoutParamsModelInfo;
import com.polidea.hierarchyviewer.internal.model.layoutparams.ViewGroupLayoutParamsModelInfo;
import com.polidea.hierarchyviewer.internal.model.layoutparams.ViewGroupMarginLayoutParamsModelInfo; | package com.polidea.hierarchyviewer.internal.logic;
enum SystemLayoutParamsConverter implements LayoutParamsConverter {
FRAME_LAYOUT_PARAMS_MODEL_INFO(FrameLayout.LayoutParams.class) {
@Override
public FrameLayoutParamsModelInfo getLayoutParamsModelInfo() {
return new FrameLayoutParamsModelInfo();
}
},
LINEAR_LAYOUT_COMPAT_PARAMS_MODEL_INFO(LinearLayoutCompat.LayoutParams.class) {
@Override
public LinearLayoutCompatParamsModelInfo getLayoutParamsModelInfo() {
return new LinearLayoutCompatParamsModelInfo();
}
},
LINEAR_LAYOUT_PARAMS_MODEL_INFO(LinearLayout.LayoutParams.class) {
@Override
public LinearLayoutParamsModelInfo getLayoutParamsModelInfo() {
return new LinearLayoutParamsModelInfo();
}
},
RELATIVE_LAYOUT_PARAMS_MODEL_INFO(RelativeLayout.LayoutParams.class) {
@Override
public RelativeLayoutParamsModelInfo getLayoutParamsModelInfo() {
return new RelativeLayoutParamsModelInfo();
}
},
VIEW_GROUP_MARGIN_LAYOUT_PARAM(ViewGroup.MarginLayoutParams.class) {
@Override | public ViewGroupMarginLayoutParamsModelInfo getLayoutParamsModelInfo() { | 5 |
MarcProe/lp2go | app/src/main/java/org/librepilot/lp2go/controller/ViewController.java | [
"public class MainActivity extends AppCompatActivity {\r\n public static final int CALLBACK_FILEPICKER_UAVO = 3456;\r\n public static final int CALLBACK_TTS = 6574;\r\n public static final int POLL_WAIT_TIME = 500;\r\n public static final int POLL_SECOND_FACTOR = 1000 / POLL_WAIT_TIME;\r\n public sta... | import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import org.librepilot.lp2go.MainActivity;
import org.librepilot.lp2go.R;
import org.librepilot.lp2go.VisualLog;
import org.librepilot.lp2go.helper.CompatHelper;
import org.librepilot.lp2go.helper.H;
import org.librepilot.lp2go.helper.SettingsHelper;
import org.librepilot.lp2go.uavtalk.UAVTalkMetaData;
import org.librepilot.lp2go.uavtalk.UAVTalkMissingObjectException;
import org.librepilot.lp2go.ui.menu.MenuItem;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
| }
mActivity.imgToolbarFlightSettings =
(ImageView) findViewById(R.id.imgToolbarFlightSettings);
if (mActivity.imgToolbarFlightSettings != null) {
mActivity.imgToolbarFlightSettings.setVisibility(mFlightSettingsVisible);
}
mActivity.imgToolbarLocalSettings =
(ImageView) findViewById(R.id.imgToolbarLocalSettings);
if (mActivity.imgToolbarLocalSettings != null) {
mActivity.imgToolbarLocalSettings.setVisibility(mLocalSettingsVisible);
}
mActivity.imgSerial = (ImageView) findViewById(R.id.imgSerial);
mActivity.imgUavoSanity = (ImageView) findViewById(R.id.imgUavoSanity);
mActivity.logViewEvent(this);
}
}
protected View findViewById(int res) {
return mActivity.findViewById(res);
}
protected String getString(int res) {
return mActivity.getString(res);
}
protected String getString(int res, int arg) {
return mActivity.getString(res, arg);
}
public void leave() {
//recycle bitmaps
for (ImageView iv : mUiImages) { //unsure if we need this.
//recycleImageViewSrc(iv);
}
mUiImages.clear();
}
public void init() {
//optional method to override
}
public void initRightMenu() {
//optional method to override
}
public Map<Integer, ViewController> getMenuRightItems() {
return mRightMenuItems;
}
public MenuItem getMenuItem() {
return mMenuItem;
}
public void update() {
mBlink = !mBlink;
//TTS
if (SettingsHelper.mText2SpeechEnabled) {
String statusArmed = getData("FlightStatus", "Armed").toString();
if (!mPreviousArmedStatus.equals(statusArmed)) {
mPreviousArmedStatus = statusArmed;
getMainActivity().getTtsHelper().speakFlush(statusArmed);
}
}
}
public void reset() {
//optional method to override
}
public void onToolbarFlightSettingsClick(View v) {
//optional method to override
}
public void onToolbarLocalSettingsClick(View v) {
//optional method to override
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//optional method to override
}
protected String getFloatData(String obj, String field, int b) {
try {
Float f1 = H.stringToFloat(getData(obj, field).toString());
return String.valueOf(H.round(f1, b));
} catch (NumberFormatException e) {
return "";
}
}
protected String getFloatOffsetData(String obj, String field, String soffset) {
try {
Float f1 = H.stringToFloat(getData(obj, field).toString());
Float f2 = (Float) mOffset.get(soffset);
return String.valueOf(H.round(f1 - f2, 2));
} catch (NumberFormatException | ClassCastException e) {
return "";
}
}
protected void setText(TextView t, String text) {
if (text != null && t != null) {
t.setText(text);
}
}
protected void setTextBGColor(TextView t, String color) {
if (color == null || color.equals(getString(R.string.EMPTY_STRING))) {
return;
}
final Context c = mActivity.getApplicationContext();
switch (color) {
case "OK":
case "None":
case "Connected":
| CompatHelper.setBackground(t, c, R.drawable.rounded_corner_ok);
| 2 |
lacuna/bifurcan | src/io/lacuna/bifurcan/durable/codecs/Reference.java | [
"public interface DurableInput extends DataInput, Closeable, AutoCloseable {\n\n /**\n * A means of generating thread-local {@link DurableInput}s, which do not need to be explicitly released.\n */\n interface Pool {\n DurableInput instance();\n }\n\n /**\n * Describes the slice window for a {@link Dura... | import io.lacuna.bifurcan.DurableInput;
import io.lacuna.bifurcan.DurableOutput;
import io.lacuna.bifurcan.IDurableCollection;
import io.lacuna.bifurcan.IDurableCollection.Fingerprint;
import io.lacuna.bifurcan.IDurableEncoding;
import io.lacuna.bifurcan.durable.BlockPrefix;
import io.lacuna.bifurcan.durable.Dependencies;
import io.lacuna.bifurcan.durable.Fingerprints;
import io.lacuna.bifurcan.durable.io.DurableBuffer; | package io.lacuna.bifurcan.durable.codecs;
public class Reference {
public final Fingerprint fingerprint;
public final long position;
private Reference(Fingerprint fingerprint, long position) {
this.fingerprint = fingerprint;
this.position = position;
}
public static Reference from(IDurableCollection c) {
// get the offset from the start of `c` to the start of the root collection
long pos = c.bytes().instance().bounds().absolute().start - c.root().bytes().instance().bounds().absolute().start;
return new Reference(c.root().fingerprint(), pos);
}
public void encode(DurableOutput out) {
DurableBuffer.flushTo(out, BlockPrefix.BlockType.REFERENCE, acc -> {
Dependencies.add(fingerprint); | Fingerprints.encode(fingerprint, acc); | 7 |
bourgesl/marlin-fx | src/main/java/com/sun/marlin/FloatArrayCache.java | [
"static final int[] ARRAY_SIZES = new int[BUCKETS];",
"static final int BUCKETS = 8;",
"static final int MAX_ARRAY_SIZE;",
"public static void logInfo(final String msg) {\n if (MarlinConst.USE_LOGGER) {\n LOG.info(msg);\n } else if (MarlinConst.ENABLE_LOGS) {\n System.out.print(\"INFO: \")... | import java.lang.ref.WeakReference;
import java.util.Arrays;
import com.sun.marlin.ArrayCacheConst.BucketStats;
import com.sun.marlin.ArrayCacheConst.CacheStats;
import static com.sun.marlin.ArrayCacheConst.ARRAY_SIZES;
import static com.sun.marlin.ArrayCacheConst.BUCKETS;
import static com.sun.marlin.ArrayCacheConst.MAX_ARRAY_SIZE;
import static com.sun.marlin.MarlinUtils.logInfo;
import static com.sun.marlin.MarlinUtils.logException; | /*
* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.marlin;
/*
* Note that the [BYTE/INT/FLOAT/DOUBLE]ArrayCache files are nearly identical except
* for a few type and name differences. Typically, the [BYTE]ArrayCache.java file
* is edited manually and then [INT/FLOAT/DOUBLE]ArrayCache.java
* files are generated with the following command lines:
*/
// % sed -e 's/(b\yte)[ ]*//g' -e 's/b\yte/int/g' -e 's/B\yte/Int/g' < B\yteArrayCache.java > IntArrayCache.java
// % sed -e 's/(b\yte)[ ]*0/0.0f/g' -e 's/(b\yte)[ ]*/(float) /g' -e 's/b\yte/float/g' -e 's/B\yte/Float/g' < B\yteArrayCache.java > FloatArrayCache.java
// % sed -e 's/(b\yte)[ ]*0/0.0d/g' -e 's/(b\yte)[ ]*/(double) /g' -e 's/b\yte/double/g' -e 's/B\yte/Double/g' < B\yteArrayCache.java > DoubleArrayCache.java
public final class FloatArrayCache implements MarlinConst {
final boolean clean;
private final int bucketCapacity;
private WeakReference<Bucket[]> refBuckets = null; | final CacheStats stats; | 6 |
decatur/j2js-compiler | src/main/java/com/j2js/assembly/Project.java | [
"public class J2JSCompiler {\n\n public static J2JSCompiler compiler;\n \n public static int errorCount = 0;\n \n private File basedir;\n private File cacheFile;\n \n List<com.j2js.Assembly> assemblies = new ArrayList<Assembly>();\n\n private List<File> classpath = new ArrayList<File>();\... | import com.j2js.J2JSCompiler;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.Type;
import com.j2js.Log;
import com.j2js.Utils;
import com.j2js.dom.ArrayCreation;
import com.j2js.dom.FieldAccess;
import com.j2js.dom.MethodBinding;
import com.j2js.dom.MethodDeclaration;
import com.j2js.dom.MethodInvocation;
import com.j2js.dom.TypeDeclaration; | package com.j2js.assembly;
public class Project implements Serializable {
static final long serialVersionUID = 0;
private static Project singleton;
// All managed classes mapped by class name.
private Map<String, ClassUnit> classesByName;
private ClassUnit javaLangObject;
private boolean compressed;
private boolean generateLineNumbers;
private Map<String, Signature> signatures;
private transient Stack<Integer> ids;
private transient int currentId;
private transient int currentIndex;
public transient int currentGeneratedMethods;
public static Project getSingleton() {
if (singleton == null) throw new NullPointerException();
return singleton;
}
public static Project createSingleton(File cacheFile) {
if (cacheFile != null && cacheFile.exists()) { | Log.getLogger().info("Using cache " + cacheFile); | 1 |
bourgesl/marlin-fx | src/main/java/com/sun/marlin/IntArrayCache.java | [
"static final int[] ARRAY_SIZES = new int[BUCKETS];",
"static final int BUCKETS = 8;",
"static final int MAX_ARRAY_SIZE;",
"public static void logInfo(final String msg) {\n if (MarlinConst.USE_LOGGER) {\n LOG.info(msg);\n } else if (MarlinConst.ENABLE_LOGS) {\n System.out.print(\"INFO: \")... | import java.lang.ref.WeakReference;
import java.util.Arrays;
import com.sun.marlin.ArrayCacheConst.BucketStats;
import com.sun.marlin.ArrayCacheConst.CacheStats;
import static com.sun.marlin.ArrayCacheConst.ARRAY_SIZES;
import static com.sun.marlin.ArrayCacheConst.BUCKETS;
import static com.sun.marlin.ArrayCacheConst.MAX_ARRAY_SIZE;
import static com.sun.marlin.MarlinUtils.logInfo;
import static com.sun.marlin.MarlinUtils.logException; | /*
* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.marlin;
/*
* Note that the [BYTE/INT/FLOAT/DOUBLE]ArrayCache files are nearly identical except
* for a few type and name differences. Typically, the [BYTE]ArrayCache.java file
* is edited manually and then [INT/FLOAT/DOUBLE]ArrayCache.java
* files are generated with the following command lines:
*/
// % sed -e 's/(b\yte)[ ]*//g' -e 's/b\yte/int/g' -e 's/B\yte/Int/g' < B\yteArrayCache.java > IntArrayCache.java
// % sed -e 's/(b\yte)[ ]*0/0.0f/g' -e 's/(b\yte)[ ]*/(float) /g' -e 's/b\yte/float/g' -e 's/B\yte/Float/g' < B\yteArrayCache.java > FloatArrayCache.java
// % sed -e 's/(b\yte)[ ]*0/0.0d/g' -e 's/(b\yte)[ ]*/(double) /g' -e 's/b\yte/double/g' -e 's/B\yte/Double/g' < B\yteArrayCache.java > DoubleArrayCache.java
public final class IntArrayCache implements MarlinConst {
final boolean clean;
private final int bucketCapacity;
private WeakReference<Bucket[]> refBuckets = null;
final CacheStats stats;
IntArrayCache(final boolean clean, final int bucketCapacity) {
this.clean = clean;
this.bucketCapacity = bucketCapacity;
this.stats = (DO_STATS) ?
new CacheStats(getLogPrefix(clean) + "IntArrayCache") : null;
}
Bucket getCacheBucket(final int length) {
final int bucket = ArrayCacheConst.getBucket(length);
return getBuckets()[bucket];
}
private Bucket[] getBuckets() {
// resolve reference:
Bucket[] buckets = (refBuckets != null) ? refBuckets.get() : null;
// create a new buckets ?
if (buckets == null) {
buckets = new Bucket[BUCKETS];
for (int i = 0; i < BUCKETS; i++) {
buckets[i] = new Bucket(clean, ARRAY_SIZES[i], bucketCapacity,
(DO_STATS) ? stats.bucketStats[i] : null);
}
// update weak reference:
refBuckets = new WeakReference<Bucket[]>(buckets);
}
return buckets;
}
Reference createRef(final int initialSize) {
return new Reference(this, initialSize);
}
static final class Reference {
// initial array reference (direct access)
final int[] initial;
private final boolean clean;
private final IntArrayCache cache;
Reference(final IntArrayCache cache, final int initialSize) {
this.cache = cache;
this.clean = cache.clean;
this.initial = createArray(initialSize);
if (DO_STATS) {
cache.stats.totalInitial += initialSize;
}
}
int[] getArray(final int length) {
if (length <= MAX_ARRAY_SIZE) {
return cache.getCacheBucket(length).getArray();
}
if (DO_STATS) {
cache.stats.oversize++;
}
if (DO_LOG_OVERSIZE) {
logInfo(getLogPrefix(clean) + "IntArrayCache: "
+ "getArray[oversize]: length=\t" + length);
}
return createArray(length);
}
int[] widenArray(final int[] array, final int usedSize,
final int needSize)
{
final int length = array.length;
if (DO_CHECKS && length >= needSize) {
return array;
}
if (DO_STATS) {
cache.stats.resize++;
}
// maybe change bucket:
// ensure getNewSize() > newSize:
final int[] res = getArray(ArrayCacheConst.getNewSize(usedSize, needSize));
// use wrapper to ensure proper copy:
System.arraycopy(array, 0, res, 0, usedSize); // copy only used elements
// maybe return current array:
putArray(array, 0, usedSize); // ensure array is cleared
if (DO_LOG_WIDEN_ARRAY) {
logInfo(getLogPrefix(clean) + "IntArrayCache: "
+ "widenArray[" + res.length
+ "]: usedSize=\t" + usedSize + "\tlength=\t" + length
+ "\tneeded length=\t" + needSize);
}
return res;
}
int[] putArray(final int[] array)
{
// dirty array helper:
return putArray(array, 0, array.length);
}
int[] putArray(final int[] array, final int fromIndex,
final int toIndex)
{
if (array.length <= MAX_ARRAY_SIZE) {
if ((clean || DO_CLEAN_DIRTY) && (toIndex != 0)) {
// clean-up array of dirty part[fromIndex; toIndex[
fill(array, fromIndex, toIndex, 0);
}
// ensure to never store initial arrays in cache:
if (array != initial) {
cache.getCacheBucket(array.length).putArray(array);
}
}
return initial;
}
}
static final class Bucket {
private int tail = 0;
private final int arraySize;
private final boolean clean;
private final int[][] arrays; | private final BucketStats stats; | 5 |
wangchongjie/multi-task | src/main/java/com/baidu/unbiz/multitask/task/AbstractParallelExePool.java | [
"public class TaskPair extends Pair<String, Object> {\n\n public TaskPair() {\n }\n\n public TaskPair(String taskName, Object param) {\n this.field1 = taskName;\n this.field2 = param;\n }\n\n public TaskPair wrap(String taskName, Object param) {\n return new TaskPair(taskName, pa... | import javax.annotation.Resource;
import org.slf4j.Logger;
import com.baidu.unbiz.multitask.common.TaskPair;
import com.baidu.unbiz.multitask.constants.ThreadPoolConfig;
import com.baidu.unbiz.multitask.log.AopLogFactory;
import com.baidu.unbiz.multitask.policy.ExecutePolicy;
import com.baidu.unbiz.multitask.spring.integration.TaskBeanContainer;
import com.baidu.unbiz.multitask.task.thread.TaskContext;
import com.baidu.unbiz.multitask.task.thread.TaskManager; | package com.baidu.unbiz.multitask.task;
/**
* 报表基础工具类
*
* @author wangchongjie
* @since 2015-8-15 下午3:08:21
*/
public abstract class AbstractParallelExePool implements ParallelExePool {
protected static final Logger LOG = AopLogFactory.getLogger(AbstractParallelExePool.class);
@Resource(name = "taskBeanContainer")
protected TaskBeanContainer container;
public TaskContext beforeSubmit(TaskContext context, ExecutePolicy policy, TaskPair... taskPairs) {
return context.putAttribute(TASK_PAIRS, taskPairs);
}
public TaskContext onSubmit(TaskContext context, ExecutePolicy policy, TaskPair... taskPairs) {
return context;
}
public TaskContext postSubmit(TaskContext context, ExecutePolicy policy, TaskPair... taskPairs) {
return context;
}
public AbstractParallelExePool() {
}
/**
* 初始化线程池配置,缺省值为DefaultThreadPoolConfig
*
* @param tpConfig 线程池配置
*/
public AbstractParallelExePool(ThreadPoolConfig tpConfig) { | TaskManager.refreshConfig(tpConfig); | 6 |
Androguide/Pimp_my_Z1 | PimpMyZ1/src/com/androguide/honamicontrol/profiles/PerformanceProfile.java | [
"public class CPUHelper {\r\n\r\n private static final String TAG = \"CPUHelper\";\r\n private static BufferedReader br;\r\n\r\n /**\r\n * Checks device for SuperUser permission\r\n *\r\n * @return If SU was granted or denied\r\n */\r\n public static boolean checkSu() {\r\n if (!n... | import java.util.Arrays;
import java.util.List;
import com.androguide.honamicontrol.helpers.CPUHelper;
import com.androguide.honamicontrol.kernel.cpucontrol.CPUInterface;
import com.androguide.honamicontrol.kernel.gpucontrol.GPUInterface;
import com.androguide.honamicontrol.kernel.iotweaks.IOTweaksInterface;
import com.androguide.honamicontrol.kernel.memory.MemoryManagementInterface;
import com.androguide.honamicontrol.kernel.misc.MiscInterface;
import com.androguide.honamicontrol.kernel.powermanagement.PowerManagementInterface;
import java.util.ArrayList; | /** Copyright (C) 2013 Louis Teboul (a.k.a Androguide)
*
* admin@pimpmyrom.org || louisteboul@gmail.com
* http://pimpmyrom.org || http://androguide.fr
* 71 quai Clémenceau, 69300 Caluire-et-Cuire, FRANCE.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**/
package com.androguide.honamicontrol.profiles;
public class PerformanceProfile extends Profile {
@Override
public String getCpuMaxFreq() {
String[] freqs = CPUHelper.getAvailableCPUFreqs();
prefs.edit().putString("CPU_MAX_FREQ", freqs[freqs.length - 1]).commit();
return toShell(freqs[freqs.length - 1], CPUInterface.MAX_FREQ) + "\n" + toShell(freqs[freqs.length - 1], CPUInterface.SNAKE_CHARMER_MAX_FREQ);
}
@Override
public String getGpuMaxFreq() {
String[] freqs = CPUHelper.getAvailableGPUFreqs();
prefs.edit().putString("GPU_MAX_FREQ", freqs[freqs.length - 1]).commit();
return toShell(freqs[freqs.length - 1], GPUInterface.maxFreq);
}
@Override
public String getCPUGovernor() {
String[] govs = CPUHelper.readOneLineNotRoot(CPUInterface.GOVERNORS_LIST).split(" ");
List<String> governors = Arrays.asList(govs);
if (governors.contains("intelliactive")) {
prefs.edit().putString("CORE0_GOVERNOR", "intelliactive").commit();
return toShell("intelliactive", CPUInterface.GOVERNOR);
} else if (governors.contains("wheatley")) {
prefs.edit().putString("CORE0_GOVERNOR", "wheatley").commit();
return toShell("wheatley", CPUInterface.GOVERNOR);
} else if (governors.contains("smartassV2")) {
prefs.edit().putString("CORE0_GOVERNOR", "smartassV2").commit();
return toShell("smartassV2", CPUInterface.GOVERNOR);
} else if (governors.contains("interactivex2")) {
prefs.edit().putString("CORE0_GOVERNOR", "interactivex2").commit();
return toShell("interactivex2", CPUInterface.GOVERNOR);
} else if (governors.contains("badass")) {
prefs.edit().putString("CORE0_GOVERNOR", "badass").commit();
return toShell("badass", CPUInterface.GOVERNOR);
} else if (governors.contains("")) {
prefs.edit().putString("CORE0_GOVERNOR", "interactive").commit();
return toShell("interactive", CPUInterface.GOVERNOR);
} else
return "";
}
@Override
public String getGPUGovernor() {
prefs.edit().putString("GPU_GOVERNOR", "msm-adreno-tz").commit();
return toShell("msm-adreno-tz", GPUInterface.currGovernor);
}
@Override
public String getIOScheduler() {
ArrayList<String> scheds = CPUHelper.getAvailableIOSchedulers();
if (scheds.contains("fiops")) {
prefs.edit().putString("IO_SCHEDULER", "fiops").commit();
prefs.edit().putString("IO_SCHEDULER_SD", "fiops").commit();
return toShell("fiops", IOTweaksInterface.IO_SCHEDULER) + "\n" + toShell("sio", IOTweaksInterface.IO_SCHEDULER_SD);
} else if (scheds.contains("bfq")) {
prefs.edit().putString("IO_SCHEDULER", "bfq").commit();
prefs.edit().putString("IO_SCHEDULER_SD", "bfq").commit();
return toShell("bfq", IOTweaksInterface.IO_SCHEDULER) + "\n" + toShell("bfq", IOTweaksInterface.IO_SCHEDULER_SD);
} else if (scheds.contains("cfq")) {
prefs.edit().putString("IO_SCHEDULER", "cfq").commit();
prefs.edit().putString("IO_SCHEDULER_SD", "cfq").commit();
return toShell("cfq", IOTweaksInterface.IO_SCHEDULER) + "\n" + toShell("deadline", IOTweaksInterface.IO_SCHEDULER_SD);
} else if (scheds.contains("row")) {
prefs.edit().putString("IO_SCHEDULER", "row").commit();
prefs.edit().putString("IO_SCHEDULER_SD", "row").commit();
return toShell("row", IOTweaksInterface.IO_SCHEDULER) + "\n" + toShell("row", IOTweaksInterface.IO_SCHEDULER_SD);
} else
return "";
}
@Override
public String isIntelliplugEnabled() {
prefs.edit().putBoolean("INTELLI_PLUG", false).commit(); | return "start mpdecision\n" + "busybox echo 1 > " + PowerManagementInterface.MSM_MPDECISION_TOGGLE + "\n" | 6 |
opentok/accelerator-core-android | accelerator-core/src/main/java/com/opentok/accelerator/core/wrapper/OTWrapper.java | [
"public class GlobalLogLevel {\n public static short sMaxLogLevel = 0xFF;\n}",
"public class ScreenSharingCapturer extends BaseVideoCapturer{\n private static final String LOG_TAG = ScreenSharingCapturer.class.getSimpleName();\n private static final short LOCAL_LOG_LEVEL = 0xFF;\n private static final L... | import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import androidx.fragment.app.FragmentActivity;
import com.opentok.accelerator.core.GlobalLogLevel;
import com.opentok.accelerator.core.listeners.*;
import com.opentok.accelerator.core.screensharing.ScreenSharingCapturer;
import com.opentok.accelerator.core.screensharing.ScreenSharingFragment;
import com.opentok.accelerator.core.signal.SignalInfo;
import com.opentok.accelerator.core.signal.SignalProtocol;
import com.opentok.accelerator.core.utils.*;
import com.opentok.android.*;
import com.tokbox.android.logging.OTKAnalytics;
import com.tokbox.android.logging.OTKAnalyticsData;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; | LOG.i(LOG_TAG, "Remove remote with ID: ", remoteId);
addLogEvent(ClientLog.LOG_ACTION_REMOVE_REMOTE, ClientLog.LOG_VARIATION_ATTEMPT);
Subscriber sub = mSubscribers.get(remoteId);
mSubscribers.remove(remoteId);
mStreams.put(remoteId, sub.getStream());
mSession.unsubscribe(sub);
}
/**
* Call to cycle between cameras, if there are multiple cameras on the device.
*/
public void cycleCamera() {
if (mPublisher != null) {
mPublisher.cycleCamera();
}
}
/**
* Returns the OpenTok Configuration
*
* @return current OpenTok Configuration
*/
public OTConfig getOTConfig() {
return this.mOTConfig;
}
private RetriableOTListener getUnfailingFromBaseListener(BaseOTListener listener) {
return listener instanceof BasicListener ?
new UnfailingBasicListener((BasicListener) listener) :
new UnfailingAdvancedListener<>((AdvancedListener) listener);
}
/**
* Adds a {@link BasicListener}. If the listener was already added, nothing is done.
*
* @param listener
* @return The added listener
*/
public BasicListener addBasicListener(BasicListener listener) {
LOG.d(LOG_TAG, "Adding BasicListener");
BasicListener returnedListener = (BasicListener) addOTListener(listener, mRetriableBasicListeners, mBasicListeners);
return returnedListener;
}
/**
* Removes a {@link BasicListener}
*
* @param listener
*/
public void removeBasicListener(BasicListener listener) {
removeOTListener(listener, mRetriableBasicListeners, mBasicListeners);
}
/**
* Adds an {@link AdvancedListener}
*
* @param listener
* @return The removed listener
*/
public AdvancedListener addAdvancedListener(AdvancedListener<OTWrapper> listener) {
AdvancedListener returnedListener = (AdvancedListener) addOTListener(listener, mRetriableAdvancedListeners,
mAdvancedListeners);
return returnedListener;
}
/**
* Removes an {@link AdvancedListener}
*
* @param listener
*/
public void removeAdvancedListener(AdvancedListener listener) {
removeOTListener(listener, mRetriableAdvancedListeners, mAdvancedListeners);
}
/**
* Registers a signal listener for a given signal.
*
* @param signalName Name of the signal this listener will listen to. Pass "*" if the listener
* is to be invoked for all signals.
* @param listener Listener that will be invoked when a signal is received.
*/
public void addSignalListener(String signalName, SignalListener listener) {
if (mSession != null) {
mSession.addSignalListener(signalName, listener);
}
}
/**
* Removes an object as signal listener everywhere it's used. This is added to support the common
* cases where an activity (or some object that depends on an activity) is used as a listener
* but the activity can be destroyed at some points (which would cause the app to crash if the
* signal was delivered).
*
* @param listener Listener to be removed
*/
public void removeSignalListener(SignalListener listener) {
if (mSession != null) {
mSession.removeSignalListener(listener);
}
}
/**
* Removes a signal listener.
*
* @param signalName Name of the signal this listener will listen to. Pass "*" if the listener
* is to be invoked for all signals.
* @param listener Listener to be removed.
*/
public void removeSignalListener(String signalName, SignalListener listener) {
if (mSession != null) {
mSession.removeSignalListener(signalName, listener);
}
}
/**
* Sends a new signal
*
* @param signalInfo {@link SignalInfo} of the signal to be sent
*/ | public void sendSignal(SignalInfo signalInfo) { | 3 |
kaichunlin/android-transition | core/src/main/java/com/kaichunlin/transition/adapter/OnPageChangeListenerAdapter.java | [
"public class DefaultTransitionManager implements TransitionManager {\n private ArrayList<TransitionManagerListener> mListenerList = new ArrayList<>();\n private ArrayList<Transition> mTransitionList = new ArrayList<>();\n private Set<Transition> mBackupTransitionList = new HashSet<>();\n\n @Override\n ... | import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.kaichunlin.transition.DefaultTransitionManager;
import com.kaichunlin.transition.R;
import com.kaichunlin.transition.Transition;
import com.kaichunlin.transition.TransitionConfig;
import com.kaichunlin.transition.transformer.ViewTransformer;
import com.kaichunlin.transition.TransitionManager;
import com.kaichunlin.transition.ViewTransition;
import com.kaichunlin.transition.ViewTransitionBuilder;
import com.kaichunlin.transition.internal.TransitionController;
import com.kaichunlin.transition.util.TransitionStateLogger;
import java.util.List;
import java.util.WeakHashMap; | adapter.addTransition(ViewTransitionBuilder.transit().range(CENTER, RIGHT_OF_CENTER).id("RIGHT_CENTER").addViewTransformer(RIGHT_IN_PLACE));
adapter.addTransition(ViewTransitionBuilder.transit().range(CENTER, RIGHT_OF_CENTER * 0.5f).rotationY(0, 90).scale(1f, 0.5f).id("RIGHT"));
return adapter;
}
private static TransitionStateLogger getTransitionStateHolder(@NonNull View view) {
return (TransitionStateLogger) view.getTag(R.id.debug_id);
}
private final ViewPager mViewPager;
private final WeakHashMap<View, PageHolder> mTransitionListMap = new WeakHashMap<>();
public OnPageChangeListenerAdapter(ViewPager viewPager) {
mViewPager = viewPager;
}
public void init(boolean reverseDrawingOrder) {
mViewPager.addOnPageChangeListener(this);
mViewPager.setPageTransformer(reverseDrawingOrder, this);
}
public OnPageChangeListenerAdapter addAndSetTransition(@NonNull ViewTransitionBuilder builder) {
return addAndSetTransition(builder, CENTER, LEFT_OF_CENTER);
}
public OnPageChangeListenerAdapter addAndSetTransition(@NonNull ViewTransitionBuilder builder, float start, float end) {
ViewTransition vt = builder.range(start, end).id("LEFT").build();
getTransitionManager().addTransition(vt);
vt = builder.clone().range(-start, -end).id("RIGHT").build();
getTransitionManager().addTransition(vt);
return this;
}
public boolean startTransition() {
throw new UnsupportedOperationException();
}
public boolean startTransition(float progress) {
throw new UnsupportedOperationException();
}
private boolean startTransition(@NonNull View page) {
if (!getAdapterState().isTransiting()) {
notifyTransitionStart();
}
PageHolder holder = mTransitionListMap.get(page);
if (holder == null) {
holder = new PageHolder(page, getTransitionManager().getTransitions());
mTransitionListMap.put(page, holder);
List<Transition> transitionList = holder.mTransitionManager.getTransitions();
final int size = transitionList.size();
Transition transition;
for (int i = 0; i < size; i++) {
transition = transitionList.get(i);
transition.setUpdateStateAfterUpdateProgress(true);
transition.setTarget(page);
transition.startTransition();
}
}
return true;
}
public void updateProgress(float value) {
throw new UnsupportedOperationException();
}
protected void updateProgress(@NonNull View page, float value) {
PageHolder holder = mTransitionListMap.get(page);
if (holder == null) {
// if (TransitionConfig.isDebug()) {
// Log.e(getClass().getSimpleName(), "updateProgress: NULL");
// }
return;
}
holder.mTransitionManager.updateProgress(value);
}
public void stopTransition() {
getAdapterState().setTransiting(false);
notifyTransitionEnd();
for (PageHolder holder : mTransitionListMap.values()) {
holder.mTransitionManager.stopTransition();
}
mTransitionListMap.clear();
}
@Override
public void transformPage(@NonNull View page, float position) {
if (getAdapterState().isTransiting()) {
startTransition(page);
updateProgress(page, position);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
switch (state) {
case ViewPager.SCROLL_STATE_IDLE:
stopTransition();
break;
case ViewPager.SCROLL_STATE_DRAGGING:
case ViewPager.SCROLL_STATE_SETTLING:
getAdapterState().setTransiting(true);
break;
}
}
private static class PageHolder { | final TransitionManager mTransitionManager = new DefaultTransitionManager(); | 0 |
YiuChoi/MicroReader | app/src/main/java/name/caiyao/microreader/ui/fragment/ItHomeFragment.java | [
"@Root(name = \"item\")\npublic class ItHomeItem implements Parcelable {\n @Attribute(name = \"t\",required = false)\n private String t;\n @Element(name = \"newsid\")\n private String newsid;\n @Element(name = \"title\")\n private String title;\n @Element(name = \"c\", required = false)\n pr... | import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import name.caiyao.microreader.R;
import name.caiyao.microreader.bean.itHome.ItHomeItem;
import name.caiyao.microreader.presenter.IItHomePresenter;
import name.caiyao.microreader.presenter.impl.ItHomePresenterImpl;
import name.caiyao.microreader.ui.adapter.ItAdapter;
import name.caiyao.microreader.ui.iView.IItHomeFragment;
import name.caiyao.microreader.ui.view.DividerItemDecoration;
import name.caiyao.microreader.utils.NetWorkUtil;
import name.caiyao.microreader.utils.SharePreferenceUtil; | package name.caiyao.microreader.ui.fragment;
/**
* Created by 蔡小木 on 2016/3/24 0024.
*/
public class ItHomeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, IItHomeFragment {
@BindView(R.id.progressBar)
ProgressBar progressBar;
@BindView(R.id.swipe_target)
RecyclerView swipeTarget;
@BindView(R.id.swipeToLoadLayout)
SwipeRefreshLayout swipeRefreshLayout;
private Unbinder mUnbinder;
private ArrayList<ItHomeItem> itHomeItems = new ArrayList<>(); | private ItAdapter itAdapter; | 3 |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/item/StatBoosterItem.java | [
"@Mod(ScalingHealth.MOD_ID)\npublic class ScalingHealth {\n public static final String MOD_ID = \"scalinghealth\";\n public static final String MOD_NAME = \"Scaling Health\";\n public static final String VERSION = \"2.5.3\";\n\n public static final Random random = new Random();\n\n public static fina... | import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.passive.TameableEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Rarity;
import net.minecraft.stats.Stats;
import net.minecraft.util.*;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.capability.IPlayerData;
import net.silentchaos512.scalinghealth.capability.PetHealthCapability;
import net.silentchaos512.scalinghealth.client.particles.ModParticles;
import net.silentchaos512.scalinghealth.config.Config;
import net.silentchaos512.scalinghealth.init.ModSounds;
import net.silentchaos512.scalinghealth.utils.SHPlayers;
import javax.annotation.Nullable;
import java.util.List; | package net.silentchaos512.scalinghealth.item;
public abstract class StatBoosterItem extends Item {
public StatBoosterItem() {
super(new Properties().group(ScalingHealth.SH));
}
private boolean usedForPet = false;
@Override
public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) {
tooltip.add(new TranslationTextComponent(this.getTranslationKey() + ".desc"));
}
@Override
public Rarity getRarity(ItemStack stack) {
return Rarity.RARE;
}
@Override
public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand handIn) {
ItemStack stack = player.getHeldItem(handIn);
if(usedForPet){
if(world.isRemote) usedForPet = false;
return new ActionResult<>(ActionResultType.FAIL, stack);
}
if (!world.isRemote) {
final boolean statIncreaseAllowed = isStatIncreaseAllowed(player);
final int levelRequirement = getLevelCost(player);
// Does player have enough XP?
if (player.experienceLevel < levelRequirement) {
String translationKey = "item.scalinghealth.stat_booster.notEnoughXP";
player.sendMessage(new TranslationTextComponent(translationKey, levelRequirement));
return new ActionResult<>(ActionResultType.PASS, stack);
}
// May be used as a healing item even if there is no stat increase
final boolean consumed = shouldConsume(player);
if (consumed) {
extraConsumeEffect(player);
}
// End here is stat increases are not allowed
if (!statIncreaseAllowed) {
return useAsConsumable(world, player, stack, levelRequirement, consumed);
}
// Increase stat, consume item
return useAsStatIncreaseItem(player, stack, levelRequirement);
}
else if(shouldConsume(player) || isStatIncreaseAllowed(player))
spawnParticlesAndPlaySound(player);
return new ActionResult<>(ActionResultType.SUCCESS, stack);
}
public void increasePetHp(PlayerEntity player, TameableEntity pet, ItemStack stack){
//check config
int levelRequirement = getLevelCost(player);
if (player.experienceLevel < levelRequirement) {
String translationKey = "item.scalinghealth.stat_booster.notEnoughXP";
player.sendMessage(new TranslationTextComponent(translationKey, levelRequirement));
return;
}
usedForPet = true;
pet.getCapability(PetHealthCapability.INSTANCE).ifPresent(data -> data.addHealth(Config.GENERAL.pets.hpGainByCrystal.get(), pet));
stack.shrink(1);
consumeLevels(player, levelRequirement);
player.addStat(Stats.ITEM_USED.get(this));
}
abstract int getLevelCost(PlayerEntity player);
abstract boolean isStatIncreaseAllowed(PlayerEntity player);
abstract boolean shouldConsume(PlayerEntity player);
abstract void extraConsumeEffect(PlayerEntity player);
abstract void increaseStat(PlayerEntity player);
abstract ModParticles getParticleType();
abstract ModSounds getSoundEffect();
private ActionResult<ItemStack> useAsConsumable(World world, PlayerEntity player, ItemStack stack, int levelRequirement, boolean consumed) {
if (consumed) {
world.playSound(null, player.getPosition(), SoundEvents.ENTITY_PLAYER_BURP, SoundCategory.PLAYERS,
0.5f, 1 + 0.1f * (float) ScalingHealth.random.nextGaussian());
stack.shrink(1);
consumeLevels(player, levelRequirement);
player.addStat(Stats.ITEM_USED.get(this));
return new ActionResult<>(ActionResultType.SUCCESS, stack);
}
return new ActionResult<>(ActionResultType.PASS, stack);
}
private ActionResult<ItemStack> useAsStatIncreaseItem(PlayerEntity player, ItemStack stack, int levelRequirement) {
increaseStat(player);
stack.shrink(1);
consumeLevels(player, levelRequirement);
player.addStat(Stats.ITEM_USED.get(this)); | IPlayerData.sendUpdatePacketTo(player); | 1 |
EKT/Biblio-Transformation-Engine | bte-io/src/main/java/gr/ekt/bteio/loaders/RISDataLoader.java | [
"public interface DataLoadingSpec {\n /**\n * Returns the number of records that should be read.\n *\n * Since the number of records cannot be an integer less than\n * zero, negative values can be used to signal that the user needs\n * all the records form a source.\n *\n * @return Th... | import gr.ekt.bte.core.DataLoadingSpec;
import gr.ekt.bte.core.RecordSet;
import gr.ekt.bte.core.StringValue;
import gr.ekt.bte.core.Value;
import gr.ekt.bte.dataloader.FileDataLoader;
import gr.ekt.bte.exceptions.EmptySourceException;
import gr.ekt.bte.exceptions.MalformedSourceException;
import gr.ekt.bte.record.MapRecord;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger; | /**
* Copyright (c) 2007-2013, National Documentation Centre (EKT, www.ekt.gr)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the National Documentation Centre nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gr.ekt.bteio.loaders;
public class RISDataLoader extends FileDataLoader {
private static Logger logger_ = Logger.getLogger(RISDataLoader.class);
private BufferedReader reader_;
private Map<String, String> field_map_;
public RISDataLoader() {
super();
reader_ = null;
field_map_ = null;
}
public RISDataLoader(String filename, Map<String, String> field_map) throws EmptySourceException {
super(filename);
field_map_ = field_map;
openReader();
}
@Override
public RecordSet getRecords() throws MalformedSourceException {
if (reader_ == null) {
throw new EmptySourceException("Input file is not open");
}
RecordSet records = new RecordSet();
try {
String line;
boolean in_record = false;
int line_cnt = 0;
MapRecord rec = null;
String ris_tag = null;
while((line = reader_.readLine()) != null) {
line_cnt++;
//Ignore empty lines
if(line.isEmpty() || line.equals("") || line.matches("^\\s*$")) {
continue;
}
Pattern ris_pattern = Pattern.compile("^([A-Z][A-Z0-9]) - (.*)$");
Matcher ris_matcher = ris_pattern.matcher(line);
Value val;
if (ris_matcher.matches()) {
ris_tag = ris_matcher.group(1);
if (!in_record) {
//The first tag of the record should be "TY". If we
//encounter it we should create a new record.
if (ris_tag.equals("TY")) {
in_record = true;
rec = new MapRecord();
}
else {
logger_.debug("Line: " + line_cnt + " in file " + filename + " should contain tag \"TY\"");
throw new MalformedSourceException("Line: " + line_cnt + " in file " + filename + " should contain tag \"TY\"");
}
}
//If the tag is the end record tag ("ER") we stop
//being in a record. Add the current record in the
//record set and skip the rest of the processing.
if (ris_tag.equals("ER")) {
in_record = false;
records.addRecord(rec);
rec = null;
continue;
}
//If there is no mapping for the current tag we do not
//know what to do with it, so we ignore it.
if (!field_map_.containsKey(ris_tag)) {
logger_.warn("Tag \"" + ris_tag + "\" is not in the field map. Ignoring");
continue;
}
val = new StringValue(ris_matcher.group(2));
}
else {
val = new StringValue(line);
}
String field = field_map_.get(ris_tag);
if (field != null) {
rec.addValue(field, val);
}
}
} catch (IOException e) {
logger_.info("Error while reading from file " + filename);
throw new MalformedSourceException("Error while reading from file " + filename);
}
return records;
}
@Override | public RecordSet getRecords(DataLoadingSpec spec) throws MalformedSourceException { | 0 |
kihira/Tails | src/main/java/uk/kihira/tails/client/render/FallbackRenderHandler.java | [
"public class Model implements IDisposable\n{\n private final ArrayList<Node> allNodes;\n private final ArrayList<Node> rootNodes;\n private final HashMap<String, Animation> animations;\n private final ArrayList<ResourceLocation> textures;\n\n public Model(ArrayList<Node> allNodes, ArrayList<Node> ro... | import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.client.renderer.model.ModelRenderer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import uk.kihira.gltf.Model;
import uk.kihira.tails.client.MountPoint;
import uk.kihira.tails.client.outfit.OutfitPart;
import uk.kihira.tails.client.PartRegistry;
import uk.kihira.tails.client.outfit.Outfit;
import uk.kihira.tails.common.Tails;
import java.util.Optional;
import java.util.UUID;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.vertex.IVertexBuilder; | package uk.kihira.tails.client.render;
/**
* Legacy renderer that uses the player render event.
* This is used for compatibility with certain mods
*/
public class FallbackRenderHandler
{
private static RenderPlayerEvent.Pre currentEvent = null;
private static Outfit currentOutfit = null;
private static ResourceLocation currentPlayerTexture = null;
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerRenderTick(RenderPlayerEvent.Pre e)
{
UUID uuid = e.getPlayer().getGameProfile().getId();
if (Tails.proxy.hasActiveOutfit(uuid) && !e.getPlayer().isInvisible())
{
currentOutfit = Tails.proxy.getActiveOutfit(uuid);
currentPlayerTexture = ((ClientPlayerEntity) e.getPlayer()).getLocationSkin();
currentEvent = e;
}
}
@SubscribeEvent()
public void onPlayerRenderTickPost(RenderPlayerEvent.Post e)
{
//Reset to null after rendering the current tail
currentOutfit = null;
currentPlayerTexture = null;
currentEvent = null;
}
public static class ModelRendererWrapper extends ModelRenderer
{
private final MountPoint mountPoint;
| public ModelRendererWrapper(net.minecraft.client.renderer.model.Model model, MountPoint mountPoint) | 0 |
bonigarcia/dualsub | src/test/java/io/github/bonigarcia/dualsub/test/TestSrt.java | [
"public class DualSrt {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(DualSrt.class);\n\n\tprivate TreeMap<String, Entry[]> subtitles;\n\n\tprivate int signatureGap;\n\tprivate int signatureTime;\n\tprivate int gap;\n\tprivate int desync;\n\tprivate int extension;\n\tprivate boolean extend;\n\tpriv... | import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.bonigarcia.dualsub.srt.DualSrt;
import io.github.bonigarcia.dualsub.srt.Merger;
import io.github.bonigarcia.dualsub.srt.Srt;
import io.github.bonigarcia.dualsub.srt.SrtUtils;
import io.github.bonigarcia.dualsub.util.Charset;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.Properties;
import org.junit.Assert; | /*
* (C) Copyright 2014 Boni Garcia (http://bonigarcia.github.io/)
*
* 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 io.github.bonigarcia.dualsub.test;
/**
* TestSrt.
*
* @author Boni Garcia (boni.gg@gmail.com)
* @since 1.0.0
*/
public class TestSrt {
private static final Logger log = LoggerFactory.getLogger(TestSrt.class);
private Srt srtEn;
private Srt srtEs;
private Merger merger;
@Before
public void setup() throws IOException {
String srtEnFile = "Game of Thrones 1x01 - Winter Is Coming (English).srt";
String srtEsFile = "Game of Thrones 1x01 - Winter Is Coming (Spanish).srt";
SrtUtils.init("624", "Tahoma", 17, false, false, ".", 50, false, null,
null);
srtEn = new Srt(srtEnFile);
srtEs = new Srt(srtEsFile);
log.info(srtEn.getFileName() + " " + Charset.detect(srtEnFile));
log.info(srtEs.getFileName() + " " + Charset.detect(srtEsFile));
Properties properties = new Properties();
InputStream inputStream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("dualsub.properties");
properties.load(inputStream);
merger = new Merger(".", true, 1000, true, properties,
Charset.ISO88591, 0, false, true);
}
@Ignore
@Test
public void testReadSrt() throws IOException {
log.info("srtEnFile size=" + srtEn.getSubtitles().size());
log.info("srtEsFile size=" + srtEs.getSubtitles().size());
Assert.assertEquals(srtEn.getSubtitles().size(), srtEs.getSubtitles()
.size());
}
@Ignore
@Test
public void testTime() throws ParseException {
String line1 = "01:27:40,480 --> 01:26:56,260";
String line2 = "01:27:40 --> 01:27:49,500";
Date init1 = SrtUtils.getInitTime(line1);
Date init2 = SrtUtils.getInitTime(line2);
Date end1 = SrtUtils.getEndTime(line1);
Date end2 = SrtUtils.getEndTime(line2);
log.info(init1 + " " + init1.getTime());
log.info(init2 + " " + init2.getTime());
log.info("---");
log.info(end1 + " " + end1.getTime());
log.info(end2 + " " + end2.getTime());
Assert.assertTrue(init1.getTime() > init2.getTime());
}
@Ignore
@Test
public void testMergedFileName() {
String mergedFileName = merger.getMergedFileName(srtEs, srtEn);
log.info(mergedFileName);
Assert.assertEquals("." + File.separator
+ "Game of Thrones 1x01 - Winter Is Coming.srt", mergedFileName);
}
@Ignore
@Test
public void testCompleteSrtISO88591() throws ParseException, IOException { | DualSrt dualSrt = merger.mergeSubs(srtEs, srtEn); | 0 |
ferstl/depgraph-maven-plugin | src/main/java/com/github/ferstl/depgraph/ReactorGraphMojo.java | [
"public final class DependencyNode {\n\n private final Artifact artifact;\n private final String effectiveVersion;\n private final NodeResolution resolution;\n private final Set<String> scopes;\n private final Set<String> classifiers;\n private final Set<String> types;\n\n\n public DependencyNode(Artifact ar... | import java.util.Set;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import com.github.ferstl.depgraph.dependency.DependencyNode;
import com.github.ferstl.depgraph.dependency.DependencyNodeIdRenderer;
import com.github.ferstl.depgraph.dependency.GraphFactory;
import com.github.ferstl.depgraph.dependency.GraphStyleConfigurer;
import com.github.ferstl.depgraph.dependency.ReactorGraphFactory;
import com.github.ferstl.depgraph.dependency.dot.style.resource.BuiltInStyleResource;
import com.github.ferstl.depgraph.graph.GraphBuilder;
import static com.github.ferstl.depgraph.dependency.dot.style.resource.BuiltInStyleResource.REACTOR_STYLE; | package com.github.ferstl.depgraph;
/**
* Creates a dependency graph of the Maven rector in a multi-module project.
*
* @since 4.0.0
*/
@Mojo(
name = "reactor",
aggregator = true,
defaultPhase = LifecyclePhase.NONE,
requiresDependencyCollection = ResolutionScope.NONE,
threadSafe = true)
public class ReactorGraphMojo extends AbstractGraphMojo {
/**
* If set to {@code true}, the created graph will show the {@code groupId} on all artifacts.
*
* @since 4.0.0
*/
@Parameter(property = "showGroupIds", defaultValue = "false")
private boolean showGroupIds;
/**
* If set to {@code true}, the created graph will show version information an all artifacts.
*
* @since 4.0.0
*/
@Parameter(property = "showVersions", defaultValue = "false")
private boolean showVersions;
@Parameter(defaultValue = "${session}", readonly = true)
private MavenSession mavenSession;
@Override
protected GraphFactory createGraphFactory(GraphStyleConfigurer graphStyleConfigurer) {
DependencyNodeIdRenderer nodeIdRenderer = DependencyNodeIdRenderer.versionlessId();
GraphBuilder<DependencyNode> graphBuilder = createGraphBuilder(graphStyleConfigurer, nodeIdRenderer);
return new ReactorGraphFactory(this.mavenSession.getProjectDependencyGraph(), graphBuilder, nodeIdRenderer);
}
private GraphBuilder<DependencyNode> createGraphBuilder(GraphStyleConfigurer graphStyleConfigurer, DependencyNodeIdRenderer nodeIdRenderer) {
return graphStyleConfigurer
.showGroupIds(this.showGroupIds)
.showArtifactIds(true)
.showScope(false)
.showVersionsOnNodes(this.showVersions)
.configure(GraphBuilder.create(nodeIdRenderer));
}
@Override | protected Set<BuiltInStyleResource> getAdditionalStyleResources() { | 5 |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/presenter/implement/CreateReplyPresenter.java | [
"public final class ApiClient {\n\n private ApiClient() {}\n\n public static final ApiService service = new Retrofit.Builder()\n .baseUrl(ApiDefine.API_BASE_URL)\n .client(new OkHttpClient.Builder()\n .addInterceptor(createUserAgentInterceptor())\n .... | import android.app.Activity;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.model.api.ApiClient;
import org.cnodejs.android.md.model.api.SessionCallback;
import org.cnodejs.android.md.model.entity.Author;
import org.cnodejs.android.md.model.entity.Reply;
import org.cnodejs.android.md.model.entity.ReplyTopicResult;
import org.cnodejs.android.md.model.storage.LoginShared;
import org.cnodejs.android.md.model.storage.SettingShared;
import org.cnodejs.android.md.presenter.contract.ICreateReplyPresenter;
import org.cnodejs.android.md.ui.view.ICreateReplyView;
import org.joda.time.DateTime;
import java.util.ArrayList;
import okhttp3.Headers; | package org.cnodejs.android.md.presenter.implement;
public class CreateReplyPresenter implements ICreateReplyPresenter {
private final Activity activity;
private final ICreateReplyView createReplyView;
public CreateReplyPresenter(@NonNull Activity activity, @NonNull ICreateReplyView createReplyView) {
this.activity = activity;
this.createReplyView = createReplyView;
}
@Override
public void createReplyAsyncTask(@NonNull String topicId, String content, final String targetId) {
if (TextUtils.isEmpty(content)) {
createReplyView.onContentError(activity.getString(R.string.content_empty_error_tip));
} else {
final String finalContent;
if (SettingShared.isEnableTopicSign(activity)) { // 添加小尾巴
finalContent = content + "\n\n" + SettingShared.getTopicSignContent(activity);
} else {
finalContent = content;
}
createReplyView.onReplyTopicStart(); | ApiClient.service.createReply(topicId, LoginShared.getAccessToken(activity), finalContent, targetId).enqueue(new SessionCallback<ReplyTopicResult>(activity) { | 1 |
WinRoad-NET/wrdocletbase | src/main/java/net/winroad/wrdoclet/data/WRDoc.java | [
"public abstract class AbstractConfiguration extends Configuration {\n\n\t/**\n\t * Argument for command line option \"-dubboconfigpath\".\n\t */\n\tpublic String dubboconfigpath = \"\";\n\n\t/**\n\t * Argument for command line option \"-springcontextconfigpath\".\n\t */\n\tpublic String springcontextconfigpath = \... | import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.winroad.wrdoclet.AbstractConfiguration;
import net.winroad.wrdoclet.builder.AbstractDocBuilder;
import net.winroad.wrdoclet.builder.DubboDocBuilder;
import net.winroad.wrdoclet.builder.MQDocBuilder;
import net.winroad.wrdoclet.builder.RESTDocBuilder;
import net.winroad.wrdoclet.builder.SOAPDocBuilder;
import net.winroad.wrdoclet.utils.Logger;
import net.winroad.wrdoclet.utils.LoggerFactory;
import com.sun.tools.doclets.internal.toolkit.Configuration; | package net.winroad.wrdoclet.data;
public class WRDoc {
private Map<String, List<OpenAPI>> taggedOpenAPIs = new HashMap<String, List<OpenAPI>>();
private List<AbstractDocBuilder> builders = new LinkedList<AbstractDocBuilder>();
// The collection of tag name in this Doc.
private Set<String> wrTags = new HashSet<String>();
private Configuration configuration;
private String docGeneratedDate;
| private Logger logger = LoggerFactory.getLogger(this.getClass()); | 6 |
ceefour/webdav-servlet | src/main/java/net/sf/webdav/methods/DoHead.java | [
"public interface IMimeTyper {\n\n /**\n * Detect the mime type of this object\n * \n * @param transaction\n * @param path\n * @return \n */\n String getMimeType(ITransaction transaction, String path);\n}",
"public class StoredObject {\n\n private boolean isFolder;\n private Da... | import net.sf.webdav.locking.ResourceLocks;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.webdav.IMimeTyper;
import net.sf.webdav.StoredObject;
import net.sf.webdav.ITransaction;
import net.sf.webdav.WebdavStatus;
import net.sf.webdav.IWebdavStore;
import net.sf.webdav.exceptions.AccessDeniedException;
import net.sf.webdav.exceptions.LockFailedException;
import net.sf.webdav.exceptions.ObjectAlreadyExistsException;
import net.sf.webdav.exceptions.WebdavException; | /*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.webdav.methods;
public class DoHead extends AbstractMethod {
protected String _dftIndexFile;
protected IWebdavStore _store;
protected String _insteadOf404;
protected ResourceLocks _resourceLocks;
protected IMimeTyper _mimeTyper;
protected int _contentLength;
private static org.slf4j.Logger LOG = org.slf4j.LoggerFactory
.getLogger(DoHead.class);
public DoHead(IWebdavStore store, String dftIndexFile, String insteadOf404,
ResourceLocks resourceLocks, IMimeTyper mimeTyper,
int contentLengthHeader) {
_store = store;
_dftIndexFile = dftIndexFile;
_insteadOf404 = insteadOf404;
_resourceLocks = resourceLocks;
_mimeTyper = mimeTyper;
_contentLength = contentLengthHeader;
}
public void execute(ITransaction transaction, HttpServletRequest req,
HttpServletResponse resp) throws IOException, LockFailedException {
// determines if the uri exists.
boolean bUriExists = false;
String path = getRelativePath(req);
LOG.trace("-- " + this.getClass().getName());
StoredObject so;
try {
so = _store.getStoredObject(transaction, path);
if (so == null) {
if (this._insteadOf404 != null && !_insteadOf404.trim().equals("")) {
path = this._insteadOf404;
so = _store.getStoredObject(transaction, this._insteadOf404);
}
} else
bUriExists = true;
} catch (AccessDeniedException e) {
resp.sendError(WebdavStatus.SC_FORBIDDEN);
return;
}
if (so != null) {
if (so.isFolder()) {
if (_dftIndexFile != null && !_dftIndexFile.trim().equals("")) {
resp.sendRedirect(resp.encodeRedirectURL(req
.getRequestURI()
+ this._dftIndexFile));
return;
}
} else if (so.isNullResource()) {
String methodsAllowed = DeterminableMethod
.determineMethodsAllowed(so);
resp.addHeader("Allow", methodsAllowed);
resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED);
return;
}
String tempLockOwner = "doGet" + System.currentTimeMillis()
+ req.toString();
if (_resourceLocks.lock(transaction, path, tempLockOwner, false, 0,
TEMP_TIMEOUT, TEMPORARY)) {
try {
String eTagMatch = req.getHeader("If-None-Match");
if (eTagMatch != null) {
if (eTagMatch.equals(getETag(so))) {
resp.setStatus(WebdavStatus.SC_NOT_MODIFIED);
return;
}
}
if (so.isResource()) {
// path points to a file but ends with / or \
if (path.endsWith("/") || (path.endsWith("\\"))) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND,
req.getRequestURI());
} else {
// setting headers
long lastModified = so.getLastModified().getTime();
resp.setDateHeader("last-modified", lastModified);
String eTag = getETag(so);
resp.addHeader("ETag", eTag);
long resourceLength = so.getResourceLength();
if (_contentLength == 1) {
if (resourceLength > 0) {
if (resourceLength <= Integer.MAX_VALUE) {
resp
.setContentLength((int) resourceLength);
} else {
resp.setHeader("content-length", ""
+ resourceLength);
// is "content-length" the right header?
// is long a valid format?
}
}
}
String mimeType = _mimeTyper.getMimeType(transaction, path);
if (mimeType != null) {
resp.setContentType(mimeType);
} else {
int lastSlash = path.replace('\\', '/')
.lastIndexOf('/');
int lastDot = path.indexOf(".", lastSlash);
if (lastDot == -1) {
resp.setContentType("text/html");
}
}
doBody(transaction, resp, path);
}
} else {
folderBody(transaction, path, resp, req);
}
} catch (AccessDeniedException e) {
resp.sendError(WebdavStatus.SC_FORBIDDEN);
} catch (ObjectAlreadyExistsException e) {
resp.sendError(WebdavStatus.SC_NOT_FOUND, req
.getRequestURI()); | } catch (WebdavException e) { | 6 |
ZevenFang/zevencourse | src/main/java/com/zeven/course/service/CourseService.java | [
"public class TeacherCommon {\n\n public static List<Map<String, Object>> teacherList(List<Teacher> teachers){\n List<Map<String, Object>> teacherList = new ArrayList<Map<String, Object>>();\n for (Teacher t:teachers){\n Map<String,Object> teacherMap = new HashMap<String, Object>();\n ... | import com.zeven.course.common.TeacherCommon;
import com.zeven.course.dao.DaoSupportImpl;
import com.zeven.course.model.Course;
import com.zeven.course.model.Teacher;
import com.zeven.course.model.TeacherCourse;
import org.hibernate.Query;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | package com.zeven.course.service;
/**
* Created by fangf on 2016/5/21.
*/
@Component
public class CourseService extends DaoSupportImpl<Course>{
public List getAvailableCourses(){
Query query = getSession().createQuery("FROM Course WHERE id not in (SELECT distinct cid FROM TeacherCourse)");
List list = query.list();
return list;
}
public List findCoursesByTid(int id){
Query query = getSession().createQuery("FROM Course WHERE id in (SELECT cid FROM TeacherCourse WHERE tid = (:tid))");
List list = query.setParameter("tid",id).list();
return list;
}
public Map<String,List> findCoursesBySid(int id){
Map<String,List> data = new HashMap<String, List>();
Query query = getSession().createQuery("FROM Course WHERE id in (SELECT cid FROM CourseStudent WHERE sid = (:sid))");
List<Course> courses = query.setParameter("sid",id).list();
data.put("courses",courses);
Integer[] cids = new Integer[courses.size()];
for (int i=0;i<courses.size();i++)
cids[i] = courses.get(i).getId();
List<Teacher> teachers; | List<TeacherCourse> tc; | 4 |
jadler-mocking/jadler | jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java | [
"public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) {\n return new BodyRequestMatcher(pred);\n}",
"public static HeaderRequestMatcher requestHeader(final String headerName,\n final Matcher<? super List<String>> pred) {\n return ne... | import org.apache.commons.lang.Validate;
import org.hamcrest.Matcher;
import java.util.ArrayList;
import java.util.List;
import static net.jadler.matchers.BodyRequestMatcher.requestBody;
import static net.jadler.matchers.HeaderRequestMatcher.requestHeader;
import static net.jadler.matchers.MethodRequestMatcher.requestMethod;
import static net.jadler.matchers.ParameterRequestMatcher.requestParameter;
import static net.jadler.matchers.PathRequestMatcher.requestPath;
import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString;
import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.notNullValue; | /*
* Copyright (c) 2012 - 2016 Jadler contributors
* This program is made available under the terms of the MIT License.
*/
package net.jadler;
/**
* A base implementation of the {@link RequestMatching} interface. Collects all request predicates to a protected
* collection available in extending classes.
*
* @param <T> type (either class or interface) of the class extending this abstract class. This type will be returned
* by all methods introduced in {@link RequestMatching} implemented by this class so fluid request matching
* is possible.
*/
public abstract class AbstractRequestMatching<T extends RequestMatching<T>> implements RequestMatching<T> {
protected final List<Matcher<? super Request>> predicates;
protected AbstractRequestMatching() {
this.predicates = new ArrayList<Matcher<? super Request>>();
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public T that(final Matcher<? super Request> predicate) {
Validate.notNull(predicate, "predicate cannot be null");
this.predicates.add(predicate);
return (T) this;
}
/**
* {@inheritDoc}
*/
@Override
public T havingMethodEqualTo(final String method) {
Validate.notEmpty(method, "method cannot be empty");
return havingMethod(equalToIgnoringCase(method));
}
/**
* {@inheritDoc}
*/
@Override
public T havingMethod(final Matcher<? super String> predicate) {
Validate.notNull(predicate, "predicate cannot be null");
return that(requestMethod(predicate));
}
/**
* {@inheritDoc}
*/
@Override
public T havingBodyEqualTo(final String requestBody) {
Validate.notNull(requestBody, "requestBody cannot be null, use an empty string instead");
return havingBody(equalTo(requestBody));
}
/**
* {@inheritDoc}
*/
@Override
public T havingBody(final Matcher<? super String> predicate) {
Validate.notNull(predicate, "predicate cannot be null");
return that(requestBody(predicate));
}
/**
* {@inheritDoc}
*/
@Override
public T havingRawBodyEqualTo(final byte[] requestBody) {
Validate.notNull(requestBody, "requestBody cannot be null, use an empty array instead");
return that(requestRawBody(equalTo(requestBody)));
}
/**
* {@inheritDoc}
*/
@Override
public T havingPathEqualTo(final String path) {
Validate.notEmpty(path, "path cannot be empty");
return havingPath(equalTo(path));
}
/**
* {@inheritDoc}
*/
@Override
public T havingPath(final Matcher<? super String> predicate) {
Validate.notNull(predicate, "predicate cannot be null");
| return that(requestPath(predicate)); | 4 |
spectralmind/sonarflow-android | app/src/main/java/com/spectralmind/sf4android/SonarflowState.java | [
"public interface BubbleLoader{\n\tpublic void onFinished(List<Bubble> bubbles);\n};",
"public class Bubble {\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(Bubble.class);\n\t\n\tprivate static final float FADE_SIZE = 25;\n\tprivate static final float MINIMUM_SIZE_TO_SHOW_CHILDREN = 340;\n\tpriva... | import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.spectralmind.sf4android.MainActivity.BubbleLoader;
import com.spectralmind.sf4android.bubble.Bubble;
import com.spectralmind.sf4android.bubble.BubbleLayouter;
import com.spectralmind.sf4android.bubble.BubblesView;
import com.spectralmind.sf4android.media.GenreLoader;
import com.spectralmind.sf4android.media.MoodLoader; | package com.spectralmind.sf4android;
public class SonarflowState {
private static final Logger LOGGER = LoggerFactory.getLogger(SonarflowState.class);
private static final String GENRES_XML = "genres.xml";
private static final String MOODS_XML = "moods.xml";
private static final String ATTRIBUTES_XML ="cluster_attributes.xml";
public static final int GENRE_BUBBLES = 0;
public static final int MOOD_BUBBLES = 1;
private List<Bubble> genreBubbles;
private List<Bubble> moodBubbles; | private BubbleLayouter layouter; | 2 |
Multiplayer-italia/AuthMe-Reloaded | src/main/java/uk/org/whoami/authme/listener/AuthMeEntityListener.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 uk.org.whoami.authme.plugin.manager.CombatTagComunicator;
import uk.org.whoami.authme.settings.Settings;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import uk.org.whoami.authme.Utils;
import uk.org.whoami.authme.cache.auth.PlayerCache;
import uk.org.whoami.authme.plugin.manager.CitizensCommunicator;
import uk.org.whoami.authme.datasource.DataSource;
| /*
* 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.listener;
public class AuthMeEntityListener implements Listener{
private DataSource data;
//private Settings settings = Settings.getInstance();
public AuthMeEntityListener(DataSource data) {
this.data = data;
}
@EventHandler
public void onEntityDamage(EntityDamageEvent event) {
if (event.isCancelled()) {
return;
}
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
/*
System.out.println("[ Entity Damage ] "+event.getEntity().toString());
@Future implementation till CombatTag dont release any apis
if(event.getEntity().toString().indexOf("PvPLogger") != -1 ) {
System.out.println("la stringa contiene PvPLogger 2");
return;
}
*/
| if(CitizensCommunicator.isNPC(entity) || Utils.getInstance().isUnrestricted((Player)entity) || CombatTagComunicator.isNPC(entity)) {
| 3 |
Simonsator/BungeecordPartyAndFriends | src/main/java/de/simonsator/partyandfriends/api/pafplayers/PAFPlayerClass.java | [
"public class BukkitBungeeAdapter {\n\tprivate static BukkitBungeeAdapter instance;\n\tprivate final Plugin PAF_EXTENSION;\n\tprivate boolean forceUuidSupport = false;\n\n\tpublic BukkitBungeeAdapter(PAFExtension pPlugin) {\n\t\tthis((PAFPluginBase) pPlugin);\n\t}\n\n\tpublic BukkitBungeeAdapter(PAFPluginBase pPlug... | import de.simonsator.partyandfriends.api.adapter.BukkitBungeeAdapter;
import de.simonsator.partyandfriends.api.events.DisplayNameProviderChangedEvent;
import de.simonsator.partyandfriends.api.friends.ServerConnector;
import de.simonsator.partyandfriends.utilities.StandardConnector;
import de.simonsator.partyandfriends.utilities.StandardDisplayNameProvider;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.protocol.packet.Chat;
import java.util.List;
import java.util.Random; | package de.simonsator.partyandfriends.api.pafplayers;
public abstract class PAFPlayerClass implements PAFPlayer {
private static DisplayNameProvider displayNameProvider = new StandardDisplayNameProvider(); | private static ServerConnector serverConnector = new StandardConnector(); | 3 |
hoijui/JavaOSC | modules/core/src/main/java/com/illposed/osc/argument/handler/BlobArgumentHandler.java | [
"public interface BytesReceiver {\n\n\t/**\n\t * Relative <i>put</i> method <i>(optional operation)</i>.\n\t *\n\t * <p> Writes the given byte into this buffer at the current\n\t * position, and then increments the position. </p>\n\t *\n\t * @param data\n\t * The byte to be written\n\t *\n\t * @... | import com.illposed.osc.BytesReceiver;
import com.illposed.osc.OSCParseException;
import com.illposed.osc.OSCSerializeException;
import com.illposed.osc.OSCSerializer;
import com.illposed.osc.argument.ArgumentHandler;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.Map; | // SPDX-FileCopyrightText: 2015-2017 C. Ramakrishnan / Illposed Software
// SPDX-FileCopyrightText: 2021 Robin Vobruba <hoijui.quaero@gmail.com>
//
// SPDX-License-Identifier: BSD-3-Clause
package com.illposed.osc.argument.handler;
/**
* Parses and serializes an OSC binary-blob type.
*/
public class BlobArgumentHandler implements ArgumentHandler<ByteBuffer>, Cloneable {
public static final ArgumentHandler<ByteBuffer> INSTANCE = new BlobArgumentHandler();
/** Allow overriding, but somewhat enforce the ugly singleton. */
protected BlobArgumentHandler() {
// declared only for setting the access level
}
@Override
public char getDefaultIdentifier() {
return 'b';
}
@Override
public Class<ByteBuffer> getJavaClass() {
return ByteBuffer.class;
}
@Override
public void setProperties(final Map<String, Object> properties) {
// we make no use of any properties
}
@Override
public boolean isMarkerOnly() {
return false;
}
@Override
@SuppressWarnings("unchecked")
public BlobArgumentHandler clone() throws CloneNotSupportedException {
return (BlobArgumentHandler) super.clone();
}
@Override
public ByteBuffer parse(final ByteBuffer input) throws OSCParseException {
final int blobLen = IntegerArgumentHandler.INSTANCE.parse(input);
final int previousLimit = input.limit();
((Buffer)input).limit(input.position() + blobLen);
final ByteBuffer value = input.slice();
((Buffer)input).limit(previousLimit);
return value;
}
@Override
public void serialize(final BytesReceiver output, final ByteBuffer value)
throws OSCSerializeException
{
final int numBytes = value.remaining();
IntegerArgumentHandler.INSTANCE.serialize(output, numBytes);
output.put(value); | OSCSerializer.align(output); | 3 |
synapticloop/routemaster | src/main/java/synapticloop/nanohttpd/example/servant/RouteMasterRestTemplarServant.java | [
"public abstract class RestRoutable extends Routable {\n\tprotected List<String> restParamNames = new ArrayList<String>();\n\n\tpublic RestRoutable(String routeContext, List<String> params) {\n\t\tsuper(routeContext);\n\t\tthis.restParamNames = params;\n\t}\n\n\t/**\n\t * Serve the correct http method (GET, POST, P... | import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import synapticloop.nanohttpd.router.RestRoutable;
import synapticloop.nanohttpd.router.Routable;
import synapticloop.nanohttpd.router.RouteMaster;
import synapticloop.nanohttpd.router.Router;
import synapticloop.nanohttpd.utils.HttpUtils;
import synapticloop.nanohttpd.utils.TemplarHelper;
import synapticloop.templar.Parser;
import synapticloop.templar.exception.ParseException;
import synapticloop.templar.exception.RenderException;
import synapticloop.templar.utils.TemplarContext;
import fi.iki.elonen.NanoHTTPD.IHTTPSession;
import fi.iki.elonen.NanoHTTPD.Response; | package synapticloop.nanohttpd.example.servant;
/*
* Copyright (c) 2013-2020 synapticloop.
*
* All rights reserved.
*
* This source code and any derived binaries are covered by the terms and
* conditions of the Licence agreement ("the Licence"). You may not use this
* source code or any derived binaries except in compliance with the Licence.
* A copy of the Licence is available in the file named LICENCE shipped with
* this source code or binaries.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations
* under the Licence.
*/
public class RouteMasterRestTemplarServant extends RestRoutable {
private static final String ROUTER_SNIPPET_TEMPLAR = "/templar/router-snippet.templar";
private static final Logger LOGGER = Logger.getLogger(RouteMasterRestServant.class.getName());
public RouteMasterRestTemplarServant(String routeContext, List<String> params) {
super(routeContext, params);
}
@Override
public Response doGet(File rootDir, IHTTPSession httpSession, Map<String, String> restParams, String unmappedParams) {
String method = restParams.get("method");
StringBuilder content = new StringBuilder();
if(method != null) {
if("routes".equals(method)) {
Router router = RouteMaster.getRouter();
printRouter(rootDir, content, router);
return(HttpUtils.okResponse(content.toString()));
} else if ("cache".equals(method)) {
printCache(content);
return(HttpUtils.okResponse(content.toString()));
}
}
return(HttpUtils.okResponse(this.getClass().getName() + " [ " + method + " ] request: says OK, with method '" + method + "'"));
}
private void printCache(StringBuilder content) { | Map<String,Routable> routerCache = RouteMaster.getRouterCache(); | 1 |
ShawnShoper/x-job | xjob-util/xjob-util-log/log-util/src/main/java/org/shoper/log/util/LogFactory.java | [
"public enum Target {\n File,Sout,Kafka\n}",
"public abstract class Appender {\n LogProperties logProperties;\n\n /**\n * 用于初始化\n */\n public abstract void init();\n\n public Appender(LogProperties logProperties) {\n this.logProperties = logProperties;\n }\n\n /**\n * 日志输出接... | import org.shoper.log.core.config.Target;
import org.shoper.log.util.appender.Appender;
import org.shoper.log.util.appender.ConsoleAppender;
import org.shoper.log.util.appender.FileAppender;
import org.shoper.log.util.appender.KafkaAppender;
import org.shoper.log.util.config.LogPattern;
import org.shoper.log.util.config.LogProperties;
import org.shoper.log.util.constans.Tag;
import org.ho.yaml.Yaml;
import org.shoper.commons.core.StringUtil;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package org.shoper.log.util;
/**
* Created by ShawnShoper on 2017/4/17.
* 日志工厂
*/
public class LogFactory {
//日志配置
private static LogProperties logProperties;
private static LogProcessor logProcessor;
public final static String PERCENT = "%";
public static LogProperties getLogProperties() {
return logProperties;
}
private static void init() {
try {
LogFactory.logProperties = Yaml.loadType(LogProperties.class.getResourceAsStream("/log.yml"), LogProperties.class);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
// if (Objects.isNull(logProperties)) {
// logProperties.setApplication(logProperties.getApplication());
// logProperties.setHost(logProperties.getHost());
// logProperties.setPort(logProperties.getPort());
// logProperties.setPartten("%-23{yyyy-MM-dd HH:mm:ss.sss}t%-5l%6p%30mn%-5ln%cn%c");
// }
List<LogPattern> logPatterns = new ArrayList<>();
String partten = LogFactory.logProperties.getPartten();
String[] log_partten = partten.split(PERCENT);
Pattern reg_pattern = Pattern.compile("(-)?(\\d*?)(\\{.*?\\})?([a-z]+)", Pattern.CASE_INSENSITIVE);
//遍历pattern
Arrays.stream(log_partten).map(String::trim).filter(StringUtil::nonEmpty).map(e -> {
Matcher matcher = reg_pattern.matcher(e);
if (matcher.find()) {
String neg = matcher.group(1);
if (Objects.nonNull(neg) && !"-".equals(neg))
throw new RuntimeException(String.format("Log express neg %s not support", neg));
String offset = matcher.group(2);
String pattern = matcher.group(3);
if (Objects.nonNull(pattern)) {
pattern = pattern.substring(1, pattern.length() - 1);
}
String name = matcher.group(4);
if (Objects.isNull(name))
throw new RuntimeException(String.format("Log express tag %s not support", name)); | Tag tag; | 7 |
roncoo/roncoo-adminlte-springmvc | src/main/java/com/roncoo/adminlte/biz/DataDictionaryBiz.java | [
"public class RcDataDictionary implements Serializable {\r\n private Long id;\r\n\r\n private String statusId;\r\n\r\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\r\n private Date createTime;\r\n\r\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\r\n private Date updateTime;\r\n\r\n private ... | import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.roncoo.adminlte.bean.entity.RcDataDictionary;
import com.roncoo.adminlte.bean.vo.Result;
import com.roncoo.adminlte.service.DataDictionaryListService;
import com.roncoo.adminlte.service.DataDictionaryService;
import com.roncoo.adminlte.util.base.Page;
| /*
* Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group.
*
* 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.roncoo.adminlte.biz;
/**
* 数据字典逻辑业务类
*
* @author LYQ
*/
@Component
public class DataDictionaryBiz {
@Autowired
private DataDictionaryService dictionaryService;
@Autowired
| private DataDictionaryListService dictionaryListService;
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.