hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
1875c1e9f898f558d1806ec6ae064613215880fb
| 1,842
|
package com.google.collide.client.plugin;
import com.google.collide.client.AppContext;
import com.google.collide.client.history.Place;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.shared.plugin.PublicService;
import com.google.collide.shared.plugin.PublicServices;
import xapi.fu.Out1;
import xapi.inject.X_Inject;
public class ClientPluginService {
protected ClientPluginService() {
}
private static final Out1<ClientPluginService> SINGLETON = X_Inject.singletonLazy(ClientPluginService.class);
public static ClientPluginService initialize(AppContext appContext, MultiPanel<?,?> masterPanel
, Place workspacePlace) {
ClientPluginService plugins = SINGLETON.out1();
plugins.init(appContext, masterPanel, workspacePlace);
return plugins;
}
@SuppressWarnings({"unchecked","rawtypes"})
protected void init(AppContext appContext, MultiPanel<?, ?> masterPanel, Place workspacePlace) {
for (ClientPlugin<?> plugin : plugins()) {
plugin.initializePlugin(appContext, masterPanel, workspacePlace);
PublicService<?>[] services = plugin.getPublicServices();
if (services != null)
for (PublicService service : plugin.getPublicServices()) {
PublicServices.registerService(service.classKey(), service);
}
}
}
public static ClientPlugin<?>[] getPlugins() {
return SINGLETON.out1().plugins();
}
@SuppressWarnings("unchecked")
public static <T extends ClientPlugin<?>> T getPlugin(Class<T> cls) {
for (ClientPlugin<?> plugin : getPlugins()) {
if (cls.isAssignableFrom(plugin.getClass())) {
return (T)plugin;
}
}
return null;
}
public ClientPlugin<?>[] plugins() {
return new ClientPlugin[0];
}
public void cleanup() {
//notify any of our plugins that require cleanup.
}
}
| 30.196721
| 111
| 0.718241
|
188ca037deef01f1d0d68ac03b27c9adbfa3e28c
| 258
|
package ua.com.fielden.platform.sample.domain;
import ua.com.fielden.platform.dao.IEntityDao;
/**
* Companion object for entity {@link TgEntityDateKey}.
*
* @author TG Team
*
*/
public interface ITgEntityDateKey extends IEntityDao<TgEntityDateKey> {
}
| 21.5
| 71
| 0.75969
|
f768c20870c20ee0d269e9b1d534a36274ed70e6
| 175
|
module rs.etf.stud.botfights.extend.java {
requires transitive rs.etf.stud.botfights.extend;
requires java.management;
exports rs.etf.stud.botfights.extend.java;
}
| 35
| 53
| 0.76
|
d4421e944c7ea8bfc759d06e0588ee06cbf5c7b2
| 3,158
|
/*
* Copyright (c) 2021, Collins Aerospace.
* Developed with the sponsorship of Defense Advanced Research Projects Agency (DARPA).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this data,
* including any software or models in source or binary form, as well as any drawings, specifications,
* and documentation (collectively "the Data"), to deal in the Data without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Data, and to permit persons to whom the Data 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 Data.
*
* THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
package com.rockwellcollins.atc.agree.analysis.preferences;
/**
* Constant definitions for plug-in preferences
*/
public class PreferenceConstants {
public static final String PREF_INDUCT_CEX = "inductiveCounterexamples";
public static final String PREF_SUPPORT = "setOfSupport";
public static final String PREF_SMOOTH_CEX = "smoothCounterexamples";
public static final String PREF_UNSPECIFIED_AADL_PROPERTIES = "analyzeUnspecifiedAadlProperties";
public static final String PREF_DISPLAY_DECIMAL_CEX = "displayCounterexamplesAsDecimal";
public static final String PREF_BLAME_CEX = "blameCounterexamples";
public static final String PREF_NO_KINDUCTION = "disableKInduction";
public static final String PREF_DEPTH = "inductionDepth";
public static final String PREF_TIMEOUT = "timeout";
public static final String PREF_PDR_MAX = "pdrMax";
public static final String PREF_SOLVER = "solver";
public static final String SOLVER_SMTINTERPOL = "SMTInterpol";
public static final String SOLVER_YICES = "Yices";
public static final String SOLVER_Z3 = "Z3";
public static final String SOLVER_CVC4 = "CVC4";
public static final String SOLVER_YICES2 = "Yices 2";
public static final String SOLVER_DREAL = "dReal";
public static final String PREF_MODEL_CHECKER = "modelChecker";
public static final String MODEL_CHECKER_JKIND = "JKind";
public static final String MODEL_CHECKER_KIND2 = "Kind 2";
public static final String MODEL_CHECKER_KIND2WEB = "Kind 2 Remote";
public static final String MODEL_CHECKER_SALLY = "Sally";
public static final String PREF_REMOTE_URL = "remoteUrl";
public static final String PREF_CONSIST_DEPTH = "consistDepth";
public static final String PREF_PROP_LOG = "propLog";
public static final String PREF_PROP_LOG_FILENAME = "propLogFileName";
public static final String PREF_DEBUG = "debug";
}
| 43.861111
| 102
| 0.783724
|
139e6ea23f4420194ff55c4841258d474e56c8cc
| 5,144
|
package com.harsh.searchwidget.Builder;
import com.harsh.searchwidget.Model.ClientSuggestionsModel;
import com.harsh.searchwidget.R;
import java.util.ArrayList;
import java.util.HashMap;
public class DefaultClientSuggestions {
ArrayList<String> suggestions;
ArrayList<HashMap<String, ArrayList<String>>> extraProperties = null;
ArrayList<String> categories = null;
ArrayList<Boolean> categoricalSearch = null;
ArrayList<Integer> searchIcon = null;
ArrayList<Integer> trendingIcon = null;
ArrayList<String> hits = null;
/**
* Builder for single suggestion entry
*
* @param suggestions List of suggestions
*/
public DefaultClientSuggestions(ArrayList<String> suggestions) {
this.suggestions = suggestions;
}
/**
* Sets values for extra fields passed in key-value format
*
* @param extraProperties Values for given extra fields in key-value format using Hashmap data structure
* @return
*/
public DefaultClientSuggestions setExtraProperties(ArrayList<HashMap<String, ArrayList<String>>> extraProperties) {
this.extraProperties = extraProperties;
return this;
}
/**
* Sets categories to be shown below search results
*
* @param categories List of categories
* @return
*/
public DefaultClientSuggestions setCategories(ArrayList<String> categories) {
this.categories = categories;
return this;
}
public DefaultClientSuggestions setCategoricalSearch(ArrayList<Boolean> categoricalSearch) {
this.categoricalSearch = categoricalSearch;
return this;
}
/**
* Sets images or icons for suggestions
*
* @param searchIcon List of resource ids for each suggestion
* @return
*/
public DefaultClientSuggestions setSearchImages(ArrayList<Integer> searchIcon) {
this.searchIcon = searchIcon;
return this;
}
/**
* Sets extra trending images or icons for suggestions - The rightmost icon
*
* @param trendingIcon List of resource ids for each suggestion
* @return
*/
public DefaultClientSuggestions setIcons(ArrayList<Integer> trendingIcon) {
this.trendingIcon = trendingIcon;
return this;
}
/**
* Sets the hit count for each suggestion
*
* @param hits List of hits
* @return
*/
public DefaultClientSuggestions hits(ArrayList<String> hits) {
this.hits = hits;
return this;
}
/**
* Binds all the parameter of Suggestion Builder and makes a list of SuggestionModel items
*
* @return List of items of SuggestionModel class
*/
public ArrayList<ClientSuggestionsModel> build() {
ArrayList<ClientSuggestionsModel> suggestions = new ArrayList<>();
String category;
boolean isCategoricalSearch;
String hit;
int searchicon;
int trendingicon;
HashMap<String, ArrayList<String>> extraProperty;
for(int i = 0; i < this.suggestions.size(); i++) {
if(this.categories == null)
category = null;
else {
if(this.categories.size() > i) {
category = this.categories.get(i);
}
else
category = null;
}
if(this.categoricalSearch == null)
isCategoricalSearch = false;
else {
if(this.categoricalSearch.size() > i)
isCategoricalSearch = this.categoricalSearch.get(i);
else
isCategoricalSearch = false;
}
if(this.hits == null)
hit = null;
else {
if(this.hits.size() > i) {
hit = this.hits.get(i);
}
else
hit = null;
}
if(this.searchIcon == null)
searchicon = R.drawable.ic_search_icon;
else {
if(this.searchIcon.size() > i) {
searchicon = this.searchIcon.get(i);
}
else
searchicon = R.drawable.ic_search_icon;
}
if(this.trendingIcon == null)
trendingicon = R.drawable.top_left_arrow;
else {
if(this.trendingIcon.size() > i) {
trendingicon = this.trendingIcon.get(i);
}
else
trendingicon = R.drawable.top_left_arrow;
}
if(this.extraProperties == null)
extraProperty = null;
else {
if(this.extraProperties.size() > i) {
extraProperty = this.extraProperties.get(i);
}
else
extraProperty = null;
}
suggestions.add(new ClientSuggestionsModel(this.suggestions.get(i), category, isCategoricalSearch, hit, searchicon, trendingicon, extraProperty));
}
return suggestions;
}
}
| 30.258824
| 158
| 0.573872
|
b1e0cf4c239e8031e1c0e655dd2d7786b2247237
| 5,631
|
package io.appium.uiautomator2.unittest.test;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.Until;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import io.appium.uiautomator2.server.ServerConfig;
import io.appium.uiautomator2.utils.Device;
import io.appium.uiautomator2.utils.Logger;
import static android.os.SystemClock.elapsedRealtime;
import static io.appium.uiautomator2.utils.Device.getUiDevice;
import static java.util.concurrent.TimeUnit.SECONDS;
public abstract class TestHelper {
public static final MediaType JSON = MediaType.parse("application/json; " + "charset=utf-8");
private static final OkHttpClient client = new OkHttpClient();
private static final String baseUrl = "http://localhost:" + ServerConfig.getServerPort();
private static final Instrumentation mInstrumentation = InstrumentationRegistry.getInstrumentation();
static {
final int timeout = 15 * 1000;
client.setConnectTimeout(timeout, SECONDS);
client.setReadTimeout(timeout, SECONDS);
client.setWriteTimeout(timeout, SECONDS);
}
public static String get(final String path) {
Request request = new Request.Builder().url(baseUrl + path).build();
return execute(request);
}
public static Response get(final String path, Response response) {
Request request = new Request.Builder().url(baseUrl + path).build();
response = execute(request,response);
return response;
}
public static final void waitForNetty() {
long start = elapsedRealtime();
boolean unsuccessful = true;
do {
try {
get("/wd/hub/status");
unsuccessful = false;
} catch (Exception e) {
Logger.info("Waiting for the server ..");
}
} while (unsuccessful && (elapsedRealtime() - start < 5000));
if (unsuccessful) {
throw new RuntimeException("Failed to contact io.appium.uiautomator2.server on " + baseUrl);
}
}
public static String post(final String path, String body) {
Request request = new Request.Builder().url(baseUrl + path).post(RequestBody.create(JSON, body)).build();
Logger.info("POST: " + body);
return execute(request);
}
public static String delete(final String path, String body) {
Request request = new Request.Builder().url(path).delete(RequestBody.create(JSON, body)).build();
Logger.info("DELETE: " + body);
return execute(request);
}
public static Response post(final String path, String body, Response response) {
Request request = new Request.Builder().url(baseUrl + path).post(RequestBody.create(JSON, body)).build();
Logger.info("POST: " + body);
return execute(request, response);
}
private static String execute(Request request) {
String result;
try {
Response response = client.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
throw new RuntimeException(request.method() + " \"" + request.urlString() + "\" failed. ", e);
}
return result;
}
private static Response execute(Request request, Response response) {
try {
response = client.newCall(request).execute();
} catch (IOException e) {
throw new RuntimeException(request.method() + " \"" + request.urlString() + "\" failed. ", e);
}
return response;
}
// Ported from android-support-test/rules/src/main/java/android/support/test/rule/ActivityTestRule.java
public static <T extends Activity> T launchActivity(Class<T> activityClass) {
final String targetPackage = mInstrumentation.getTargetContext().getPackageName();
Intent startIntent = new Intent(Intent.ACTION_MAIN);
startIntent.setClassName(targetPackage, activityClass.getName());
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// The following cast is correct because the activity we're creating is of the
// same type as the one passed in
T mActivity = activityClass.cast(mInstrumentation.startActivitySync(startIntent));
mInstrumentation.waitForIdleSync();
return mActivity;
}
public static void waitForAppToLaunch(String testAppPkg, int LAUNCH_TIMEOUT) throws InterruptedException {
long start = elapsedRealtime();
boolean waitStatus;
do {
Device.waitForIdle();
waitStatus = getUiDevice().wait(Until.hasObject(By.pkg(testAppPkg).depth(0)), LAUNCH_TIMEOUT);
if (waitStatus) break;
} while ((elapsedRealtime() - start < LAUNCH_TIMEOUT));
}
/**
* return JSONObjects count in a JSONArray
*
* @param jsonArray
*
* @return
*/
public static int getJsonObjectCountInJsonArray(JSONArray jsonArray) {
int count = 0;
try {
for (int i = 0; i < jsonArray.length(); i++, count++) {
jsonArray.getJSONObject(i);
}
return count;
} catch (JSONException e) {
return count;
}
}
}
| 36.329032
| 113
| 0.659386
|
13d2dddae895d79075f43a410637ca47ab96b059
| 253
|
package com.coding.zxm.lib_apm_plugin.core.job.watchDog;
import com.coding.zxm.lib_apm_plugin.core.job.block.BlockInfo;
/**
* @author ArgusAPM Team
*/
public class WatchDogInfo extends BlockInfo {
private final String SUB_TAG = "WachDogInfo";
}
| 23
| 62
| 0.766798
|
b5e1e6ba883b6774514d5939dc5ba7b677258dc3
| 3,089
|
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.viewer.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.util.viewer.model.ViewerModel;
import net.sourceforge.pmd.util.viewer.model.ViewerModelEvent;
import net.sourceforge.pmd.util.viewer.model.ViewerModelListener;
import net.sourceforge.pmd.util.viewer.util.NLS;
/**
* source code panel
*
* @author Boris Gruschko ( boris at gruschko.org )
* @version $Id$
*/
@Deprecated // to be removed with PMD 7.0.0
public class SourceCodePanel extends JPanel implements ViewerModelListener {
private ViewerModel model;
private JTextArea sourceCodeArea;
private static final Color HIGHLIGHT_COLOR = new Color(79, 237, 111);
public SourceCodePanel(ViewerModel model) {
this.model = model;
init();
}
private void init() {
model.addViewerModelListener(this);
setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), NLS.nls("SOURCE.PANEL.TITLE")));
setLayout(new BorderLayout());
sourceCodeArea = new JTextArea();
add(new JScrollPane(sourceCodeArea), BorderLayout.CENTER);
}
/**
* retrieves the string representation of the source code
*
* @return source code's string representation
*/
public String getSourceCode() {
return sourceCodeArea.getText();
}
/**
* @see ViewerModelListener#viewerModelChanged(ViewerModelEvent)
*/
@Override
public void viewerModelChanged(ViewerModelEvent e) {
if (e.getReason() == ViewerModelEvent.NODE_SELECTED) {
final Node node = (Node) e.getParameter();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
sourceCodeArea.getHighlighter().removeAllHighlights();
if (node == null) {
return;
}
int startOffset = sourceCodeArea.getLineStartOffset(node.getBeginLine() - 1)
+ node.getBeginColumn() - 1;
int end = sourceCodeArea.getLineStartOffset(node.getEndLine() - 1) + node.getEndColumn();
sourceCodeArea.getHighlighter().addHighlight(startOffset, end,
new DefaultHighlighter.DefaultHighlightPainter(HIGHLIGHT_COLOR));
sourceCodeArea.moveCaretPosition(startOffset);
} catch (BadLocationException exc) {
throw new IllegalStateException(exc.getMessage());
}
}
});
}
}
}
| 35.102273
| 119
| 0.634833
|
236f296d3aafa9b21ffe22ae9f4216f3d62c797f
| 1,400
|
package org.usfirst.frc.team4488.robot.routines.defaults;
import org.usfirst.frc.team4488.lib.logging.Logging;
import org.usfirst.frc.team4488.lib.operator.Controllers;
import org.usfirst.frc.team4488.robot.systems.drive.FalconDrive;
public class FalconDriveRoutine extends DefaultRoutine {
private FalconDrive drive;
private Controllers xbox = Controllers.getInstance();
public FalconDriveRoutine(FalconDrive drive) {
requireSystem(drive);
this.drive = drive;
}
public void start() {
Logging.getInstance()
.writeToLogFormatted(
this, "Falcon Drive", "Drive", "Started falcon drive (manual control)");
}
public void update() {
/* Commented to temporarily disable auto shifting
FalconDrive.getInstance()
.setDriveGears(xbox.getLeftBumper(xbox.m_primary), xbox.getRightBumper(xbox.m_primary));
*/
FalconDrive.getInstance().setDriveGears(xbox.getLeftBumper(xbox.m_primary), false);
double forward = xbox.deadzone(xbox.getLeftStickY(xbox.m_primary));
double strafe = xbox.deadzone(xbox.getLeftStickX(xbox.m_primary));
double turn = xbox.deadzone(xbox.getRightStickX(xbox.m_primary));
drive.controllerUpdate(strafe, forward, turn);
}
public void abort() {
Logging.getInstance()
.writeToLogFormatted(
this, "Falcon Drive", "Drive", "Stopped falcon drive (manual control)");
}
}
| 33.333333
| 96
| 0.725
|
8e29b0572d03863e135e391c2bff3e79727a6e1c
| 2,862
|
package seedu.address.ui;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.testutil.TypicalTasks.getTypicalTasks;
import java.time.YearMonth;
import java.util.Collections;
import org.junit.Test;
import guitests.guihandles.CalendarPanelHandle;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.address.logic.Logic;
import seedu.address.model.task.Due;
import seedu.address.model.task.Module;
import seedu.address.model.task.Name;
import seedu.address.model.task.Priority;
import seedu.address.model.task.Task;
import seedu.address.model.util.Month;
public class CalendarPanelTest extends GuiUnitTest {
private static final ObservableList<Task> TYPICAL_TASKS =
FXCollections.observableList(getTypicalTasks());
private final SimpleObjectProperty<Task> selectedTask = new SimpleObjectProperty<>();
private CalendarPanelHandle calendarPanelHandle;
private Logic logic;
/**
* Verifies that creating the calendarPanel works
*/
@Test
public void initTest() {
initUi(createBackingList(1));
assertTrue(calendarPanelHandle.isWindowPresent());
}
@Test
public void gridTest() {
initUi(createBackingList(1));
assertTrue(calendarPanelHandle.isGridPresent());
}
@Test(timeout = 1000)
public void timingTest() {
initUi(createBackingList(250));
}
/**
* Returns a list of persons containing {@code personCount} persons that is used to populate the
* {@code CalendarPanel}.
*/
private ObservableList<Task> createBackingList(int personCount) {
ObservableList<Task> backingList = FXCollections.observableArrayList();
for (int i = 0; i < personCount; i++) {
Name name = new Name(i + "a");
Module module = new Module("CS2113");
Due due = new Due("01-03");
Priority priority = new Priority("1");
Task task = new Task(name, module, due, priority, Collections.emptySet());
backingList.add(task);
}
return backingList;
}
/**
* Initializes {@code personListPanelHandle} with a {@code TaskListPanel} backed by {@code backingList}.
* Also shows the {@code Stage} that displays only {@code TaskListPanel}.
*/
private void initUi(ObservableList<Task> backingList) {
SimpleObjectProperty<Month> testMonth = new SimpleObjectProperty<>();
testMonth.setValue(new Month(Integer.toString(YearMonth.now().getMonthValue())));
CalendarPanel calendarPanel =
new CalendarPanel(backingList, selectedTask, testMonth, logic);
uiPartRule.setUiPart(calendarPanel);
calendarPanelHandle = new CalendarPanelHandle(calendarPanel);
}
}
| 34.481928
| 108
| 0.70021
|
d37c62270e199f9bdc4c9040028225430ab29ccb
| 2,005
|
package com.kymart.shop.Bean;
import java.util.List;
/**
* Created by Administrator on 2017/9/6.
*/
public class MessageBean {
/**
* status : 1
* msg :
* result : [{"id":1,"title":"测试一下","content":"<p s以一限公司<\/span><\/p><p><br/><\/p>","status":1,"create_time":1504595777}]
*/
private int status;
private String msg;
private List<ResultBean> result;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<ResultBean> getResult() {
return result;
}
public void setResult(List<ResultBean> result) {
this.result = result;
}
public static class ResultBean {
/**
* id : 1
* title : 测试一下
* content : <p s以一限公司</span></p><p><br/></p>
* status : 1
* create_time : 1504595777
*/
private int id;
private String title;
private String content;
private int status;
private int create_time;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getCreate_time() {
return create_time;
}
public void setCreate_time(int create_time) {
this.create_time = create_time;
}
}
}
| 19.656863
| 125
| 0.513217
|
87dcdf6f2158db5fe0f97f3aa9abae1380b2ec7a
| 452
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jp.co.kodnet.plugins.sample;
import net.java.ao.Entity;
import net.java.ao.OneToMany;
/**
*
* @author haunt
*/
public interface Blog extends Entity {
public String getName();
public void setName(String name);
@OneToMany
public Post[] getPosts();
}
| 20.545455
| 79
| 0.725664
|
d28ec87e9fc769c9fc7df34d3679d0baf2b5f773
| 2,349
|
/*
* Copyright 2016-2018 www.jeesuite.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.jeesuite.confcenter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import com.jeesuite.common.json.JsonUtils;
import com.jeesuite.common.util.ResourceUtils;
/**
* @description <br>
* @author <a href="mailto:vakinge@gmail.com">vakin</a>
* @date 2018年12月24日
*/
public class LocalCacheUtils {
private static String localStorageDir = ResourceUtils.getProperty("jeesuite.configcenter.local-storage-dir",
System.getProperty("user.dir"));
public static void write(Map<String, Object> datas) {
try {
File dir = new File(localStorageDir);
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, "config-cache.json");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(), false);
fileWritter.write(JsonUtils.toJson(datas));
fileWritter.close();
} catch (Exception e) {
}
}
@SuppressWarnings("unchecked")
public static Map<String, Object> read() {
try {
File dir = new File(localStorageDir);
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, "config-cache.json");
if (!file.exists()) {
return null;
}
StringBuilder buffer = new StringBuilder();
InputStream is = new FileInputStream(file);
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
line = reader.readLine();
while (line != null) {
buffer.append(line);
line = reader.readLine();
}
reader.close();
is.close();
return JsonUtils.toObject(buffer.toString(), Map.class);
} catch (Exception e) {
}
return null;
}
}
| 27.964286
| 109
| 0.701149
|
a1eabf7575fa7f451cc48865e27f636c64af71bd
| 7,984
|
package com.example.pranav.stack;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by pranav on 29/09/15.
*/
public class ImagesFragment extends Fragment {
public static String TAG= ImagesFragment.class.getSimpleName();
ImagesListAdapter imagesListAdapter;
OpenStackDatabase openStackDatabase;
private ProgressDialog progressDialog;
public static List<Image> ImageList=new ArrayList<Image>();
//ImageButton imageButton;
public ImagesFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedImagestate) {
super.onCreate(savedImagestate);
Log.d(TAG, "---ImageFragment---");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedImagestate) {
View rootView = inflater.inflate(R.layout.fragment_images, container, false);
final RecyclerView recyclerView=(RecyclerView)rootView.findViewById(R.id.images_list);
//imageButton=(ImageButton)rootView.findViewById(R.id.fab_image);
final SwipeRefreshLayout swipeRefreshLayout=(SwipeRefreshLayout)rootView.findViewById(R.id.swipeRefreshLayout);
LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
imagesListAdapter =new ImagesListAdapter();
recyclerView.setAdapter(imagesListAdapter);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
SendRequest(null, getImageURL());
swipeRefreshLayout.setRefreshing(false);
}
});
ItemTouchHelper itemTouchHelper=new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT,ItemTouchHelper.LEFT| ItemTouchHelper.RIGHT){
@Override
public boolean onMove(RecyclerView recyclerView,RecyclerView.ViewHolder viewHolder,RecyclerView.ViewHolder target){
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder,int direction){
Log.d(TAG, "---Item location----");
Log.d(TAG, "---Item location----");
if(viewHolder.getAdapterPosition() < ImageList.size()) {
ImageList.remove(viewHolder.getAdapterPosition());
//openStackDatabase.
}
imagesListAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
});
itemTouchHelper.attachToRecyclerView(recyclerView);
// Inflate the layout for this fragment
return rootView;
}
private void SendRequest(JSONObject jsonObject, String url)
{
showDialog();
JsonObjectRequest request = new JsonObjectRequest((jsonObject == null) ? Request.Method.GET:Request.Method.POST,url,jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//Log.d(TAG, response.toString());
hideDialog();
getImageDetails(response);
Log.d(TAG, "Response-image--------");
Log.d(TAG, response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "overview error:");
Log.d(TAG,error.toString());
hideDialog();
if(error instanceof TimeoutError || error instanceof NoConnectionError)
{
Toast.makeText(getActivity(), "Please check you connection!", Toast.LENGTH_LONG).show();
}
else if(error instanceof AuthFailureError) {
Toast.makeText(getActivity(), "Incorrect Username or Password.", Toast.LENGTH_LONG).show();
}
}
}
){
@Override
public Map<String,String> getHeaders() throws AuthFailureError {
HashMap<String,String> headers=new HashMap<String,String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("X-Auth-Token",App_urls.TokenID);
Log.d(TAG, "--------headers----");
Log.d(TAG,headers.toString());
return headers;
}
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
Volley.newRequestQueue(getActivity()).add(request);
}
public void getImageDetails(JSONObject jsonObject) {
openStackDatabase.getWritableDatabase();
try{
for (int i = 0; i <jsonObject.getJSONArray("images").length(); i++) {
Image image=new Image();
JSONObject imageObj=jsonObject.getJSONArray("images").getJSONObject(i);
image.setImageID(imageObj.getString("id"));
image.setImageName(imageObj.getString("name"));
image.setImageSize(imageObj.getString("size"));
image.setImageState(imageObj.getString("status"));
image.setImageType(imageObj.getString("disk_format"));
openStackDatabase.insertImage(image);
ImageList=openStackDatabase.getAllImages();
imagesListAdapter.notifyDataSetChanged();
}
}catch (JSONException js){}
openStackDatabase.close();
}
public String getImageURL(){
String imageURL=App_urls.allURLs.get("image");
if(imageURL==null){
Toast.makeText(getActivity(), "Unable to fetch image details!", Toast.LENGTH_LONG).show();
imageURL="";
}
else
imageURL=imageURL.concat("/v2/images");
return imageURL;
}
private void showDialog() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Fetching Data...");
progressDialog.setCancelable(false);
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog(){
if(progressDialog.isShowing())
progressDialog.dismiss();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
openStackDatabase = new OpenStackDatabase(getActivity());
SendRequest(null, getImageURL());
//ImageList=openStackDatabase.getAllInstances();
}
@Override
public void onDetach() {
super.onDetach();
openStackDatabase.close();
}
}
| 39.524752
| 185
| 0.622745
|
319f3267f963f31b2a17d15808e93f68884d199f
| 1,019
|
package com.xzh.kingtv.mvp.base;
import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.king.base.util.LogUtils;
import com.xzh.kingtv.App;
import com.xzh.kingtv.dao.greendao.DaoSession;
import com.xzh.kingtv.di.component.AppComponent;
import javax.inject.Inject;
public class BasePresenter<V extends BaseView> extends MvpBasePresenter<V> {
private App app;
private DaoSession mDaoSession;
private AppComponent mAppComponent;
@Inject
public BasePresenter(App app){
super();
this.app = app;
mDaoSession = app.getDaoSession();
mAppComponent = app.getAppCommponent();
}
public AppComponent getAppComponent(){
return mAppComponent;
}
public DaoSession getDaoSession(){
return mDaoSession;
}
public App getApp(){
return getApp();
}
@Override
public boolean isViewAttached() {
LogUtils.d("isViewAttached:" + super.isViewAttached());
return super.isViewAttached();
}
}
| 20.795918
| 76
| 0.682041
|
71595b0ff5d3f58955c6780f9d5047b94ac77341
| 4,461
|
package ru.skillbox.socialnetwork.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.skillbox.socialnetwork.api.responses.CityResponse;
import ru.skillbox.socialnetwork.api.responses.CountryResponse;
import ru.skillbox.socialnetwork.api.responses.LanguageResponse;
import ru.skillbox.socialnetwork.api.responses.ResponseList;
import ru.skillbox.socialnetwork.services.PlatformService;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/platform")
public class PlatformController {
@Autowired
private PlatformService platformService;
private final Integer itemPerPageDefault = 20;
private final Integer offsetDefault = 0;
private final String searchStringDefault = "";
@GetMapping("/languages")
public ResponseList<List<LanguageResponse>> searchLanguages(
@RequestParam(value = "language", required = false) String searchString,
@RequestParam(value = "offset", required = false) Integer offset,
@RequestParam(value = "itemPerPage", required = false) Integer itemPerPage) {
if (offset == null) {
offset = offsetDefault;
}
if (searchString == null) {
searchString = searchStringDefault;
}
if (itemPerPage == null) {
itemPerPage = itemPerPageDefault;
}
List<LanguageResponse> languages = platformService.getLanguages(searchString,offset,itemPerPage);
ResponseList<List<LanguageResponse>> responseList = new ResponseList<>(languages);
responseList.setOffset(offset);
responseList.setPerPage(itemPerPage);
responseList.setTimestamp(System.currentTimeMillis());
responseList.setTotal(languages.size());
return responseList;
}
@GetMapping("/countries")
public ResponseList<List<CountryResponse>> searchCountries(
@RequestParam(value = "country", required = false) String searchString,
@RequestParam(value = "offset", required = false) Integer offset,
@RequestParam(value = "itemPerPage", required = false) Integer itemPerPage) {
if (offset == null) {
offset = offsetDefault;
}
if (searchString == null) {
searchString = searchStringDefault;
}
if (itemPerPage == null) {
itemPerPage = itemPerPageDefault;
}
List<CountryResponse> countries = platformService.getCountries(searchString,offset,itemPerPage);
ResponseList<List<CountryResponse>> responseList = new ResponseList<>(countries);
responseList.setOffset(offset);
responseList.setPerPage(itemPerPage);
responseList.setTimestamp(System.currentTimeMillis());
responseList.setTotal(countries.size());
return responseList;
}
@GetMapping("/cities")
public ResponseList<List<CityResponse>> searchCities(
@RequestParam(value = "countryId") Integer countryId,
@RequestParam(value = "city", required = false) String searchString,
@RequestParam(value = "offset", required = false) Integer offset,
@RequestParam(value = "itemPerPage", required = false) Integer itemPerPage) {
if (countryId == null) {
return new ResponseList<>("Error! Country id is null!", new ArrayList<>());
}
if (offset == null) {
offset = offsetDefault;
}
if (searchString == null) {
searchString = searchStringDefault;
}
if (itemPerPage == null) {
itemPerPage = itemPerPageDefault;
}
List<CityResponse> cities = platformService.getCities(countryId, searchString, offset, itemPerPage);
ResponseList<List<CityResponse>> responseList = new ResponseList<>(cities);
responseList.setOffset(offset);
responseList.setPerPage(itemPerPage);
responseList.setTimestamp(System.currentTimeMillis());
responseList.setTotal(cities.size());
return responseList;
}
}
| 44.61
| 108
| 0.659493
|
0553acd480be516db1d3ec062a500018922d090c
| 1,154
|
package modelo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public abstract class Pessoa {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String nome;
private String endereco;
private String dtNascimento;
public Pessoa() {}
public Pessoa(String nome, String endereco, String dtNasc) {
this.nome = nome;
this.endereco = endereco;
this.dtNascimento = dtNasc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return this.nome;
}
public String getEndereco() {
return this.endereco;
}
public String getDtNascimento() {
return this.dtNascimento;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setDtNascimento(String dt) {
this.dtNascimento = dt;
}
@Override
public String toString() {
return "Pessoa [Nome = " + nome + "; Endereco = " + endereco + "; Data de Nascimento = " + dtNascimento + "]";
}
}
| 18.03125
| 112
| 0.704506
|
b3e7b2669f4c2e269bea2a6b97a39aae9ffff1bd
| 4,862
|
package eu.zidek.augustin.bellrock.server;
import java.time.Instant;
import java.util.List;
import eu.zidek.augustin.bellrock.identification.AnonymousID;
import eu.zidek.augustin.bellrock.identification.ID;
import eu.zidek.augustin.bellrock.identification.IDDecryptor;
import eu.zidek.augustin.bellrock.identification.UID;
/**
* Class for storing observations of the clients, i.e. the signals they heard.
*
* @author Augustin Zidek
*
*/
public class Observation {
private final UID observerUID;
private final AnonymousID observedAID;
private UID resolvedUID;
private boolean isAIDResolved = false;
private final Instant time;
private final Location location;
/**
* @param observer The observer of this observation.
* @param anonymousID The Anonymous ID that was heard.
* @param time The time when the AID was heard.
* @param location The location where the AID was heard.
*/
public Observation(final UID observer, final AnonymousID anonymousID,
final Instant time, final Location location) {
this.observerUID = observer;
this.observedAID = anonymousID;
this.time = time;
this.location = location;
}
/**
* @return The UID of the observer of this observation, i.e. the user that
* recorded this Anonymous ID at the given time and location.
*/
public UID getObserverUID() {
return this.observerUID;
}
/**
* @return The Anonymous AID that was heard.
*/
public AnonymousID getAID() {
return this.observedAID;
}
/**
* @return The time when the AID was heard.
*/
public Instant getTime() {
return this.time;
}
/**
* @return The location where the AID was heard. Set to <code>null</code> if
* unknown.
*/
public Location getLocation() {
return this.location;
}
/**
* Resolves the AID into a UID using the information about users and their
* keys. I.e., the AID is brute force decrypted using all possible keys in
* the system (with some heuristic to make this more efficient) and if a
* matching UID is found, it is set as the UID which resolved this AID.
*
* @param aidDecryptor The Anonymous ID decryptor.
* @param users All Bellrock users that should be tried to decrypt this AID.
* @return The Bellrock user who sent the AID.
*/
public BellrockUser resolveAID(final List<BellrockUser> users) {
// Try to resolve the AID
final BellrockUser resolvedUser = IDDecryptor
.decryptAnonymousIDParallel(this.observedAID, users);
// User UID not resolved
if (resolvedUser == null) {
this.isAIDResolved = false;
return null;
}
// User UID resolved
this.resolvedUID = resolvedUser.getUID();
this.isAIDResolved = true;
return resolvedUser;
}
/**
* @param resolvedUID The resolved Anonymous ID.
*/
public void addResolvedUID(final UID resolvedUID) {
this.resolvedUID = resolvedUID;
this.isAIDResolved = true;
}
/**
*
* @return The resolved Anonymous ID. Note that <code>resolveAID()</code>
* has to be called before or the resolved UID has to be added
* manually before this method is called. If the UID has not been
* resolved, <code>null</code> is returned.
*/
public ID getResolvedUID() {
return this.resolvedUID;
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof Observation)) {
return false;
}
final Observation other = (Observation) obj;
return this.getObserverUID().equals(other.getObserverUID())
&& this.getAID().equals(other.getAID())
&& this.getTime().equals(other.getTime())
&& this.getLocation().equals(other.getLocation());
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Observer: ");
sb.append(this.observerUID.toHexString());
sb.append(System.lineSeparator());
sb.append("Observee (AID): ");
sb.append(this.observedAID.toHexString());
sb.append(System.lineSeparator());
if (this.isAIDResolved) {
sb.append("Observee (UID): ");
sb.append(this.resolvedUID.toHexString());
sb.append(System.lineSeparator());
}
sb.append("Time: ");
sb.append(this.time.toString());
sb.append(System.lineSeparator());
sb.append("Location: ");
sb.append(this.location.toString());
return sb.toString();
}
}
| 31.986842
| 80
| 0.623817
|
f34217602a63caac356b5905c9d3034443b2ce61
| 498
|
package cn.aposoft.wechat.config;
public class WechatAccountConfigException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public WechatAccountConfigException() {
super();
}
public WechatAccountConfigException(String message) {
super(message);
}
public WechatAccountConfigException(String message, Throwable cause) {
super(message, cause);
}
public WechatAccountConfigException(Throwable cause) {
super(cause);
}
}
| 19.92
| 72
| 0.716867
|
b4e32480f57223bec416ba7cf831ac9ee243c68e
| 8,891
|
package com.soj.m1kes.nits.sqlite.adapters;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.soj.m1kes.nits.models.Agent;
import com.soj.m1kes.nits.models.AgentContact;
import com.soj.m1kes.nits.models.AgentGroup;
import com.soj.m1kes.nits.models.Job;
import com.soj.m1kes.nits.sqlite.providers.DatabaseContentProvider;
import com.soj.m1kes.nits.sqlite.tables.AgentsTable;
import com.soj.m1kes.nits.sqlite.tables.JobsTable;
import com.soj.m1kes.nits.util.DBUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AgentsAdapter {
public static List<Agent> getAllAgents(Context context){
List<Agent> agents = new ArrayList<>();
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query (DatabaseContentProvider.AGENTS_CONTENT_URI , null, null, null, null);
if (null != cursor && !(cursor.getCount() < 1)) {
while (cursor.moveToNext()) {
Agent agent = new Agent();
int id = cursor.getInt(cursor.getColumnIndex(AgentsTable.ID));
String agentName = cursor.getString(cursor.getColumnIndex(AgentsTable.NAME));
String address = cursor.getString(cursor.getColumnIndex(AgentsTable.ADDRESS));
String officeID = cursor.getString(cursor.getColumnIndex(AgentsTable.OFFICEID));
String helpDeskPin = cursor.getString(cursor.getColumnIndex(AgentsTable.HELPDESKPIN));
boolean isSynced = DBUtils.convertIntToBool(cursor.getInt(cursor.getColumnIndex(AgentsTable.COLUMN_IS_SYNCED)));
int group_id = cursor.getInt(cursor.getColumnIndex(AgentsTable.GROUP_ID));
AgentGroup group = AgentGroupsAdapter.getAgentGroup(context,group_id);
List<AgentContact> contacts = AgentContactsAdapter.getContactsForAgent(context,id);
agent.setId(id);
agent.setName(agentName);
agent.setAddress(address);
agent.setOfficeID(officeID);
agent.setHelpDeskPin(helpDeskPin);
agent.setGroup(group);
agent.setContacts(contacts);
agent.setSynced(isSynced);
// Show phone number in Logcat
System.out.println("Loading from DB: " + agent.toString());
// end of while loop
agents.add(agent);
}
cursor.close();
}
return agents;
}
public static List<Agent> getUnsyncedAgents(Context context){
String dateTimeParseFormat = "dd-MM-yyyy HH:mm:ss";
List<Agent> agents = new ArrayList<>();
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query (DatabaseContentProvider.AGENTS_CONTENT_URI , null, AgentsTable.COLUMN_IS_SYNCED + " = " + 0 + "", null, null);
if (null != cursor && !(cursor.getCount() < 1)) {
while (cursor.moveToNext()) {
// Gets the value from the column.
Agent agent = new Agent();
int id = cursor.getInt(cursor.getColumnIndex(AgentsTable.ID));
String agentName = cursor.getString(cursor.getColumnIndex(AgentsTable.NAME));
String address = cursor.getString(cursor.getColumnIndex(AgentsTable.ADDRESS));
String officeID = cursor.getString(cursor.getColumnIndex(AgentsTable.OFFICEID));
String helpDeskPin = cursor.getString(cursor.getColumnIndex(AgentsTable.HELPDESKPIN));
boolean isSynced = DBUtils.convertIntToBool(cursor.getInt(cursor.getColumnIndex(AgentsTable.COLUMN_IS_SYNCED)));
int group_id = cursor.getInt(cursor.getColumnIndex(AgentsTable.GROUP_ID));
AgentGroup group = AgentGroupsAdapter.getAgentGroup(context,group_id);
List<AgentContact> contacts = AgentContactsAdapter.getContactsForAgent(context,id);
agent.setId(id);
agent.setName(agentName);
agent.setAddress(address);
agent.setOfficeID(officeID);
agent.setHelpDeskPin(helpDeskPin);
agent.setGroup(group);
agent.setContacts(contacts);
agent.setSynced(isSynced);
// Show phone number in Logcat
System.out.println("Loading from DB: " + agent.toString());
// end of while loop
agents.add(agent);
}
cursor.close();
}
return agents;
}
public static void addAgent(Agent agent, Context context) {
String format = "yyyy-MM-dd HH:mm:ss";
ContentValues initialValues = new ContentValues();
initialValues.put(AgentsTable.ID, agent.getId());
initialValues.put(AgentsTable.NAME,agent.getName());
initialValues.put(AgentsTable.ADDRESS, agent.getAddress());
initialValues.put(AgentsTable.OFFICEID, agent.getOfficeID());
initialValues.put(AgentsTable.HELPDESKPIN, agent.getHelpDeskPin());
initialValues.put(AgentsTable.GROUP_ID, agent.getGroup().getId());
initialValues.put(AgentsTable.COLUMN_IS_SYNCED,DBUtils.convertBoolToInt(agent.isSynced()));
System.out.println("Adding Agent : "+agent.toString());
Uri contentUri = Uri.withAppendedPath(DatabaseContentProvider.CONTENT_URI, AgentsTable.TABLE_AGENTS);
Uri resultUri = context.getContentResolver().insert(contentUri, initialValues);
AgentContactsAdapter.addAll(agent.getContacts(),context);
}
public static void addAgents(List<Agent> agents,Context context){
deleteAll(context);
for(Agent a : agents){
addAgent(a,context);
}
}
public static int updateAgent(Agent agent,Context context){
ContentValues updateValues = new ContentValues();
ContentValues initialValues = new ContentValues();
initialValues.put(AgentsTable.ID, agent.getId());
initialValues.put(AgentsTable.NAME,agent.getName());
initialValues.put(AgentsTable.ADDRESS, agent.getAddress());
initialValues.put(AgentsTable.OFFICEID, agent.getOfficeID());
initialValues.put(AgentsTable.HELPDESKPIN, agent.getHelpDeskPin());
initialValues.put(AgentsTable.GROUP_ID, agent.getGroup().getId());
initialValues.put(AgentsTable.COLUMN_IS_SYNCED,DBUtils.convertBoolToInt(agent.isSynced()));
Uri contentUri = Uri.withAppendedPath(DatabaseContentProvider.CONTENT_URI,AgentsTable.TABLE_AGENTS);
int rowsAffected = context.getContentResolver().update(contentUri,updateValues,
AgentsTable.ID+"=?",new String[]{String.valueOf(agent.getId())});
if(rowsAffected>0){
AgentContactsAdapter.addAll(agent.getContacts(),context);
System.out.println("Successfully Updated Agent ");
}else{
System.out.println("Failed to Update Agent");
}
return rowsAffected;
}
public static int setAgentSynced(Agent agent, Context context){
ContentValues updateValues = new ContentValues();
updateValues.put(AgentsTable.COLUMN_IS_SYNCED, DBUtils.convertIntToBool(1));
Uri contentUri = Uri.withAppendedPath(DatabaseContentProvider.CONTENT_URI,AgentsTable.TABLE_AGENTS);
int rowsAffected = context.getContentResolver().update(contentUri,updateValues,
AgentsTable.NAME+"=?",new String[]{agent.getName()});
if(rowsAffected>0){
System.out.println("Successfully set Agent to Synced ");
}else{
System.out.println("Failed to set Agent to synced");
}
return rowsAffected;
}
public static int setAgentUnSynced(int agentID, Context context){
ContentValues updateValues = new ContentValues();
updateValues.put(AgentsTable.COLUMN_IS_SYNCED, DBUtils.convertIntToBool(0));
Uri contentUri = Uri.withAppendedPath(DatabaseContentProvider.CONTENT_URI,AgentsTable.TABLE_AGENTS);
int rowsAffected = context.getContentResolver().update(contentUri,updateValues,
AgentsTable.ID+"=?",new String[]{String.valueOf(agentID)});
if(rowsAffected>0){
System.out.println("Successfully set Agent to UnSynced ");
}else{
System.out.println("Failed to set Agent to Unsynced");
}
return rowsAffected;
}
private static void deleteAll(Context context){
Uri contentUri = Uri.withAppendedPath(DatabaseContentProvider.CONTENT_URI, AgentsTable.TABLE_AGENTS);
int result = context.getContentResolver().delete(contentUri,null,null);
System.out.println("Deleted status: "+result);
}
}
| 40.04955
| 144
| 0.660781
|
d0419c5324fe0f3a42234d10b04ecf10d90dab72
| 831
|
package com.gck.movies.response.models;
import javax.validation.constraints.NotNull;
public class MovieCatalog {
private Long movieId;
@NotNull
private String movieName;
private String movieDescription;
private boolean isAvailable;
public Long getMovieId() {
return movieId;
}
public void setMovieId(Long movieId) {
this.movieId = movieId;
}
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public String getMovieDescription() {
return movieDescription;
}
public void setMovieDescription(String movieDescription) {
this.movieDescription = movieDescription;
}
public boolean isAvailable() {
return isAvailable;
}
public void setAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}
}
| 16.62
| 59
| 0.749699
|
f4b6a70ee5befb3645f57cb474253c8e579caf59
| 13,009
|
package sanavesa.net;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
/**
* The Server class is the backend foundation for the server. It contains all
* the network functionality with clients such as accepting new connections,
* sending, and receiving new data.
*
* The <code>Server</code> class is the back-end foundation for the
* client-server architecture. It contains the essential features required to
* represent a server. To fully utilize this class' capabilities, it is
* preferable to extend the class to fine-tune the server. The data transmission
* for each connected client is handled by the {@link NetworkCommunication}
* class. Also, each client has its own thread for network data transmission.
*
* @see NetworkCommunication
* @see ServerClient
*
* @since 1.0
* @author Mohammad Alali
*/
public class Server
{
/** A list of the connected clients. */
final List<ServerClient> clientList = new ArrayList<>();
/** The server's own thread for listening to new connections. */
private Thread listeningThread = null;
/** A flag for whether the server is running or not. */
private volatile boolean running = false;
/** The socket of the server. */
private ServerSocket serverSocket = null;
/**
* Constructs a new <code>Server</code> instance. The constructor sets up
* the shutdown hook for when the server is terminated unexpectedly by
* disconnecting all clients from the server. It will terminate all server
* connections and stop the listening thread.
*
* @since 1.1
* @author Mohammad Alali
*/
public Server()
{
// Sets up the hook
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
stopServer();
}
});
}
/**
* Returns an <b>unmodifiable</b> list of all currently connected clients.
*
* @return the unmodifiable list of all connected clients
*
* @since 1.0
* @author Mohammad Alali
*/
public final List<ServerClient> getClientList()
{
return Collections.unmodifiableList(clientList);
}
/**
* Returns the connection status of the server.
*
* @return true if the server is running; false otherwise
*
* @since 1.0
* @author Mohammad Alali
*/
public final boolean isRunning()
{
return running;
}
/**
* This method is triggered automatically when the client has successfully
* connected to the server.
*
* @param client
* - the client that connected to the server
*
* @since 1.0
* @author Mohammad Alali
*/
protected void onClientConnected(ServerClient client)
{
}
/**
* This method is triggered automatically when the client has disconnected
* from the server.
*
* @param client
* - the client that disconnected from the server
*
* @since 1.0
* @author Mohammad Alali
*/
protected void onClientDisconnected(ServerClient client)
{
}
/**
* This method is triggered automatically when the server has received data
* from any client. The data received is a class that implements the
* {@link NetworkSerializable} interface. The data received is handled by
* the interface via the {@link NetworkSerializable#handleOnServer(Server, ServerClient)}
* method.
*
* @param <T>
* - the class type of the data received
* @param data
* - the data object received
* @param sender
* - the sender of the data
*
* @see NetworkSerializable
* @see ServerClient
*
* @since 1.0
* @author Mohammad Alali
*/
final <T extends NetworkSerializable> void onReceivedData(T data, ServerClient sender)
{
data.handleOnServer(this, sender);
}
/**
* This method is triggered automatically when the server has failed to
* start running {@link #startServer(int)} method.
*
* @param port
* - the attempted port of the server
*
* @since 1.0
* @author Mohammad Alali
*/
protected void onServerFailedToStart(int port)
{
}
/**
* This method is triggered automatically when the server has successfully
* started running via the {@link #startServer(int)} method.
*
* @param port
* - the port of the server that started
*
* @since 1.0
* @author Mohammad Alali
*/
protected void onServerStarted(int port)
{
}
/**
* This method is triggered automatically when the server has stopped
* running via the {@link #stopServer()} method.
*
* @param port
* - the port of the server that stopped
*
* @since 1.0
* @author Mohammad Alali
*/
protected void onServerStopped(int port)
{
}
/**
* Used internally to reset the instance's variables. It will terminate all
* server connections and stop the listening thread.
*
* @since 1.0
* @author Mohammad Alali
*/
private final void resetInstance()
{
// Change the running flag
running = false;
// Terminate all client connections
ArrayList<ServerClient> copy = new ArrayList<>(clientList);
for (ServerClient client : copy)
{
client.disconnect();
}
// Clear the connected client list
clientList.clear();
// Stop and reset listening thread
if (listeningThread != null)
{
try
{
listeningThread.join(10);
}
catch (InterruptedException e)
{
// Ignore handling
}
listeningThread = null;
}
// Close and reset server socket
if (serverSocket != null)
{
try
{
serverSocket.close();
}
catch (IOException e)
{
// Ignore handling
}
serverSocket = null;
}
}
/**
* The <code>run</code> method handles the new client connections. This
* method should never be explicitly called as it automatically handled by
* the {@link ServerThread} class, which calls this method on a separate
* thread. Incoming data will trigger the
* {@link #onReceivedData(NetworkSerializable, ServerClient)} method, where
* the user is able to override and handle the data as he or she wishes.
*
* @see ClientThread
*
* @since 1.0
* @author Mohammad Alali
*/
final void run()
{
while (isRunning())
{
try
{
/*
* Accept new connections: The accept method will block the
* thread until a client asks for a connection. The only way to
* break the thread blocking is to close the server socket.
*/
Socket newSocket = serverSocket.accept();
new ServerClient(this, newSocket);
}
catch (Exception e)
{
// Ignore handling
}
}
}
/**
* Sends the specified data object to the specified client.
*
* @param <T>
* - the class type of the data to send
* @param data
* - the data to send to the specified client
* @param recipient
* - the client who we want to send to
*
* @throws IllegalArgumentException
* - thrown when <code>data</code> or <code>recipient</code> is
* null
* @throws IllegalStateException
* - thrown when <code>recipient</code> is not connected
*
* @since 1.0
* @author Mohammad Alali
*/
public final <T extends NetworkSerializable> void sendDataTo(T data, ServerClient recipient)
throws IllegalArgumentException, IllegalStateException
{
if (data == null)
{
throw new IllegalArgumentException("Method parameter 'data' in Server::sendDataTo cannot be null.");
}
if (recipient == null)
{
throw new IllegalArgumentException("Method parameter 'recipient' in Server::sendDataTo cannot be null.");
}
if (!recipient.isConnected())
{
throw new IllegalStateException(
"Failed to send data to 'recipient' in Server::sendDataTo because the client is not connected.");
}
recipient.sendData(data);
}
/**
* Sends the specified data object to all connected clients.
*
* @param <T>
* - the class type of the data to send
* @param data
* - the data to send to all connected clients
*
*
* @throws IllegalArgumentException
* - thrown when <code>data</code> is null
* @throws IllegalStateException
* - thrown when any supposedly connected {@link ServerClient}
* instance is not connected
*
* @since 1.0
* @author Mohammad Alali
*/
public final <T extends NetworkSerializable> void sendDataToAll(T data)
throws IllegalArgumentException, IllegalStateException
{
if (data == null)
{
throw new IllegalArgumentException("Method parameter 'data' in Server::sendDataToAll cannot be null.");
}
for (ServerClient client : clientList)
{
if (!client.isConnected())
{
throw new IllegalStateException(
"Failed to send data to a client in Server::sendDataToAll because the client is not connected.");
}
client.sendData(data);
}
}
/**
* Sends the specified data object to the specified clients that are
* identified by the predicate. All clients that match the condition
* specified in the predicate will get the data.
*
* @param <T>
* - the class type of the data to send
* @param data
* - the data object to send
* @param predicate
* - a predicate that defines which clients receive the packet
*
* @throws IllegalArgumentException
* - thrown when <code>data</code> or <code>predicate</code> is
* null
* @throws IllegalStateException
* - thrown when any supposedly connected {@link ServerClient}
* instance that matches the condition in the predicate is not
* connected
*
* @since 1.0
* @author Mohammad Alali
*/
public final <T extends NetworkSerializable> void sendDataToMatch(T data, Predicate<ServerClient> predicate)
throws IllegalArgumentException, IllegalStateException
{
if (data == null)
{
throw new IllegalArgumentException("Method parameter 'data' in Server::sendDataToMatch cannot be null.");
}
if (predicate == null)
{
throw new IllegalArgumentException(
"Method parameter 'predicate' in Server::sendDataToMatch cannot be null.");
}
for (ServerClient client : clientList)
{
if (predicate.test(client))
{
if (!client.isConnected())
{
throw new IllegalStateException(
"Failed to send data to a client in Server::sendDataToMatch because the client is not connected.");
}
client.sendData(data);
}
}
}
/**
* Attempts to start the server. If the server is already running on any
* port, then this method will terminate early and do nothing. The following
* methods will get triggered:
*
* <ul>
* <li>{@link #onServerStarted(int)} - if the server started
* successfully</li>
* <li>{@link #onServerFailedToStart(int)} - if the server failed to start,
* most likely that the port is already in use</li>
* </ul>
*
* @param port
* - the port to run the server on
*
* @since 1.0
* @author Mohammad Alali
*/
public final void startServer(int port)
{
// Terminate early if the server is already running on any port
if (isRunning())
{
return;
}
try
{
// Attempt to create the server socket
serverSocket = new ServerSocket(port);
// Clear the list of connected clients
clientList.clear();
// All was successful, now setup separate thread for listening for
// new connections
running = true;
listeningThread = new Thread(new ServerThread(this));
listeningThread.start();
}
catch (Exception e)
{
// An error occurred
resetInstance();
}
// Trigger events based on conditions
if (isRunning())
{
onServerStarted(port);
}
else
{
onServerFailedToStart(port);
}
}
/**
* Stops the server from running, which terminates all connections. Attempts
* to start the server. If the server is not running, then this method will
* terminate early and do nothing. The method {@link #onServerStopped(int)}
* will be triggered.
*
* @since 1.0
* @author Mohammad Alali
*/
public final void stopServer()
{
// Terminate early if server is not running.
if (!isRunning())
{
return;
}
// Cache port before reseting it
int port = serverSocket.getLocalPort();
// Reset instance
resetInstance();
// Trigger the event
onServerStopped(port);
}
/**
* Returns a nicely formatted string representation of the server object
* along with its connection status and number of connected clients.
*
* @return formatted string of the server object
*
* @since 1.1
* @author Mohammad Alali
*/
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("Server ");
builder.append(super.toString());
builder.append("\n");
builder.append("Server Status: ");
if (isRunning())
{
builder.append("Online\n");
builder.append("Number of Connected Clients: ");
builder.append(clientList.size());
}
else
{
builder.append("Offline\n");
}
return builder.toString();
}
}
| 25.21124
| 109
| 0.66723
|
09a8996b76234251ecc375aee8d91f6bf6a05f6a
| 1,371
|
package com.lhy.web.system;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.lhy.modules.system.domain.CommonUser;
import com.lhy.web.WebConstants;
public class CommonLoginInterceptor implements HandlerInterceptor {
private String indexURL;
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception
{
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mv)
throws Exception
{
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception
{
String type = request.getHeader("X-Requested-With");
CommonUser loginUser = (CommonUser)request.getSession().getAttribute(WebConstants.LOGIN_USER_KEY);
if (loginUser!=null){
return true;
}
if ("XMLHttpRequest".equalsIgnoreCase(type)) {// AJAX REQUEST PROCES
response.addHeader("sessionstatus", "timeout");
}else{
response.sendRedirect(request.getContextPath()+this.indexURL);
}
return false;
}
public void setIndexURL(String indexURL) {
this.indexURL = indexURL;
}
}
| 28.5625
| 118
| 0.762217
|
184a5324cbe45b87f1452f20af644397af1c0aa5
| 263
|
package me.chanjar.weixin.cp.api;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
/**
* 消息匹配器,用在消息路由的时候
*/
public interface WxCpMessageMatcher {
/**
* 消息是否匹配某种模式
* @param message
* @return
*/
public boolean match(WxCpXmlMessage message);
}
| 14.611111
| 48
| 0.692015
|
9c62374a3579210ad65c7e9533729313dca1c7f4
| 1,702
|
package org.jruby.parlib;
import java.util.ArrayList;
import org.jruby.runtime.builtin.IRubyObject;
public class SomeTrueContext extends ParallelContext {
// All tasks in this some true context
private ArrayList<SomeTrueTask> tasks;
// The result of this .someTrue call
private volatile IRubyObject result = null;
public SomeTrueContext(int numTasks) {
super(numTasks);
this.tasks = new ArrayList<SomeTrueTask>();
}
public SomeTrueContext() {
this.tasks = new ArrayList<SomeTrueTask>();
}
// Add a task in
public void addTask(SomeTrueTask task) {
this.tasks.add(task);
super.addTask();
}
// Report an error if this method is called
public void addTask() {
System.out.println("Error: Wrong addTask called! ");
}
// The task is done if a result is found or all tasks are done.
public boolean finished() {
// System.out.println("result: "+this.result);
return (this.result != null) || super.finished();
}
public void arrive(IRubyObject result) {
if (result != null) {
// We found something
// TODO: Trying to avoid locks, is this right?
this.result = result;
// Disable all tasks
for (SomeTrueTask t : this.tasks) {
t.disable();
}
}
// Mark as arrived
super.arrive();
}
// Return the result of this context
public IRubyObject getResult() {
if (this.result != null) {
return this.result;
}
//System.out.println("SomeTrue results null");
return null;
}
}
| 27.015873
| 68
| 0.583431
|
2c76c02ed17cd98b7b8c52c8b21dbc5843a1cbdf
| 8,940
|
package com.massfords.jaxb;
import static com.massfords.jaxb.ClassDiscoverer.findAllDeclaredAndInheritedFields;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import com.sun.codemodel.JAnnotationUse;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;
import com.sun.codemodel.JTypeVar;
import com.sun.codemodel.JVar;
import com.sun.tools.xjc.model.CPropertyInfo;
import com.sun.tools.xjc.outline.ClassOutline;
import com.sun.tools.xjc.outline.FieldOutline;
import com.sun.tools.xjc.outline.Outline;
/**
* Creates an implementation of the traverser that traverses the beans in depth first order
* according to the order returned from the field iterator within the code model.
*
* The default traverser will traverse each of the child beans that are not null.
*
* @author markford
*/
class CreateDepthFirstTraverserClass extends CodeCreator {
private final JDefinedClass visitor;
private final JDefinedClass traverser;
private final JDefinedClass visitable;
/**
* Function that accepts a type name and returns the name of the method to
* create. This encapsulates the behavior associated with the includeType
* flag.
*/
private final Function<String,String> traverseMethodNamer;
private final boolean noIdrefTraversal;
CreateDepthFirstTraverserClass(JDefinedClass visitor, JDefinedClass traverser,
JDefinedClass visitable,
Outline outline,
JPackage jPackageackage,
Function<String, String> traverseMethodNamer, boolean noIdrefTraversal) {
super(outline, jPackageackage);
this.visitor = visitor;
this.traverser = traverser;
this.visitable = visitable;
this.traverseMethodNamer = traverseMethodNamer;
this.noIdrefTraversal = noIdrefTraversal;
}
@Override
protected void run(Set<ClassOutline> classes, Set<JClass> directClasses) {
// create the class
JDefinedClass defaultTraverser = getOutline().getClassFactory().createClass(getPackage(),
"DepthFirstTraverserImpl", null);
JDefinedClass scratch = getOutline().getClassFactory().createInterface(getPackage(), "scratch", null);
try {
final JTypeVar exceptionType = defaultTraverser.generify("E", Throwable.class);
JClass narrowedVisitor = visitor.narrow(scratch.generify("?")).narrow(exceptionType);
JClass narrowedTraverser = traverser.narrow(exceptionType);
defaultTraverser._implements(narrowedTraverser);
setOutput(defaultTraverser);
Map<String, JClass> dcMap = new HashMap<>();
for (JClass dc : directClasses) {
dcMap.put(dc.fullName(), dc);
}
for (ClassOutline classOutline : classes) {
if (classOutline.target.isAbstract()) {
continue;
}
// add the bean to the traverserImpl
JMethod traverseMethodImpl;
String traverseMethodName = traverseMethodNamer.apply(classOutline.implClass.name());
traverseMethodImpl = defaultTraverser.method(JMod.PUBLIC, void.class, traverseMethodName);
traverseMethodImpl._throws(exceptionType);
JVar beanParam = traverseMethodImpl.param(classOutline.implClass, "aBean");
JVar vizParam = traverseMethodImpl.param(narrowedVisitor, "aVisitor");
traverseMethodImpl.annotate(Override.class);
JBlock traverseBlock = traverseMethodImpl.body();
// for each field, if it's a bean, then visit it
List<FieldOutline> fields = findAllDeclaredAndInheritedFields(classOutline);
for (FieldOutline fieldOutline : fields) {
JType rawType = fieldOutline.getRawType();
JMethod getter = ClassDiscoverer.getter(fieldOutline);
if (getter != null && !(noIdrefTraversal && isIdrefField(fieldOutline))) {
boolean isJAXBElement = ClassDiscoverer.isJAXBElement(getter.type());
CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();
boolean isCollection = propertyInfo.isCollection();
if (isCollection) {
JClass collClazz = (JClass) rawType;
JClass collType = collClazz.getTypeParameters().get(0);
TraversableCodeGenStrategy t = getTraversableStrategy(collType, dcMap);
if (collType.name().startsWith("JAXBElement")) {
t.jaxbElementCollection(traverseBlock, collType, beanParam, getter, vizParam, visitable);
} else {
t.collection(getOutline(), traverseBlock, (JClass) rawType, beanParam, getter, vizParam, visitable, directClasses);
}
} else {
TraversableCodeGenStrategy t = getTraversableStrategy(rawType, dcMap);
if (isJAXBElement) {
t.jaxbElement(traverseBlock, (JClass) rawType, beanParam, getter, vizParam, visitable);
} else {
t.bean(traverseBlock, beanParam, getter, vizParam, visitable);
}
}
}
}
}
for (JClass dc : directClasses) {
JMethod traverseMethodImpl = defaultTraverser.method(JMod.PUBLIC, void.class, "traverse");
traverseMethodImpl._throws(exceptionType);
traverseMethodImpl.param(dc, "aBean");
traverseMethodImpl.param(narrowedVisitor, "aVisitor");
traverseMethodImpl.annotate(Override.class);
JBlock traverseBlock = traverseMethodImpl.body();
String[] source = {"// details about %s are not known at compile time.",
"// For now, applications using external classes will have to",
"// implement their own traversal logic."};
for (String s : source) {
traverseBlock.directStatement(String.format(s, dc.fullName()));
}
}
} finally {
getPackage().remove(scratch);
}
}
private boolean isIdrefField(FieldOutline fieldOutline) {
JFieldVar field = ClassDiscoverer.field(fieldOutline);
if(field == null) {
return false;
}
for(JAnnotationUse use : field.annotations()) {
if(use.getAnnotationClass().fullName().equals("javax.xml.bind.annotation.XmlIDREF")) {
return true;
}
}
return false;
}
/**
* Tests to see if the rawType is traversable
*
* @return TraversableCodeGenStrategy VISITABLE, NO, MAYBE, DIRECT
*
* @param rawType
*/
private TraversableCodeGenStrategy getTraversableStrategy(JType rawType, Map<String,JClass> directClasses) {
if (rawType.isPrimitive()) {
// primitive types are never traversable
return TraversableCodeGenStrategy.NO;
}
JClass clazz = (JClass) rawType;
if (clazz.isParameterized()) {
// if it's a parameterized type, then we should use the parameter
clazz = clazz.getTypeParameters().get(0);
if (clazz.name().startsWith("?")) {
// when we have a wildcard we should use the bounding class.
clazz = clazz._extends();
}
}
String name = clazz.fullName();
if (name.equals("java.lang.Object")) {
// it could be anything so we'll test with an instanceof in the generated code
return TraversableCodeGenStrategy.MAYBE;
} else if (clazz.isInterface()) {
// if it is an interface (like Serializable) it could also be anything
// handle it like java.lang.Object
return TraversableCodeGenStrategy.MAYBE;
} else if (visitable.isAssignableFrom(clazz)) {
// it's a real type. if it's one of ours, then it'll be assignable from Visitable
return TraversableCodeGenStrategy.VISITABLE;
} else if (directClasses.containsKey(name)) {
return TraversableCodeGenStrategy.DIRECT;
} else {
return TraversableCodeGenStrategy.NO;
}
}
}
| 44.477612
| 147
| 0.612416
|
8044c1ed0807e39aeae9e8e6a88a2821662fba4d
| 2,320
|
package org.shirolang.interpreter.ast;
import org.shirolang.interpreter.Defaults;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Defines a state definition in Shiro
*/
public class StateDefinition implements Codeable{
private String name;
private String graph;
private List<OptionSelection> options;
public StateDefinition(){
this.name = Defaults.STATE_NAME;
this.graph = Defaults.GRAPH_NAME;
this.options = new ArrayList<>();
}
public StateDefinition(String name) {
this.name = name;
this.graph = Defaults.GRAPH_NAME;
this.options = new ArrayList<>();
}
public StateDefinition(String name, String graph) {
this.name = name;
this.graph = graph;
this.options = new ArrayList<>();
}
public StateDefinition(String name, String graph, OptionSelection... selections){
this(name, graph);
this.options = Arrays.asList(selections);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGraph() {
return graph;
}
public List<OptionSelection> getOptions() {
return options;
}
public boolean hasOptions() {
return !options.isEmpty();
}
public String toCode() {
String path = GraphDefinition.class.getResource("shiro.stg").getPath();
STGroup templates = new STGroupFile(path);
ST code = templates.getInstanceOf("stateDef");
code.add("s", this);
return code.render();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StateDefinition that = (StateDefinition) o;
if (!name.equals(that.name)) return false;
if (!graph.equals(that.graph)) return false;
return options.equals(that.options);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + graph.hashCode();
result = 31 * result + options.hashCode();
return result;
}
}
| 24.946237
| 85
| 0.626293
|
5ebcf7417566c6fa04ad5ff451750bc39126f7b3
| 315
|
package bg.ehealth.prescriptions.services.medicine.nonproprietary;
import bg.ehealth.prescriptions.persistence.model.NonProprietaryMedicineName;
import java.io.InputStream;
import java.util.Set;
public interface MedicineNamesMedia {
Set<NonProprietaryMedicineName> medicineNames(InputStream inputStream);
}
| 26.25
| 77
| 0.844444
|
24285a4ca8def74b4873cadbb99edef92777c321
| 2,888
|
package com.flycms.web.tags;
import com.flycms.core.base.AbstractTagPlugin;
import com.flycms.core.entity.PageVo;
import com.flycms.core.utils.StringHelperUtils;
import com.flycms.module.search.model.Info;
import com.flycms.module.search.service.SolrService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* 分页信息整理
* @author cs
* @date 2020/10/11
*/
@Service
public class Infopage extends AbstractTagPlugin {
@Resource
private SolrService solrService;
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
/**
* 问题id 获取页面的参数
*/
String title = null;
/**
* 用户id
*/
Long userId = null;
/**
* 信息类型,0是全部,1问答,2文章,3分享
*/
Integer infoType = null;
/**
* 按信息分类id查询
*/
Long categoryId = null;
/**
* 需要排除id
*/
String notId=null;
/**
* 排序规则,recommend按推荐值排序,weight按权重值排序
*/
String orderby=null;
/**
* 当前页数
*/
int p = 1;
/**
* 每页记录数
*/
int rows = 10;
/**
* 处理标签变量
*/
Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
for(String str:paramWrap.keySet()){
if("title".equals(str)){
title = paramWrap.get(str).toString();
}
if("userId".equals(str)){
userId = Long.parseLong(paramWrap.get(str).toString());
}
if("infoType".equals(str)){
if(!StringUtils.isBlank(paramWrap.get(str).toString())) {
if(!StringHelperUtils.checkInteger(paramWrap.get(str).toString())) {
infoType=0;
}else{
infoType = Integer.parseInt(paramWrap.get(str).toString());
}
}else{
infoType=0;
}
}
if("categoryId".equals(str)){
if(!StringUtils.isBlank(paramWrap.get(str).toString())){
categoryId = Long.parseLong(paramWrap.get(str).toString());
}else{
categoryId = null;
}
}
if("notId".equals(str)){
notId = paramWrap.get(str).toString();
}
if("orderby".equals(str)){
orderby = paramWrap.get(str).toString();
}
if("p".equals(str)){
p = Integer.parseInt(paramWrap.get(str).toString());
}
if("rows".equals(str)){
rows = Integer.parseInt(paramWrap.get(str).toString());
}
}
// 获取文件的分页
try {
PageVo<Info> pageVo = solrService.searchInfo(title,userId,infoType,categoryId,notId,orderby,p,rows);
env.setVariable("info_page", builder.build().wrap(pageVo));
} catch (Exception e) {
env.setVariable("info_page", builder.build().wrap(null));
}
body.render(env.getOut());
}
}
| 24.474576
| 143
| 0.670706
|
cfcc4dd81bcfba2df0de1b93b6c3eb673389cd8d
| 680
|
package org.team3197.frc2019.robot.commands.defaults;
import edu.wpi.first.wpilibj.command.Command;
import org.team3197.frc2019.robot.OI;
import org.team3197.frc2019.robot.subsystems.Hatch;
public class Speak extends Command {
private Hatch hatch;
public Speak(Hatch hatch) {
requires(hatch);
this.hatch = hatch;
}
/**
* Takes the speed from OI that the hatch beak should drive at, and moves them.
*/
@Override
protected void execute() {
double speed = OI.hatchSpeed();
hatch.drive(speed, true);
}
@Override
protected boolean isFinished() {
return false;
}
@Override
protected void end() {
hatch.drive(0, true);
}
}
| 18.888889
| 81
| 0.688235
|
15d2f2fedccb7b9476aa35bfbe1576d5ac27300a
| 999
|
package cn.edu.gdut.douyintoutiao.base;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
/**
* @author : cypang
* @description : TODO:类的作用
* @email : 516585610@qq.com
* @date : 2020/11/12 11:14
*/
public abstract class ObserverManager<T> implements Observer<T> {
@Override
public void onSubscribe(@NonNull Disposable d) {
onDisposable(d);
}
@Override
public void onNext(@NonNull T t) {
onSuccess(t);
}
@Override
public void onError(@NonNull Throwable e) {
onFail(e);
}
@Override
public void onComplete() {
onFinish();
}
public abstract void onSuccess(T t); //调用成功
public abstract void onFail(Throwable throwable); //调用失败或者报错
public abstract void onFinish(); //调用完成
public abstract void onDisposable(Disposable disposable); //调用前准备工作
}
| 25.615385
| 74
| 0.634635
|
fa0cdbac9ef7b76a178d03f77629f4419f18df32
| 1,137
|
package com.apicasadocodigo.casadocodigo.request;
import com.apicasadocodigo.casadocodigo.model.Address;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class ClientRegistrationRequest {
@Email
private String email;
@NotNull
@NotEmpty
private String name;
@Column(name = "last_name")
private String lastName;
@NotNull
@NotEmpty
private String cpfOrcnpj;
@NotNull
@Embedded
private Address address;
public ClientRegistrationRequest(@Email String email, @NotNull @NotEmpty String name, String lastName,
@NotNull @NotEmpty String cpfOrcnpj, @NotNull Address address) {
this.email = email;
this.name = name;
this.lastName = lastName;
this.cpfOrcnpj = cpfOrcnpj;
this.address = address;
}
public ClientRegistrationRequest toModel(){
return new ClientRegistrationRequest(email, name, lastName, cpfOrcnpj, address);
}
}
| 25.840909
| 106
| 0.701847
|
8f309c90df6f8cede9a1e828a281112659f63470
| 3,082
|
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.common.dto.search;
import com.netflix.genie.common.external.util.GenieObjectMapper;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.UUID;
/**
* Unit tests for the BaseSearchResult class.
*
* @author tgianos
* @since 3.0.0
*/
class BaseSearchResultTest {
/**
* Make sure the constructor and getters work properly.
*/
@Test
void canConstruct() {
final String id = UUID.randomUUID().toString();
final String name = UUID.randomUUID().toString();
final String user = UUID.randomUUID().toString();
final BaseSearchResult searchResult = new BaseSearchResult(id, name, user);
Assertions.assertThat(searchResult.getId()).isEqualTo(id);
Assertions.assertThat(searchResult.getName()).isEqualTo(name);
Assertions.assertThat(searchResult.getUser()).isEqualTo(user);
}
/**
* Make sure the equals function only acts on id.
*/
@Test
void canFindEquality() {
final String id = UUID.randomUUID().toString();
final BaseSearchResult searchResult1
= new BaseSearchResult(id, UUID.randomUUID().toString(), UUID.randomUUID().toString());
final BaseSearchResult searchResult2
= new BaseSearchResult(id, UUID.randomUUID().toString(), UUID.randomUUID().toString());
final BaseSearchResult searchResult3 = new BaseSearchResult(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
);
Assertions.assertThat(searchResult1).isEqualTo(searchResult2);
Assertions.assertThat(searchResult1).isNotEqualTo(searchResult3);
Assertions.assertThat(searchResult1.hashCode()).isEqualTo(searchResult2.hashCode());
Assertions.assertThat(searchResult1.hashCode()).isNotEqualTo(searchResult3.hashCode());
}
/**
* Test to make sure we can create a valid JSON string from a DTO object.
*/
@Test
void canCreateValidJsonString() {
final BaseSearchResult searchResult = new BaseSearchResult(
UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString()
);
final String json = searchResult.toString();
Assertions.assertThatCode(() -> GenieObjectMapper.getMapper().readTree(json)).doesNotThrowAnyException();
}
}
| 35.837209
| 113
| 0.673589
|
33a9ad06ba6a1f699f028b9dd5a010b007b8ed0d
| 10,870
|
package net.bflows.pagafatture.controller;
import static org.hamcrest.core.Is.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.json.JSONObject;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.bflows.pagafatture.entities.InvoicingConnectionEntity;
import net.bflows.pagafatture.entities.InvoicingEntity;
import net.bflows.pagafatture.entities.MerchantEntity;
import net.bflows.pagafatture.entities.UserEntity;
import net.bflows.pagafatture.model.InvoicingConnectionReq;
import net.bflows.pagafatture.model.UserReq;
import net.bflows.pagafatture.repositories.InvoicingRepository;
import net.bflows.pagafatture.repositories.MerchantRepository;
import net.bflows.pagafatture.repositories.UserRepository;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class InvoicingsApiControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private MerchantRepository merchantRepository;
@Autowired
private InvoicingRepository invoicingRepository;
@Autowired
private ObjectMapper mapper;
@Autowired
private UserRepository userRepository;
@Test
@Order(1)
void testCreateInvocingConnection_Fail_By_Credential() throws Exception {
InvoicingEntity invoicingEntity = invoicingRepository.findById(1l).get();
InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq();
invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c0862123");
invoicingConnection.setApiUid("88864");
invoicingConnection.setTypeId(invoicingEntity.getId());
MerchantEntity merchant = new MerchantEntity();
merchant.setName("Merchant2");
merchant.setVatNumber("12345678901");
merchant.setDirectUrl("Http:www.www.it");
merchant.setAddressCity("Cagliari");
merchant.setAddressState("Sardinia");
merchant.setAddressCAP("09100");
merchant.setAddressStreet("Via PPP");
merchant = merchantRepository.save(merchant);
String URI = "/v1/invoicings/" + merchant.getId() + "/connections";
mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest()).andExpect(jsonPath("$.message", is("Invalid credentials.")));
}
@Test
@Order(2)
void testCreateInvocingConnection_Fail_By_invoicingId() throws Exception {
InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq();
invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c086");
invoicingConnection.setApiUid("88864");
invoicingConnection.setTypeId(0l);
MerchantEntity merchantEntity = merchantRepository.findById(2l).get();
String URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections";
mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
@Test
@Order(3)
void testCreateInvocingConnection_Success() throws Exception {
InvoicingEntity invoicingEntity = invoicingRepository.findById(1l).get();
InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq();
invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c086");
invoicingConnection.setApiUid("88864");
invoicingConnection.setTypeId(invoicingEntity.getId());
MerchantEntity merchantEntity = merchantRepository.findById(2l).get();
String URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections";
mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.data.apiKey", is(invoicingConnection.getApiKey())));
URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections";
mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
@Order(4)
void testGetInvoicing() throws Exception {
String URI = "/v1/invoicings";
mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isOk());
}
@Test
@Order(5)
void testGetInvoicingConnectionByMerchantId_Sucess() throws Exception {
InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq();
invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c086");
invoicingConnection.setApiUid("88864");
invoicingConnection.setTypeId(1l);
UserReq user = new UserReq();
user.setId(1l);
user.setCompanyName("Test InvoicingConnection");
user.setConfPassword("test12345678");
user.setEmail("testInvoicingConnection@test.com");
user.setFirstName("test");
user.setLastName("test lastname");
user.setPassword("test12345678");
user.setPhone("2424856");
String URI = "/v1/users";
mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(user))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated());
UserEntity userEntity = userRepository.findByEmailIgnoreCase(user.getEmail()).get();
URI = "/v1/invoicings/" + userEntity.getMerchant().getId() + "/connections";
ResultActions resultActions = mvc.perform(post(URI).content(new ObjectMapper().writeValueAsString(invoicingConnection))
.contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isCreated());
MvcResult result = resultActions.andReturn();
String contentAsString = result.getResponse().getContentAsString();
JSONObject json = new JSONObject(contentAsString);
InvoicingConnectionEntity response = mapper.readValue(json.get("data").toString(), InvoicingConnectionEntity.class);
URI = "/v1/invoicings/" + response.getMerchantEntity().getId() + "/connections";
mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isOk());
}
@Test
@Order(6)
void testGetInvoicingConnectionByMerchantId_Fail() throws Exception {
String URI = "/v1/invoicings/" + 0 + "/connections";
mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isNotFound());
MerchantEntity merchant = new MerchantEntity();
merchant.setName("InvoicingConnection Merchant");
merchant.setVatNumber("12345678901");
merchant.setDirectUrl("Http:www.www.it");
merchant.setAddressCity("Cagliari");
merchant.setAddressState("Sardinia");
merchant.setAddressCAP("09100");
merchant.setAddressStreet("Via PPP");
merchant = merchantRepository.save(merchant);
URI = "/v1/invoicings/" + merchant.getId() + "/connections";
mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isNotFound());
}
@Test
@Order(7)
void testCreateInvocingConnection_Fail_By_MerchantId() throws Exception {
InvoicingEntity invoicingEntity = invoicingRepository.findById(1l).get();
InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq();
invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c086");
invoicingConnection.setApiUid("88864");
invoicingConnection.setTypeId(invoicingEntity.getId());
String URI = "/v1/invoicings/" + 0 + "/connections";
mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
@Test
@Order(8)
void testCreateInvocingConnection_FailByTypeId() throws Exception {
InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq();
invoicingConnection.setApiKey("d0f99891fa6d8ec7606fd3ed09f2c086");
invoicingConnection.setApiUid("88864");
MerchantEntity merchantEntity = merchantRepository.findById(2l).get();
String URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections";
mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
@Test
@Order(9)
void testGetInvoicingConnection() throws Exception {
String URI = "/v1/invoicings/connections";
mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isOk());
URI = "/v1/invoicings/connections?type=1";
mvc.perform(MockMvcRequestBuilders.get(URI)).andExpect(status().isOk());
}
/* @Test
@Order(10)
void testCreateInvocingConnection_WithPasspartout() throws Exception {
InvoicingEntity invoicingEntity = invoicingRepository.findById(2l).get();
InvoicingConnectionReq invoicingConnection = new InvoicingConnectionReq();
invoicingConnection.setApiKey("137918001");
invoicingConnection.setApiUid("STU");
invoicingConnection.setTypeId(invoicingEntity.getId());
MerchantEntity merchantEntity = new MerchantEntity();
merchantEntity.setName("Test merchant");
merchantEntity.setEmail("testpasspartout@test.test");
merchantEntity = merchantRepository.save(merchantEntity);
String URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections";
mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
invoicingConnection = new InvoicingConnectionReq();
invoicingConnection.setApiKey("1379185000");
invoicingConnection.setApiUid("STU");
invoicingConnection.setTypeId(invoicingEntity.getId());
URI = "/v1/invoicings/" + merchantEntity.getId() + "/connections";
mvc.perform(MockMvcRequestBuilders.post(URI).content(mapper.writeValueAsString(invoicingConnection))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.data.apiKey", is(invoicingConnection.getApiKey())));
}*/
}
| 40.864662
| 121
| 0.790616
|
d5dc746c27514424711fb30fc64459272f56a27f
| 423
|
package DabEngine.Easing;
/**
* Provides easing functions that can be used to change a value over time.
*/
public enum Easing {
LINEAR{
@Override
public float ease(float from, float to, float time, float duration) {
return time * (to - from) / duration + from;
}
};
/**
* Has to be overrided by each function
*/
public float ease(float from, float to, float time, float duration){
return 0;
}
}
| 19.227273
| 74
| 0.664303
|
c9321d389ee8633ef2f59620dfaeace128727208
| 174
|
package org.jfrog.artifactory.client.model;
/**
* @author jbaruch
* @since 13/08/12
*/
public interface SnapshotVersionBehavior {
@Override
String toString();
}
| 14.5
| 43
| 0.695402
|
6d51ef6353539ae45f3bd16ba5a52d090f777da6
| 3,875
|
/*
* Copyright (C) 2006-2021 Talend Inc. - www.talend.com
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.talend.components.rest.configuration;
import lombok.Data;
import org.talend.components.rest.service.client.Body;
import org.talend.sdk.component.api.configuration.Option;
import org.talend.sdk.component.api.configuration.condition.ActiveIf;
import org.talend.sdk.component.api.configuration.ui.layout.GridLayout;
import org.talend.sdk.component.api.configuration.ui.widget.Code;
import org.talend.sdk.component.api.configuration.ui.widget.TextArea;
import org.talend.sdk.component.api.meta.Documentation;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Data
@GridLayout({ @GridLayout.Row({ "type" }), @GridLayout.Row({ "textValue" }), @GridLayout.Row({ "jsonValue" }),
@GridLayout.Row({ "xmlValue" }), @GridLayout.Row({ "params" }) })
@Documentation("")
public class RequestBody implements Serializable {
@Option
@Documentation("")
private Type type = Type.TEXT;
@Option
@TextArea
@ActiveIf(target = "type", value = "TEXT")
@Documentation("")
private String textValue;
@Option
@Code("json")
@ActiveIf(target = "type", value = "JSON")
@Documentation("")
private String jsonValue;
@Option
@Code("xml")
@ActiveIf(target = "type", value = "XML")
@Documentation("")
private String xmlValue;
@Option
@ActiveIf(target = "type", value = { "FORM_DATA", "X_WWW_FORM_URLENCODED" })
@Documentation("")
private List<Param> params = new ArrayList<>();
public List<Param> getParams() {
if (params == null) {
return null;
}
params.stream().filter(p -> p.getValue() == null).forEach(p -> p.setValue(""));
return params
.stream()
.filter(p -> p.getKey() != null)
.filter(p -> !p.getKey().isEmpty())
.collect(Collectors.toList());
}
public void setTextContent(String content) {
switch (this.getType()) {
case TEXT:
this.setTextValue(content);
break;
case JSON:
this.setJsonValue(content);
break;
case XML:
this.setXmlValue(content);
break;
default:
throw new IllegalArgumentException("You can't set text content for body type " + this.getType());
}
}
public String getTextContent() {
switch (this.getType()) {
case TEXT:
return this.getTextValue();
case JSON:
return this.getJsonValue();
case XML:
return this.getXmlValue();
default:
throw new IllegalArgumentException("You can't get text content for body type " + this.getType());
}
}
public enum Type {
TEXT("text/plain"),
JSON("application/json"),
XML("text/xml"),
FORM_DATA("multipart/form-data; boundary=" + Body.BODY_FORMADATA_BOUNDARY),
X_WWW_FORM_URLENCODED("application/x-www-form-urlencoded");
private final String contentType;
Type(final String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return this.contentType;
}
}
}
| 31.25
| 118
| 0.633806
|
428073b128d31f9d89ba5808ea6985d3dddccb8e
| 1,397
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public class Employee implements Printable {
protected static int employeeIDCounter = 0;
private String name;
private String jobTitle;
private int employeeID;
private int level;
public void calculateEmployeeID(){
employeeIDCounter++; // increment so that employeeID will be unique
setEmployeeID(employeeIDCounter);
}
public void print(){
System.out.println("Name: "+ getName());
System.out.println("Job Title: "+ getJobTitle());
System.out.println("Employee ID: "+ getEmployeeID());
System.out.println("Level: "+ getLevel());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public int getEmployeeID() {
return employeeID;
}
private void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
| 22.901639
| 77
| 0.586972
|
334ae159e6cf1849fb2888db6e9e6c207a0d9386
| 417
|
package io.confluent.parallelconsumer.offsets;
/*-
* Copyright (C) 2020-2022 Confluent, Inc.
*/
import io.confluent.parallelconsumer.internal.ParallelConsumerInternalException;
/*-
* Copyright (C) 2020-2021 Confluent, Inc.
*/
public class EncodingNotSupportedException extends ParallelConsumerInternalException {
public EncodingNotSupportedException(final String message) {
super(message);
}
}
| 24.529412
| 86
| 0.767386
|
536c44b424274d9d509d19e47c1ec4136cf0480f
| 1,005
|
package org.radargun.jpa;
import java.util.Random;
import org.radargun.config.DefinitionElement;
import org.radargun.config.Property;
import org.radargun.jpa.entities.Constant;
import org.radargun.utils.RandomHelper;
/**
* @author Radim Vansa <rvansa@redhat.com>
*/
@DefinitionElement(name = "constant", doc = "Immutable entity with simple string")
public class ConstantGenerator implements EntityGenerator<Constant> {
@Property(doc = "Length of the contained string")
int length;
@Override
public Constant create(Random random) {
return new Constant(RandomHelper.randomString(length, length, random));
}
@Override
public void mutate(Constant entity, Random random) {
throw new UnsupportedOperationException();
}
@Override
public Class<Constant> entityClass() {
return Constant.class;
}
@Override
public boolean hasGeneratedId() {
return true;
}
@Override
public boolean hasForeignKeys() {
return false;
}
}
| 23.372093
| 82
| 0.717413
|
8ab497de9735dc8986131134c4b21a4e84d81c1d
| 3,049
|
package lesx.ui.reports;
import java.util.Arrays;
import java.util.HashSet;
import javafx.fxml.FXML;
import lesx.gui.message.LesxMessage;
import lesx.property.properties.LesxProperty;
import lesx.property.properties.LesxReportTree;
import lesx.ui.costumer.dialog.LesxCostumerDialogPaneController;
import lesx.ui.costumer.dialog.propertysheet.LesxPropertySheet;
import lesx.ui.mainpage.datamodel.LesxCostumerDataModel;
import lesx.ui.reports.datamodel.LesxReportsDataModel;
public class LesxReportEditDialogController extends LesxCostumerDialogPaneController {
private LesxReportsDataModel dataModel;
private LesxReportTree tree;
private boolean isCreate;
private LesxPropertySheet propertySheet;
@FXML
@Override
public void initialize() {
super.initialize();
}
@Override
public void init(LesxCostumerDataModel dataModel, boolean isCreate) {
//Nothing
}
@Override
protected void reInitialize() {
isCreate = false;
dataModel.setSelectedReportTree(tree);
init(dataModel, isCreate);
}
public void init(LesxReportsDataModel dataModel, boolean isCreate) {
setTitle(LesxMessage.getMessage("TEXT-TITLE_REPORT_DIALOG_CREATE"));
this.dataModel = dataModel;
this.isCreate = isCreate;
if (isCreate) {
tree = new LesxReportTree();
tree.setId(dataModel.createNewKeyForTreeId());
tree.setCostumers(new HashSet<>());
if (dataModel.getSelectedReportTree() != null) {
tree.setParent_id(dataModel.getSelectedReportTree()
.getId());
}
else {
tree.setParent_id(-1L);
}
getDescriptionLabel().setText(LesxMessage.getMessage("TEXT-DESCRIPTION_LABEL_NEW_REPORT"));
}
else {
tree = dataModel.getSelectedReportTree();
getDescriptionLabel().setText(LesxMessage.getMessage("TEXT-DESCRIPTION_LABEL_EDIT_REPORT"));
}
getDefaultName().setText(getHeader(isCreate));
propertySheet = new LesxPropertySheet(getPropertiesPane(), getEditorsPane(), tree,
(Long newKey, LesxProperty property) -> dataModel.isUniqueProperty(property, newKey, this.isCreate));
getPendingChanges().bind(propertySheet.getPendingChangesProperty());
installButtonsBinding();
}
@Override
public String getTitle() {
return super.getTitle();
}
@Override
protected String getHeader(boolean isCreate) {
StringBuilder string;
string = new StringBuilder(128);
if (isCreate) {
string.append(LesxMessage.getMessage("TEXT-HEADER_LABEL_REPORT_PANE", "Nuevo"));
string.append(".");
}
else {
string.append(LesxMessage.getMessage("TEXT-HEADER_LABEL_REPORT_PANE", tree.getName()));
string.append(".");
}
return string.toString();
}
@Override
protected boolean isDuplicate() {
return dataModel.addReport(Arrays.asList(tree));
}
@Override
protected LesxPropertySheet getPropertySheet() {
return propertySheet;
}
@Override
protected String getComponentName() {
return tree.getName() == null ? "*No Name*" : tree.getName();
}
}
| 29.601942
| 109
| 0.725156
|
e7a5b97d5eccc43b6960b3666513476b918f8a56
| 455
|
package com.madhusudhan.j8.interfaces.functional;
// Functional Interfaces
public class FunctionalInterfaces {
// Functional interface
@FunctionalInterface
interface Multiplier {
int multiply(int i, int j);
};
// Lambda expression
Multiplier multiplierLambda = (p, q) -> p*q;
public static void main(String[] args) {
FunctionalInterfaces client = new FunctionalInterfaces();
System.out.println(client.multiplierLambda.multiply(2, 3));
}
}
| 25.277778
| 61
| 0.753846
|
18e38ce3bc43bdb4bffa4f8f321f6a470e7f10ec
| 1,253
|
package NO_0077_Combinations;
import java.util.ArrayList;
import java.util.List;
class Solution {
private List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
if (n <= 0 || k <= 0 || k > n) {
return res;
}
List<Integer> c = new ArrayList<>();
generateCombination(n, k, 1, c);
return res;
}
/**
* 求解组合 C(n, k),当前已经找到的组合存储在 c 中,需要从 start 中开始搜索新的元素
*
* @param n
* @param k
* @param start
* @param c
*/
private void generateCombination(int n, int k, int start, List<Integer> c) {
if (c.size() == k) {
res.add(new ArrayList<>(c));
return;
}
// 从 start 开始,主要是因为组合不讲究顺序,所以类似 [1, 2, 3]、[1, 3, 2]、[2, 3, 1] 等是一种情况,因此限定 start
// 这里对 i 的取值使用剪枝法,因为 c 中还有 k - c.size() 个空位,所以 i 的取值范围 [i, n] 中至少要有 k - c.size() 个元素
// 因此 i 最多为 n - (k - c.size()) + 1
for (int i = start; i <= n - (k - c.size()) + 1; i++) {
c.add(i);
generateCombination(n, k, i + 1, c);
c.remove(c.size() - 1);
}
}
public static void main(String[] args) {
System.out.println(new Solution().combine(3, 2));
}
}
| 27.844444
| 92
| 0.500399
|
1ce6d6b46b789aa26830f122acd27776725c16ab
| 25,750
|
package cc.cxsj.nju.gobang.ui;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import cc.cxsj.nju.gobang.config.ServerProperties;
import cc.cxsj.nju.gobang.info.ContestResult;
import cc.cxsj.nju.gobang.info.ContestResults;
import cc.cxsj.nju.gobang.info.Players;
import cc.cxsj.nju.gobang.info.RecordResolver;
import cc.cxsj.nju.gobang.info.ReplayStep;
import cc.cxsj.nju.gobang.task.CreateServiceRunnable;
import cc.cxsj.nju.gobang.task.DebugServiceRunnable;
@SuppressWarnings("serial")
public class MainFrame extends JFrame {
private static final int ROWS = Integer.valueOf(ServerProperties.instance().getProperty("chess.board.rows"));
private static final int COLS = Integer.valueOf(ServerProperties.instance().getProperty("chess.board.cols"));
private static final int ROUNDS = Integer.valueOf(ServerProperties.instance().getProperty("contest.rounds"));
private static final Integer MODE = Integer.valueOf(ServerProperties.instance().getProperty("server.mode"));
private static final int REPLAY_SPEED = Integer.valueOf(ServerProperties.instance().getProperty("replay.speed"));
private static final Color THEME_COLOR = Color.CYAN;
private Thread rt;
private static MainFrame instance = new MainFrame();
// the selected info
private ArrayList<Integer> resultsIdList = new ArrayList<Integer>();
private int selectedContestId = -1;
private int selectedRound = 0;
private int stepNum = 0;
private int mode = 0;
// ui element
// west panel
private DefaultListModel<String> resultListModel;
private JList<String> resultList;
private JPopupMenu popupMenu;
private JMenuItem replayItem = new JMenuItem("Replay Contest");
private JMenuItem refreshItem = new JMenuItem("Refresh Results");
private JMenuItem saveResultsItem = new JMenuItem("Save Results");
private JMenuItem generateNextPlayersItem = new JMenuItem("Generate Promotion Players");
private JMenuItem nextContestItem = new JMenuItem("Start Next Contest");
private JMenuItem loadContestItem = new JMenuItem("Load Contest Results");
private JMenuItem loadTestItem = new JMenuItem("Load Test Results");
private JMenuItem loadDebugItem = new JMenuItem("Load Debug Results");
private JMenuItem debugItem = new JMenuItem("Debug");
private JMenuItem aboutItem = new JMenuItem("About");
// center panel - grid panel 0 row - north panel
private JTextField player1info, player2info;
private JLabel vsLabel = new JLabel("VS");
private JLabel selectRoundLabel = new JLabel("Round");
private JComboBox<Integer> roundSelectComboBox;
private JLabel scoreOfRoundLabel = new JLabel("Score"), scoreVS = new JLabel(":");
private JTextField score1OfRound, score2OfRound;
private JLabel errorOfRoundLabel = new JLabel("Error"), errorVS = new JLabel(":");
private JTextField error1OfRound, error2OfRound;
private JLabel stepLabel = new JLabel("Step Info");
private JTextField stepInfo;
// center panel - grid panel 0 row - center panel - center panel
private JLabel[][] chessBoard = new JLabel[ROWS][COLS];
// center panel - grid panel 0 row - center panel - east panel
private JLabel stepNumLabel = new JLabel("Num");
private JTextField stepNumIuput;
private JButton stepJumpButton = new JButton("Jump");
private JButton stepBackButton = new JButton("Back");
private JButton stepNextButton = new JButton("Next");
private JButton stepAutoReplayButton = new JButton("Auto Replay");
private JButton stepCtrlAutoReplay = new JButton("Pause");
// center panel - east panel
private JTextArea logInfo;
boolean suspend = false;
private MainFrame() {
mode = Integer.valueOf(ServerProperties.instance().getProperty("server.mode"));
// set mainframe layout
this.setLayout(new BorderLayout());
// west panel
JPanel westPanel = new JPanel();
// westPanel.setSize(100, 400);
westPanel.setLayout(new BorderLayout());
{
resultListModel = new DefaultListModel<String>();
// initialize result list
StringBuilder resultListWidthPlaceHolder = new StringBuilder("");
int width = Integer.valueOf(ServerProperties.instance().getProperty("ui.result.list.width"));
for (int w = 0; w < width; w++) {
resultListWidthPlaceHolder.append("-");
}
resultListModel.addElement(resultListWidthPlaceHolder.toString());
resultList = new JList<String>(resultListModel);
resultList.setBackground(Color.WHITE);
JScrollPane scrollResultList = new JScrollPane(resultList);
scrollResultList.setBackground(Color.WHITE);
scrollResultList.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollResultList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollResultList.setBorder(new TitledBorder("Contest Result"));
westPanel.add(BorderLayout.CENTER, scrollResultList);
}
this.add(BorderLayout.WEST, westPanel);
// center panel
JPanel centerPanel = new JPanel();
// centerPanel.setSize(200, 400);
centerPanel.setLayout(new BorderLayout(5, 5));
{
// center panel - grid panel 0 row
JPanel centerPanel0Row = new JPanel();
centerPanel0Row.setLayout(new BorderLayout(5, 5));
// center panel - grid panel 0 row - north panel
{
JPanel centerPanel0RowNorthPanel = new JPanel();
centerPanel0RowNorthPanel.setLayout(new GridLayout(4, 1));
centerPanel0RowNorthPanel.setBackground(Color.WHITE);
centerPanel0RowNorthPanel.setBorder(new TitledBorder("Result Info"));
{
JPanel centerPanel0RowNorthPanel0Row = new JPanel();
centerPanel0RowNorthPanel0Row.setLayout(new FlowLayout(FlowLayout.LEFT));
centerPanel0RowNorthPanel0Row.setBackground(THEME_COLOR);
centerPanel0RowNorthPanel0Row.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1, true));
player1info = new JTextField("", 7);
player1info.setHorizontalAlignment(JTextField.CENTER);
centerPanel0RowNorthPanel0Row.add(player1info);
centerPanel0RowNorthPanel0Row.add(vsLabel);
player2info = new JTextField("", 7);
player2info.setHorizontalAlignment(JTextField.CENTER);
centerPanel0RowNorthPanel0Row.add(player2info);
centerPanel0RowNorthPanel0Row.add(selectRoundLabel);
roundSelectComboBox = new JComboBox<Integer>();
roundSelectComboBox.setBackground(Color.WHITE);
for (int round = 0; round < ROUNDS; round++) {
roundSelectComboBox.addItem(round);
}
selectedRound = 0;
centerPanel0RowNorthPanel0Row.add(roundSelectComboBox);
centerPanel0RowNorthPanel.add(centerPanel0RowNorthPanel0Row);
}
// score and error
{
JPanel centerPanel0RowNorthPanel1Row = new JPanel();
centerPanel0RowNorthPanel1Row.setLayout(new FlowLayout(FlowLayout.LEFT));
centerPanel0RowNorthPanel1Row.setBackground(THEME_COLOR);
centerPanel0RowNorthPanel1Row.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1, true));
centerPanel0RowNorthPanel1Row.add(scoreOfRoundLabel);
score1OfRound = new JTextField("", 3);
score1OfRound.setHorizontalAlignment(JTextField.CENTER);
centerPanel0RowNorthPanel1Row.add(score1OfRound);
centerPanel0RowNorthPanel1Row.add(scoreVS);
score2OfRound = new JTextField("", 3);
score2OfRound.setHorizontalAlignment(JTextField.CENTER);
centerPanel0RowNorthPanel1Row.add(score2OfRound);
centerPanel0RowNorthPanel1Row.add(errorOfRoundLabel);
error1OfRound = new JTextField("", 3);
error1OfRound.setHorizontalAlignment(JTextField.CENTER);
centerPanel0RowNorthPanel1Row.add(error1OfRound);
centerPanel0RowNorthPanel1Row.add(errorVS);
error2OfRound = new JTextField("", 3);
error2OfRound.setHorizontalAlignment(JTextField.CENTER);
centerPanel0RowNorthPanel1Row.add(error2OfRound);
centerPanel0RowNorthPanel.add(centerPanel0RowNorthPanel1Row);
}
// Num Jump Back Next Auto Ctrl
{
JPanel centerPanel0RowNorthPanel2Row = new JPanel();
centerPanel0RowNorthPanel2Row.setLayout(new FlowLayout(FlowLayout.LEFT));
centerPanel0RowNorthPanel2Row.setBackground(THEME_COLOR);
centerPanel0RowNorthPanel2Row.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1, true));
centerPanel0RowNorthPanel2Row.add(stepNumLabel);
stepNumIuput = new JTextField("0", 3);
centerPanel0RowNorthPanel2Row.add(stepNumIuput);
centerPanel0RowNorthPanel2Row.add(stepJumpButton);
centerPanel0RowNorthPanel2Row.add(stepBackButton);
centerPanel0RowNorthPanel2Row.add(stepNextButton);
centerPanel0RowNorthPanel2Row.add(stepAutoReplayButton);
centerPanel0RowNorthPanel2Row.add(stepCtrlAutoReplay);
centerPanel0RowNorthPanel.add(centerPanel0RowNorthPanel2Row);
}
// Step Info
{
JPanel centerPanel0RowNorthPanel3Row = new JPanel();
centerPanel0RowNorthPanel3Row.setLayout(new FlowLayout(FlowLayout.LEFT));
centerPanel0RowNorthPanel3Row.setBackground(THEME_COLOR);
centerPanel0RowNorthPanel3Row.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1, true));
centerPanel0RowNorthPanel3Row.add(stepLabel);
stepInfo = new JTextField("", 27);
centerPanel0RowNorthPanel3Row.add(stepInfo);
centerPanel0RowNorthPanel.add(centerPanel0RowNorthPanel3Row);
}
centerPanel0Row.add(BorderLayout.NORTH, centerPanel0RowNorthPanel);
}
// center panel - grid panel 0 row - center panel
{
JPanel centerPanel0RowCenterPanel = new JPanel();
centerPanel0RowCenterPanel.setLayout(new GridLayout(ROWS, COLS));
centerPanel0RowCenterPanel.setBorder(new TitledBorder("Chess Board"));
Color color = new Color(207, 141, 47);
centerPanel0RowCenterPanel.setBackground(color);
{
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
// chessBoard[r][c] = new JTextField(" ");
chessBoard[r][c] = new JLabel("");
chessBoard[r][c].setBorder(BorderFactory.createLineBorder(color.darker()));
chessBoard[r][c].setBackground(color);
chessBoard[r][c].setIcon(null);
if ((r == 7 && c == 7) || (r == 2 && c == 2) || (r == 12 && c == 2) || (r == 2 && c == 12) || (r == 12 && c == 12))
chessBoard[r][c].setBackground(Color.ORANGE);
else
chessBoard[r][c].setBackground(color);
chessBoard[r][c].setHorizontalAlignment(JLabel.CENTER);
centerPanel0RowCenterPanel.add(chessBoard[r][c]);
}
}
}
centerPanel0Row.add(BorderLayout.CENTER, centerPanel0RowCenterPanel);
}
centerPanel.add(centerPanel0Row);
}
this.add(BorderLayout.CENTER, centerPanel);
// center panel - grid panel 1 row
JPanel logPanel = new JPanel();
// logPanel.setSize(150, 400);
logPanel.setLayout(new BorderLayout());
{
logInfo = new JTextArea();
JScrollPane scrollLogInfo = new JScrollPane(logInfo);
scrollLogInfo.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollLogInfo.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollLogInfo.setBackground(Color.WHITE);
scrollLogInfo.setBorder(new TitledBorder("Log Info"));
logPanel.add(BorderLayout.CENTER, scrollLogInfo);
}
this.add(BorderLayout.EAST, logPanel);
// right click menu and response
popupMenu = new JPopupMenu();
popupMenu.add(replayItem);
popupMenu.addSeparator();
popupMenu.add(refreshItem);
popupMenu.add(saveResultsItem);
popupMenu.add(generateNextPlayersItem);
popupMenu.add(nextContestItem);
popupMenu.addSeparator();
popupMenu.add(loadContestItem);
popupMenu.add(loadTestItem);
popupMenu.add(loadDebugItem);
popupMenu.addSeparator();
popupMenu.add(debugItem);
popupMenu.addSeparator();
popupMenu.add(aboutItem);
switch (MODE) {
case 0:
loadTestItem.setEnabled(false);
loadDebugItem.setEnabled(false);
debugItem.setEnabled(false);
break;
case 1:
loadContestItem.setEnabled(false);
loadDebugItem.setEnabled(false);
generateNextPlayersItem.setEnabled(false);
nextContestItem.setEnabled(false);
debugItem.setEnabled(false);
break;
case 2:
loadContestItem.setEnabled(false);
loadTestItem.setEnabled(false);
generateNextPlayersItem.setEnabled(false);
nextContestItem.setEnabled(false);
break;
default:
break;
}
replayItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ContestResult result = ContestResults.getContestResult(selectedContestId);
if (result == null) {
MainFrame.instance().log("No result with id: " + selectedContestId);
return;
}
// System.out.println("Click replayItem");
roundSelectComboBox.setSelectedIndex(0);
selectedRound = 0;
if (RecordResolver.resolve(mode, result, selectedRound)) {
player1info.setText("");
player1info.setText(result.players[0].getId());
player2info.setText("");
player2info.setText(result.players[1].getId());
score1OfRound.setText("");
score1OfRound.setText(String.valueOf(result.scores[0][selectedRound]));
score2OfRound.setText("");
score2OfRound.setText(String.valueOf(result.scores[1][selectedRound]));
error1OfRound.setText("");
error1OfRound.setText(String.valueOf(result.errors[0][selectedRound]));
error2OfRound.setText("");
error2OfRound.setText(String.valueOf(result.errors[1][selectedRound]));
stepNum = 0;
stepNumIuput.setText("0");
fillChessBoard(0);
}
}
});
refreshItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
refreshResultListModal();
}
});
saveResultsItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ContestResults.saveContestResults();
}
});
generateNextPlayersItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Players.GenerateNextPlayersNameListFile();
}
});
nextContestItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (JOptionPane.showConfirmDialog(null, "Are you sure to start next contest?\n"
+ "Please ensure that the promotion players list has been produced!", "Start next contest?",
JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return;
ContestResults.clear();
refreshResultListModal();
Players.loadPlayers();
CreateServiceRunnable.updateService();
}
});
loadContestItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
log("Load contest result...");
mode = 0;
ContestResults.loadContestResults(0);
refreshResultListModal();
}
});
loadTestItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
log("Load test result...");
mode = 1;
ContestResults.loadContestResults(1);
refreshResultListModal();
}
});
loadDebugItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
log("Load debug result...");
mode = 2;
ContestResults.loadContestResults(2);
refreshResultListModal();
}
});
debugItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
log("Debug...");
new Thread(new DebugServiceRunnable()).start();
}
});
aboutItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Just Enjoy it :-)", "From whatbeg", JOptionPane.INFORMATION_MESSAGE,
null);
}
});
resultList.addMouseListener(new PopupListener());
// result list selection response
resultList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int selection = resultList.getSelectedIndex();
if (selection < resultsIdList.size() && selection >= 0) {
selectedContestId = resultsIdList.get(selection);
}
}
});
// chess replay control
stepJumpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String stepNumS = stepNumIuput.getText();
if (stepNumS.matches("[0-9]+")) {
int temp = Integer.valueOf(stepNumS);
if (temp >= 0 && temp < RecordResolver.record.size()) {
stepNum = temp;
fillChessBoard(stepNum);
log("Jump step " + stepNum);
} else {
log("Invalid input step num!");
}
} else {
log("Invalid input step num!");
}
}
});
stepBackButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (stepNum - 1 >= 0) {
stepNum--;
stepNumIuput.setText(String.valueOf(stepNum));
fillChessBoard(stepNum);
} else {
log("Already is the first step, can not back any more!");
}
}
});
stepNextButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (stepNum + 1 < RecordResolver.record.size()) {
stepNum++;
stepNumIuput.setText(String.valueOf(stepNum));
fillChessBoard(stepNum);
} else {
log("Already is the last step, can not next any more!");
}
}
});
stepAutoReplayButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startAutoReplay();
}
});
stepCtrlAutoReplay.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String txt = stepCtrlAutoReplay.getText();
if (txt.equals("Pause")) {
pauseAutoReplay();
}
}
});
// select which round
roundSelectComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
int round = roundSelectComboBox.getSelectedIndex();
if (round < ROUNDS && round >= 0) {
ContestResult result = ContestResults.getContestResult(selectedContestId);
if (result == null) {
MainFrame.instance().log("No result with id: " + selectedContestId);
return;
}
selectedRound = round;
if (RecordResolver.resolve(mode, result, selectedRound)) {
player1info.setText("");
player1info.setText(result.players[0].getId());
player2info.setText("");
player2info.setText(result.players[1].getId());
score1OfRound.setText("");
score1OfRound.setText(String.valueOf(result.scores[0][selectedRound]));
score2OfRound.setText("");
score2OfRound.setText(String.valueOf(result.scores[1][selectedRound]));
error1OfRound.setText("");
error1OfRound.setText(String.valueOf(result.errors[0][selectedRound]));
error2OfRound.setText("");
error2OfRound.setText(String.valueOf(result.errors[1][selectedRound]));
stepNum = 0;
stepNumIuput.setText("0");
fillChessBoard(0);
}
}
}
}
});
}
class PopupListener extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
}
private void startAutoReplay() {
suspend = false;
rt = new Thread (
new Runnable() {
public void run() {
try {
Robot rbt = new Robot();
String stepNumS = stepNumIuput.getText();
int temp = Integer.valueOf(stepNumS);
while (temp + 1 < RecordResolver.record.size()) {
stepNextButton.doClick();
rbt.delay(REPLAY_SPEED);
synchronized (this) {
if (suspend) {
break;
}
}
temp++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
rt.start();
}
private void pauseAutoReplay() {
try {
suspend = true;
} catch (Exception e) {
e.printStackTrace();
}
}
private void fillChessBoard(int stepNum) {
ReplayStep step = RecordResolver.record.get(stepNum);
stepInfo.setText(step.step);
if (step.isValidStep) {
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
chessBoard[r][c].setIcon(step.board[r][c]);
}
}
}
}
public void updateChessBoardUI(int lastRow, int lastCol, int r, int c, int color) {
Color backcolor = new Color(207, 141, 47);
if (lastRow != -1) {
chessBoard[r][c].setIcon(null);
chessBoard[lastRow][lastCol].setBorder(BorderFactory.createLineBorder(backcolor.darker()));
chessBoard[lastRow][lastCol].setBackground(backcolor);
}
if (color == -1) {
chessBoard[r][c].setIcon(null);
chessBoard[lastRow][lastCol].setBorder(BorderFactory.createLineBorder(backcolor.darker()));
chessBoard[lastRow][lastCol].setBackground(backcolor);
}
else
chessBoard[r][c].setIcon(color == 0 ? ReplayStep.icon_b : ReplayStep.icon_w);
chessBoard[r][c].setBorder(BorderFactory.createLineBorder(Color.RED, 2));
// System.out.println(String.format("Put %d %d with color %d", r, c, color));
}
public void updateStepInfo(String step, int num) {
stepInfo.setText(step);
stepNumIuput.setText(String.valueOf(num));
}
public void setPlayerId(String playerA, String playerB) {
player1info.setText(playerA);
player2info.setText(playerB);
// selectRoundLabel.setText(round);
// selectedRound = Integer.valueOf(round);
// roundSelectComboBox.setSelectedIndex(Integer.valueOf(round));
}
public void ClearChessBoardUI() {
Color color = new Color(207, 141, 47);
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
chessBoard[r][c].setText("");
chessBoard[r][c].setBorder(BorderFactory.createLineBorder(color.darker()));
chessBoard[r][c].setBackground(color);
chessBoard[r][c].setIcon(null);
}
}
}
private void refreshResultListModal() {
resultsIdList = ContestResults.getContestIdsOrderly();
int resultNum = resultsIdList.size();
if (resultNum == 0) {
resultListModel.clear();
System.out.println("ResultsIdList has " + resultNum);
return;
}
resultsIdList.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
if (o1 < o2) {
return -1;
} else if (o1 > o2) {
return 1;
} else {
return 0;
}
}
});
resultListModel.clear();
for (Integer id : resultsIdList) {
ContestResult result = ContestResults.getContestResult(id);
StringBuilder sb = new StringBuilder(" ");
if (id < 10) {
sb.append("0");
}
sb.append(id);
sb.append(" ");
sb.append(String.format("%9s", result.players[0].getId()));
sb.append(" VS ");
sb.append(String.format("%9s", result.players[1].getId()));
sb.append(" ");
sb.append(result.winRound[0]);
sb.append(":");
sb.append(result.winRound[1]);
sb.append(" ");
resultListModel.addElement(sb.toString());
}
log("Refresh result list complete!");
}
public synchronized void log(String info) {
logInfo.append(info);
System.out.println(info);
logInfo.append("\n");
logInfo.selectAll();
}
public static MainFrame instance() {
return instance;
}
}
| 38.148148
| 144
| 0.649786
|
bcb600811bf53855e1b20c6ac1aec547d88524ea
| 1,016
|
//假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
//
// 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
//
// 注意:给定 n 是一个正整数。
//
// 示例 1:
//
// 输入: 2
//输出: 2
//解释: 有两种方法可以爬到楼顶。
//1. 1 阶 + 1 阶
//2. 2 阶
//
// 示例 2:
//
// 输入: 3
//输出: 3
//解释: 有三种方法可以爬到楼顶。
//1. 1 阶 + 1 阶 + 1 阶
//2. 1 阶 + 2 阶
//3. 2 阶 + 1 阶
//
// Related Topics 记忆化搜索 数学 动态规划 👍 2042 👎 0
package com.daniel.leetcode.editor.cn;
public class Q70ClimbingStairs{
public static void main(String[] args) {
Solution solution = new Q70ClimbingStairs().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
int[] a;
public int climbStairs(int n) {
a = new int[n + 1];
return fb(n);
}
private int fb(int n) {
if (a[n] > 0) {
return a[n];
}
if (n == 1 || n == 0) {
return 1;
}
a[n] = fb(n - 1) + fb(n - 2);
return a[n];
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
| 18.814815
| 72
| 0.514764
|
af50430ba88ee33c154303d77bbc51608e14317b
| 945
|
/*
* Copyright (c) 2018-2019 ActionTech.
* License: http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 or higher.
*/
package com.actionsky.txle.repository;
import com.actionsky.txle.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Gannalyo
* @since 2019/3/29
*/
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
@Transactional
@Modifying(clearAutomatically = true)
@Query("UPDATE UserEntity T SET T.balance = T.balance - :balance WHERE id = :userId")
int updateBalanceByUserId(@Param("userId") long userId, @Param("balance") double balance);
}
| 35
| 94
| 0.778836
|
4fc8db24d208a88bde5df8b2ec78997a218b1c6c
| 2,348
|
package com.budgetplanner.batch;
import static org.junit.Assert.assertEquals;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import javax.batch.runtime.BatchStatus;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.test.AssertFile;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.test.context.junit4.SpringRunner;
import com.budgetplanner.TestUtilities;
import com.budgetplanner.repository.TransactionRepository;
import com.budgetplanner.util.BudgetAppConstants;
@SpringBatchTest
@SpringBootTest
@RunWith(SpringRunner.class)
public class NationwideTxnProcessorTest {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
private TransactionRepository transactionRepo;
@Before
public void setUp() {
TestUtilities.clearOutputDirectories();
transactionRepo.deleteAll();
}
@Test
public void testProcessNationwideTxnsJob() throws Exception {
final String testDirPath = "unittest/NationwideTxnProcessorTest";
// Add the unit test files
FileSystem fs = FileSystems.getDefault();
Path source = fs.getPath(testDirPath, BudgetAppConstants.NATIONWIDE_STATEMENT_FILE_NAME);
Path target = fs.getPath(BudgetAppConstants.STATEMENTS_DIR, BudgetAppConstants.NATIONWIDE_STATEMENT_FILE_NAME);
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
assertEquals(BatchStatus.COMPLETED.toString(),
jobExecution.getExitStatus().getExitCode());
// verify output file contains the expected content
AssertFile.assertFileEquals(new FileSystemResource(testDirPath + "/" + BudgetAppConstants.ALL_TRANSACTIONS_REPORT_NAME),
new FileSystemResource(BudgetAppConstants.REPORTS_DIR + "/" + BudgetAppConstants.ALL_TRANSACTIONS_REPORT_NAME));
}
}
| 35.575758
| 124
| 0.801107
|
c5498af018648298773c1b2ea9b2c5963e17dce7
| 9,505
|
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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.graphhopper.jsprit.core.problem.constraint;
import com.graphhopper.jsprit.core.algorithm.state.InternalStates;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingActivityCosts;
import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingTransportCosts;
import com.graphhopper.jsprit.core.problem.misc.JobInsertionContext;
import com.graphhopper.jsprit.core.problem.solution.route.activity.End;
import com.graphhopper.jsprit.core.problem.solution.route.activity.TourActivity;
import com.graphhopper.jsprit.core.problem.solution.route.state.RouteAndActivityStateGetter;
/**
* @author stefan
*/
public class VehicleDependentTimeWindowConstraints implements HardActivityConstraint {
protected RouteAndActivityStateGetter states;
protected VehicleRoutingTransportCosts routingCosts;
protected VehicleRoutingActivityCosts activityCosts;
public VehicleDependentTimeWindowConstraints(RouteAndActivityStateGetter states, VehicleRoutingTransportCosts routingCosts, VehicleRoutingActivityCosts activityCosts) {
super();
this.states = states;
this.routingCosts = routingCosts;
this.activityCosts = activityCosts;
}
@Override
public ConstraintsStatus fulfilled(JobInsertionContext iFacts, TourActivity prevAct, TourActivity newAct, TourActivity nextAct, double prevActDepTime) {
double latestVehicleArrival = iFacts.getNewVehicle().getLatestArrival();
Double latestArrTimeAtNextAct;
Location nextActLocation;
if (nextAct instanceof End) {
latestArrTimeAtNextAct = latestVehicleArrival;
nextActLocation = iFacts.getNewVehicle().getEndLocation();
if (!iFacts.getNewVehicle().isReturnToDepot()) {
nextActLocation = newAct.getLocation();
}
} else {
latestArrTimeAtNextAct = states.getActivityState(nextAct, iFacts.getNewVehicle(), InternalStates.LATEST_OPERATION_START_TIME, Double.class);
if (latestArrTimeAtNextAct == null) {//otherwise set it to theoretical_latest_operation_startTime
latestArrTimeAtNextAct = nextAct.getTheoreticalLatestOperationStartTime();
}
nextActLocation = nextAct.getLocation();
}
/*
* if latest arrival of vehicle (at its end) is smaller than earliest operation start times of activities,
* then vehicle can never conduct activities.
*
* |--- vehicle's operation time ---|
* |--- prevAct or newAct or nextAct ---|
*/
double newAct_theoreticalEarliestOperationStartTime = newAct.getTheoreticalEarliestOperationStartTime();
if (latestVehicleArrival < prevAct.getTheoreticalEarliestOperationStartTime() ||
latestVehicleArrival < newAct_theoreticalEarliestOperationStartTime ||
latestVehicleArrival < nextAct.getTheoreticalEarliestOperationStartTime()) {
return ConstraintsStatus.NOT_FULFILLED_BREAK;
}
/*
* if the latest operation start-time of new activity is smaller than the earliest start of prev. activity,
* then
*
* |--- prevAct ---|
* |--- newAct ---|
*/
if (newAct.getTheoreticalLatestOperationStartTime() < prevAct.getTheoreticalEarliestOperationStartTime()) {
return ConstraintsStatus.NOT_FULFILLED_BREAK;
}
/*
* |--- prevAct ---|
* |- earliest arrival of vehicle
* |--- nextAct ---|
*/
double arrTimeAtNextOnDirectRouteWithNewVehicle = prevActDepTime + routingCosts.getTransportTime(prevAct.getLocation(), nextActLocation, prevActDepTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
if (arrTimeAtNextOnDirectRouteWithNewVehicle > latestArrTimeAtNextAct) {
return ConstraintsStatus.NOT_FULFILLED_BREAK;
}
/*
* |--- newAct ---|
* |--- nextAct ---|
*/
if (newAct.getTheoreticalEarliestOperationStartTime() > nextAct.getTheoreticalLatestOperationStartTime()) {
return ConstraintsStatus.NOT_FULFILLED;
}
// log.info("check insertion of " + newAct + " between " + prevAct + " and " + nextAct + ". prevActDepTime=" + prevActDepTime);
double routingFromNewToNext = routingCosts.getTransportTime(newAct.getLocation(), nextActLocation, latestArrTimeAtNextAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
double arrTimeAtNewAct = prevActDepTime + routingCosts.getTransportTime(prevAct.getLocation(), newAct.getLocation(), prevActDepTime, iFacts.getNewDriver(), iFacts.getNewVehicle());
double endTimeAtNewAct = Math.max(arrTimeAtNewAct, newAct.getTheoreticalEarliestOperationStartTime()) + activityCosts.getActivityDuration(prevAct, newAct, arrTimeAtNewAct,iFacts.getNewDriver(),iFacts.getNewVehicle());
double savingsInNextActivityDuration =
activityCosts.getActivityDuration(prevAct, nextAct, arrTimeAtNextOnDirectRouteWithNewVehicle, iFacts.getNewDriver(), iFacts.getNewVehicle()) -
activityCosts.getActivityDuration(newAct, nextAct, endTimeAtNewAct + routingFromNewToNext, iFacts.getNewDriver(), iFacts.getNewVehicle());
latestArrTimeAtNextAct = Math.min(nextAct.getTheoreticalLatestOperationStartTime(), latestArrTimeAtNextAct + savingsInNextActivityDuration);
double latestArrTimeAtNewAct =
Math.min(newAct.getTheoreticalLatestOperationStartTime(),
latestArrTimeAtNextAct - routingFromNewToNext
- activityCosts.getActivityDuration(prevAct, newAct, arrTimeAtNewAct, iFacts.getNewDriver(), iFacts.getNewVehicle())
);
/*
* |--- prevAct ---|
* |--- vehicle's arrival @newAct
* latest arrival of vehicle @newAct ---|
*/
if (arrTimeAtNewAct > latestArrTimeAtNewAct) {
return ConstraintsStatus.NOT_FULFILLED;
}
if (nextAct instanceof End) {
if (endTimeAtNewAct > latestArrTimeAtNextAct) {
return ConstraintsStatus.NOT_FULFILLED;
}
if (!iFacts.getNewVehicle().isReturnToDepot()) {
return ConstraintsStatus.FULFILLED;
}
}
// log.info(newAct + " arrTime=" + arrTimeAtNewAct);
double arrTimeAtNextAct = endTimeAtNewAct + routingCosts.getTransportTime(newAct.getLocation(), nextActLocation, endTimeAtNewAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
/*
* |--- newAct ---|
* |--- vehicle's arrival @nextAct
* latest arrival of vehicle @nextAct ---|
*/
if (arrTimeAtNextAct > latestArrTimeAtNextAct) {
return ConstraintsStatus.NOT_FULFILLED;
}
if (savingsInNextActivityDuration != 0) {
double depTimeAtNextAct = Math.max(nextAct.getTheoreticalEarliestOperationStartTime(), arrTimeAtNextAct) +
activityCosts.getActivityDuration(newAct, nextAct, arrTimeAtNextAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
return validateNotLateToActivityAfterNext(iFacts, nextAct, depTimeAtNextAct);
}
return ConstraintsStatus.FULFILLED;
}
ConstraintsStatus validateNotLateToActivityAfterNext(JobInsertionContext iFacts, TourActivity nextAct, double depTimeAtNextAct) {
TourActivity nextAfterNext = iFacts.getRoute().getEnd();
Double latestArrTimeAtNextAfterNextAct = iFacts.getNewVehicle().getLatestArrival();
if (iFacts.getActivityContext().getInsertionIndex() + 1 < iFacts.getRoute().getActivities().size()) {
nextAfterNext = iFacts.getRoute().getActivities().get(iFacts.getActivityContext().getInsertionIndex() + 1);
latestArrTimeAtNextAfterNextAct = this.states.getActivityState(nextAfterNext, iFacts.getNewVehicle(), InternalStates.LATEST_OPERATION_START_TIME, Double.class);
if (latestArrTimeAtNextAfterNextAct == null)
latestArrTimeAtNextAfterNextAct = nextAfterNext.getTheoreticalLatestOperationStartTime();
}
double arrTimeAtNextAfterNextAct = depTimeAtNextAct +
routingCosts.getTransportTime(nextAct.getLocation(), nextAfterNext.getLocation(), depTimeAtNextAct, iFacts.getNewDriver(), iFacts.getNewVehicle());
if (arrTimeAtNextAfterNextAct > latestArrTimeAtNextAfterNextAct)
return ConstraintsStatus.NOT_FULFILLED;
return ConstraintsStatus.FULFILLED;
}
}
| 53.700565
| 225
| 0.697633
|
6195a303b2a7188edfd18fc5a9a274af4ec3b62a
| 724
|
/*
水仙花数
*/
public class LC09_palindrome {
public boolean isPalindrome(int x) {
String str=String.valueOf(x);
int length=str.length();
int begin=0;
int end=length-1;
while(begin<end){
if(str.charAt(begin)==str.charAt(end)){
begin++;
end--;
}else{
return false;
}
}
return true;
}
//最优算法
public boolean isPalindrome1(int x) {
if(x<0 || (x!=0 && x%10==0))
return false;
int reversnum=0;
while(x>reversnum){
reversnum=reversnum*10+x%10;
x/=10;
}
return x==reversnum || x==reversnum/10;
}
}
| 21.939394
| 51
| 0.459945
|
c9991b4103663255ca496a9456dd9aa79f6c6d8a
| 9,184
|
package com.bitdubai.fermat_cbp_plugin.layer.world.fiat_index.developer.bitdubai.version_1.database;
import com.bitdubai.fermat_api.FermatException;
import com.bitdubai.fermat_api.layer.all_definition.enums.FiatCurrency;
import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins;
import com.bitdubai.fermat_api.layer.all_definition.exceptions.InvalidParameterException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterType;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableFilter;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantInsertRecordException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_cbp_api.layer.world.exceptions.CantGetFiatIndexException;
import com.bitdubai.fermat_cbp_api.layer.world.interfaces.FiatIndex;
import com.bitdubai.fermat_cbp_plugin.layer.world.fiat_index.developer.bitdubai.version_1.exceptions.CantInitializeFiatIndexWorldDatabaseException;
import com.bitdubai.fermat_cbp_plugin.layer.world.fiat_index.developer.bitdubai.version_1.structure.FiatIndexImpl;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.interfaces.ErrorManager;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.enums.UnexpectedPluginExceptionSeverity;
import com.bitdubai.fermat_cbp_api.layer.world.exceptions.CantCreateFiatIndexException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* Created by Alejandro Bicelis on 11/21/2015.
*/
public class FiatIndexWorldDao {
private final ErrorManager errorManager;
private final PluginDatabaseSystem pluginDatabaseSystem;
private final UUID pluginId;
private Database database;
public FiatIndexWorldDao(final PluginDatabaseSystem pluginDatabaseSystem, final UUID pluginId, final ErrorManager errorManager) {
this.pluginDatabaseSystem = pluginDatabaseSystem;
this.pluginId = pluginId;
this.errorManager = errorManager;
}
public void initialize() throws CantInitializeFiatIndexWorldDatabaseException {
try {
database = this.pluginDatabaseSystem.openDatabase(pluginId, pluginId.toString());
} catch (DatabaseNotFoundException e) {
FiatIndexWorldDatabaseFactory databaseFactory = new FiatIndexWorldDatabaseFactory(pluginDatabaseSystem);
try {
database = databaseFactory.createDatabase(pluginId, pluginId.toString());
} catch (CantCreateDatabaseException cantCreateDatabaseException) {
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_CSH_MONEY_TRANSACTION_HOLD, UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN, cantCreateDatabaseException);
throw new CantInitializeFiatIndexWorldDatabaseException("Database could not be opened", cantCreateDatabaseException, "Database Name: " + pluginId.toString(), "");
}
}catch (CantOpenDatabaseException cantOpenDatabaseException) {
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_CSH_MONEY_TRANSACTION_HOLD, UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN, cantOpenDatabaseException);
throw new CantInitializeFiatIndexWorldDatabaseException("Database could not be opened", cantOpenDatabaseException, "Database Name: " + pluginId.toString(), "");
} catch (Exception e) {
errorManager.reportUnexpectedPluginException(Plugins.BITDUBAI_CSH_MONEY_TRANSACTION_HOLD, UnexpectedPluginExceptionSeverity.DISABLES_THIS_PLUGIN, e);
throw new CantInitializeFiatIndexWorldDatabaseException("Database could not be opened", FermatException.wrapException(e), "Database Name: " + pluginId.toString(), "");
}
}
public void saveFiatIndex(FiatIndex fiatIndex) throws CantCreateFiatIndexException {
DatabaseTable transactionTable = this.database.getTable(FiatIndexWorldDatabaseConstants.FIAT_INDEX_TABLE_NAME);
DatabaseTableRecord newRecord = transactionTable.getEmptyRecord();
constructRecordFromFiatIndex(newRecord, fiatIndex); //Insertar valores en el record
try {
transactionTable.insertRecord(newRecord);
}catch (CantInsertRecordException e) {
throw new CantCreateFiatIndexException(e.getMessage(), e, "Fiat Index Plugin", "Cant insert new record in table");
}
}
public List<FiatIndex> getQueriedIndexHistory(FiatCurrency fiatCurrency) throws CantGetFiatIndexException
{
List<FiatIndex> fiatIndexList = new ArrayList<>();
DatabaseTableFilter filter = getEmptyHoldTableFilter();
filter.setColumn(FiatIndexWorldDatabaseConstants.FIAT_INDEX_CURRENCY_COLUMN_NAME);
filter.setValue(fiatCurrency.getCode());
filter.setType(DatabaseFilterType.EQUAL);
try {
for (DatabaseTableRecord record : getRecordsByFilter(filter)) {
FiatIndex fiatIndex = constructFiatIndexFromRecord(record);
fiatIndexList.add(fiatIndex);
}
} catch (CantCreateFiatIndexException e) {
throw new CantGetFiatIndexException(CantGetFiatIndexException.DEFAULT_MESSAGE, e, "Failed to get Queried Fiat Index History list. Filter: " + filter.toString(), "");
} catch (CantLoadTableToMemoryException e) {
throw new CantGetFiatIndexException(CantGetFiatIndexException.DEFAULT_MESSAGE, e, "Failed to get Queried Fiat Index History list. Filter: " + filter.toString(), "");
}
return fiatIndexList;
}
/* INTERNAL HELPER FUNCTIONS */
private DatabaseTableFilter getEmptyHoldTableFilter() {
return this.database.getTable(FiatIndexWorldDatabaseConstants.FIAT_INDEX_TABLE_NAME).getEmptyTableFilter();
}
private List<DatabaseTableRecord> getRecordsByFilter(DatabaseTableFilter filter) throws CantLoadTableToMemoryException {
DatabaseTable table = this.database.getTable(FiatIndexWorldDatabaseConstants.FIAT_INDEX_TABLE_NAME);
if (filter != null)
table.addStringFilter(filter.getColumn(), filter.getValue(), filter.getType());
table.loadToMemory();
return table.getRecords();
}
private void constructRecordFromFiatIndex(DatabaseTableRecord newRecord, FiatIndex fiatIndex) {
newRecord.setUUIDValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_ID_COLUMN_NAME, UUID.randomUUID());
newRecord.setStringValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_CURRENCY_COLUMN_NAME, fiatIndex.getCurrency().getCode());
newRecord.setDoubleValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_SALE_PRICE_COLUMN_NAME, fiatIndex.getSalePrice());
newRecord.setDoubleValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_PURCHASE_PRICE_COLUMN_NAME, fiatIndex.getPurchasePrice());
newRecord.setStringValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_PROVIDER_DESCRIPTION_COLUMN_NAME, fiatIndex.getProviderDescription());
newRecord.setLongValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_TIMESTAMP_COLUMN_NAME, (new Date().getTime() / 1000));
}
private FiatIndex constructFiatIndexFromRecord(DatabaseTableRecord record) throws CantCreateFiatIndexException{
UUID id = record.getUUIDValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_ID_COLUMN_NAME);
double salePrice = record.getDoubleValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_SALE_PRICE_COLUMN_NAME);
double purchasePrice = record.getDoubleValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_PURCHASE_PRICE_COLUMN_NAME);
String providerDescription = record.getStringValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_PROVIDER_DESCRIPTION_COLUMN_NAME);
long timestamp = record.getLongValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_TIMESTAMP_COLUMN_NAME);
FiatCurrency currency;
try {
currency = FiatCurrency.getByCode(record.getStringValue(FiatIndexWorldDatabaseConstants.FIAT_INDEX_CURRENCY_COLUMN_NAME));
} catch (InvalidParameterException e) {
throw new CantCreateFiatIndexException(e.getMessage(), e, "Hold Transaction", "Invalid FiatCurrency value stored in table"
+ FiatIndexWorldDatabaseConstants.FIAT_INDEX_TABLE_NAME + " for id " + id);
}
return new FiatIndexImpl(currency, FiatCurrency.US_DOLLAR, salePrice, purchasePrice, timestamp, providerDescription);
}
}
| 54.023529
| 191
| 0.786694
|
e534e637d845f444ac3eaa43cfc6e76cb2c6e69a
| 14,751
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2012-2017 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://oss.oracle.com/licenses/CDDL+GPL-1.1
* or LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.json;
import org.glassfish.json.api.BufferPool;
import javax.json.*;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* JsonArrayBuilder implementation
*
* @author Jitendra Kotamraju
* @author Kin-man Chung
*/
class JsonArrayBuilderImpl implements JsonArrayBuilder {
private ArrayList<JsonValue> valueList;
private final BufferPool bufferPool;
JsonArrayBuilderImpl(BufferPool bufferPool) {
this.bufferPool = bufferPool;
}
JsonArrayBuilderImpl(JsonArray array, BufferPool bufferPool) {
this.bufferPool = bufferPool;
valueList = new ArrayList<>();
valueList.addAll(array);
}
JsonArrayBuilderImpl(Collection<?> collection, BufferPool bufferPool) {
this.bufferPool = bufferPool;
valueList = new ArrayList<>();
populate(collection);
}
@Override
public JsonArrayBuilder add(JsonValue value) {
validateValue(value);
addValueList(value);
return this;
}
@Override
public JsonArrayBuilder add(String value) {
validateValue(value);
addValueList(new JsonStringImpl(value));
return this;
}
@Override
public JsonArrayBuilder add(BigDecimal value) {
validateValue(value);
addValueList(JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder add(BigInteger value) {
validateValue(value);
addValueList(JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder add(int value) {
addValueList(JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder add(long value) {
addValueList(JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder add(double value) {
addValueList(JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder add(boolean value) {
addValueList(value ? JsonValue.TRUE : JsonValue.FALSE);
return this;
}
@Override
public JsonArrayBuilder addNull() {
addValueList(JsonValue.NULL);
return this;
}
@Override
public JsonArrayBuilder add(JsonObjectBuilder builder) {
if (builder == null) {
throw new NullPointerException(JsonMessages.ARRBUILDER_OBJECT_BUILDER_NULL());
}
addValueList(builder.build());
return this;
}
@Override
public JsonArrayBuilder add(JsonArrayBuilder builder) {
if (builder == null) {
throw new NullPointerException(JsonMessages.ARRBUILDER_ARRAY_BUILDER_NULL());
}
addValueList(builder.build());
return this;
}
@Override
public JsonArrayBuilder addAll(JsonArrayBuilder builder) {
if (builder == null) {
throw new NullPointerException(JsonMessages.ARRBUILDER_ARRAY_BUILDER_NULL());
}
if (valueList == null) {
valueList = new ArrayList<>();
}
valueList.addAll(builder.build());
return this;
}
@Override
public JsonArrayBuilder add(int index, JsonValue value) {
validateValue(value);
addValueList(index, value);
return this;
}
@Override
public JsonArrayBuilder add(int index, String value) {
validateValue(value);
addValueList(index, new JsonStringImpl(value));
return this;
}
@Override
public JsonArrayBuilder add(int index, BigDecimal value) {
validateValue(value);
addValueList(index, JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder add(int index, BigInteger value) {
validateValue(value);
addValueList(index, JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder add(int index, int value) {
addValueList(index, JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder add(int index, long value) {
addValueList(index, JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder add(int index, double value) {
addValueList(index, JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder add(int index, boolean value) {
addValueList(index, value ? JsonValue.TRUE : JsonValue.FALSE);
return this;
}
@Override
public JsonArrayBuilder addNull(int index) {
addValueList(index, JsonValue.NULL);
return this;
}
@Override
public JsonArrayBuilder add(int index, JsonObjectBuilder builder) {
if (builder == null) {
throw new NullPointerException(JsonMessages.ARRBUILDER_OBJECT_BUILDER_NULL());
}
addValueList(index, builder.build());
return this;
}
@Override
public JsonArrayBuilder add(int index, JsonArrayBuilder builder) {
if (builder == null) {
throw new NullPointerException(JsonMessages.ARRBUILDER_OBJECT_BUILDER_NULL());
}
addValueList(index, builder.build());
return this;
}
@Override
public JsonArrayBuilder set(int index, JsonValue value) {
validateValue(value);
setValueList(index, value);
return this;
}
@Override
public JsonArrayBuilder set(int index, String value) {
validateValue(value);
setValueList(index, new JsonStringImpl(value));
return this;
}
@Override
public JsonArrayBuilder set(int index, BigDecimal value) {
validateValue(value);
setValueList(index, JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder set(int index, BigInteger value) {
validateValue(value);
setValueList(index, JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder set(int index, int value) {
setValueList(index, JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder set(int index, long value) {
setValueList(index, JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder set(int index, double value) {
setValueList(index, JsonNumberImpl.getJsonNumber(value));
return this;
}
@Override
public JsonArrayBuilder set(int index, boolean value) {
setValueList(index, value ? JsonValue.TRUE : JsonValue.FALSE);
return this;
}
@Override
public JsonArrayBuilder setNull(int index) {
setValueList(index, JsonValue.NULL);
return this;
}
@Override
public JsonArrayBuilder set(int index, JsonObjectBuilder builder) {
if (builder == null) {
throw new NullPointerException(JsonMessages.ARRBUILDER_OBJECT_BUILDER_NULL());
}
setValueList(index, builder.build());
return this;
}
@Override
public JsonArrayBuilder set(int index, JsonArrayBuilder builder) {
if (builder == null) {
throw new NullPointerException(JsonMessages.ARRBUILDER_OBJECT_BUILDER_NULL());
}
setValueList(index, builder.build());
return this;
}
@Override
public JsonArrayBuilder remove(int index) {
if (valueList == null) {
throw new IndexOutOfBoundsException(JsonMessages.ARRBUILDER_VALUELIST_NULL(index, 0));
}
valueList.remove(index);
return this;
}
@Override
public JsonArray build() {
List<JsonValue> snapshot;
if (valueList == null) {
snapshot = Collections.emptyList();
} else {
// Should we trim to minimize storage ?
// valueList.trimToSize();
snapshot = Collections.unmodifiableList(valueList);
}
valueList = null;
return new JsonArrayImpl(snapshot, bufferPool);
}
private void populate(Collection<?> collection) {
for (Object value : collection) {
if (value != null && value instanceof Optional) {
((Optional<?>) value).ifPresent(v ->
this.valueList.add(MapUtil.handle(v, bufferPool)));
} else {
this.valueList.add(MapUtil.handle(value, bufferPool));
}
}
}
private void addValueList(JsonValue value) {
if (valueList == null) {
valueList = new ArrayList<>();
}
valueList.add(value);
}
private void addValueList(int index, JsonValue value) {
if (valueList == null) {
valueList = new ArrayList<>();
}
valueList.add(index, value);
}
private void setValueList(int index, JsonValue value) {
if (valueList == null) {
throw new IndexOutOfBoundsException(JsonMessages.ARRBUILDER_VALUELIST_NULL(index, 0));
}
valueList.set(index, value);
}
private void validateValue(Object value) {
if (value == null) {
throw new NullPointerException(JsonMessages.ARRBUILDER_VALUE_NULL());
}
}
private static final class JsonArrayImpl extends AbstractList<JsonValue> implements JsonArray {
private final List<JsonValue> valueList; // Unmodifiable
private final BufferPool bufferPool;
JsonArrayImpl(List<JsonValue> valueList, BufferPool bufferPool) {
this.valueList = valueList;
this.bufferPool = bufferPool;
}
@Override
public int size() {
return valueList.size();
}
@Override
public JsonObject getJsonObject(int index) {
return (JsonObject)valueList.get(index);
}
@Override
public JsonArray getJsonArray(int index) {
return (JsonArray)valueList.get(index);
}
@Override
public JsonNumber getJsonNumber(int index) {
return (JsonNumber)valueList.get(index);
}
@Override
public JsonString getJsonString(int index) {
return (JsonString)valueList.get(index);
}
@Override
@SuppressWarnings("unchecked")
public <T extends JsonValue> List<T> getValuesAs(Class<T> clazz) {
return (List<T>)valueList;
}
@Override
public String getString(int index) {
return getJsonString(index).getString();
}
@Override
public String getString(int index, String defaultValue) {
try {
return getString(index);
} catch (Exception e) {
return defaultValue;
}
}
@Override
public int getInt(int index) {
return getJsonNumber(index).intValue();
}
@Override
public int getInt(int index, int defaultValue) {
try {
return getInt(index);
} catch (Exception e) {
return defaultValue;
}
}
@Override
public boolean getBoolean(int index) {
JsonValue jsonValue = get(index);
if (jsonValue == JsonValue.TRUE) {
return true;
} else if (jsonValue == JsonValue.FALSE) {
return false;
} else {
throw new ClassCastException();
}
}
@Override
public boolean getBoolean(int index, boolean defaultValue) {
try {
return getBoolean(index);
} catch (Exception e) {
return defaultValue;
}
}
@Override
public boolean isNull(int index) {
return valueList.get(index).equals(JsonValue.NULL);
}
@Override
public ValueType getValueType() {
return ValueType.ARRAY;
}
@Override
public JsonValue get(int index) {
return valueList.get(index);
}
@Override
public String toString() {
StringWriter sw = new StringWriter();
try (JsonWriter jw = new JsonWriterImpl(sw, bufferPool)) {
jw.write(this);
}
return sw.toString();
}
@Override
public JsonArray asJsonArray() {
return this;
}
}
}
| 29.267857
| 99
| 0.626466
|
1c1f26350963fe08417a099163deba2a4a7a3a2f
| 2,990
|
package File;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Random;
import java.util.Scanner;
/**
* Project: LearnJava
* Package: File
* Author: Novemser
* 2017/9/5
*/
public class Java7FileIO {
private String path;
public Java7FileIO(String path) {
this.path = path;
}
public static void main(String[] args) throws IOException {
Java7FileIO fileIO = new Java7FileIO("F:\\IAMLARGE.txt");
// fileIO.writeFileTest();
// fileIO.readFileTest();
// fileIO.readFileByBuffer();
// fileIO.readFileNIO();
fileIO.readFileCommonIO();
}
public void writeFileTest() throws IOException {
File fileToWrite = new File(path);
Path filePath = fileToWrite.toPath();
BufferedWriter writer =
Files.newBufferedWriter(filePath, Charset.defaultCharset(), StandardOpenOption.APPEND);
Random random = new Random();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String content = String.valueOf(random.nextInt());
writer.write(content);
writer.newLine();
}
writer.flush();
writer.close();
}
private Long count = 0L;
public void readFileTest() throws IOException {
try (Scanner scanner = new Scanner(Paths.get(path))) {
while (scanner.hasNext()) {
count++;
if (count % 10000000 == 0) {
System.out.println(count);
}
}
}
}
public void readFileByBuffer() throws IOException {
BufferedReader reader =
Files.newBufferedReader(Paths.get(path));
String line = null;
while ((line = reader.readLine()) != null) {
count++;
if (count % 10000000 == 0) {
System.out.println(count);
}
}
}
/**
* TODO:Pending to validate this method
*
* @throws IOException
*/
public void readFileNIO() throws IOException {
try (SeekableByteChannel ch = Files.newByteChannel(Paths.get(path))) {
ByteBuffer bb = ByteBuffer.allocateDirect(10000000);
for (; ; ) {
StringBuilder line = new StringBuilder();
int n = ch.read(bb);
line.append((char) n);
// add chars to line
// ...
if (line.length() >= 10000000) {
System.out.println("Yeah");
break;
}
}
}
}
public void readFileCommonIO() throws IOException {
Files.readAllLines(Paths.get(path));
}
}
| 27.943925
| 103
| 0.565552
|
b05bab2ce93f2578dc497578bd051bb7873a7313
| 2,431
|
package com.dcj.security.core.authentication.mobile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
//之后通过apply放在WebConfig链上
@Component
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {//因为是Web方式 所以是HttpSecurity
@Autowired
private AuthenticationFailureHandler failureHandler;
@Autowired
private AuthenticationSuccessHandler successHandler;
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(HttpSecurity http) throws Exception {
super.configure(http);
//配置filter
SmsAuthenticationFilter filter = new SmsAuthenticationFilter();
//设置AuthenticationManager (从http中获取)
filter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
//设置成功 失败后的处理方式
filter.setAuthenticationFailureHandler(failureHandler);
filter.setAuthenticationSuccessHandler(successHandler);
//配置provider 设置自定义参数userService
SmsCodeAuthenticationProvider provider = new SmsCodeAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
//设置http provider 以及 filter(放置在密码校验之后)
////把smsCodeAuthenticationFilter过滤器添加在UsernamePasswordAuthenticationFilter之前
http.authenticationProvider(provider)
.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
}
}
/*UsernamePasswordAuthenticationFilter拦截登录请求
UsernamePasswordAuthenticationFilter获取到用户名和密码构造一个UsernamePasswordAuthenticationToken传入AuthenticationManager
AuthenticationManager找到对应的Provider进行具体校验逻辑处理(如何找到对应的provider? 在这里进行配置的provider与filter对应起来即可)
最后登录信息保存进SecurityContext*/
| 46.75
| 152
| 0.830934
|
85b73710c51b00c9460af7c16d101915f78c7511
| 757
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.bumptech.glide;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import java.io.File;
import java.net.URL;
interface ModelTypes
{
public abstract Object load(Bitmap bitmap);
public abstract Object load(Drawable drawable);
public abstract Object load(Uri uri);
public abstract Object load(File file);
public abstract Object load(Integer integer);
public abstract Object load(Object obj);
public abstract Object load(String s);
public abstract Object load(URL url);
public abstract Object load(byte abyte0[]);
}
| 22.264706
| 62
| 0.770145
|
dd342c722bb249b7cd5fa679918bd0a4528f78a0
| 1,405
|
package com.blastedstudios.thrall.world.encounter;
import com.badlogic.gdx.scenes.scene2d.ui.Window;
import com.blastedstudios.thrall.util.Log;
import com.blastedstudios.thrall.world.IEncounterListener;
import com.blastedstudios.thrall.world.World;
public class EncounterSuccessFailOption extends EncounterOption{
private static final String TAG = EncounterSuccessFailOption.class.getCanonicalName();
protected final float probability; // [0-1] success
protected final IEncounterHandler failure;
private final IEncounterListener listener;
public EncounterSuccessFailOption(float probability, IEncounterListener listener,
String choiceText, IEncounterHandler success, IEncounterHandler failure){
super(choiceText, success);
this.probability = probability;
this.listener = listener;
this.failure = failure;
}
@Override
public String getChoiceText() {
return String.format("%.2f", probability*100) + "%: " + choiceText;
}
@Override
public void execute(World world) {
listener.triggerSkillCheck((Window window, float resultProbability) -> {
float roll = world.random.nextFloat();
float successChance = probability*resultProbability;
if(roll <= probability*resultProbability)
result.execute();
else
failure.execute();
Log.log(TAG, String.format("Rolled %.2f vs p=%.2f*%.2f=%.2f",
1f-roll, probability, resultProbability, successChance));
});
}
}
| 34.268293
| 87
| 0.768683
|
ebd0671fbd322f34d07ced6b7ba2ba20d4e15121
| 317
|
package org.bootstrapbugz.api.auth.security.user.details;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
public interface CustomUserDetailsService extends UserDetailsService {
UserDetails loadUserByUserId(Long userId);
}
| 35.222222
| 72
| 0.861199
|
4c1a05be6e1c1fe256a711574b4c5aeaf77e5f80
| 5,323
|
/*
* Copyright 2018 Nafundi
*
* 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.redrosecps.collect.android.utilities;
import android.content.Context;
import android.database.Cursor;
import com.redrosecps.collect.android.R;
import com.redrosecps.collect.android.application.Collect;
import com.redrosecps.collect.android.dao.InstancesDao;
import com.redrosecps.collect.android.provider.InstanceProviderAPI;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class InstanceUploaderUtils {
public static final String DEFAULT_SUCCESSFUL_TEXT = "full submission upload was successful!";
public static final String SPREADSHEET_UPLOADED_TO_GOOGLE_DRIVE = "Failed. Records can only be submitted to spreadsheets created in Google Sheets. The submission spreadsheet specified was uploaded to Google Drive.";
private InstanceUploaderUtils() {
}
/**
* Returns a formatted message including submission results for all the filled forms accessible
* through instancesProcessed in the following structure:
*
* Form name 1 - result
*
* Form name 2 - result
*/
public static String getUploadResultMessage(Context context, Map<String, String> result) {
Set<String> keys = result.keySet();
Iterator<String> it = keys.iterator();
StringBuilder message = new StringBuilder();
int count = keys.size();
while (count > 0) {
String[] selectionArgs;
if (count > ApplicationConstants.SQLITE_MAX_VARIABLE_NUMBER) {
selectionArgs = new String[ApplicationConstants.SQLITE_MAX_VARIABLE_NUMBER];
} else {
selectionArgs = new String[count];
}
StringBuilder selection = new StringBuilder();
selection.append(InstanceProviderAPI.InstanceColumns._ID + " IN (");
int i = 0;
while (it.hasNext() && i < selectionArgs.length) {
selectionArgs[i] = it.next();
selection.append('?');
if (i != selectionArgs.length - 1) {
selection.append(',');
}
i++;
}
selection.append(')');
count -= selectionArgs.length;
message.append(InstanceUploaderUtils
.getUploadResultMessageForInstances(new InstancesDao().getInstancesCursor(selection.toString(), selectionArgs), result));
}
if (message.length() == 0) {
message = new StringBuilder(context.getString(R.string.no_forms_uploaded));
}
return message.toString().trim();
}
private static String getUploadResultMessageForInstances(Cursor instancesProcessed,
Map<String, String> resultMessagesByInstanceId) {
StringBuilder queryMessage = new StringBuilder();
try {
if (instancesProcessed != null && instancesProcessed.getCount() > 0) {
instancesProcessed.moveToPosition(-1);
while (instancesProcessed.moveToNext()) {
String name =
instancesProcessed.getString(
instancesProcessed.getColumnIndex(InstanceProviderAPI.InstanceColumns.DISPLAY_NAME));
String id = instancesProcessed.getString(instancesProcessed.getColumnIndex(InstanceProviderAPI.InstanceColumns._ID));
String text = localizeDefaultAggregateSuccessfulText(resultMessagesByInstanceId.get(id));
queryMessage
.append(name)
.append(" - ")
.append(text)
.append("\n\n");
}
}
} finally {
if (instancesProcessed != null) {
instancesProcessed.close();
}
}
return String.valueOf(queryMessage);
}
private static String localizeDefaultAggregateSuccessfulText(String text) {
if (text != null && text.equals(DEFAULT_SUCCESSFUL_TEXT)) {
text = Collect.getInstance().getString(R.string.success);
}
return text;
}
// If a spreadsheet is created using Excel (or a similar tool) and uploaded to GD it contains:
// drive.google.com/file/d/ instead of docs.google.com/spreadsheets/d/
// Such a file can't be used. We can write data only to documents generated via Google Sheets
// https://forum.opendatakit.org/t/error-400-bad-request-failed-precondition-on-collect-to-google-sheets/19801/5?u=grzesiek2010
public static boolean doesUrlRefersToGoogleSheetsFile(String url) {
return !url.contains("drive.google.com/file/d/");
}
}
| 40.633588
| 219
| 0.634417
|
6997e2cc040b6cd3ef57ca2c49286187e948ea0a
| 257
|
package org.marcodave.szotar;
import org.marcodave.szotar.data.DictionaryInput;
import org.marcodave.szotar.data.DictionaryResult;
import java.util.Set;
public interface Dictionary {
Set<DictionaryResult> getTranslations(DictionaryInput input);
}
| 19.769231
| 62
| 0.809339
|
5bb3ced0eb1f79ef701c786a1f60b857ba25a53b
| 960
|
package com.example.springbootdocker.Models;
public class BodyResponse {
Boolean ok;
String message;
String error;
public BodyResponse(Boolean ok, String message, String error) {
super();
this.ok = ok;
this.message = message;
this.error = error;
}
public Boolean getOk() {
return ok;
}
public void setOk(Boolean ok) {
this.ok = ok;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public BodyResponse(Exception e) {
super();
this.ok = false;
this.message = e.getMessage();
this.error = e.toString();
}
public BodyResponse() {
super();
}
@Override
public String toString() {
return "BodyResponse [ok=" + ok + ", message=" + message + ", error=" + error + "]";
}
}
| 16.842105
| 87
| 0.614583
|
935d7dc4a38a935b8bebc08559c829b00776b28d
| 7,341
|
/*
* Copyright 2014-2021 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.rest.core.mapping;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.data.rest.core.mapping.ResourceType.*;
import static org.springframework.http.HttpMethod.*;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.annotation.ReadOnlyProperty;
import org.springframework.data.annotation.Reference;
import org.springframework.data.keyvalue.core.mapping.KeyValuePersistentEntity;
import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.CrudMethods;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.DefaultCrudMethods;
import org.springframework.data.repository.core.support.DefaultRepositoryMetadata;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.http.HttpMethod;
/**
* Unit tests for {@link CrudMethodsSupportedHttpMethods}.
*
* @author Oliver Gierke
*/
@ExtendWith(MockitoExtension.class)
class CrudMethodsSupportedHttpMethodsUnitTests {
@Mock RepositoryResourceMappings mappings;
@BeforeEach
void setUp() {
when(mappings.exposeMethodsByDefault()).thenReturn(true);
}
@Test // DATACMNS-589, DATAREST-409
void doesNotSupportAnyHttpMethodForEmptyRepository() {
SupportedHttpMethods supportedMethods = getSupportedHttpMethodsFor(RawRepository.class);
assertMethodsSupported(supportedMethods, ResourceType.COLLECTION, true, OPTIONS);
assertMethodsSupported(supportedMethods, ResourceType.COLLECTION, false, GET, PUT, POST, PATCH, DELETE, HEAD);
assertMethodsSupported(supportedMethods, ITEM, true, OPTIONS);
assertMethodsSupported(supportedMethods, ITEM, false, GET, PUT, POST, PATCH, DELETE, HEAD);
}
@Test // DATAREST-217, DATAREST-330, DATACMNS-589, DATAREST-409
void defaultsSupportedHttpMethodsForItemResource() {
SupportedHttpMethods supportedHttpMethods = getSupportedHttpMethodsFor(SampleRepository.class);
assertMethodsSupported(supportedHttpMethods, ITEM, true, GET, PUT, PATCH, DELETE, OPTIONS, HEAD);
assertMethodsSupported(supportedHttpMethods, ITEM, false, POST);
}
@Test // DATAREST-217, DATAREST-330, DATACMNS-589, DATAREST-409
void defaultsSupportedHttpMethodsForCollectionResource() {
SupportedHttpMethods supportedHttpMethods = getSupportedHttpMethodsFor(SampleRepository.class);
assertMethodsSupported(supportedHttpMethods, ResourceType.COLLECTION, true, GET, POST, OPTIONS, HEAD);
assertMethodsSupported(supportedHttpMethods, ResourceType.COLLECTION, false, PUT, PATCH, DELETE);
}
@Test // DATACMNS-589, DATAREST-409
void doesNotSupportDeleteIfDeleteMethodIsNotExported() {
SupportedHttpMethods supportedHttpMethods = getSupportedHttpMethodsFor(HidesDelete.class);
assertMethodsSupported(supportedHttpMethods, ITEM, false, DELETE);
}
@Test // DATAREST-523
void exposesMethodsForProperties() {
KeyValueMappingContext<?, ?> context = new KeyValueMappingContext<>();
KeyValuePersistentEntity<?, ?> entity = context.getRequiredPersistentEntity(Entity.class);
SupportedHttpMethods methods = getSupportedHttpMethodsFor(EntityRepository.class);
assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("embedded"))).isEmpty();
assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("embeddedCollection"))).isEmpty();
assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("related")))//
.contains(GET, DELETE, PATCH, PUT)//
.doesNotContain(POST);
assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("relatedCollection")))//
.contains(GET, DELETE, PATCH, PUT, POST);
assertThat(methods.getMethodsFor(entity.getRequiredPersistentProperty("readOnlyReference")))//
.contains(GET)//
.doesNotContain(DELETE, PATCH, PUT, POST);
}
@Test // DATAREST-825
void supportsDeleteIfFindOneIsHidden() {
assertMethodsSupported(getSupportedHttpMethodsFor(HidesFindOne.class), ITEM, true, DELETE, PATCH, PUT, OPTIONS);
}
@Test // DATAREST-825
void doesNotSupportDeleteIfNoFindOneAvailable() {
assertMethodsSupported(getSupportedHttpMethodsFor(NoFindOne.class), ITEM, false, DELETE);
}
@Test // DATAREST-1176
void onlyExposesExplicitlyAnnotatedMethodsIfConfigured() {
reset(mappings);
when(mappings.exposeMethodsByDefault()).thenReturn(false);
assertMethodsSupported(getSupportedHttpMethodsFor(MethodsExplicitlyExportedRepository.class),
ResourceType.COLLECTION, true,
POST, OPTIONS);
assertMethodsSupported(getSupportedHttpMethodsFor(MethodsExplicitlyExportedRepository.class), ITEM, true, OPTIONS,
PUT, PATCH);
}
private SupportedHttpMethods getSupportedHttpMethodsFor(Class<?> repositoryInterface) {
RepositoryMetadata metadata = new DefaultRepositoryMetadata(repositoryInterface);
CrudMethods crudMethods = new DefaultCrudMethods(metadata);
return new CrudMethodsSupportedHttpMethods(crudMethods, mappings.exposeMethodsByDefault());
}
private static void assertMethodsSupported(SupportedHttpMethods methods, ResourceType type, boolean supported,
HttpMethod... httpMethods) {
HttpMethods result = methods.getMethodsFor(type);
if (supported) {
assertThat(result).containsExactlyInAnyOrder(httpMethods);
} else {
assertThat(result).doesNotContain(httpMethods);
}
}
interface RawRepository extends Repository<Object, Long> {}
interface SampleRepository extends CrudRepository<Object, Long> {}
interface HidesDelete extends CrudRepository<Object, Long> {
@RestResource(exported = false)
void delete(Object entity);
}
interface HidesFindOne extends CrudRepository<Object, Long> {
@Override
@RestResource(exported = false)
Optional<Object> findById(Long id);
}
interface NoFindOne extends Repository<Object, Long> {
void delete(Object entity);
}
interface EntityRepository extends CrudRepository<Entity, Long> {}
interface MethodsExplicitlyExportedRepository extends Repository<Object, Long> {
@RestResource
<S extends Object> S save(S entity);
@RestResource
void delete(Object entity);
}
class Entity {
Entity embedded;
@Reference Entity related;
List<Entity> embeddedCollection;
@Reference List<Entity> relatedCollection;
@ReadOnlyProperty @Reference Entity readOnlyReference;
}
}
| 35.985294
| 116
| 0.79921
|
1eafe73dce8328a4e02e4310da7e326c49d25684
| 1,769
|
package com.xceptance.xlt.report.providers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.xceptance.xlt.api.engine.Data;
import com.xceptance.xlt.api.engine.RequestData;
import com.xceptance.xlt.api.report.AbstractReportProvider;
/**
* Provides basic content type statistics.
*/
public class ContentTypesReportProvider extends AbstractReportProvider
{
/**
* A mapping from content types to their corresponding {@link ContentTypeReport} objects.
*/
private final Map<String, ContentTypeReport> contentTypeReports = new HashMap<String, ContentTypeReport>();
/**
* {@inheritDoc}
*/
@Override
public Object createReportFragment()
{
final ContentTypesReport report = new ContentTypesReport();
report.contentTypes = new ArrayList<ContentTypeReport>(contentTypeReports.values());
return report;
}
/**
* {@inheritDoc}
*/
@Override
public void processDataRecord(final Data stat)
{
if (stat instanceof RequestData)
{
final RequestData reqStats = (RequestData) stat;
String contentType = reqStats.getContentType();
if (StringUtils.isBlank(contentType))
{
contentType = "(none)";
}
ContentTypeReport contentTypeReport = contentTypeReports.get(contentType);
if (contentTypeReport == null)
{
contentTypeReport = new ContentTypeReport();
contentTypeReport.contentType = contentType;
contentTypeReports.put(contentType, contentTypeReport);
}
contentTypeReport.count++;
}
}
}
| 27.215385
| 111
| 0.651215
|
dcb015c5abd14be7aac8cf8ec685fd29d5b6cddf
| 7,732
|
/*
* Copyright (c) 2019-2020 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/PackConverter
*
*/
package org.geysermc.packconverter.api.converters;
import lombok.Getter;
import org.geysermc.packconverter.api.utils.ImageUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class OverlayToTranslateConverter extends AbstractConverter {
@Getter
public static final List<Object[]> defaultData = new ArrayList<>();
static {
// Cat
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/allblackcat.png", "textures/entity/cat/allblackcat_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/britishshorthair.png", "textures/entity/cat/britishshorthair_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/calico.png", "textures/entity/cat/calico_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/jellie.png", "textures/entity/cat/jellie_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/ocelot.png", "textures/entity/cat/ocelot_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/persian.png", "textures/entity/cat/persian_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/ragdoll.png", "textures/entity/cat/ragdoll_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/redtabby.png", "textures/entity/cat/redtabby_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/siamesecat.png", "textures/entity/cat/siamesecat_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/tabby.png", "textures/entity/cat/tabby_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/tuxedo.png", "textures/entity/cat/tuxedo_tame.png", false, true});
defaultData.add(new Object[] {"textures/entity/cat/graytabby_tame.png", "textures/entity/cat/white.png", "textures/entity/cat/white_tame.png", false, true});
// Enderman
defaultData.add(new Object[] {"textures/entity/enderman/enderman.png", "textures/entity/enderman/enderman_eyes.png", "textures/entity/enderman/enderman.png", true});
// Firework
defaultData.add(new Object[] {"textures/items/fireworks_charge.png", "textures/items/firework_star.png", "textures/items/fireworks_charge.png", false});
// Grass
defaultData.add(new Object[] {"textures/blocks/grass_side.png", "textures/blocks/grass_side_carried.png", "textures/blocks/grass_side.png", false, true});
// Leather
defaultData.add(new Object[] {"textures/items/leather_boots.png", "textures/items/leather_boots_overlay.png", "textures/items/leather_boots.png", true});
defaultData.add(new Object[] {"textures/items/leather_chestplate.png", "textures/items/leather_chestplate_overlay.png", "textures/items/leather_chestplate.png", true});
defaultData.add(new Object[] {"textures/items/leather_helmet.png", "textures/items/leather_helmet_overlay.png", "textures/items/leather_helmet.png", true});
defaultData.add(new Object[] {"textures/items/leather_leggings.png", "textures/items/leather_leggings_overlay.png", "textures/items/leather_leggings.png", true});
defaultData.add(new Object[] {"textures/models/armor/leather_1.png", "textures/models/armor/leather_1_overlay.png", "textures/models/armor/leather_1.png", true});
defaultData.add(new Object[] {"textures/models/armor/leather_2.png", "textures/models/armor/leather_2_overlay.png", "textures/models/armor/leather_2.png", true});
// Phantom
defaultData.add(new Object[] {"textures/entity/phantom.png", "textures/entity/phantom_eyes.png", "textures/entity/phantom.png", true});
// Spider
defaultData.add(new Object[] {"textures/entity/spider/cave_spider.png", "textures/entity/spider_eyes.png", "textures/entity/spider/cave_spider.png", true, true});
defaultData.add(new Object[] {"textures/entity/spider/spider.png", "textures/entity/spider_eyes.png", "textures/entity/spider/spider.png", true});
// Wolf
defaultData.add(new Object[] {"textures/entity/wolf/wolf_collar.png", "textures/entity/wolf/wolf_tame.png", "textures/entity/wolf/wolf_tame.png", false, true});
}
public OverlayToTranslateConverter(Path storage, Object[] data) {
super(storage, data);
}
@Override
public List<AbstractConverter> convert() {
List<AbstractConverter> delete = new ArrayList<>();
try {
String from = (String) this.data[0];
String overlay = (String) this.data[1];
String to = (String) this.data[2];
boolean reverse = (boolean) this.data[3];
boolean dontDelete = this.data.length > 4 ? (boolean) this.data[4] : false;
BufferedImage image = ImageIO.read(storage.resolve(from).toFile());
BufferedImage imageOverlay = ImageIO.read(storage.resolve(overlay).toFile());
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
Color c = new Color(image.getRGB(x, y), true);
if (reverse ? c.getAlpha() > 0 : c.getAlpha() < 255) {
Color newCol = new Color(imageOverlay.getRGB(x, y), true);
newCol = new Color(newCol.getRed(), newCol.getGreen(), newCol.getBlue(), 2);
image.setRGB(x, y, ImageUtils.colorToARGB(newCol));
}
}
}
ImageUtils.write(image, "png", storage.resolve(to).toFile());
if (!dontDelete) {
delete.add(new DeleteConverter(storage, new Object[] {overlay}));
}
System.out.println(String.format("Create translated overlay %s", to));
} catch (IOException e) { }
return delete;
}
}
| 59.476923
| 187
| 0.692059
|
6ec4b9a6c38478feb9a927c7c4f8e92fa5f45a54
| 6,075
|
package com.example.upgradedwolves.entities.goals;
import java.util.EnumSet;
import com.example.upgradedwolves.capabilities.IWolfStats;
import com.example.upgradedwolves.capabilities.WolfStatsEnum;
import com.example.upgradedwolves.capabilities.WolfStatsHandler;
import com.example.upgradedwolves.entities.WolfChaseableEntity;
import com.example.upgradedwolves.entities.plushy.MobPlushyEntity;
import com.example.upgradedwolves.itemHandler.WolfItemStackHandler;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.goal.Goal;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.animal.Wolf;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.level.pathfinder.Node;
import net.minecraft.world.level.pathfinder.Path;
import net.minecraft.util.Mth;
public class WolfFindAndPickUpItemGoal extends Goal implements IUpdateableGoal{
Wolf wolf;
WolfItemStackHandler wolfInventory;
Entity item;
int unseenMemoryTicks;
int targetUnseenTicks;
double distance;
Vec3 initialPoint;
Vec3 endPoint;
public WolfFindAndPickUpItemGoal(Wolf owner){
this.wolf = owner;
IWolfStats handler = WolfStatsHandler.getHandler(wolf);
this.wolfInventory = handler.getInventory();
this.unseenMemoryTicks = 10 * handler.getLevel(WolfStatsEnum.Intelligence);
distance = 12.0D + handler.getDetectionBonus();
this.setFlags(EnumSet.of(Goal.Flag.MOVE,Goal.Flag.LOOK));
}
@Override
public boolean canUse() {
item = null;
if(item != null || wolf.isInSittingPose() || wolf.getMainHandItem() != ItemStack.EMPTY)
return false;
for(ItemEntity itementity : wolf.level.getEntitiesOfClass(ItemEntity.class, wolf.getBoundingBox().inflate(12.0D, 0.0D, 12.0D))) {
if (wolfInventory.getAvailableSlot(itementity.getItem()) >= 0 && canEasilyReach(itementity)) {
item = itementity;
return true;
}
}
for(WolfChaseableEntity wolfToy : wolf.level.getEntitiesOfClass(WolfChaseableEntity.class, wolf.getBoundingBox().inflate(36.0D, 5.0D, 36.0D))){
if (wolfInventory.getAvailableSlot(wolfToy.getItem()) >= 0 && canEasilyReach(wolfToy)){
item = wolfToy;
initialPoint = wolf.getPosition(1);
return true;
}
}
for(MobPlushyEntity mobPlushy : wolf.level.getEntitiesOfClass(MobPlushyEntity.class, wolf.getBoundingBox().inflate(12.0D, 0.0D, 12.0D))){
if (wolfInventory.getAvailableSlot(mobPlushy.getItem()) >= 0 && canEasilyReach(mobPlushy)){
item = mobPlushy;
return true;
}
}
return false;
}
public boolean canContinueToUse() {
if(item instanceof ItemEntity){
ItemEntity item = (ItemEntity)wolf.level.getEntity(this.item.getId());
if (item == null || wolfInventory.getAvailableSlot(item.getItem()) < 0) {
return false;
} else {
return shouldChase(1,item);
}
} else if(item instanceof WolfChaseableEntity) {
WolfChaseableEntity item = (WolfChaseableEntity)wolf.level.getEntity(this.item.getId());
if (endPoint != null){
double distance = initialPoint.distanceTo(endPoint);
IWolfStats stats = WolfStatsHandler.getHandler(wolf);
stats.addXp(WolfStatsEnum.Speed, (int)(distance/2));
endPoint = null;
initialPoint = null;
return false;
}
else if (item == null || wolfInventory.getAvailableSlot(item.getItem()) < 0) {
return false;
} else {
return shouldChase(3, item);
}
} else{
MobPlushyEntity item = (MobPlushyEntity)wolf.level.getEntity(this.item.getId());
if (item == null || wolfInventory.getAvailableSlot(item.getItem()) < 0 || wolf.getMainHandItem() != ItemStack.EMPTY) {
return false;
} else {
return shouldChase(1,item);
}
}
}
private boolean shouldChase(double multiplier, Entity item){
double d0 = this.getTargetDistance();
if (wolf.distanceToSqr(item) > d0 * d0 * multiplier) {
this.item = null;
return false;
} else {
if (wolf.getSensing().hasLineOfSight(item)) {
this.targetUnseenTicks = 0;
} else if (++this.targetUnseenTicks > this.unseenMemoryTicks * multiplier) {
this.item = null;
return false;
}
return true;
}
}
protected double getTargetDistance() {
return wolf.getAttributeValue(Attributes.FOLLOW_RANGE);
}
private boolean canEasilyReach(Entity target) {
Path path = wolf.getNavigation().createPath(target, 0);
if (path == null) {
return false;
} else {
Node pathpoint = path.getEndNode();
if (pathpoint == null) {
return false;
} else {
int i = pathpoint.x - Mth.floor(target.getX());
int j = pathpoint.z - Mth.floor(target.getZ());
return (double)(i * i + j * j) <= 2.25D;
}
}
}
@Override
public void tick(){
wolf.getMoveControl().setWantedPosition(item.getX(), item.getY(), item.getZ(), 1.0);
}
@Override
public void Update(IWolfStats handler, Wolf wolf) {
distance = 12.0D + handler.getDetectionBonus();
}
public void setEndPoint(Vec3 end){
endPoint = end;
}
}
| 40.231788
| 152
| 0.597366
|
805d3e7f69163f6227cce6cd3c49383d1fece821
| 502
|
package co.fitcom.fancywebrtc;
import org.webrtc.*;
/**
* Created by Osei Fortune on 8/15/18
*/
public class FancyWebRTCEglUtils {
private static EglBase rootEglBase;
public static EglBase getRootEglBase() {
if (rootEglBase == null) {
// rootEglBase = EglBase.create();
}
return rootEglBase;
}
public static EglBase.Context getRootEglBaseContext() {
return getRootEglBase() != null ? getRootEglBase().getEglBaseContext() : null;
}
}
| 22.818182
| 86
| 0.649402
|
d8271749ee6bfed874392cb9f33fd266affacaac
| 137
|
package cn.edu.dao;
import cn.edu.vo.Role;
import tk.mybatis.mapper.common.Mapper;
public interface RoleMapper extends Mapper<Role> {
}
| 19.571429
| 50
| 0.781022
|
b78064e77b4cb16d82351b04813c85e7e620d251
| 1,819
|
package pl.umk.mat.imare.reco;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Reprezentuje zapis nutowy na dwóch pięcioliniach,
* łącznie z określoną tonacją oraz tempem.
* @author PieterEr
*/
public class StaveData implements Serializable {
/**
* Nuty znajdujące się na górnej pięciolinii.
*/
public final ArrayList<Note> top;
/**
* Nuty znajdujące się na dolnej pięciolinii.
*/
public final ArrayList<Note> bottom;
private Tonality tonality;
private double tempo;
/**
* Zwraca tempo przechowywanej muzyki.
* @return tempo w całych nutach na sekundę
*/
public double getTempo() {
return tempo;
}
/**
* Ustala tempo dla przechowywanej muzyki.
* @param tempo tempo w całych nutach na sekundę
*/
public void setTempo(double tempo) {
if (tempo > 0) this.tempo = tempo;
}
/**
* Zwraca tonację przechowywanej muzyki.
* @return obiekt określający tonację
* @see Tonality
*/
public Tonality getTonality() {
return tonality;
}
/**
* Wskazuje tonację dla przechowywanej muzyki.
* @param tonality obiekt określający tonację
* @throws IllegalArgumentException jeśli <code>tonality == null</code>
* @see Tonality
*/
public void setTonality(Tonality tonality) {
if (tonality == null) {
throw new IllegalArgumentException("tonality must not be null");
}
this.tonality = tonality;
}
/**
* Tworzy pusty obiekt klasy StaveData, z domyślnym tempem
* i tonacją C-dur.
*/
public StaveData() {
top = new ArrayList<Note>();
bottom = new ArrayList<Note>();
tempo = Sonst.DEFAULT_TEMPO;
tonality = new SharpTonality(0);
}
}
| 24.253333
| 76
| 0.62232
|
2f442a75a5918e7bd7d8526606b8d618661e714f
| 265
|
package com.fase.model.service;
public class Command {
private String command;
public Command() {
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
| 14.722222
| 44
| 0.615094
|
a5efaf5e4672f58b9caf9d781eb49ede2d3a8007
| 319
|
package com.github.fanlychie.excelutils.read;
import java.util.List;
/**
* 用于处理分页的数据。当读取到的数据达到ExcelReaderBuilder.pageSize设定的阀值时, 触发PagingHandler.handle处理数据
*/
public interface PagingHandler<T> {
/**
* 解析EXCEL文件数据完成, 回调该函数来处理数据
*
* @param items 分页中的一页数据
*/
void handle(List<T> items);
}
| 18.764706
| 83
| 0.695925
|
bd6d72a16c8b7341a2f99b86d3f158f2132da9c6
| 953
|
package com.my;
/**
* 至少是其他数字两倍的最大数
* @author shang
*/
public class DominantIndex {
public static int dominantIndex(int[] nums) {
if(nums == null){
return -1;
}
int result = 0;
//一开始默认twiceNum是0
int twiceNum = 0;
int max = nums[0];
for (int i = 0; i <nums.length ; i++) {
if(nums[i]>=max){
max = nums[i];
if(nums[i]>=twiceNum){
result = i;
}else {
result = -1;
}
twiceNum = nums[i]*2;
}else {
//存在当前值小于max,但2倍大于max
if(max <2*nums[i]){
result = -1;
twiceNum = nums[i]*2;
}
}
}
return result;
}
public static void main(String[] args) {
System.out.println(dominantIndex(new int[]{2, 0, 0, 3}));
}
}
| 23.825
| 65
| 0.398741
|
7f683e3feb4710dc3d6b8f0a9eab081e49846764
| 1,776
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package marisol.nasaapi;
import marisol.core.Core;
import marisol.deo.photolist.PhotoList;
import tools.apiclient.ApiClient;
/**
*
* @author Augusto Flores
*/
class NASAapi_Logic extends NASAapi_DAO
{
protected ApiClient mApi;
/**
* Defautl consructor.
*/
public NASAapi_Logic()
{
super();
mApi = new ApiClient();
mApi.setHost(NASA_HOST);
this.setApiKey( Core.getKeyApi() );
}
/**
* It return a list of Photos accroding the number of sols used.
* @param sol It is the number of Martian sol used.
* @return It is hte List of Photo objects.
*/
public PhotoList getPhotos_MartialSol(int sol)
{
mApi.setEndPoint( this.getPhotosByMartianSol_query( sol ) );
String res =mApi.get();
PhotoList photos = new PhotoList();
photos.parser(res);
return photos;
}
/**
* It return a list of Photos using a 100 Martian sol by default.
* @return It is hte List of Photo objects.
*/
public PhotoList getPhotos_MartialSol()
{
return getPhotos_MartialSol(1000);
}
public PhotoList getPhotos_EarthDate( String earthDate )
{
mApi.setEndPoint( this.getPhotosByEarthDate_query( earthDate ) );
String res =mApi.get();
PhotoList photos = new PhotoList();
photos.parser(res);
return photos;
}
public PhotoList getPhotos_EarthDate()
{
String date = ApiClient.getCurrentDate();
return getPhotos_EarthDate( date );
}
}
| 25.73913
| 79
| 0.626689
|
742f544569118e751c0cd599720bd69323f69518
| 802
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*/
package com.microsoft.embeddedsocial.server.model.like;
import com.microsoft.embeddedsocial.autorest.models.ContentType;
import com.microsoft.embeddedsocial.server.model.UserRequest;
public class GenericLikeRequest extends UserRequest {
protected final String contentHandle;
protected final ContentType contentType;
public GenericLikeRequest(String contentHandle, ContentType contentType) {
if (contentType == ContentType.UNKNOWN) {
throw new IllegalArgumentException("Content type cannot be unknown");
}
this.contentHandle = contentHandle;
this.contentType = contentType;
}
}
| 33.416667
| 91
| 0.754364
|
1507f724d8ab94a4868f18f886abe19ceb43b511
| 910
|
import java.util.*;
import java.io.*;
class aoc2 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new BufferedReader(new FileReader("input.txt")));
//Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int h = 0; int v = 0; int a = 0;
while (in.hasNext()) {
String dir = in.next();
int val = in.nextInt();
out.println(dir + " " + val);
if (dir.equals("down")) {
a += val;
} else if (dir.equals("up")) {
a -= val;
} else if (dir.equals("forward")) {
h += val;
v += (val * a);
}
out.println(h + " " + v + " " + a);
}
out.println(h + " " + v);
out.print(h * v);
in.close();
out.close();
}
}
| 30.333333
| 82
| 0.438462
|
84d86b49612041b34ad8590f9a8ff9ca8add33dd
| 1,570
|
package br.edu.utfpr.troubleshootingstandards.repository;
import br.edu.utfpr.troubleshootingstandards.model.Lecturer;
import org.assertj.core.api.Assertions;
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.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.*;
@Sql(value = "/load-database.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(value = "/clean-database.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource("classpath:application-test.properties")
public class LecturerRepositoryTest {
@Autowired
LecturerRepository lecturerRepository;
@Test
public void shouldGetData() {
Optional<Lecturer> optional = lecturerRepository.findById((long)123456);
assertThat(optional.isPresent()).isTrue();
Lecturer lecturer = optional.get();
assertThat(lecturer.getId()).isEqualTo(123456);
assertThat(lecturer.getName()).isEqualTo("Joe");
}
@Test
public void shouldNotGetData() {
Optional<Lecturer> optional = lecturerRepository.findById((long)123);
assertThat(optional.isPresent()).isFalse();
}
}
| 34.130435
| 90
| 0.768153
|
c695594ddd564c7fc428bcd8d3c92ad43d5c5f6b
| 540
|
package info.ericlin.kotlin.customviews;
import java.util.List;
import android.support.annotation.NonNull;
import io.reactivex.Observable;
public class RandomJava {
public static void example(@NonNull List<Weather> weathers) {
// calling static method from MainActivity
final io.reactivex.Observable<Integer> observable = MainActivityKt.runInBackground(Observable.just(1));
// calling static method from "WeatherUtilJava"
final String displayText = WeatherUtilJava.toDisplayText(weathers);
}
}
| 28.421053
| 111
| 0.75
|
9cdb77eb4863153dda9e47458917e83c9fd33114
| 2,206
|
package repository.mongo.driver;
import com.google.inject.Inject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import play.Configuration;
import utils.Konstants;
/**
* Created by mitesh on 12/11/16.
*/
public class DbStore implements IDbStore {
private Morphia morphia = null;
private Datastore morphiaStore = null;
private MongoDatabase nativeStore;
Configuration configuration;
@Inject
public DbStore(Configuration _configuration) {
this.configuration = _configuration;
morphia = new Morphia();
}
public Datastore getMaster() {
if (morphiaStore == null) {
synchronized (DbStore.class) {
if (morphiaStore == null) {
String masterDbName = configuration.getString(Konstants.KEY_MASTER_DB_NAME, Konstants.DEFAULT_MASTER_DB_NAME);
String mapMorphiaPackage = configuration.getString(Konstants.KEY_MASTER_MAP_PACKAGE);
if (mapMorphiaPackage != null) {
morphia.mapPackage(mapMorphiaPackage);
}
morphiaStore = morphia.createDatastore(getMongoClient(), masterDbName);
morphiaStore.ensureIndexes();
}
}
}
return morphiaStore;
}
public MongoDatabase getShard() {
if (nativeStore == null) {
synchronized (DbStore.class) {
if (nativeStore == null) {
String shard1DbName = configuration.getString(Konstants.KEY_SHARD1_DB_NAME, Konstants.DEFAULT_SHARD1_DB_NAME);
nativeStore = getMongoClient().getDatabase(shard1DbName);
}
}
}
return nativeStore;
}
private MongoClient getMongoClient() {
String mongoURI = configuration.getString(Konstants.KEY_MONGO_URI, Konstants.DEFAULT_MONGO_URI);
MongoClientURI mongoClientURI = new MongoClientURI(mongoURI);
MongoClient mongoClient = new MongoClient(mongoClientURI);
return mongoClient;
}
}
| 34.46875
| 130
| 0.644152
|
f6a5c7403e1a2717223ee5fc0695ed854de01952
| 2,986
|
/*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. DynamoBI 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.eigenbase.rel.rules;
import java.util.*;
import org.eigenbase.rel.*;
import org.eigenbase.relopt.*;
import org.eigenbase.reltype.*;
import org.eigenbase.rex.*;
/**
* Planner rule which converts a {@link FilterRel} to a {@link CalcRel}.
*
* <p>The rule does <em>NOT</em> fire if the child is a {@link FilterRel} or a
* {@link ProjectRel} (we assume they they will be converted using {@link
* FilterToCalcRule} or {@link ProjectToCalcRule}) or a {@link CalcRel}. This
* {@link FilterRel} will eventually be converted by {@link
* MergeFilterOntoCalcRule}.
*
* @author jhyde
* @version $Id$
* @since Mar 7, 2004
*/
public class FilterToCalcRule
extends RelOptRule
{
//~ Static fields/initializers ---------------------------------------------
public static final FilterToCalcRule instance = new FilterToCalcRule();
//~ Constructors -----------------------------------------------------------
private FilterToCalcRule()
{
super(
new RelOptRuleOperand(
FilterRel.class,
ANY));
}
//~ Methods ----------------------------------------------------------------
public void onMatch(RelOptRuleCall call)
{
final FilterRel filter = (FilterRel) call.rels[0];
final RelNode rel = filter.getChild();
// Create a program containing a filter.
final RexBuilder rexBuilder = filter.getCluster().getRexBuilder();
final RelDataType inputRowType = rel.getRowType();
final RexProgramBuilder programBuilder =
new RexProgramBuilder(inputRowType, rexBuilder);
programBuilder.addIdentity();
if (filter.getCondition() != null) {
programBuilder.addCondition(filter.getCondition());
}
final RexProgram program = programBuilder.getProgram();
final CalcRel calc =
new CalcRel(
filter.getCluster(),
RelOptUtil.clone(filter.getTraits()),
rel,
inputRowType,
program,
Collections.<RelCollation>emptyList());
call.transformTo(calc);
}
}
// End FilterToCalcRule.java
| 33.177778
| 80
| 0.628935
|
89e9f9a487edcd4d5e32529af3e7a9d771a95541
| 2,294
|
/*
* Copyright (c) 2014 Jeffrey Bian
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.taibaisoft.chip8.chipmunk.commands;
import com.taibaisoft.chip8.chipmunk.Board;
import com.taibaisoft.chip8.chipmunk.ConfigAndPrefs;
import com.taibaisoft.framework.UICommand;
/*
*
*
*/
public class CSpeedSelection extends UICommand<Board> {
@Override
public String getText() {
return "100Hz;200Hz;300Hz;400Hz;500Hz;600Hz;" +
"700Hz;800Hz;900Hz;1000Hz;" +
"2,000Hz;5,000Hz;10,000Hz;";
}
@Override
public String getID() {
return "100;200;300;400;500;600;" +
"700;800;900;1000;" +
"2000;5000;10000;";
}
@Override
public String getDescription() {
return "100Hz;200Hz;300Hz;400Hz;500Hz;600Hz;" +
"700Hz;800Hz;900Hz;1000Hz;" +
"2,000Hz;5,000Hz;10,000Hz;";
}
public int getDefaultRadioButton() {
return ConfigAndPrefs.getInstance().getSpeedSelection();
}
@Override
public void action(Board obj) {
String sel = getRadioSelectionActionCommand();
int index = getRadioSelectionIndex();
int freq = Integer.parseInt(sel);
ConfigAndPrefs cap = ConfigAndPrefs.getInstance();
cap.setDefaultSpeed(freq);
cap.setDefaultSpeedSelection(index);
obj.getCPU().setCpuFrequency(freq);
}
}
| 31
| 73
| 0.730166
|
cde837c4bf2cfde32925f074a78bf3859a575ba0
| 938
|
/**
*
*/
package io.alanda.base.mapper;
import org.dozer.CustomConverter;
import org.dozer.DozerConverter;
import io.alanda.base.dto.SimplePhaseDto;
import io.alanda.base.entity.PmcProjectPhase;
/**
* @author jlo
*/
public class PhaseMapper extends DozerConverter<PmcProjectPhase, SimplePhaseDto> implements CustomConverter {
/**
*
*/
public PhaseMapper() {
super(PmcProjectPhase.class, SimplePhaseDto.class);
}
@Override
public SimplePhaseDto convertTo(PmcProjectPhase source, SimplePhaseDto destination) {
if (source == null)
return null;
return new SimplePhaseDto(
source.getPmcProjectPhaseDefinition().getIdName(),
source.getEnabled(),
source.getActive(),
source.getStartDate(),
source.getEndDate(),
source.getFrozen());
}
@Override
public PmcProjectPhase convertFrom(SimplePhaseDto source, PmcProjectPhase destination) {
return null;
}
}
| 21.813953
| 109
| 0.714286
|
d8ffe3ca0fa7581462114868981fa173483df315
| 13,324
|
package wannabit.io.cosmostaion.task.SimpleBroadTxTask;
import static wannabit.io.cosmostaion.base.BaseConstant.BINANCE_MAIN_BNB_DEPUTY;
import static wannabit.io.cosmostaion.base.BaseConstant.BINANCE_MAIN_BTCB_DEPUTY;
import static wannabit.io.cosmostaion.base.BaseConstant.BINANCE_MAIN_BUSD_DEPUTY;
import static wannabit.io.cosmostaion.base.BaseConstant.BINANCE_MAIN_XRPB_DEPUTY;
import static wannabit.io.cosmostaion.base.BaseConstant.ERROR_CODE_BROADCAST;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MAIN_BNB_DEPUTY;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MAIN_BTCB_DEPUTY;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MAIN_BUSD_DEPUTY;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MAIN_XRPB_DEPUTY;
import static wannabit.io.cosmostaion.base.BaseConstant.TASK_GEN_TX_HTLC_CREATE;
import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_HTLC_BINANCE_BNB;
import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_HTLC_BINANCE_BTCB;
import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_HTLC_BINANCE_BUSD;
import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_HTLC_BINANCE_XRPB;
import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_HTLC_KAVA_BNB;
import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_HTLC_KAVA_BTCB;
import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_HTLC_KAVA_BUSD;
import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_HTLC_KAVA_XRPB;
import com.binance.dex.api.client.BinanceDexApiClientFactory;
import com.binance.dex.api.client.BinanceDexApiRestClient;
import com.binance.dex.api.client.BinanceDexEnvironment;
import com.binance.dex.api.client.Wallet;
import com.binance.dex.api.client.domain.TransactionMetadata;
import com.binance.dex.api.client.domain.broadcast.HtltReq;
import com.binance.dex.api.client.domain.broadcast.TransactionOption;
import com.fulldive.wallet.interactors.secret.MnemonicUtils;
import com.fulldive.wallet.models.BaseChain;
import com.fulldive.wallet.models.WalletBalance;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.RandomUtils;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.DeterministicKey;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import cosmos.auth.v1beta1.QueryGrpc;
import cosmos.auth.v1beta1.QueryOuterClass;
import cosmos.tx.v1beta1.ServiceGrpc;
import cosmos.tx.v1beta1.ServiceOuterClass;
import retrofit2.Response;
import wannabit.io.cosmostaion.BuildConfig;
import wannabit.io.cosmostaion.R;
import wannabit.io.cosmostaion.base.BaseApplication;
import wannabit.io.cosmostaion.cosmos.MsgGenerator;
import wannabit.io.cosmostaion.cosmos.Signer;
import wannabit.io.cosmostaion.crypto.CryptoHelper;
import wannabit.io.cosmostaion.crypto.Sha256;
import wannabit.io.cosmostaion.dao.Account;
import wannabit.io.cosmostaion.model.type.Coin;
import wannabit.io.cosmostaion.model.type.Fee;
import wannabit.io.cosmostaion.network.ApiClient;
import wannabit.io.cosmostaion.network.ChannelBuilder;
import wannabit.io.cosmostaion.network.res.ResBnbAccountInfo;
import wannabit.io.cosmostaion.task.CommonTask;
import wannabit.io.cosmostaion.task.TaskListener;
import wannabit.io.cosmostaion.task.TaskResult;
import wannabit.io.cosmostaion.utils.WKey;
import wannabit.io.cosmostaion.utils.WLog;
import wannabit.io.cosmostaion.utils.WUtil;
public class HtlcCreateTask extends CommonTask {
private Account mSendAccount;
private final Account mReceiveAccount;
private final BaseChain mSendChain;
private final BaseChain mReceiveChain;
private final ArrayList<Coin> mToSendCoins;
private final Fee mSendFee;
private byte[] mRandomNumberHash;
private String mRandomNumber;
private String mExpectedSwapId;
private ECKey ecKey;
public HtlcCreateTask(BaseApplication app, TaskListener listener, Account sender, Account recipient, BaseChain sendChain, BaseChain receiveChain, ArrayList<Coin> toSendCoins, Fee sendFee) {
super(app, listener);
this.mSendAccount = sender;
this.mReceiveAccount = recipient;
this.mSendChain = sendChain;
this.mReceiveChain = receiveChain;
this.mToSendCoins = toSendCoins;
this.mSendFee = sendFee;
this.result.taskType = TASK_GEN_TX_HTLC_CREATE;
}
@Override
protected TaskResult doInBackground(String... strings) {
try {
if (mSendChain.equals(BaseChain.BNB_MAIN.INSTANCE)) {
Response<ResBnbAccountInfo> response = ApiClient.getBnbChain(context).getAccountInfo(mSendAccount.address).execute();
if (!response.isSuccessful()) {
result.errorCode = ERROR_CODE_BROADCAST;
return result;
}
final Account account = WUtil.getAccountFromBnbLcd(mReceiveAccount.id, response.body());
accountsInteractor.updateAccount(
mReceiveAccount.id,
account.address,
account.sequenceNumber,
account.accountNumber
);
final List<WalletBalance> balances = WUtil.getBalancesFromBnbLcd(mReceiveAccount.id, response.body());
final Throwable error = balancesInteractor.updateBalances(mReceiveAccount.id, balances).blockingGet();
if (error != null) {
error.printStackTrace();
}
mSendAccount = accountsInteractor.getAccount(mSendAccount.id).blockingGet();
if (mSendAccount.fromMnemonic) {
String entropy = CryptoHelper.decryptData(context.getString(R.string.key_mnemonic) + mSendAccount.uuid, mSendAccount.resource, mSendAccount.spec);
DeterministicKey deterministicKey = WKey.getKeyWithPathfromEntropy(mSendAccount, entropy);
ecKey = ECKey.fromPrivate(new BigInteger(deterministicKey.getPrivateKeyAsHex(), 16));
} else {
String privateKey = CryptoHelper.decryptData(context.getString(R.string.key_private) + mSendAccount.uuid, mSendAccount.resource, mSendAccount.spec);
ecKey = ECKey.fromPrivate(new BigInteger(privateKey, 16));
}
Wallet wallet = new Wallet(ecKey.getPrivateKeyAsHex(), BinanceDexEnvironment.PROD);
wallet.setAccountNumber(mSendAccount.accountNumber);
wallet.setSequence(Long.valueOf(mSendAccount.sequenceNumber));
long timestamp = Calendar.getInstance().getTimeInMillis() / 1000;
byte[] randomNumber = RandomUtils.nextBytes(32);
byte[] originData = ArrayUtils.addAll(randomNumber, WUtil.long2Bytes(timestamp));
HtltReq htltReq = MsgGenerator.getBnbHtlcCreateMsg(mSendChain, mReceiveChain, mSendAccount, mReceiveAccount, mToSendCoins, timestamp, originData);
mRandomNumber = MnemonicUtils.INSTANCE.byteArrayToHexString(randomNumber).toUpperCase();
mRandomNumberHash = htltReq.getRandomNumberHash();
if (mToSendCoins.get(0).denom.equals(TOKEN_HTLC_BINANCE_BNB)) {
mExpectedSwapId = WKey.getSwapId(mRandomNumberHash, KAVA_MAIN_BNB_DEPUTY, mSendAccount.address).toUpperCase();
} else if (mToSendCoins.get(0).denom.equals(TOKEN_HTLC_BINANCE_BTCB)) {
mExpectedSwapId = WKey.getSwapId(mRandomNumberHash, KAVA_MAIN_BTCB_DEPUTY, mSendAccount.address).toUpperCase();
} else if (mToSendCoins.get(0).denom.equals(TOKEN_HTLC_BINANCE_XRPB)) {
mExpectedSwapId = WKey.getSwapId(mRandomNumberHash, KAVA_MAIN_XRPB_DEPUTY, mSendAccount.address).toUpperCase();
} else if (mToSendCoins.get(0).denom.equals(TOKEN_HTLC_BINANCE_BUSD)) {
mExpectedSwapId = WKey.getSwapId(mRandomNumberHash, KAVA_MAIN_BUSD_DEPUTY, mSendAccount.address).toUpperCase();
}
WLog.w("BNB_MAIN mRandomNumberHash " + mRandomNumberHash);
WLog.w("BNB_MAIN mRandomNumber " + mRandomNumber);
WLog.w("BNB_MAIN Send mExpectedSwapId " + mExpectedSwapId);
TransactionOption options = new TransactionOption(context.getString(R.string.str_create_swap_memo_c), 82, null);
BinanceDexApiRestClient client = BinanceDexApiClientFactory.newInstance().newRestClient(BinanceDexEnvironment.PROD.getBaseUrl());
List<TransactionMetadata> resp = client.htlt(htltReq, wallet, options, true);
if (resp.get(0).isOk()) {
if (BuildConfig.DEBUG) WLog.w("Send suceess txhash " + resp.get(0).getHash());
result.resultData = resp.get(0).getHash();
result.resultData2 = mExpectedSwapId;
result.resultData3 = mRandomNumber;
result.isSuccess = true;
} else {
if (BuildConfig.DEBUG)
WLog.w("Send error " + resp.get(0).getCode() + " " + resp.get(0).getLog());
result.errorCode = resp.get(0).getCode();
result.errorMsg = resp.get(0).getLog();
result.isSuccess = false;
}
} else if (mSendChain.equals(BaseChain.KAVA_MAIN.INSTANCE)) {
if (mSendAccount.fromMnemonic) {
String entropy = CryptoHelper.decryptData(context.getString(R.string.key_mnemonic) + mSendAccount.uuid, mSendAccount.resource, mSendAccount.spec);
DeterministicKey deterministicKey = WKey.getKeyWithPathfromEntropy(mSendAccount, entropy);
ecKey = ECKey.fromPrivate(new BigInteger(deterministicKey.getPrivateKeyAsHex(), 16));
} else {
String privateKey = CryptoHelper.decryptData(context.getString(R.string.key_private) + mSendAccount.uuid, mSendAccount.resource, mSendAccount.spec);
ecKey = ECKey.fromPrivate(new BigInteger(privateKey, 16));
}
QueryGrpc.QueryBlockingStub authStub = QueryGrpc.newBlockingStub(ChannelBuilder.getChain(mSendChain));
QueryOuterClass.QueryAccountRequest request = QueryOuterClass.QueryAccountRequest.newBuilder().setAddress(mSendAccount.address).build();
QueryOuterClass.QueryAccountResponse mAuthResponse = authStub.account(request);
long timestamp = Calendar.getInstance().getTimeInMillis() / 1000;
byte[] randomNumber = RandomUtils.nextBytes(32);
byte[] originData = ArrayUtils.addAll(randomNumber, WUtil.long2Bytes(timestamp));
mRandomNumber = MnemonicUtils.INSTANCE.byteArrayToHexString(randomNumber).toUpperCase();
mRandomNumberHash = MnemonicUtils.INSTANCE.hexStringToByteArray(MnemonicUtils.INSTANCE.byteArrayToHexString(Sha256.getSha256Digest().digest(originData)).toUpperCase());
if (mToSendCoins.get(0).denom.equals(TOKEN_HTLC_KAVA_BNB)) {
mExpectedSwapId = WKey.getSwapId(mRandomNumberHash, BINANCE_MAIN_BNB_DEPUTY, mSendAccount.address).toUpperCase();
} else if (mToSendCoins.get(0).denom.equals(TOKEN_HTLC_KAVA_BTCB)) {
mExpectedSwapId = WKey.getSwapId(mRandomNumberHash, BINANCE_MAIN_BTCB_DEPUTY, mSendAccount.address).toUpperCase();
} else if (mToSendCoins.get(0).denom.equals(TOKEN_HTLC_KAVA_XRPB)) {
mExpectedSwapId = WKey.getSwapId(mRandomNumberHash, BINANCE_MAIN_XRPB_DEPUTY, mSendAccount.address).toUpperCase();
} else if (mToSendCoins.get(0).denom.equals(TOKEN_HTLC_KAVA_BUSD)) {
mExpectedSwapId = WKey.getSwapId(mRandomNumberHash, BINANCE_MAIN_BUSD_DEPUTY, mSendAccount.address).toUpperCase();
}
//broadCast
ServiceGrpc.ServiceBlockingStub txService = ServiceGrpc.newBlockingStub(ChannelBuilder.getChain(mSendChain));
ServiceOuterClass.BroadcastTxRequest broadcastTxRequest = Signer.getGrpcKavaCreateHTLCSwapReq(mAuthResponse, mSendAccount.address, mReceiveAccount.address, mToSendCoins, timestamp, MnemonicUtils.INSTANCE.byteArrayToHexString(Sha256.getSha256Digest().digest(originData)).toUpperCase(), mSendFee, context.getString(R.string.str_create_swap_memo_c), ecKey, context.getBaseDao().getChainIdGrpc());
ServiceOuterClass.BroadcastTxResponse response = txService.broadcastTx(broadcastTxRequest);
result.resultData = response.getTxResponse().getTxhash();
if (response.getTxResponse().getCode() > 0) {
result.errorCode = response.getTxResponse().getCode();
result.errorMsg = response.getTxResponse().getRawLog();
result.isSuccess = false;
} else {
result.isSuccess = true;
result.resultData2 = mExpectedSwapId;
result.resultData3 = mRandomNumber;
}
}
} catch (Exception e) {
if (BuildConfig.DEBUG) e.printStackTrace();
}
return result;
}
}
| 58.183406
| 409
| 0.704668
|
8d573289372be172d8cec1fb2382f3712e8c5fca
| 2,964
|
package ru.job4j.pseudo;
import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.StringJoiner;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* В Java есть класс, который отвечает за управления выводом информации.
* По умолчанию весь вывод настроен на консоль.
* Мы можем заменить класс для вывода в консоль и заменить ее выводом в память.
*
* PrintStream stdout = System.out;
* получаем ссылку на стандартный вывод в консоль.
*
* Для загрузки нового объекта для управлении выводом нам нужно
* использовать метод System.setOut
*
* Этот метод принимает объект типа PrintStream.
* У этого класса есть конструктор, который принимает объект типа OutputStream.
* Этот поток нам и надо заменить на свой.
*
* У класса OutputStream есть реализации ByteArrayOutputStream.
* Этот массив байт, который мы можем проверить в нашем тесте.
*
* ByteArrayOutputStream out = new ByteArrayOutputStream();
* Создаем буфур для хранения вывода.
*
* System.setOut(new PrintStream(out));
* Заменяем стандартный вывод на вывод в пямять для тестирования.
*
* new Paint().draw(new Square());
* выполняем действия пишушиее в консоль.
*
* System.setOut(stdout);
* возвращаем обратно стандартный вывод в консоль.
*/
public class PaintTest {
/**
* Как мы видим наш код имеет повторяющиеся куски кода.
* Эти куски кода устанавливают начальное значения и убирают их в конце.
* выносим из тестов в поля
*/
private final PrintStream stdout = System.out;
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
/**
* Эти куски кода устанавливают начальное значения и убирают их в конце.
* Давайте мы вынесем эти куски в отдельные методы.
* System.out.println("execute before method"); - в тестировании
* будет прописываться использование этой аннотации
*/
@Before
public void loadOutput() {
System.out.println("execute before method");
System.setOut(new PrintStream(this.out));
}
@After
public void backOutput() {
System.setOut(this.stdout);
System.out.println("execute after method");
}
@Test
public void drawSquare() {
new Paint().draw(new Square());
assertThat(this.out.toString(), is(new StringJoiner(System.lineSeparator(), "", System.lineSeparator())
.add("++++")
.add("++++")
.add("++++")
.add("++++")
.toString()
));
}
@Test
public void drawTriangle() {
new Paint().draw(new Triangle());
assertThat(this.out.toString(), is(new StringJoiner(System.lineSeparator(), "", System.lineSeparator())
.add("+")
.add("++")
.add("+++")
.add("++++")
.toString()
));
}
}
| 32.217391
| 111
| 0.653509
|
ec2077d8d36aaba41e78b6c5ae865b39ba3afdf3
| 60,107
|
/*
* Copyright (c) 2009, 2016, 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.
*
* 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 org.graalvm.compiler.core.amd64;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64BinaryArithmetic.ADD;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64BinaryArithmetic.AND;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64BinaryArithmetic.CMP;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64BinaryArithmetic.OR;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64BinaryArithmetic.SUB;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64BinaryArithmetic.XOR;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64MOp.NEG;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64MOp.NOT;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.BSF;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.BSR;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.LZCNT;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.MOV;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.MOVSD;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.MOVSS;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.MOVSX;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.MOVSXB;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.MOVSXD;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.MOVZX;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.MOVZXB;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.POPCNT;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.TEST;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.TESTB;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp.TZCNT;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64Shift.ROL;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64Shift.ROR;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64Shift.SAR;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64Shift.SHL;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64Shift.SHR;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.DWORD;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.PD;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.PS;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.QWORD;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.SD;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.SS;
import static org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.WORD;
import static org.graalvm.compiler.core.common.GraalOptions.GeneratePIC;
import static org.graalvm.compiler.lir.LIRValueUtil.asConstantValue;
import static org.graalvm.compiler.lir.LIRValueUtil.asJavaConstant;
import static org.graalvm.compiler.lir.LIRValueUtil.isConstantValue;
import static org.graalvm.compiler.lir.LIRValueUtil.isJavaConstant;
import static org.graalvm.compiler.lir.amd64.AMD64Arithmetic.DREM;
import static org.graalvm.compiler.lir.amd64.AMD64Arithmetic.FREM;
import static org.graalvm.compiler.lir.amd64.AMD64MathIntrinsicBinaryOp.BinaryIntrinsicOpcode.POW;
import static org.graalvm.compiler.lir.amd64.AMD64MathIntrinsicUnaryOp.UnaryIntrinsicOpcode.COS;
import static org.graalvm.compiler.lir.amd64.AMD64MathIntrinsicUnaryOp.UnaryIntrinsicOpcode.EXP;
import static org.graalvm.compiler.lir.amd64.AMD64MathIntrinsicUnaryOp.UnaryIntrinsicOpcode.LOG;
import static org.graalvm.compiler.lir.amd64.AMD64MathIntrinsicUnaryOp.UnaryIntrinsicOpcode.LOG10;
import static org.graalvm.compiler.lir.amd64.AMD64MathIntrinsicUnaryOp.UnaryIntrinsicOpcode.SIN;
import static org.graalvm.compiler.lir.amd64.AMD64MathIntrinsicUnaryOp.UnaryIntrinsicOpcode.TAN;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64BinaryArithmetic;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64MIOp;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64MOp;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64MROp;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMIOp;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RMOp;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64RRMOp;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.AMD64Shift;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.AVXOp;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize;
import org.graalvm.compiler.asm.amd64.AMD64Assembler.SSEOp;
import org.graalvm.compiler.core.common.LIRKind;
import org.graalvm.compiler.core.common.NumUtil;
import org.graalvm.compiler.core.common.calc.FloatConvert;
import org.graalvm.compiler.debug.GraalError;
import org.graalvm.compiler.lir.ConstantValue;
import org.graalvm.compiler.lir.LIRFrameState;
import org.graalvm.compiler.lir.LIRValueUtil;
import org.graalvm.compiler.lir.Variable;
import org.graalvm.compiler.lir.amd64.AMD64AddressValue;
import org.graalvm.compiler.lir.amd64.AMD64Arithmetic.FPDivRemOp;
import org.graalvm.compiler.lir.amd64.AMD64ArithmeticLIRGeneratorTool;
import org.graalvm.compiler.lir.amd64.AMD64Binary;
import org.graalvm.compiler.lir.amd64.AMD64BinaryConsumer;
import org.graalvm.compiler.lir.amd64.AMD64ClearRegisterOp;
import org.graalvm.compiler.lir.amd64.AMD64MathIntrinsicBinaryOp;
import org.graalvm.compiler.lir.amd64.AMD64MathIntrinsicUnaryOp;
import org.graalvm.compiler.lir.amd64.AMD64Move;
import org.graalvm.compiler.lir.amd64.AMD64MulDivOp;
import org.graalvm.compiler.lir.amd64.AMD64ShiftOp;
import org.graalvm.compiler.lir.amd64.AMD64SignExtendOp;
import org.graalvm.compiler.lir.amd64.AMD64Unary;
import org.graalvm.compiler.lir.gen.ArithmeticLIRGenerator;
import org.graalvm.compiler.lir.gen.LIRGenerator;
import jdk.vm.ci.amd64.AMD64;
import jdk.vm.ci.amd64.AMD64.CPUFeature;
import jdk.vm.ci.amd64.AMD64Kind;
import jdk.vm.ci.code.CodeUtil;
import jdk.vm.ci.code.Register;
import jdk.vm.ci.code.RegisterValue;
import jdk.vm.ci.code.TargetDescription;
import jdk.vm.ci.meta.AllocatableValue;
import jdk.vm.ci.meta.Constant;
import jdk.vm.ci.meta.JavaConstant;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.PlatformKind;
import jdk.vm.ci.meta.VMConstant;
import jdk.vm.ci.meta.Value;
import jdk.vm.ci.meta.ValueKind;
/**
* This class implements the AMD64 specific portion of the LIR generator.
*/
public class AMD64ArithmeticLIRGenerator extends ArithmeticLIRGenerator implements AMD64ArithmeticLIRGeneratorTool {
private static final RegisterValue RCX_I = AMD64.rcx.asValue(LIRKind.value(AMD64Kind.DWORD));
public AMD64ArithmeticLIRGenerator(Maths maths) {
this.maths = maths == null ? new Maths() {
} : maths;
}
private final Maths maths;
/**
* Interface for emitting LIR for selected {@link Math} routines. A {@code null} return value
* for any method in this interface means the caller must emit the LIR itself.
*/
public interface Maths {
@SuppressWarnings("unused")
default Variable emitLog(LIRGenerator gen, Value input, boolean base10) {
return null;
}
@SuppressWarnings("unused")
default Variable emitCos(LIRGenerator gen, Value input) {
return null;
}
@SuppressWarnings("unused")
default Variable emitSin(LIRGenerator gen, Value input) {
return null;
}
@SuppressWarnings("unused")
default Variable emitTan(LIRGenerator gen, Value input) {
return null;
}
}
@Override
public Variable emitNegate(Value inputVal) {
AllocatableValue input = getLIRGen().asAllocatable(inputVal);
Variable result = getLIRGen().newVariable(LIRKind.combine(input));
TargetDescription target = getLIRGen().target();
boolean isAvx = ((AMD64) target.arch).getFeatures().contains(CPUFeature.AVX);
switch ((AMD64Kind) input.getPlatformKind()) {
case DWORD:
getLIRGen().append(new AMD64Unary.MOp(NEG, DWORD, result, input));
break;
case QWORD:
getLIRGen().append(new AMD64Unary.MOp(NEG, QWORD, result, input));
break;
case SINGLE:
if (isAvx) {
getLIRGen().append(new AMD64Binary.DataThreeOp(AVXOp.XOR, PS, result, input, JavaConstant.forFloat(Float.intBitsToFloat(0x80000000)), 16));
} else {
getLIRGen().append(new AMD64Binary.DataTwoOp(SSEOp.XOR, PS, result, input, JavaConstant.forFloat(Float.intBitsToFloat(0x80000000)), 16));
}
break;
case DOUBLE:
if (isAvx) {
getLIRGen().append(new AMD64Binary.DataThreeOp(AVXOp.XOR, PD, result, input, JavaConstant.forDouble(Double.longBitsToDouble(0x8000000000000000L)), 16));
} else {
getLIRGen().append(new AMD64Binary.DataTwoOp(SSEOp.XOR, PD, result, input, JavaConstant.forDouble(Double.longBitsToDouble(0x8000000000000000L)), 16));
}
break;
default:
throw GraalError.shouldNotReachHere(input.getPlatformKind().toString());
}
return result;
}
@Override
public Variable emitNot(Value inputVal) {
AllocatableValue input = getLIRGen().asAllocatable(inputVal);
Variable result = getLIRGen().newVariable(LIRKind.combine(input));
switch ((AMD64Kind) input.getPlatformKind()) {
case DWORD:
getLIRGen().append(new AMD64Unary.MOp(NOT, DWORD, result, input));
break;
case QWORD:
getLIRGen().append(new AMD64Unary.MOp(NOT, QWORD, result, input));
break;
default:
throw GraalError.shouldNotReachHere();
}
return result;
}
private Variable emitBinary(LIRKind resultKind, AMD64BinaryArithmetic op, OperandSize size, boolean commutative, Value a, Value b, boolean setFlags) {
if (isJavaConstant(b)) {
return emitBinaryConst(resultKind, op, size, commutative, getLIRGen().asAllocatable(a), asConstantValue(b), setFlags);
} else if (commutative && isJavaConstant(a)) {
return emitBinaryConst(resultKind, op, size, commutative, getLIRGen().asAllocatable(b), asConstantValue(a), setFlags);
} else {
return emitBinaryVar(resultKind, op.getRMOpcode(size), size, commutative, getLIRGen().asAllocatable(a), getLIRGen().asAllocatable(b));
}
}
private Variable emitBinary(LIRKind resultKind, AMD64RMOp op, OperandSize size, boolean commutative, Value a, Value b) {
if (isJavaConstant(b)) {
return emitBinaryConst(resultKind, op, size, getLIRGen().asAllocatable(a), asJavaConstant(b));
} else if (commutative && isJavaConstant(a)) {
return emitBinaryConst(resultKind, op, size, getLIRGen().asAllocatable(b), asJavaConstant(a));
} else {
return emitBinaryVar(resultKind, op, size, commutative, getLIRGen().asAllocatable(a), getLIRGen().asAllocatable(b));
}
}
private Variable emitBinary(LIRKind resultKind, AMD64RRMOp op, OperandSize size, boolean commutative, Value a, Value b) {
if (isJavaConstant(b)) {
return emitBinaryConst(resultKind, op, size, getLIRGen().asAllocatable(a), asJavaConstant(b));
} else if (commutative && isJavaConstant(a)) {
return emitBinaryConst(resultKind, op, size, getLIRGen().asAllocatable(b), asJavaConstant(a));
} else {
return emitBinaryVar(resultKind, op, size, commutative, getLIRGen().asAllocatable(a), getLIRGen().asAllocatable(b));
}
}
private Variable emitBinaryConst(LIRKind resultKind, AMD64BinaryArithmetic op, OperandSize size, boolean commutative, AllocatableValue a, ConstantValue b, boolean setFlags) {
long value = b.getJavaConstant().asLong();
if (NumUtil.isInt(value)) {
Variable result = getLIRGen().newVariable(resultKind);
int constant = (int) value;
if (!setFlags) {
AMD64MOp mop = getMOp(op, constant);
if (mop != null) {
getLIRGen().append(new AMD64Unary.MOp(mop, size, result, a));
return result;
}
}
getLIRGen().append(new AMD64Binary.ConstOp(op, size, result, a, constant));
return result;
} else {
return emitBinaryVar(resultKind, op.getRMOpcode(size), size, commutative, a, getLIRGen().asAllocatable(b));
}
}
private static AMD64MOp getMOp(AMD64BinaryArithmetic op, int constant) {
if (constant == 1) {
if (op.equals(AMD64BinaryArithmetic.ADD)) {
return AMD64MOp.INC;
}
if (op.equals(AMD64BinaryArithmetic.SUB)) {
return AMD64MOp.DEC;
}
} else if (constant == -1) {
if (op.equals(AMD64BinaryArithmetic.ADD)) {
return AMD64MOp.DEC;
}
if (op.equals(AMD64BinaryArithmetic.SUB)) {
return AMD64MOp.INC;
}
}
return null;
}
private Variable emitBinaryConst(LIRKind resultKind, AMD64RMOp op, OperandSize size, AllocatableValue a, JavaConstant b) {
Variable result = getLIRGen().newVariable(resultKind);
getLIRGen().append(new AMD64Binary.DataTwoOp(op, size, result, a, b));
return result;
}
private Variable emitBinaryConst(LIRKind resultKind, AMD64RRMOp op, OperandSize size, AllocatableValue a, JavaConstant b) {
Variable result = getLIRGen().newVariable(resultKind);
getLIRGen().append(new AMD64Binary.DataThreeOp(op, size, result, a, b));
return result;
}
private Variable emitBinaryVar(LIRKind resultKind, AMD64RMOp op, OperandSize size, boolean commutative, AllocatableValue a, AllocatableValue b) {
Variable result = getLIRGen().newVariable(resultKind);
if (commutative) {
getLIRGen().append(new AMD64Binary.CommutativeTwoOp(op, size, result, a, b));
} else {
getLIRGen().append(new AMD64Binary.TwoOp(op, size, result, a, b));
}
return result;
}
private Variable emitBinaryVar(LIRKind resultKind, AMD64RRMOp op, OperandSize size, boolean commutative, AllocatableValue a, AllocatableValue b) {
Variable result = getLIRGen().newVariable(resultKind);
if (commutative) {
getLIRGen().append(new AMD64Binary.CommutativeThreeOp(op, size, result, a, b));
} else {
getLIRGen().append(new AMD64Binary.ThreeOp(op, size, result, a, b));
}
return result;
}
@Override
protected boolean isNumericInteger(PlatformKind kind) {
return ((AMD64Kind) kind).isInteger();
}
private Variable emitBaseOffsetLea(LIRKind resultKind, Value base, int offset, OperandSize size) {
Variable result = getLIRGen().newVariable(resultKind);
AMD64AddressValue address = new AMD64AddressValue(resultKind, getLIRGen().asAllocatable(base), offset);
getLIRGen().append(new AMD64Move.LeaOp(result, address, size));
return result;
}
@Override
public Variable emitAdd(LIRKind resultKind, Value a, Value b, boolean setFlags) {
TargetDescription target = getLIRGen().target();
boolean isAvx = ((AMD64) target.arch).getFeatures().contains(CPUFeature.AVX);
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
if (isJavaConstant(b) && !setFlags) {
long displacement = asJavaConstant(b).asLong();
if (NumUtil.isInt(displacement) && displacement != 1 && displacement != -1) {
return emitBaseOffsetLea(resultKind, a, (int) displacement, OperandSize.DWORD);
}
}
return emitBinary(resultKind, ADD, DWORD, true, a, b, setFlags);
case QWORD:
if (isJavaConstant(b) && !setFlags) {
long displacement = asJavaConstant(b).asLong();
if (NumUtil.isInt(displacement) && displacement != 1 && displacement != -1) {
return emitBaseOffsetLea(resultKind, a, (int) displacement, OperandSize.QWORD);
}
}
return emitBinary(resultKind, ADD, QWORD, true, a, b, setFlags);
case SINGLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.ADD, SS, true, a, b);
} else {
return emitBinary(resultKind, SSEOp.ADD, SS, true, a, b);
}
case DOUBLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.ADD, SD, true, a, b);
} else {
return emitBinary(resultKind, SSEOp.ADD, SD, true, a, b);
}
default:
throw GraalError.shouldNotReachHere();
}
}
@Override
public Variable emitSub(LIRKind resultKind, Value a, Value b, boolean setFlags) {
TargetDescription target = getLIRGen().target();
boolean isAvx = ((AMD64) target.arch).getFeatures().contains(CPUFeature.AVX);
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitBinary(resultKind, SUB, DWORD, false, a, b, setFlags);
case QWORD:
return emitBinary(resultKind, SUB, QWORD, false, a, b, setFlags);
case SINGLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.SUB, SS, false, a, b);
} else {
return emitBinary(resultKind, SSEOp.SUB, SS, false, a, b);
}
case DOUBLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.SUB, SD, false, a, b);
} else {
return emitBinary(resultKind, SSEOp.SUB, SD, false, a, b);
}
default:
throw GraalError.shouldNotReachHere();
}
}
private Variable emitIMULConst(OperandSize size, AllocatableValue a, ConstantValue b) {
long value = b.getJavaConstant().asLong();
if (NumUtil.isInt(value)) {
int imm = (int) value;
AMD64RMIOp op;
if (NumUtil.isByte(imm)) {
op = AMD64RMIOp.IMUL_SX;
} else {
op = AMD64RMIOp.IMUL;
}
Variable ret = getLIRGen().newVariable(LIRKind.combine(a, b));
getLIRGen().append(new AMD64Binary.RMIOp(op, size, ret, a, imm));
return ret;
} else {
return emitBinaryVar(LIRKind.combine(a, b), AMD64RMOp.IMUL, size, true, a, getLIRGen().asAllocatable(b));
}
}
private Variable emitIMUL(OperandSize size, Value a, Value b) {
if (isJavaConstant(b)) {
return emitIMULConst(size, getLIRGen().asAllocatable(a), asConstantValue(b));
} else if (isJavaConstant(a)) {
return emitIMULConst(size, getLIRGen().asAllocatable(b), asConstantValue(a));
} else {
return emitBinaryVar(LIRKind.combine(a, b), AMD64RMOp.IMUL, size, true, getLIRGen().asAllocatable(a), getLIRGen().asAllocatable(b));
}
}
@Override
public Variable emitMul(Value a, Value b, boolean setFlags) {
LIRKind resultKind = LIRKind.combine(a, b);
TargetDescription target = getLIRGen().target();
boolean isAvx = ((AMD64) target.arch).getFeatures().contains(CPUFeature.AVX);
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitIMUL(DWORD, a, b);
case QWORD:
return emitIMUL(QWORD, a, b);
case SINGLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.MUL, SS, true, a, b);
} else {
return emitBinary(resultKind, SSEOp.MUL, SS, true, a, b);
}
case DOUBLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.MUL, SD, true, a, b);
} else {
return emitBinary(resultKind, SSEOp.MUL, SD, true, a, b);
}
default:
throw GraalError.shouldNotReachHere();
}
}
private RegisterValue moveToReg(Register reg, Value v) {
RegisterValue ret = reg.asValue(v.getValueKind());
getLIRGen().emitMove(ret, v);
return ret;
}
private Value emitMulHigh(AMD64MOp opcode, OperandSize size, Value a, Value b) {
AMD64MulDivOp mulHigh = getLIRGen().append(new AMD64MulDivOp(opcode, size, LIRKind.combine(a, b), moveToReg(AMD64.rax, a), getLIRGen().asAllocatable(b)));
return getLIRGen().emitMove(mulHigh.getHighResult());
}
@Override
public Value emitMulHigh(Value a, Value b) {
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitMulHigh(AMD64MOp.IMUL, DWORD, a, b);
case QWORD:
return emitMulHigh(AMD64MOp.IMUL, QWORD, a, b);
default:
throw GraalError.shouldNotReachHere();
}
}
@Override
public Value emitUMulHigh(Value a, Value b) {
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitMulHigh(AMD64MOp.MUL, DWORD, a, b);
case QWORD:
return emitMulHigh(AMD64MOp.MUL, QWORD, a, b);
default:
throw GraalError.shouldNotReachHere();
}
}
public Value emitBinaryMemory(AMD64RMOp op, OperandSize size, AllocatableValue a, AMD64AddressValue location, LIRFrameState state) {
Variable result = getLIRGen().newVariable(LIRKind.combine(a));
getLIRGen().append(new AMD64Binary.MemoryTwoOp(op, size, result, a, location, state));
return result;
}
public Value emitBinaryMemory(AMD64RRMOp op, OperandSize size, AllocatableValue a, AMD64AddressValue location, LIRFrameState state) {
Variable result = getLIRGen().newVariable(LIRKind.combine(a));
getLIRGen().append(new AMD64Binary.MemoryThreeOp(op, size, result, a, location, state));
return result;
}
protected Value emitConvertMemoryOp(PlatformKind kind, AMD64RMOp op, OperandSize size, AMD64AddressValue address, LIRFrameState state) {
Variable result = getLIRGen().newVariable(LIRKind.value(kind));
getLIRGen().append(new AMD64Unary.MemoryOp(op, size, result, address, state));
return result;
}
protected Value emitZeroExtendMemory(AMD64Kind memoryKind, int resultBits, AMD64AddressValue address, LIRFrameState state) {
// Issue a zero extending load of the proper bit size and set the result to
// the proper kind.
Variable result = getLIRGen().newVariable(LIRKind.value(resultBits <= 32 ? AMD64Kind.DWORD : AMD64Kind.QWORD));
switch (memoryKind) {
case BYTE:
getLIRGen().append(new AMD64Unary.MemoryOp(MOVZXB, DWORD, result, address, state));
break;
case WORD:
getLIRGen().append(new AMD64Unary.MemoryOp(MOVZX, DWORD, result, address, state));
break;
case DWORD:
getLIRGen().append(new AMD64Unary.MemoryOp(MOV, DWORD, result, address, state));
break;
case QWORD:
getLIRGen().append(new AMD64Unary.MemoryOp(MOV, QWORD, result, address, state));
break;
default:
throw GraalError.shouldNotReachHere();
}
return result;
}
private AMD64MulDivOp emitIDIV(OperandSize size, Value a, Value b, LIRFrameState state) {
LIRKind kind = LIRKind.combine(a, b);
AMD64SignExtendOp sx = getLIRGen().append(new AMD64SignExtendOp(size, kind, moveToReg(AMD64.rax, a)));
return getLIRGen().append(new AMD64MulDivOp(AMD64MOp.IDIV, size, kind, sx.getHighResult(), sx.getLowResult(), getLIRGen().asAllocatable(b), state));
}
private AMD64MulDivOp emitDIV(OperandSize size, Value a, Value b, LIRFrameState state) {
LIRKind kind = LIRKind.combine(a, b);
RegisterValue rax = moveToReg(AMD64.rax, a);
RegisterValue rdx = AMD64.rdx.asValue(kind);
getLIRGen().append(new AMD64ClearRegisterOp(size, rdx));
return getLIRGen().append(new AMD64MulDivOp(AMD64MOp.DIV, size, kind, rdx, rax, getLIRGen().asAllocatable(b), state));
}
public Value[] emitSignedDivRem(Value a, Value b, LIRFrameState state) {
AMD64MulDivOp op;
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
op = emitIDIV(DWORD, a, b, state);
break;
case QWORD:
op = emitIDIV(QWORD, a, b, state);
break;
default:
throw GraalError.shouldNotReachHere();
}
return new Value[]{getLIRGen().emitMove(op.getQuotient()), getLIRGen().emitMove(op.getRemainder())};
}
public Value[] emitUnsignedDivRem(Value a, Value b, LIRFrameState state) {
AMD64MulDivOp op;
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
op = emitDIV(DWORD, a, b, state);
break;
case QWORD:
op = emitDIV(QWORD, a, b, state);
break;
default:
throw GraalError.shouldNotReachHere();
}
return new Value[]{getLIRGen().emitMove(op.getQuotient()), getLIRGen().emitMove(op.getRemainder())};
}
@Override
public Value emitDiv(Value a, Value b, LIRFrameState state) {
TargetDescription target = getLIRGen().target();
boolean isAvx = ((AMD64) target.arch).getFeatures().contains(CPUFeature.AVX);
LIRKind resultKind = LIRKind.combine(a, b);
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
AMD64MulDivOp op = emitIDIV(DWORD, a, b, state);
return getLIRGen().emitMove(op.getQuotient());
case QWORD:
AMD64MulDivOp lop = emitIDIV(QWORD, a, b, state);
return getLIRGen().emitMove(lop.getQuotient());
case SINGLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.DIV, SS, false, a, b);
} else {
return emitBinary(resultKind, SSEOp.DIV, SS, false, a, b);
}
case DOUBLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.DIV, SD, false, a, b);
} else {
return emitBinary(resultKind, SSEOp.DIV, SD, false, a, b);
}
default:
throw GraalError.shouldNotReachHere();
}
}
@Override
public Value emitRem(Value a, Value b, LIRFrameState state) {
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
AMD64MulDivOp op = emitIDIV(DWORD, a, b, state);
return getLIRGen().emitMove(op.getRemainder());
case QWORD:
AMD64MulDivOp lop = emitIDIV(QWORD, a, b, state);
return getLIRGen().emitMove(lop.getRemainder());
case SINGLE: {
Variable result = getLIRGen().newVariable(LIRKind.combine(a, b));
getLIRGen().append(new FPDivRemOp(FREM, result, getLIRGen().load(a), getLIRGen().load(b)));
return result;
}
case DOUBLE: {
Variable result = getLIRGen().newVariable(LIRKind.combine(a, b));
getLIRGen().append(new FPDivRemOp(DREM, result, getLIRGen().load(a), getLIRGen().load(b)));
return result;
}
default:
throw GraalError.shouldNotReachHere();
}
}
@Override
public Variable emitUDiv(Value a, Value b, LIRFrameState state) {
AMD64MulDivOp op;
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
op = emitDIV(DWORD, a, b, state);
break;
case QWORD:
op = emitDIV(QWORD, a, b, state);
break;
default:
throw GraalError.shouldNotReachHere();
}
return getLIRGen().emitMove(op.getQuotient());
}
@Override
public Variable emitURem(Value a, Value b, LIRFrameState state) {
AMD64MulDivOp op;
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
op = emitDIV(DWORD, a, b, state);
break;
case QWORD:
op = emitDIV(QWORD, a, b, state);
break;
default:
throw GraalError.shouldNotReachHere();
}
return getLIRGen().emitMove(op.getRemainder());
}
@Override
public Variable emitAnd(Value a, Value b) {
LIRKind resultKind = LIRKind.combine(a, b);
TargetDescription target = getLIRGen().target();
boolean isAvx = ((AMD64) target.arch).getFeatures().contains(CPUFeature.AVX);
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitBinary(resultKind, AND, DWORD, true, a, b, false);
case QWORD:
return emitBinary(resultKind, AND, QWORD, true, a, b, false);
case SINGLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.AND, PS, true, a, b);
} else {
return emitBinary(resultKind, SSEOp.AND, PS, true, a, b);
}
case DOUBLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.AND, PD, true, a, b);
} else {
return emitBinary(resultKind, SSEOp.AND, PD, true, a, b);
}
default:
throw GraalError.shouldNotReachHere();
}
}
@Override
public Variable emitOr(Value a, Value b) {
LIRKind resultKind = LIRKind.combine(a, b);
TargetDescription target = getLIRGen().target();
boolean isAvx = ((AMD64) target.arch).getFeatures().contains(CPUFeature.AVX);
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitBinary(resultKind, OR, DWORD, true, a, b, false);
case QWORD:
return emitBinary(resultKind, OR, QWORD, true, a, b, false);
case SINGLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.OR, PS, true, a, b);
} else {
return emitBinary(resultKind, SSEOp.OR, PS, true, a, b);
}
case DOUBLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.OR, PD, true, a, b);
} else {
return emitBinary(resultKind, SSEOp.OR, PD, true, a, b);
}
default:
throw GraalError.shouldNotReachHere();
}
}
@Override
public Variable emitXor(Value a, Value b) {
LIRKind resultKind = LIRKind.combine(a, b);
TargetDescription target = getLIRGen().target();
boolean isAvx = ((AMD64) target.arch).getFeatures().contains(CPUFeature.AVX);
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitBinary(resultKind, XOR, DWORD, true, a, b, false);
case QWORD:
return emitBinary(resultKind, XOR, QWORD, true, a, b, false);
case SINGLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.XOR, PS, true, a, b);
} else {
return emitBinary(resultKind, SSEOp.XOR, PS, true, a, b);
}
case DOUBLE:
if (isAvx) {
return emitBinary(resultKind, AVXOp.XOR, PD, true, a, b);
} else {
return emitBinary(resultKind, SSEOp.XOR, PD, true, a, b);
}
default:
throw GraalError.shouldNotReachHere();
}
}
private Variable emitShift(AMD64Shift op, OperandSize size, Value a, Value b) {
Variable result = getLIRGen().newVariable(LIRKind.combine(a, b).changeType(a.getPlatformKind()));
AllocatableValue input = getLIRGen().asAllocatable(a);
if (isJavaConstant(b)) {
JavaConstant c = asJavaConstant(b);
if (c.asLong() == 1) {
getLIRGen().append(new AMD64Unary.MOp(op.m1Op, size, result, input));
} else {
/*
* c is implicitly masked to 5 or 6 bits by the CPU, so casting it to (int) is
* always correct, even without the NumUtil.is32bit() test.
*/
getLIRGen().append(new AMD64Binary.ConstOp(op.miOp, size, result, input, (int) c.asLong()));
}
} else {
getLIRGen().emitMove(RCX_I, b);
getLIRGen().append(new AMD64ShiftOp(op.mcOp, size, result, input, RCX_I));
}
return result;
}
@Override
public Variable emitShl(Value a, Value b) {
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitShift(SHL, DWORD, a, b);
case QWORD:
return emitShift(SHL, QWORD, a, b);
default:
throw GraalError.shouldNotReachHere();
}
}
@Override
public Variable emitShr(Value a, Value b) {
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitShift(SAR, DWORD, a, b);
case QWORD:
return emitShift(SAR, QWORD, a, b);
default:
throw GraalError.shouldNotReachHere();
}
}
@Override
public Variable emitUShr(Value a, Value b) {
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitShift(SHR, DWORD, a, b);
case QWORD:
return emitShift(SHR, QWORD, a, b);
default:
throw GraalError.shouldNotReachHere();
}
}
public Variable emitRol(Value a, Value b) {
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitShift(ROL, DWORD, a, b);
case QWORD:
return emitShift(ROL, QWORD, a, b);
default:
throw GraalError.shouldNotReachHere();
}
}
public Variable emitRor(Value a, Value b) {
switch ((AMD64Kind) a.getPlatformKind()) {
case DWORD:
return emitShift(ROR, DWORD, a, b);
case QWORD:
return emitShift(ROR, QWORD, a, b);
default:
throw GraalError.shouldNotReachHere();
}
}
private AllocatableValue emitConvertOp(LIRKind kind, AMD64RMOp op, OperandSize size, Value input) {
Variable result = getLIRGen().newVariable(kind);
getLIRGen().append(new AMD64Unary.RMOp(op, size, result, getLIRGen().asAllocatable(input)));
return result;
}
private AllocatableValue emitConvertOp(LIRKind kind, AMD64MROp op, OperandSize size, Value input) {
Variable result = getLIRGen().newVariable(kind);
getLIRGen().append(new AMD64Unary.MROp(op, size, result, getLIRGen().asAllocatable(input)));
return result;
}
@Override
public Value emitReinterpret(LIRKind to, Value inputVal) {
ValueKind<?> from = inputVal.getValueKind();
if (to.equals(from)) {
return inputVal;
}
AllocatableValue input = getLIRGen().asAllocatable(inputVal);
/*
* Conversions between integer to floating point types require moves between CPU and FPU
* registers.
*/
AMD64Kind fromKind = (AMD64Kind) from.getPlatformKind();
switch ((AMD64Kind) to.getPlatformKind()) {
case DWORD:
switch (fromKind) {
case SINGLE:
return emitConvertOp(to, AMD64MROp.MOVD, DWORD, input);
}
break;
case QWORD:
switch (fromKind) {
case DOUBLE:
return emitConvertOp(to, AMD64MROp.MOVQ, QWORD, input);
}
break;
case SINGLE:
switch (fromKind) {
case DWORD:
return emitConvertOp(to, AMD64RMOp.MOVD, DWORD, input);
}
break;
case DOUBLE:
switch (fromKind) {
case QWORD:
return emitConvertOp(to, AMD64RMOp.MOVQ, QWORD, input);
}
break;
}
throw GraalError.shouldNotReachHere();
}
@Override
public Value emitFloatConvert(FloatConvert op, Value input) {
switch (op) {
case D2F:
return emitConvertOp(LIRKind.combine(input).changeType(AMD64Kind.SINGLE), SSEOp.CVTSD2SS, SD, input);
case D2I:
return emitConvertOp(LIRKind.combine(input).changeType(AMD64Kind.DWORD), SSEOp.CVTTSD2SI, DWORD, input);
case D2L:
return emitConvertOp(LIRKind.combine(input).changeType(AMD64Kind.QWORD), SSEOp.CVTTSD2SI, QWORD, input);
case F2D:
return emitConvertOp(LIRKind.combine(input).changeType(AMD64Kind.DOUBLE), SSEOp.CVTSS2SD, SS, input);
case F2I:
return emitConvertOp(LIRKind.combine(input).changeType(AMD64Kind.DWORD), SSEOp.CVTTSS2SI, DWORD, input);
case F2L:
return emitConvertOp(LIRKind.combine(input).changeType(AMD64Kind.QWORD), SSEOp.CVTTSS2SI, QWORD, input);
case I2D:
return emitConvertOp(LIRKind.combine(input).changeType(AMD64Kind.DOUBLE), SSEOp.CVTSI2SD, DWORD, input);
case I2F:
return emitConvertOp(LIRKind.combine(input).changeType(AMD64Kind.SINGLE), SSEOp.CVTSI2SS, DWORD, input);
case L2D:
return emitConvertOp(LIRKind.combine(input).changeType(AMD64Kind.DOUBLE), SSEOp.CVTSI2SD, QWORD, input);
case L2F:
return emitConvertOp(LIRKind.combine(input).changeType(AMD64Kind.SINGLE), SSEOp.CVTSI2SS, QWORD, input);
default:
throw GraalError.shouldNotReachHere();
}
}
@Override
public Value emitNarrow(Value inputVal, int bits) {
if (inputVal.getPlatformKind() == AMD64Kind.QWORD && bits <= 32) {
// TODO make it possible to reinterpret Long as Int in LIR without move
return emitConvertOp(LIRKind.combine(inputVal).changeType(AMD64Kind.DWORD), AMD64RMOp.MOV, DWORD, inputVal);
} else {
return inputVal;
}
}
@Override
public Value emitSignExtend(Value inputVal, int fromBits, int toBits) {
assert fromBits <= toBits && toBits <= 64;
if (fromBits == toBits) {
return inputVal;
} else if (toBits > 32) {
// sign extend to 64 bits
switch (fromBits) {
case 8:
return emitConvertOp(LIRKind.combine(inputVal).changeType(AMD64Kind.QWORD), MOVSXB, QWORD, inputVal);
case 16:
return emitConvertOp(LIRKind.combine(inputVal).changeType(AMD64Kind.QWORD), MOVSX, QWORD, inputVal);
case 32:
return emitConvertOp(LIRKind.combine(inputVal).changeType(AMD64Kind.QWORD), MOVSXD, QWORD, inputVal);
default:
throw GraalError.unimplemented("unsupported sign extension (" + fromBits + " bit -> " + toBits + " bit)");
}
} else {
// sign extend to 32 bits (smaller values are internally represented as 32 bit values)
switch (fromBits) {
case 8:
return emitConvertOp(LIRKind.combine(inputVal).changeType(AMD64Kind.DWORD), MOVSXB, DWORD, inputVal);
case 16:
return emitConvertOp(LIRKind.combine(inputVal).changeType(AMD64Kind.DWORD), MOVSX, DWORD, inputVal);
case 32:
return inputVal;
default:
throw GraalError.unimplemented("unsupported sign extension (" + fromBits + " bit -> " + toBits + " bit)");
}
}
}
@Override
public Value emitZeroExtend(Value inputVal, int fromBits, int toBits) {
assert fromBits <= toBits && toBits <= 64;
if (fromBits == toBits) {
return inputVal;
} else if (fromBits > 32) {
assert inputVal.getPlatformKind() == AMD64Kind.QWORD;
Variable result = getLIRGen().newVariable(LIRKind.combine(inputVal));
long mask = CodeUtil.mask(fromBits);
getLIRGen().append(new AMD64Binary.DataTwoOp(AND.getRMOpcode(QWORD), QWORD, result, getLIRGen().asAllocatable(inputVal), JavaConstant.forLong(mask)));
return result;
} else {
LIRKind resultKind = LIRKind.combine(inputVal);
if (toBits > 32) {
resultKind = resultKind.changeType(AMD64Kind.QWORD);
} else {
resultKind = resultKind.changeType(AMD64Kind.DWORD);
}
/*
* Always emit DWORD operations, even if the resultKind is Long. On AMD64, all DWORD
* operations implicitly set the upper half of the register to 0, which is what we want
* anyway. Compared to the QWORD oparations, the encoding of the DWORD operations is
* sometimes one byte shorter.
*/
switch (fromBits) {
case 8:
return emitConvertOp(resultKind, MOVZXB, DWORD, inputVal);
case 16:
return emitConvertOp(resultKind, MOVZX, DWORD, inputVal);
case 32:
return emitConvertOp(resultKind, MOV, DWORD, inputVal);
}
// odd bit count, fall back on manual masking
Variable result = getLIRGen().newVariable(resultKind);
JavaConstant mask;
if (toBits > 32) {
mask = JavaConstant.forLong(CodeUtil.mask(fromBits));
} else {
mask = JavaConstant.forInt((int) CodeUtil.mask(fromBits));
}
getLIRGen().append(new AMD64Binary.DataTwoOp(AND.getRMOpcode(DWORD), DWORD, result, getLIRGen().asAllocatable(inputVal), mask));
return result;
}
}
@Override
public Variable emitBitCount(Value value) {
Variable result = getLIRGen().newVariable(LIRKind.combine(value).changeType(AMD64Kind.DWORD));
assert ((AMD64Kind) value.getPlatformKind()).isInteger();
if (value.getPlatformKind() == AMD64Kind.QWORD) {
getLIRGen().append(new AMD64Unary.RMOp(POPCNT, QWORD, result, getLIRGen().asAllocatable(value)));
} else {
getLIRGen().append(new AMD64Unary.RMOp(POPCNT, DWORD, result, getLIRGen().asAllocatable(value)));
}
return result;
}
@Override
public Variable emitBitScanForward(Value value) {
Variable result = getLIRGen().newVariable(LIRKind.combine(value).changeType(AMD64Kind.DWORD));
getLIRGen().append(new AMD64Unary.RMOp(BSF, QWORD, result, getLIRGen().asAllocatable(value)));
return result;
}
@Override
public Variable emitBitScanReverse(Value value) {
Variable result = getLIRGen().newVariable(LIRKind.combine(value).changeType(AMD64Kind.DWORD));
assert ((AMD64Kind) value.getPlatformKind()).isInteger();
if (value.getPlatformKind() == AMD64Kind.QWORD) {
getLIRGen().append(new AMD64Unary.RMOp(BSR, QWORD, result, getLIRGen().asAllocatable(value)));
} else {
getLIRGen().append(new AMD64Unary.RMOp(BSR, DWORD, result, getLIRGen().asAllocatable(value)));
}
return result;
}
@Override
public Value emitCountLeadingZeros(Value value) {
Variable result = getLIRGen().newVariable(LIRKind.combine(value).changeType(AMD64Kind.DWORD));
assert ((AMD64Kind) value.getPlatformKind()).isInteger();
if (value.getPlatformKind() == AMD64Kind.QWORD) {
getLIRGen().append(new AMD64Unary.RMOp(LZCNT, QWORD, result, getLIRGen().asAllocatable(value)));
} else {
getLIRGen().append(new AMD64Unary.RMOp(LZCNT, DWORD, result, getLIRGen().asAllocatable(value)));
}
return result;
}
@Override
public Value emitCountTrailingZeros(Value value) {
Variable result = getLIRGen().newVariable(LIRKind.combine(value).changeType(AMD64Kind.DWORD));
assert ((AMD64Kind) value.getPlatformKind()).isInteger();
if (value.getPlatformKind() == AMD64Kind.QWORD) {
getLIRGen().append(new AMD64Unary.RMOp(TZCNT, QWORD, result, getLIRGen().asAllocatable(value)));
} else {
getLIRGen().append(new AMD64Unary.RMOp(TZCNT, DWORD, result, getLIRGen().asAllocatable(value)));
}
return result;
}
@Override
public Value emitMathAbs(Value input) {
Variable result = getLIRGen().newVariable(LIRKind.combine(input));
switch ((AMD64Kind) input.getPlatformKind()) {
case SINGLE:
getLIRGen().append(new AMD64Binary.DataTwoOp(SSEOp.AND, PS, result, getLIRGen().asAllocatable(input), JavaConstant.forFloat(Float.intBitsToFloat(0x7FFFFFFF)), 16));
break;
case DOUBLE:
getLIRGen().append(new AMD64Binary.DataTwoOp(SSEOp.AND, PD, result, getLIRGen().asAllocatable(input), JavaConstant.forDouble(Double.longBitsToDouble(0x7FFFFFFFFFFFFFFFL)), 16));
break;
default:
throw GraalError.shouldNotReachHere();
}
return result;
}
@Override
public Value emitMathSqrt(Value input) {
Variable result = getLIRGen().newVariable(LIRKind.combine(input));
switch ((AMD64Kind) input.getPlatformKind()) {
case SINGLE:
getLIRGen().append(new AMD64Unary.RMOp(SSEOp.SQRT, SS, result, getLIRGen().asAllocatable(input)));
break;
case DOUBLE:
getLIRGen().append(new AMD64Unary.RMOp(SSEOp.SQRT, SD, result, getLIRGen().asAllocatable(input)));
break;
default:
throw GraalError.shouldNotReachHere();
}
return result;
}
@Override
public Value emitMathLog(Value input, boolean base10) {
LIRGenerator gen = getLIRGen();
Variable result = maths.emitLog(gen, input, base10);
if (result == null) {
result = gen.newVariable(LIRKind.combine(input));
AllocatableValue stackSlot = gen.getResult().getFrameMapBuilder().allocateSpillSlot(LIRKind.value(AMD64Kind.QWORD));
gen.append(new AMD64MathIntrinsicUnaryOp(getAMD64LIRGen(), base10 ? LOG10 : LOG, result, gen.asAllocatable(input), stackSlot));
}
return result;
}
@Override
public Value emitMathCos(Value input) {
LIRGenerator gen = getLIRGen();
Variable result = maths.emitCos(gen, input);
if (result == null) {
result = gen.newVariable(LIRKind.combine(input));
AllocatableValue stackSlot = gen.getResult().getFrameMapBuilder().allocateSpillSlot(LIRKind.value(AMD64Kind.QWORD));
gen.append(new AMD64MathIntrinsicUnaryOp(getAMD64LIRGen(), COS, result, gen.asAllocatable(input), stackSlot));
}
return result;
}
@Override
public Value emitMathSin(Value input) {
LIRGenerator gen = getLIRGen();
Variable result = maths.emitSin(gen, input);
if (result == null) {
result = gen.newVariable(LIRKind.combine(input));
AllocatableValue stackSlot = gen.getResult().getFrameMapBuilder().allocateSpillSlot(LIRKind.value(AMD64Kind.QWORD));
gen.append(new AMD64MathIntrinsicUnaryOp(getAMD64LIRGen(), SIN, result, gen.asAllocatable(input), stackSlot));
}
return result;
}
@Override
public Value emitMathTan(Value input) {
LIRGenerator gen = getLIRGen();
Variable result = maths.emitTan(gen, input);
if (result == null) {
result = gen.newVariable(LIRKind.combine(input));
AllocatableValue stackSlot = gen.getResult().getFrameMapBuilder().allocateSpillSlot(LIRKind.value(AMD64Kind.QWORD));
gen.append(new AMD64MathIntrinsicUnaryOp(getAMD64LIRGen(), TAN, result, gen.asAllocatable(input), stackSlot));
}
return result;
}
@Override
public Value emitMathExp(Value input) {
Variable result = getLIRGen().newVariable(LIRKind.combine(input));
AllocatableValue stackSlot = getLIRGen().getResult().getFrameMapBuilder().allocateSpillSlot(LIRKind.value(AMD64Kind.QWORD));
getLIRGen().append(new AMD64MathIntrinsicUnaryOp(getAMD64LIRGen(), EXP, result, getLIRGen().asAllocatable(input), stackSlot));
return result;
}
@Override
public Value emitMathPow(Value input1, Value input2) {
Variable result = getLIRGen().newVariable(LIRKind.combine(input1));
getLIRGen().append(new AMD64MathIntrinsicBinaryOp(getAMD64LIRGen(), POW, result, getLIRGen().asAllocatable(input1), getLIRGen().asAllocatable(input2)));
return result;
}
protected AMD64LIRGenerator getAMD64LIRGen() {
return (AMD64LIRGenerator) getLIRGen();
}
@Override
public Variable emitLoad(LIRKind kind, Value address, LIRFrameState state) {
AMD64AddressValue loadAddress = getAMD64LIRGen().asAddressValue(address);
Variable result = getLIRGen().newVariable(getLIRGen().toRegisterKind(kind));
switch ((AMD64Kind) kind.getPlatformKind()) {
case BYTE:
getLIRGen().append(new AMD64Unary.MemoryOp(MOVSXB, DWORD, result, loadAddress, state));
break;
case WORD:
getLIRGen().append(new AMD64Unary.MemoryOp(MOVSX, DWORD, result, loadAddress, state));
break;
case DWORD:
getLIRGen().append(new AMD64Unary.MemoryOp(MOV, DWORD, result, loadAddress, state));
break;
case QWORD:
getLIRGen().append(new AMD64Unary.MemoryOp(MOV, QWORD, result, loadAddress, state));
break;
case SINGLE:
getLIRGen().append(new AMD64Unary.MemoryOp(MOVSS, SS, result, loadAddress, state));
break;
case DOUBLE:
getLIRGen().append(new AMD64Unary.MemoryOp(MOVSD, SD, result, loadAddress, state));
break;
default:
throw GraalError.shouldNotReachHere();
}
return result;
}
protected void emitStoreConst(AMD64Kind kind, AMD64AddressValue address, ConstantValue value, LIRFrameState state) {
Constant c = value.getConstant();
if (JavaConstant.isNull(c)) {
assert kind == AMD64Kind.DWORD || kind == AMD64Kind.QWORD;
OperandSize size = kind == AMD64Kind.DWORD ? DWORD : QWORD;
getLIRGen().append(new AMD64BinaryConsumer.MemoryConstOp(AMD64MIOp.MOV, size, address, 0, state));
return;
} else if (c instanceof VMConstant) {
// only 32-bit constants can be patched
if (kind == AMD64Kind.DWORD) {
if (getLIRGen().target().inlineObjects || !(c instanceof JavaConstant)) {
// if c is a JavaConstant, it's an oop, otherwise it's a metaspace constant
assert !(c instanceof JavaConstant) || ((JavaConstant) c).getJavaKind() == JavaKind.Object;
getLIRGen().append(new AMD64BinaryConsumer.MemoryVMConstOp(AMD64MIOp.MOV, address, (VMConstant) c, state));
return;
}
}
} else {
JavaConstant jc = (JavaConstant) c;
assert jc.getJavaKind().isPrimitive();
AMD64MIOp op = AMD64MIOp.MOV;
OperandSize size;
long imm;
switch (kind) {
case BYTE:
op = AMD64MIOp.MOVB;
size = BYTE;
imm = jc.asInt();
break;
case WORD:
size = WORD;
imm = jc.asInt();
break;
case DWORD:
size = DWORD;
imm = jc.asInt();
break;
case QWORD:
size = QWORD;
imm = jc.asLong();
break;
case SINGLE:
size = DWORD;
imm = Float.floatToRawIntBits(jc.asFloat());
break;
case DOUBLE:
size = QWORD;
imm = Double.doubleToRawLongBits(jc.asDouble());
break;
default:
throw GraalError.shouldNotReachHere("unexpected kind " + kind);
}
if (NumUtil.isInt(imm)) {
getLIRGen().append(new AMD64BinaryConsumer.MemoryConstOp(op, size, address, (int) imm, state));
return;
}
}
// fallback: load, then store
emitStore(kind, address, getLIRGen().asAllocatable(value), state);
}
protected void emitStore(AMD64Kind kind, AMD64AddressValue address, AllocatableValue value, LIRFrameState state) {
switch (kind) {
case BYTE:
getLIRGen().append(new AMD64BinaryConsumer.MemoryMROp(AMD64MROp.MOVB, BYTE, address, value, state));
break;
case WORD:
getLIRGen().append(new AMD64BinaryConsumer.MemoryMROp(AMD64MROp.MOV, WORD, address, value, state));
break;
case DWORD:
getLIRGen().append(new AMD64BinaryConsumer.MemoryMROp(AMD64MROp.MOV, DWORD, address, value, state));
break;
case QWORD:
getLIRGen().append(new AMD64BinaryConsumer.MemoryMROp(AMD64MROp.MOV, QWORD, address, value, state));
break;
case SINGLE:
getLIRGen().append(new AMD64BinaryConsumer.MemoryMROp(AMD64MROp.MOVSS, SS, address, value, state));
break;
case DOUBLE:
getLIRGen().append(new AMD64BinaryConsumer.MemoryMROp(AMD64MROp.MOVSD, SD, address, value, state));
break;
default:
throw GraalError.shouldNotReachHere();
}
}
@Override
public void emitStore(ValueKind<?> lirKind, Value address, Value input, LIRFrameState state) {
AMD64AddressValue storeAddress = getAMD64LIRGen().asAddressValue(address);
AMD64Kind kind = (AMD64Kind) lirKind.getPlatformKind();
if (isConstantValue(input)) {
emitStoreConst(kind, storeAddress, asConstantValue(input), state);
} else {
emitStore(kind, storeAddress, getLIRGen().asAllocatable(input), state);
}
}
@Override
public void emitCompareOp(AMD64Kind cmpKind, Variable left, Value right) {
OperandSize size;
switch (cmpKind) {
case BYTE:
size = BYTE;
break;
case WORD:
size = WORD;
break;
case DWORD:
size = DWORD;
break;
case QWORD:
size = QWORD;
break;
case SINGLE:
getLIRGen().append(new AMD64BinaryConsumer.Op(SSEOp.UCOMIS, PS, left, getLIRGen().asAllocatable(right)));
return;
case DOUBLE:
getLIRGen().append(new AMD64BinaryConsumer.Op(SSEOp.UCOMIS, PD, left, getLIRGen().asAllocatable(right)));
return;
default:
throw GraalError.shouldNotReachHere("unexpected kind: " + cmpKind);
}
if (isConstantValue(right)) {
Constant c = LIRValueUtil.asConstant(right);
if (JavaConstant.isNull(c)) {
getLIRGen().append(new AMD64BinaryConsumer.Op(TEST, size, left, left));
return;
} else if (c instanceof VMConstant) {
VMConstant vc = (VMConstant) c;
if (size == DWORD && !GeneratePIC.getValue(getOptions())) {
getLIRGen().append(new AMD64BinaryConsumer.VMConstOp(CMP.getMIOpcode(DWORD, false), left, vc));
} else {
getLIRGen().append(new AMD64BinaryConsumer.DataOp(CMP.getRMOpcode(size), size, left, vc));
}
return;
} else if (c instanceof JavaConstant) {
JavaConstant jc = (JavaConstant) c;
if (jc.isDefaultForKind()) {
AMD64RMOp op = size == BYTE ? TESTB : TEST;
getLIRGen().append(new AMD64BinaryConsumer.Op(op, size, left, left));
return;
} else if (NumUtil.is32bit(jc.asLong())) {
getLIRGen().append(new AMD64BinaryConsumer.ConstOp(CMP, size, left, (int) jc.asLong()));
return;
}
}
}
// fallback: load, then compare
getLIRGen().append(new AMD64BinaryConsumer.Op(CMP.getRMOpcode(size), size, left, getLIRGen().asAllocatable(right)));
}
@Override
public Value emitRound(Value value, RoundingMode mode) {
Variable result = getLIRGen().newVariable(LIRKind.combine(value));
assert ((AMD64Kind) value.getPlatformKind()).isXMM();
if (value.getPlatformKind() == AMD64Kind.SINGLE) {
getLIRGen().append(new AMD64Binary.RMIOp(AMD64RMIOp.ROUNDSS, OperandSize.PD, result, getLIRGen().asAllocatable(value), mode.encoding));
} else {
getLIRGen().append(new AMD64Binary.RMIOp(AMD64RMIOp.ROUNDSD, OperandSize.PD, result, getLIRGen().asAllocatable(value), mode.encoding));
}
return result;
}
}
| 44.755771
| 193
| 0.610378
|
b9bff8c50c1ba74983e914d8625f04698957ad85
| 669
|
/**
*
*/
package querqy.rewrite.commonrules.model;
import querqy.model.ExpandedQuery;
import querqy.model.Term;
/**
*
* A single right-hand side clause of a rewrite rule. It represents one of
* possibly more actions that should be taken if the input matches the rule
* condition(s).
*
* @author René Kriegler, @renekrie
*
*/
public interface Instruction {
/**
*
* @param sequence
* @param matchedTerms
* @param startPosition
* @param endPosition
* @param expandedQuery
*/
void apply(PositionSequence<Term> sequence, TermMatches termMatches, int startPosition, int endPosition,
ExpandedQuery expandedQuery);
}
| 21.580645
| 107
| 0.692078
|
5aaa2d8ab42a50be63c4faeb1a0f88323799a773
| 1,162
|
package com.milulost.telegram_display.service.impl;
import com.milulost.telegram_display.bean.Channel;
import com.milulost.telegram_display.mapper.ChannelMapper;
import com.milulost.telegram_display.service.ChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ChannelServiceImpl implements ChannelService {
@Autowired
private ChannelMapper channelMapper;
@Override
public List<Channel> findAllByUserId(Integer userId) {
return channelMapper.findAllByUserId(userId);
}
@Override
public List<Channel> findAllByUserIdByPage(Integer start, Integer limit, Integer userId) {
return channelMapper.findAllByUserIdByPage(start, limit, userId);
}
@Override
public List<Integer> findUserByChannelId(Integer channelId) {
return channelMapper.findUserByChannelId(channelId);
}
@Override
public List<Integer> findUserByChannelIdByPage(Integer start, Integer limit, Integer channelId) {
return channelMapper.findUserByChannelIdByPage(start, limit, channelId);
}
}
| 32.277778
| 101
| 0.777108
|
fce689c6e560aa833f9ccdd26286f0387af6e0e1
| 1,396
|
package org.dashbuilder.client.widgets.dataset.editor.bean;
import javax.enterprise.context.Dependent;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import org.dashbuilder.common.client.editor.ValueBoxEditor;
/**
* <p>The Bean Data Set attributes editor view.</p>
*
* @since 0.4.0
*/
@Dependent
public class BeanDataSetDefAttributesEditorView extends Composite implements BeanDataSetDefAttributesEditor.View {
interface Binder extends UiBinder<Widget, BeanDataSetDefAttributesEditorView> {
Binder BINDER = GWT.create(Binder.class);
}
BeanDataSetDefAttributesEditor presenter;
@UiField(provided = true)
ValueBoxEditor.View generatorClassView;
@UiField(provided = true)
IsWidget parameterMapView;
@Override
public void init(final BeanDataSetDefAttributesEditor presenter) {
this.presenter = presenter;
}
@Override
public void initWidgets(final ValueBoxEditor.View generatorClassView, final IsWidget parameterMapView) {
this.generatorClassView = generatorClassView;
this.parameterMapView = parameterMapView;
initWidget(Binder.BINDER.createAndBindUi(this));
}
}
| 30.347826
| 114
| 0.762178
|
39701aa6f496065128a97d47187958c97b9d1014
| 2,831
|
/*
* This file is part of Cubic Chunks, licensed under the MIT License (MIT).
*
* Copyright (c) 2014 Tall Worlds
*
* 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 cubicchunks.generator.features;
import java.util.Random;
import net.minecraft.block.BlockTallGrass;
import net.minecraft.block.Blocks;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
public class TallGrassGenerator extends SurfaceFeatureGenerator {
private final IBlockState block;
public TallGrassGenerator(final World world, final BlockTallGrass.TallGrassTypes tallGrassType) {
super(world);
// TODO: HACK! Obfuscation doesn't work correctly in this class when code below is used.
// It fails at runtime with NoSuchMethodError:
// java.lang.NoSuchMethodError: ama.setProperty(Lamp;Ljava/lang/Object;)Lama;
// use metadata until it's fixed
// actually there is method to get metadata but it doesn't have deobf mappings
// And to use new mappings I would need to update m3l
// and I can't do that. So I used ordinal()
//this.block = Blocks.TALLGRASS.getDefaultState().setProperty(BlockTallGrass.type, tallGrassType);
this.block = Blocks.TALLGRASS.getBlockStateForMetadata(tallGrassType.ordinal());
}
@Override
public void generateAt(final Random rand, final BlockPos pos, final Biome biome) {
BlockPos currentPos = pos;
for(int i = 0; i < 128; ++i) {
BlockPos randomPos = currentPos.add(rand.nextInt(8) - rand.nextInt(8),
rand.nextInt(4) - rand.nextInt(4),
rand.nextInt(8) - rand.nextInt(8));
if(world.hasAirAt(randomPos) && Blocks.TALLGRASS.canBePlacedAt(world, randomPos, block)) {
this.setBlockOnly(randomPos, block);
}
}
}
}
| 41.632353
| 100
| 0.748852
|
a51a99321b3a3082cf63fb6ac8ca03c364a18b9f
| 675
|
/*
Copyright © 2019 Pasqual K. | All rights reserved
*/
package systems.reformcloud.network.packets.in;
import systems.reformcloud.ReformCloudClient;
import systems.reformcloud.configurations.Configuration;
import systems.reformcloud.network.interfaces.NetworkInboundHandler;
import java.io.Serializable;
/**
* @author _Klaro | Pasqual K. / created on 15.04.2019
*/
public final class PacketInEnableDebug implements Serializable, NetworkInboundHandler {
@Override
public void handle(Configuration configuration) {
ReformCloudClient.getInstance().getColouredConsoleProvider()
.setDebug(configuration.getBooleanValue("enabled"));
}
}
| 27
| 87
| 0.768889
|
e07200bcf29863efd9e6061d4dd58b2e38048ed7
| 486
|
package ex01h;
import javax.swing.JOptionPane;
public class Ex01h {
public static void main(String[] args) {
double r, a, v;
r = Double.parseDouble(JOptionPane.showInputDialog(null,"Insira o raio do galão"));
a = Double.parseDouble(JOptionPane.showInputDialog(null,"Insira a altura do galão"));
v = 3.141592653589793 *r*r*a ;
JOptionPane.showMessageDialog(null,"O Volume desse galão é: "+ v);
}
}
| 28.588235
| 94
| 0.615226
|
de1aca82a33305fc4e9b48430963b8cc2e5138ff
| 98
|
package javax.schema;
public interface Closure {
public void call(Table table);
}
| 10.888889
| 33
| 0.653061
|
0bf2552badfc6232c306fe7759f0bd87af1a315c
| 2,152
|
package it.unifi.ing.swam.controller;
import it.unifi.ing.swam.bean.UserSessionBean;
import it.unifi.ing.swam.dao.InvoiceDao;
import it.unifi.ing.swam.model.Invoice;
import java.util.UUID;
import org.apache.commons.lang3.reflect.FieldUtils;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.runners.model.InitializationError;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ViewInvoicePageControllerTest {
private ViewInvoicePageController invoiceViewController;
private UserSessionBean userSession;
private InvoiceDao invoiceDao;
private Invoice invoiceData;
private Invoice invoiceDataMock;
@Before
public void setUp() throws InitializationError {
invoiceViewController = new ViewInvoicePageController();
userSession = new UserSessionBean();
invoiceData = new Invoice(UUID.randomUUID().toString());
invoiceDataMock = new Invoice(UUID.randomUUID().toString());
invoiceDao = mock(InvoiceDao.class);
try {
FieldUtils.writeField(invoiceData, "id", Long.valueOf(10), true);
FieldUtils.writeField(invoiceDataMock, "id", Long.valueOf(30), true);
FieldUtils.writeField(userSession, "userId", Long.valueOf(20), true);
FieldUtils.writeField(invoiceViewController, "invoiceData", invoiceData, true);
FieldUtils.writeField(invoiceViewController, "invoiceId", "30", true);
FieldUtils.writeField(invoiceViewController, "invoiceDao", invoiceDao, true);
FieldUtils.writeField(invoiceViewController, "userSession", userSession, true);
} catch (IllegalAccessException e) {
throw new InitializationError(e);
}
}
@Test
public void testRetrieveInvoiceDataFromDB() {
when(invoiceDao.findById(any(Long.class))).thenReturn(invoiceDataMock);
invoiceViewController.retrieveInvoiceDataFromDB();
assertEquals(invoiceDataMock.getId(), invoiceViewController.getInvoiceData().getId());
}
}
| 33.625
| 94
| 0.724442
|
6fcf024ab50a731b99e2f9dbe1be540ae06330cd
| 1,813
|
package com.quangnguyen.stackoverflowclient.data.repository;
import com.quangnguyen.stackoverflowclient.data.model.Question;
import io.reactivex.Flowable;
import java.util.List;
import javax.inject.Inject;
/**
* @author QuangNguyen (quangctkm9207).
*/
public class QuestionRepository implements QuestionDataSource {
private QuestionDataSource remoteDataSource;
private QuestionDataSource localDataSource;
@Inject
public QuestionRepository(@Local QuestionDataSource localDataSource,
@Remote QuestionDataSource remoteDataSource) {
this.localDataSource = localDataSource;
this.remoteDataSource = remoteDataSource;
}
@Override
public Flowable<List<Question>> loadQuestions(boolean forceRemote) {
Flowable<List<Question>> questions;
if (forceRemote) {
questions = remoteDataSource.loadQuestions(true).doOnEach(notification -> {
// Save new data to local data source
List<Question> list = notification.getValue();
if (list != null && !list.isEmpty()) {
saveDataToLocal(list);
}
});
} else {
questions =
localDataSource.loadQuestions(false);
}
return questions;
}
@Override
public void addQuestion(Question question) {
//Currently, we do not need this.
throw new UnsupportedOperationException("Unsupported operation");
}
@Override
public void clearData() {
//Currently, we do not need this.
throw new UnsupportedOperationException("Unsupported operation");
}
// A helper method to save data in database after fetching new data from remote source.
private void saveDataToLocal(List<Question> questions) {
// Clear old data
localDataSource.clearData();
for (Question question : questions) {
localDataSource.addQuestion(question);
}
}
}
| 29.241935
| 89
| 0.71925
|
a61bb3f8e5309fc37abeca687472f96a3303a466
| 9,943
|
package com.example.user.century;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.user.century.Cart.Cart;
import com.example.user.century.Cart.CartActivity;
import com.example.user.century.Home.MainActivity;
import com.example.user.century.Register.RegisterActivity;
import com.example.user.century.Session.SessionCek;
import com.example.user.century.Session.SessionManagement;
import com.example.user.century.produkKategori.DetailProduk;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class LoginCartActivity extends AppCompatActivity {
EditText etUsername,etPass;
Button btnLogin,btnRegister;
SessionManagement session;
TextView tvLupa;
AlertDialog dialog;
AlertDialog.Builder builder;
ProgressBar pb;
RequestQueue queue;
String user,pass;
String namafb,emailfb,genderfb;
String emailSQL;
public static String cekFB = null;
private FirebaseAuth mAuth;
SessionCek sessionCek;
public static final String INSERT_CART_URL = "http://fransis.rawatwajah.com/century/insertCart.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_cart);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
queue = Volley.newRequestQueue(this);
mAuth = FirebaseAuth.getInstance();
session = new SessionManagement(getApplicationContext());
sessionCek = new SessionCek(getApplicationContext());
etUsername = (EditText) findViewById(R.id.etUsername);
etPass = (EditText) findViewById(R.id.etPass);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnRegister = (Button) findViewById(R.id.btnRegister);
tvLupa= (TextView) findViewById(R.id.tvLupa);
SpannableString content = new SpannableString("Lupa Kata Sandi?");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
tvLupa.setText(content);
tvLupa.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(LoginCartActivity.this,LupaPassword.class);
startActivity(i);
}
});
builder = new AlertDialog.Builder(this);
pb = (ProgressBar) findViewById(R.id.progressBar);
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(LoginCartActivity.this,RegisterActivity.class);
startActivity(i);
}
});
////////////////////////////////////////////////////////////////////////////////////////////////////////
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(new Intent(LoginCartActivity.this, ServiceCentury.class));
signIn(etUsername.getText().toString(), etPass.getText().toString());
}
});
}
@Override
public void onBackPressed() {
// builder.setMessage("Ingin keluar dari aplikasi ?");
// builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// Intent intent = new Intent(Intent.ACTION_MAIN);
// intent.addCategory(Intent.CATEGORY_HOME);
// startActivity(intent);
// return;
// }
// });
//
// builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
//
// }
// });
//
// dialog = builder.show();
finish();
}
private void signIn(String email, String password) {
pb.setVisibility(View.VISIBLE);
if (email.equals("") || password.equals("")) {
builder.setMessage("Email atau Password tidak boleh kosong");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pb.setVisibility(View.GONE);
}
});
dialog = builder.show();
}
else{
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
final DatabaseHandler db = new DatabaseHandler(LoginCartActivity.this);
List<ProdukTemp> produkTemp = db.getAllProdukTemp();
JSONObject objAdd2 = new JSONObject();
try {
JSONArray arrData = new JSONArray();
for (ProdukTemp pt : produkTemp) {
JSONObject objDetail = new JSONObject();
objDetail.put("qty",String.valueOf(pt.getQty()));
objDetail.put("email",etUsername.getText().toString());
objDetail.put("id_produk_per_lokasi",String.valueOf(pt.getId_produk_per_lokasi()));
objDetail.put("diskon_member","0");
arrData.put(objDetail);
db.deleteProdukTemp(pt);
}
objAdd2.put("data",arrData);
} catch (JSONException e1) {
e1.printStackTrace();
}
JsonObjectRequest stringRequest2 = new JsonObjectRequest(Request.Method.POST, INSERT_CART_URL, objAdd2,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if(response.getString("status").equals("OK")) {
sessionCek.createCek("login");
CONFIG.CekGuest.equals("tidak");
CONFIG.CekBelanja="ya";
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
Intent intent = new Intent(LoginCartActivity.this, MainActivity.class);
startActivity(intent);
}
else{
pb.setVisibility(View.GONE);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pb.setVisibility(View.GONE);
}
}) ;
RequestQueue requestQueue2 = Volley.newRequestQueue(LoginCartActivity.this);
requestQueue2.add(stringRequest2);
} else {
Toast.makeText(LoginCartActivity.this, "Email atau password salah", Toast.LENGTH_SHORT).show();
updateUI(null);
pb.setVisibility(View.GONE);
}
}
});
}
}
private void updateUI(FirebaseUser user) {
if (user != null) {
session.createLoginSession(etUsername.getText().toString(), "");
} else {
}
}
}
| 43.609649
| 135
| 0.522579
|
8b5f86c01ecc276ef7e69a6713b472d40b633b31
| 576
|
package edu.fudan.eservice.common.utils;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class ThreadPoolHelper {
private static ThreadPoolHelper tph=null;
private static ScheduledExecutorService sch=null;
protected ThreadPoolHelper()
{
sch=Executors.newScheduledThreadPool(20);
}
public static synchronized ThreadPoolHelper getInstance()
{
if(tph==null)
tph=new ThreadPoolHelper();
return tph;
}
public ScheduledExecutorService getSchPool()
{
return sch;
}
}
| 19.2
| 59
| 0.734375
|
2fdd620d7f803353c49e6ea9e9ac1de4a3854a8b
| 7,379
|
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.view.rest;
import static com.opengamma.lambdava.streams.Lambdava.merge;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.UriBuilder;
import org.threeten.bp.Instant;
import com.opengamma.core.position.Portfolio;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.depgraph.DependencyGraph;
import com.opengamma.engine.depgraph.DependencyGraphExplorer;
import com.opengamma.engine.function.FunctionParameters;
import com.opengamma.engine.marketdata.manipulator.DistinctMarketDataSelector;
import com.opengamma.engine.target.ComputationTargetReference;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.engine.view.ViewDefinition;
import com.opengamma.engine.view.compilation.CompiledViewCalculationConfiguration;
import com.opengamma.engine.view.compilation.CompiledViewDefinition;
import com.opengamma.engine.view.compilation.CompiledViewDefinitionWithGraphs;
import com.opengamma.id.UniqueId;
import com.opengamma.id.VersionCorrection;
import com.opengamma.util.rest.FudgeRestClient;
/**
* Remote implementation of {@link CompiledViewDefinition}.
*/
public class RemoteCompiledViewDefinitionWithGraphs implements CompiledViewDefinitionWithGraphs {
private final URI _baseUri;
private final FudgeRestClient _client;
public RemoteCompiledViewDefinitionWithGraphs(final URI baseUri) {
_baseUri = baseUri;
_client = FudgeRestClient.create();
}
private RemoteCompiledViewDefinitionWithGraphs(final URI baseUri, final FudgeRestClient client) {
_baseUri = baseUri;
_client = client;
}
@Override
public VersionCorrection getResolverVersionCorrection() {
throw new UnsupportedOperationException("TODO: Implement this method over REST");
}
@Override
public String getCompilationIdentifier() {
throw new UnsupportedOperationException("TODO: Implement this method over REST");
}
@Override
public CompiledViewDefinitionWithGraphs withResolverVersionCorrection(final VersionCorrection versionCorrection) {
return new RemoteCompiledViewDefinitionWithGraphs(_baseUri, _client) {
@Override
public VersionCorrection getResolverVersionCorrection() {
return versionCorrection;
}
};
}
@Override
public CompiledViewDefinitionWithGraphs withMarketDataManipulationSelections(Map<DependencyGraph, Map<DistinctMarketDataSelector, Set<ValueSpecification>>> selectionsByGraph,
Map<DependencyGraph, Map<DistinctMarketDataSelector, FunctionParameters>> paramsByGraph) {
throw new UnsupportedOperationException("TODO: Implement this method over REST");
}
@Override
public ViewDefinition getViewDefinition() {
final URI uri = UriBuilder.fromUri(_baseUri).path(DataCompiledViewDefinitionResource.PATH_VIEW_DEFINITION).build();
return _client.accessFudge(uri).get(ViewDefinition.class);
}
@Override
public Portfolio getPortfolio() {
final URI uri = UriBuilder.fromUri(_baseUri).path(DataCompiledViewDefinitionResource.PATH_PORTFOLIO).build();
return _client.accessFudge(uri).get(Portfolio.class);
}
@Override
public CompiledViewCalculationConfiguration getCompiledCalculationConfiguration(final String viewCalculationConfiguration) {
final URI baseUri = UriBuilder.fromUri(_baseUri).path(DataCompiledViewDefinitionResource.PATH_COMPILED_CALCULATION_CONFIGURATIONS).build();
final URI uri = DataCompiledViewDefinitionResource.uriCompiledCalculationConfiguration(baseUri, viewCalculationConfiguration);
return _client.accessFudge(uri).get(CompiledViewCalculationConfiguration.class);
}
@SuppressWarnings("unchecked")
@Override
public Collection<CompiledViewCalculationConfiguration> getCompiledCalculationConfigurations() {
final URI uri = UriBuilder.fromUri(_baseUri).path(DataCompiledViewDefinitionResource.PATH_COMPILED_CALCULATION_CONFIGURATIONS).build();
return _client.accessFudge(uri).get(List.class);
}
@SuppressWarnings("unchecked")
@Override
public Map<String, CompiledViewCalculationConfiguration> getCompiledCalculationConfigurationsMap() {
final URI uri = UriBuilder.fromUri(_baseUri).path(DataCompiledViewDefinitionResource.PATH_COMPILED_CALCULATION_CONFIGURATIONS_MAP).build();
return _client.accessFudge(uri).get(Map.class);
}
@SuppressWarnings("unchecked")
@Override
public Set<ValueSpecification> getMarketDataRequirements() {
final URI uri = UriBuilder.fromUri(_baseUri).path(DataCompiledViewDefinitionResource.PATH_MARKET_DATA_REQUIREMENTS).build();
return _client.accessFudge(uri).get(Set.class);
}
@SuppressWarnings("unchecked")
@Override
public Set<ComputationTargetSpecification> getComputationTargets() {
final URI uri = UriBuilder.fromUri(_baseUri).path(DataCompiledViewDefinitionResource.PATH_COMPUTATION_TARGETS).build();
return _client.accessFudge(uri).get(Set.class);
}
@Override
public Instant getValidFrom() {
final URI uri = UriBuilder.fromUri(_baseUri).path(DataCompiledViewDefinitionResource.PATH_VALID_FROM).build();
return _client.accessFudge(uri).get(Instant.class);
}
@Override
public Instant getValidTo() {
final URI uri = UriBuilder.fromUri(_baseUri).path(DataCompiledViewDefinitionResource.PATH_VALID_TO).build();
return _client.accessFudge(uri).get(Instant.class);
}
@Override
public Collection<DependencyGraphExplorer> getDependencyGraphExplorers() {
final Collection<CompiledViewCalculationConfiguration> configurations = getCompiledCalculationConfigurations();
final List<DependencyGraphExplorer> explorers = new ArrayList<DependencyGraphExplorer>(configurations.size());
for (CompiledViewCalculationConfiguration configuration : configurations) {
explorers.add(getDependencyGraphExplorer(configuration.getName()));
}
return explorers;
}
@Override
public DependencyGraphExplorer getDependencyGraphExplorer(final String calcConfig) {
final URI uri = UriBuilder.fromUri(_baseUri).path(DataCompiledViewDefinitionResource.PATH_GRAPHS).path(calcConfig).build();
return new RemoteDependencyGraphExplorer(uri);
}
@Override
public Map<ComputationTargetReference, UniqueId> getResolvedIdentifiers() {
throw new UnsupportedOperationException("TODO: Implement this method over REST");
}
@Override
public Map<ValueSpecification, Set<ValueRequirement>> getTerminalValuesRequirements() {
final Map<ValueSpecification, Set<ValueRequirement>> terminalValuesRequirements = new HashMap<ValueSpecification, Set<ValueRequirement>>();
final Collection<CompiledViewCalculationConfiguration> compiledCalculationConfigurations = getCompiledCalculationConfigurations();
for (final CompiledViewCalculationConfiguration compiledCalculationConfiguration : compiledCalculationConfigurations) {
merge(terminalValuesRequirements, compiledCalculationConfiguration.getTerminalOutputSpecifications());
}
return terminalValuesRequirements;
}
}
| 42.653179
| 176
| 0.801057
|
798b240c2329eff7f38434c0444384ca83d94d6c
| 105
|
/**
* Events used for notifying the model and view of changes.
*/
package com.oskopek.transport.event;
| 21
| 59
| 0.733333
|
e8f1153cdf7538de4a30fdbcfb4a03bf2635fadc
| 4,827
|
package com.yz.video;
import java.io.File;
import java.util.List;
public class ConvertVideo {
// 原始文件
private String videoPath;
// 目标文件
private String targetPath;
public ConvertVideo(String videoPath, String targetPath) {
this.videoPath = videoPath;
this.targetPath = targetPath;
}
public synchronized void process() {
int type = checkContentType();
if (type == 0) {
this.ffmpegTransVideo();
} else if (type == 1) {
this.mencoderTransVideo();
}
}
public synchronized int checkContentType() {
String type = videoPath.substring(videoPath.lastIndexOf(".") + 1,
videoPath.length()).toLowerCase();
// ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)
if (type.equals("avi")) {
return 0;
} else if (type.equals("mpg")) {
return 0;
} else if (type.equals("wmv")) {
return 0;
} else if (type.equals("3gp")) {
return 0;
} else if (type.equals("mov")) {
return 0;
} else if (type.equals("mp4")) {
return 0;
} else if (type.equals("asf")) {
return 0;
} else if (type.equals("asx")) {
return 0;
} else if (type.equals("flv")) {
return 0;
}
// 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),
// 可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式.
else if (type.equals("wmv9")) {
return 1;
} else if (type.equals("rm")) {
return 1;
} else if (type.equals("rmvb")) {
return 1;
}
return 9;
}
public synchronized static boolean checkfile(String path) {
File file = new File(path);
if (!file.isFile()) {
return false;
}
return true;
}
/**
* 使用mencoder转码
*
* @param videoPath
* 源路径 -- 要转换的视频文件
* @param targetPath
* 目标路径 -- 转换后的视频flv
* @return 返回目标路径
*/
public synchronized String mencoderTransVideo() {
List<String> commend = new java.util.ArrayList<String>();
commend.add("d:\\importentDCHCFile\\videoConvert\\mencoder.exe");
commend.add(videoPath);
// 音频采用mp3编码
commend.add("-oac");
commend.add("mp3lame");
// 采用高质DivX视频编码,视频码率为112kbps
commend.add("-ovc");
commend.add("lavc");
commend.add("-lavcopts");
commend
.add("vcodec=flv:vbitrate=500:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:dia=-1:cmp=3:vb_strategy=1");
commend.add("-lameopts");
commend.add("abr:br=56");
// 声音采样频率设置,现为22K
commend.add("-srate");
commend.add("22050");
// -sws就是用来设置品质的,默认值为2
commend.add("-sws");
commend.add("3");
// 宽度为208,高度自动调整保持比例;
// -vf scale=-3:176宽度自动调整保持比例,高度为176;如果想保持原来的大小可以不要这个参数
commend.add("-vf");
commend.add("scale=512:-3");
// 帧速率设置
commend.add("-ofps");
commend.add("18");
/*
* mode=3:cbr:br=24单声道 音频码率为24kbps;-lameopts
* mode=0:cbr:br=24立体声,音频码率为24kbps; 还可设置音量,-lameopts
* mode=3:cbr:br=32:vol=1,设置范置为1~10,但不宜设得太高
*/
commend.add("-lameopts");
commend.add("vbr=3:br=128");
commend.add("-o");
commend.add(targetPath);
// 控制台显示执行的命令
// System.out.println(commend);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.start();
return targetPath;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public synchronized String ffmpegTransVideo() {
List<String> commend = new java.util.ArrayList<String>();
commend.add("d:\\importentDCHCFile\\videoConvert\\ffmpeg.exe");
commend.add("-i");
commend.add(videoPath);
commend.add("-vcodec");
commend.add("h264");
commend.add("-ab");
commend.add("64");
// commend.add(" -acodec ");
// commend.add("codec");
commend.add("-ac");
commend.add("2");
commend.add("-ar");
commend.add("22050");
// 清晰度 -qscale 4 为最好可是文件大, -qscale 6就可以了
commend.add("-qscale");
commend.add("6");
// commend.add("-b");
// commend.add("768");
// commend.add("230");
// commend.add("-s");
// commend.add("352x240");
// commend.add("-r");
// commend.add("29.97");
commend.add("-f");
commend.add("mp4");
commend.add("-y");
commend.add(targetPath);
System.out.println(commend);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.start();
return targetPath;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// 生成图片 参数String newfilename, String newimg
public synchronized boolean ffmpegTransImage() {
List<String> commend = new java.util.ArrayList<String>();
commend.add("d:\\videoConvert\\ffmpeg.exe");
commend.add("-i");
commend.add("d:\\test\\a.mpg");
commend.add("-y");
commend.add("-f");
commend.add("image2");
commend.add("-ss");
commend.add("38");
commend.add("-t");
commend.add("0.001");
commend.add("-s");
commend.add("320x240");
commend.add("d:\\test\\b.jpg");
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.start();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
| 23.778325
| 100
| 0.633105
|
88bc40a58093a42d86e3fb9f45aaa19ce1502672
| 710
|
package Example16_20__BigInteger;
import java.math.BigDecimal;
/**
* Created by User on 22/05/2017.
*/
public class Example20 {
public static void main(String[] args) {
BigDecimal e = new BigDecimal("1");
for (int i = 1; i <= 1000; i++) {
e = e.add(new BigDecimal("1").divide(factorial(new BigDecimal(i + "")), 25, BigDecimal.ROUND_UP));
}
System.out.println(e);
}
public static BigDecimal factorial(BigDecimal d) {
BigDecimal e = new BigDecimal("1");
long lo = d.longValue();
for (long i = 1; i <= lo; i++) {
e = e.multiply(new BigDecimal(i));
}
return e;
}
}
| 24.482759
| 111
| 0.533803
|
0b16a4ff4a697aa22702b77e8b039f1b1dc1d425
| 1,629
|
package regalowl.simpledatalib.sql;
import static org.junit.Assert.*;
import org.junit.Test;
import regalowl.simpledatalib.SimpleDataLib;
import regalowl.simpledatalib.TestLogger;
import regalowl.simpledatalib.sql.Field;
import regalowl.simpledatalib.sql.FieldType;
import regalowl.simpledatalib.sql.SQLManager;
import regalowl.simpledatalib.sql.Table;
public class TestWriteAndRead {
@Test
public void testCreateShutdownAndLoad() {
SimpleDataLib sdl = new SimpleDataLib("test");
sdl.initialize();
sdl.setDebug(true);
new TestLogger(sdl);
SQLManager sm = sdl.getSQLManager();
sm.setWriteTaskInterval(1L);
sm.createDatabase();
SQLWrite sw = sm.getSQLWrite();
Table t = sm.addTable("hyperconomy_object_data");
Field f = t.addField("ID", FieldType.INTEGER);f.setPrimaryKey();f.setAutoIncrement();
f = t.addField("DATA", FieldType.TEXT);
sm.saveTables();
sw.writeSync(true);
String statement = "DELETE FROM hyperconomy_object_data";
sw.addToQueue(statement);
sw.writeSyncQueue();
sw.writeSync(false);
statement = "INSERT INTO hyperconomy_object_data (ID, DATA) VALUES ('" + 1 + "', ?)";
WriteStatement ws = new WriteStatement(statement, sdl);
ws.addParameter("test");
sw.addToQueue(ws);
sm.shutDown();
sdl.initialize();
sdl.setDebug(true);
new TestLogger(sdl);
sm = sdl.getSQLManager();
sm.createDatabase();
SQLRead sr = sm.getSQLRead();
QueryResult qr = sr.select("SELECT * FROM hyperconomy_object_data WHERE ID = '1'");
qr.next();
assertTrue(qr.getString("DATA").equals("test"));
}
}
| 28.578947
| 88
| 0.699816
|
ebc7a6ae0b9e43daae1acb3d939a0f260d3c531c
| 4,936
|
package com.extend.dubbo.filter;
import com.extend.common.constant.CommonConstant;
import com.extend.common.exception.BaseException;
import com.extend.core.config.MessageResourcesManage;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.service.GenericService;
import java.lang.reflect.Method;
/**
* ExceptionFilter.
*
* @author KevinClair
*/
@Slf4j
@Activate(group = CommonConstants.PROVIDER)
public class ExceptionFilter implements Filter, Filter.Listener {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
if (appResponse.hasException() && GenericService.class != invoker.getInterface()) {
try {
Throwable exception = appResponse.getException();
// directly throw if it's checked exception
if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) {
return;
}
// directly throw if the exception appears in the signature
try {
Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
Class<?>[] exceptionClassses = method.getExceptionTypes();
for (Class<?> exceptionClass : exceptionClassses) {
if (exception.getClass().equals(exceptionClass)) {
return;
}
}
} catch (NoSuchMethodException e) {
return;
}
// for the exception not found in method's signature, print ERROR message in server's log.
log.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception);
// directly throw if exception class and interface class are in the same jar file.
String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface());
String exceptionFile = ReflectUtils.getCodeBase(exception.getClass());
if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) {
return;
}
// directly throw if it's JDK exception
String className = exception.getClass().getName();
if (className.startsWith("java.") || className.startsWith("javax.")) {
return;
}
// directly throw if it's dubbo exception
if (exception instanceof RpcException) {
return;
}
// directly throw if it's BaseException or ValidationException
if (exception instanceof BaseException) {
String message = MessageResourcesManage.getMessage(RpcContext.getContext().getAttachment(CommonConstant.LANGUAGE), exception.getMessage());
appResponse.setException(new BaseException(((BaseException) exception).getCode(), StringUtils.isBlank(message) ? exception.getMessage() : message, ((BaseException) exception).getStatus()));
return;
}
// otherwise, wrap with RuntimeException and throw back to the client
appResponse.setException(new RuntimeException(StringUtils.toString(exception)));
} catch (Throwable e) {
log.warn("Fail to ExceptionFilter when called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
}
}
}
@Override
public void onError(Throwable e, Invoker<?> invoker, Invocation invocation) {
log.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
}
}
| 51.416667
| 316
| 0.630875
|
a2d060af26a6f10b10cc0bf0ed86e1ba0ad11fdc
| 1,508
|
package com.kahzerx.rubik.discord.commands;
import com.kahzerx.rubik.discord.utils.DiscordPermission;
import com.kahzerx.rubik.discord.utils.DiscordUtils;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.minecraft.server.MinecraftServer;
public class WList extends Commands {
public WList() {
super.setCBody("list");
super.setPermission(DiscordPermission.WHITELIST_CHAT);
}
@Override
public void execute(final MessageReceivedEvent event, final MinecraftServer server) {
if (DiscordUtils.isAllowed(this.getPermission(), event.getChannel().getIdLong())) {
String[] names = server.getPlayerManager().getWhitelistedNames();
if (names.length == 0) {
event.getChannel().sendMessage("Whitelist is empty").queue();
} else {
StringBuilder msg = new StringBuilder("`");
final int maxLength = 1500;
for (int i = 0; i < names.length - 1; i++) {
msg.append(names[i]);
if (msg.length() < maxLength) {
msg.append(", ");
} else {
event.getChannel().sendMessage(msg.append("`")).queue();
msg.setLength(0);
msg.append("`");
}
}
event.getChannel().sendMessage(msg.append(names[names.length - 1]).append("`")).queue();
}
}
}
}
| 39.684211
| 104
| 0.559682
|
2d43c4a70914640f6ccda7538a87ad59fc0b9c92
| 3,890
|
package org.hzero.autoconfigure.gateway.helper;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.client.RestTemplate;
import org.hzero.core.redis.RedisHelper;
import org.hzero.gateway.helper.api.AuthenticationHelper;
import org.hzero.gateway.helper.api.HelperFilter;
import org.hzero.gateway.helper.api.reactive.ReactiveAuthenticationHelper;
import org.hzero.gateway.helper.config.GatewayHelperProperties;
import org.hzero.gateway.helper.impl.DefaultAuthenticationHelper;
import org.hzero.gateway.helper.impl.HelperChain;
import org.hzero.gateway.helper.impl.reactive.DefaultReactiveAuthenticationHelper;
import org.hzero.gateway.helper.service.CustomPermissionCheckService;
import org.hzero.gateway.helper.service.SignatureService;
import org.hzero.gateway.helper.service.impl.DefaultCustomPermissionCheckService;
import org.hzero.gateway.helper.service.impl.DefaultSignatureService;
@ComponentScan(value = {
"org.hzero.gateway.helper"
})
@EnableCaching
@Configuration
@EnableAsync
@Order(SecurityProperties.BASIC_AUTH_ORDER)
public class GatewayHelperAutoConfiguration {
@Bean
public HelperChain helperChain(Optional<List<HelperFilter>> optionalHelperFilters){
return new HelperChain(optionalHelperFilters);
}
@Bean
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnMissingBean(AuthenticationHelper.class)
public DefaultAuthenticationHelper authenticationHelper(HelperChain helperChain) {
return new DefaultAuthenticationHelper(helperChain);
}
@Bean
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnMissingBean(ReactiveAuthenticationHelper.class)
public DefaultReactiveAuthenticationHelper reactiveAuthenticationHelper(HelperChain helperChain) {
return new DefaultReactiveAuthenticationHelper(helperChain);
}
@Bean(name = "helperRestTemplate")
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = GatewayHelperProperties.PREFIX, value = "signature.enabled", havingValue = "true")
public SignatureService signatureService(GatewayHelperProperties properties, RedisHelper redisHelper) {
return new DefaultSignatureService(properties, redisHelper);
}
@Bean
@Qualifier("permissionCheckSaveExecutor")
public AsyncTaskExecutor commonAsyncTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("ps-check-save-");
executor.setMaxPoolSize(200);
executor.setCorePoolSize(50);
return executor;
}
@Bean
@ConditionalOnMissingBean(CustomPermissionCheckService.class)
public CustomPermissionCheckService customPermissionCheckService() {
return new DefaultCustomPermissionCheckService();
}
}
| 41.827957
| 118
| 0.816195
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.