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
bb124d1190ba6b1fddc45d4d2617b5699105c755
480
package com.mediscreen.common.restclient; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.List; /** * A serializer to perform REST body serialization and deserialization in JSON. */ public interface RestSerializer { void serialize(Writer dst, Object value) throws IOException; <T> T deserialize(Reader src, Class<T> type) throws IOException; <T> List<T> deserializeList(Reader src, Class<T> type) throws IOException; }
26.666667
79
0.75625
924cbaa3e90e643c64266e1450073ba9c46a0c19
6,627
package com.andres.multiwork.pc.connection; import com.andres.multiwork.pc.GlobalValues; import jvisa.JVisa; import jvisa.JVisaException; import jvisa.JVisaReturnString; import visatype.VisatypeLibrary; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; @SuppressWarnings("FieldCanBeLocal") public class MultiConnectionManager { // Connections private BluetoothConnection bluetoothConnection; // Managers private ArrayList<ConnectionManager> managers = new ArrayList<>(); // Events private ArrayList<OnNewDataReceived> listeners = new ArrayList<>(); private final String bluetoothName = "linvor"; private final String instrumentString = "USB0::0x1AB1::0x0588::DS1ET164267347::INSTR"; /** Listener for incoming data from USB and Bluetooth */ private OnNewDataReceived dataReceiverListener = this::notifyListeners; private ConnectionManager.CaptureType currentCaptureType = null; private ConnectionManager.DeviceType currentDeviceType = null; public MultiConnectionManager() { // Add every ConnectionManager available managers.add(new BTLogicAnalyzerManager(null, null, dataReceiverListener)); managers.add(new RigolManager(dataReceiverListener)); } /** * Start a capture with the specified {@link com.andres.multiwork.pc.connection.ConnectionManager.CaptureType} */ public void startCapture(ConnectionManager.CaptureType captureType){ if(currentDeviceType == null || captureType == null) return; currentCaptureType = captureType; // Call the startCapture() method of managers with the specified captureType and with the deviceType of // the current connection managers.stream().filter(manager -> manager.getCaptureType() == currentCaptureType && manager.getDeviceType() == currentDeviceType ).forEach(ConnectionManager::startCapture); } public byte[] getData(ConnectionManager.CaptureType captureType){ for(ConnectionManager manager : managers){ if(manager.getDeviceType() == currentDeviceType && manager.getCaptureType() == currentCaptureType){ return manager.getData(); } } return new byte[0]; } public ConnectionManager.CaptureType getCurrentCaptureType() { return currentCaptureType; } public ConnectionManager.DeviceType getCurrentDeviceType() { return currentDeviceType; } /** * Add a listener when new incoming data is available * @param onNewDataReceived {@link com.andres.multiwork.pc.connection.OnNewDataReceived} to be added */ public void addDataReceivedListener(OnNewDataReceived onNewDataReceived){ listeners.add(onNewDataReceived); } /** * Remove the specified listener * @param onNewDataReceived {@link com.andres.multiwork.pc.connection.OnNewDataReceived} to remove */ public void removeDataReceivedListener(OnNewDataReceived onNewDataReceived){ listeners.remove(onNewDataReceived); } public void closeConnection(){ bluetoothConnection.closeConnection(); } /** Notify to all registered listener of new incoming data */ private void notifyListeners(byte[] data, ConnectionManager.CaptureType captureType, ConnectionManager.DeviceType deviceType){ for(OnNewDataReceived listener : listeners){ listener.onNewDataReceived(data, captureType, deviceType); } } /** * Connect using Bluetooth */ public void connectByBluetooth(){ bluetoothConnection = new BluetoothConnection(new BluetoothEvent() { @Override public void onBluetoothConnected(InputStream inputStream, OutputStream outputStream) { currentDeviceType = ConnectionManager.DeviceType.BLUETOOTH; for(ConnectionManager manager : managers){ if(manager.getDeviceType() == currentDeviceType){ manager.setStreams(outputStream, inputStream); } } } @Override public void onBluetoothDataReceived(InputStream inputStream, OutputStream outputStream) { for(ConnectionManager manager : managers){ if(manager.getDeviceType() == currentDeviceType && manager.getCaptureType() == currentCaptureType){ manager.onNewDataReceived(inputStream, outputStream); } } } }); bluetoothConnection.startConnection(bluetoothName); } public void connectByUSB(){ //TODO: USB connection currentDeviceType = ConnectionManager.DeviceType.USB; } public void connectWithOscilloscope() throws JVisaException{ JVisa jVisa = new JVisa(); long status = jVisa.openDefaultResourceManager(); if(status != VisatypeLibrary.VI_SUCCESS){ throw new JVisaException("Could not create session for resource manager."); } status = jVisa.openInstrument(instrumentString); if(status != VisatypeLibrary.VI_SUCCESS){ throw new JVisaException("Could not open instrument session for " + instrumentString); } jVisa.write("*IDN?"); JVisaReturnString r = new JVisaReturnString(); jVisa.read(r); String[] scopeInfo = r.returnString.split(","); if(scopeInfo.length >= 4) { System.out.println("Company: " + scopeInfo[0]); System.out.println("Model: " + scopeInfo[1]); System.out.println("Serial Number: " + scopeInfo[2]); System.out.println("Software Version: " + scopeInfo[3]); }else { throw new JVisaException("Could not communicate with " + instrumentString); } currentDeviceType = ConnectionManager.DeviceType.RIGOL_SCOPE; managers.stream().filter(manager -> manager.getDeviceType() == currentDeviceType).forEach(manager -> manager.setStreams(jVisa, jVisa)); } public long getCurrentSampleRate(){ if(getCurrentDeviceType() != ConnectionManager.DeviceType.RIGOL_SCOPE) return GlobalValues.xmlSettings.getInt("sampleRate", 4000000); else { for(ConnectionManager manager : managers){ if(manager.getDeviceType() == currentDeviceType){ return ((RigolManager)manager).getScope().getSampleFrequency(); } } } return -1; } }
38.982353
143
0.661234
7c5ae113e47340a036d076b6151bfac827dc8adb
1,109
package com.mishin870.exforbidden.thaumcraftcomp; import com.mishin870.exforbidden.Main; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; /** * База для всех блоков, хранящих эссенции Thaumcraft * по механизму ExForbidden */ public class EssentiaContainer extends Block implements ITileEntityProvider { public EssentiaContainer(String unlocName) { super(Material.rock); this.setBlockName(unlocName); this.setBlockTextureName(Main.MODID + ":" + unlocName); this.setCreativeTab(Main.eftab); this.setHardness(2.0f); } @Override public TileEntity createNewTileEntity(World w, int p_149915_2_) { return new TileEntityEssentiaContainer(); } /*@Override public boolean onBlockActivated(World w, int x, int y, int z, EntityPlayer e, int p_149727_6_, float p_149727_7_, float p_149727_8_, float p_149727_9_) { TileEntityAlvearyLighter te = (TileEntityAlvearyLighter) w.getTileEntity(x, y, z); te.trace(); return true; }*/ }
29.972973
154
0.779982
71942cfc9d0babc7f52660470d9922cd1d9ddc50
744
package com.milo.ms.services.inventory; import com.milo.ms.bootstrap.BeerLoader; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @Disabled // utility for manual testing @SpringBootTest class BeerInventoryServiceRestTemplateImplTest { @Autowired BeerInventoryService beerInventoryService; @BeforeEach void setUp() { } @Test void getOnhandInventory() { // todo improve with upc // Integer qoh = beerInventoryService.getOnHandInventory(BeerLoader.BEER_1_UUID); // // System.out.println(qoh); } }
24.8
88
0.751344
c2acba3327ecd2cfa5469e88a0138ed8b383d04a
210
package com.stnetix.cloudraid.api.exception; /** * Exception on some action with CloudRaidAPI * * @author Cloudraid Dev Team (cloudraid.stnetix.com) */ public class CloudApiException extends Exception { }
21
53
0.761905
b9ed5c5b440324e40b17a65e069bdb528127f451
2,084
package dfa.framework; import java.util.Map; import java.util.Set; import soot.Unit; import soot.toolkits.graph.Block; /** * A {@code CompositeDataFlowAnalysis} combines a {@code Join}, a {@code Transition} and an {@code Initializer} into a * {@code DataFlowAnalysis}. * * @param <E> * the type of {@code LatticeElement} used in this {@code CompositeDataFlowAnalysis} * * @author Sebastian Rauch * */ public class CompositeDataFlowAnalysis<E extends LatticeElement> implements DataFlowAnalysis<E> { private Join<E> join; private Transition<E> transition; private Initializer<E> initializer; /** * Creates a {@code CompositeDataFlowAnalysis} from a {@code Join} and a {@code Transition}. * * @param join * the {@code Join} to use to perform {@code transition} * @param transition * the {@code Transition} to use perform {@code join} * @param initializer * the {@code Initializer} used to initialize the analysis * * @throws IllegalArgumentException * if {@code join} or {@code transition} or {@code initializer} is {@code null} */ public CompositeDataFlowAnalysis(Join<E> join, Transition<E> transition, Initializer<E> initializer) { if (join == null) { throw new IllegalArgumentException("join must not be null"); } if (transition == null) { throw new IllegalArgumentException("transition must not be null"); } if (initializer == null) { throw new IllegalArgumentException("initializer must not be null"); } this.join = join; this.transition = transition; this.initializer = initializer; } @Override public E transition(E element, Unit unit) { return transition.transition(element, unit); } @Override public E join(Set<E> elements) { return join.join(elements); } @Override public Map<Block, BlockState<E>> getInitialStates() { return initializer.getInitialStates(); } }
28.944444
118
0.636756
4f2e3230c7cdb003e2392ae5e0d1f499e8a06e65
319
package lanse505.renaissance.utils.inventory; import net.minecraft.item.ItemStack; public interface IUpdatingInventory { /** * Method called when a slot is updated * * @param slot Slot being updated * @param stack stack being updated */ void updateSlot(int slot, ItemStack stack); }
22.785714
47
0.69279
eb2bfca28791d390b74ace77bb355d7f0e825807
754
package com.is.smartlight.utility; import com.is.smartlight.models.DefaultPresetsData; import com.is.smartlight.services.DefaultPresetService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class DataLoader implements ApplicationRunner { private final DefaultPresetService defaultPresetService; @Autowired public DataLoader(DefaultPresetService defaultPresetService) { this.defaultPresetService = defaultPresetService; } public void run(ApplicationArguments args) { defaultPresetService.loadDefaultPresetsOnStartup(); } }
32.782609
66
0.816976
290bafaebf9bf85de99cf8f169140011475f362c
1,058
package com.noobanidus.brazier.util; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; import javax.annotation.Nonnull; public class ItemStackWrapper implements IItemHandler { private int index; private IItemHandler handler; public ItemStackWrapper (int index, IItemHandler handler) { this.index = index; this.handler = handler; } @Override public int getSlots () { return 1; } @Nonnull @Override public ItemStack getStackInSlot (int slot) { return this.handler.getStackInSlot(this.index); } @Nonnull @Override public ItemStack insertItem (int slot, @Nonnull ItemStack stack, boolean simulate) { return this.handler.insertItem(this.index, stack, simulate); } @Nonnull @Override public ItemStack extractItem (int slot, int amount, boolean simulate) { return this.handler.extractItem(this.index, amount, simulate); } @Override public int getSlotLimit (int slot) { ItemStack cur = this.getStackInSlot(0); if (!cur.isEmpty()) { return cur.getMaxStackSize(); } return 64; } }
21.591837
85
0.746692
592beac525ed9e10a74a22efd9507b82f37afb69
1,185
package com.zhongweixian.excel.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author caoliang1918@aliyun.com * @Date 2017/11/4:22:32 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Excel { String databaseFormat() default "yyyyMMddHHmmss"; String exportFormat() default ""; String importFormat() default ""; String format() default ""; String numFormat() default ""; double height() default 10.0D; int imageType() default 1; String suffix() default ""; boolean isWrap() default true; int[] mergeRely() default {}; boolean mergeVertical() default false; String name(); String groupName() default ""; boolean needMerge() default false; String orderNum() default "0"; String[] replace() default {}; String savePath() default "upload"; int type() default 1; double width() default 10.0D; boolean isStatistics() default false; boolean isHyperlink() default false; String isImportField() default "false"; }
19.42623
53
0.688608
58d8bf02802bdf131a8b72602a97b8ed66d18a24
5,501
package at.tuwien.ifs.somtoolbox.visualization; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.logging.Logger; import at.tuwien.ifs.somtoolbox.layers.LayerAccessException; import at.tuwien.ifs.somtoolbox.layers.Unit; import at.tuwien.ifs.somtoolbox.layers.quality.QeMqeDifference; import at.tuwien.ifs.somtoolbox.layers.quality.QualityMeasureNotFoundException; import at.tuwien.ifs.somtoolbox.models.GrowingSOM; /** * Creates the visualizations for the difference between the quantization error and the mean quantization error. * * @author Stefan Belk * @author Herbert Pajer * @version $Id: */ public class QeMqeDifferenceVisualizer extends AbstractMatrixVisualizer implements QualityMeasureVisualizer { private QeMqeDifference diffQeMqe = null; public QeMqeDifferenceVisualizer() { NUM_VISUALIZATIONS = 4; VISUALIZATION_NAMES = new String[] { "Difference QE/MQE", "Difference QE/MQE - Logarithmic ", "Difference QE/MQE - Squared ", "Difference QE/MQE - Exponential " }; VISUALIZATION_SHORT_NAMES = VISUALIZATION_NAMES; VISUALIZATION_DESCRIPTIONS = VISUALIZATION_NAMES; neededInputObjects = null; } @Override public BufferedImage createVisualization(int index, GrowingSOM gsom, int width, int height) { if (diffQeMqe == null) { diffQeMqe = new QeMqeDifference(gsom.getLayer(), null); } switch (index) { case 0: { return createImage(gsom, width, height, QeMqeDifference.DIFF_QE_MQE); } case 1: { return createImage(gsom, width, height, QeMqeDifference.LOG_DIFF_QE_MQE); } case 2: { return createImage(gsom, width, height, QeMqeDifference.SQUARE_DIFF_QE_MQE); } case 3: { return createImage(gsom, width, height, QeMqeDifference.EXP_DIFF_QE_MQE); } default: { return null; } } } /** * Applies min-max normalization to the supplied value. * * @param val The value that shall be normalized. * @param max The maximum of all corresponding values. * @param min The minimum of all corresponding values. * @return The normalized value. */ private double normalize(double val, double max, double min) { return (val - min) / (max - min); } /** * @param gsom A GrowingSOM. * @param width Width of the image. * @param height Height of the image. * @param visualType Type of the visualization: "diff_qe_mqe", "log_diff_qe_mqe", "square_diff_qe_mqe", * "exp_diff_qe_mqe" * @return A BufferedImage. */ private BufferedImage createImage(GrowingSOM gsom, int width, int height, String visualType) { double maxDiff = Double.MIN_VALUE; double minDiff = Double.MAX_VALUE; double[][] unitQualities; try { unitQualities = diffQeMqe.getUnitQualities(visualType); } catch (QualityMeasureNotFoundException e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(e.getMessage()); return null; } // find the maximum and minimum for normalization for (int j = 0; j < gsom.getLayer().getYSize(); j++) { for (int i = 0; i < gsom.getLayer().getXSize(); i++) { try { Unit u = gsom.getLayer().getUnit(i, j); if (u.getNumberOfMappedInputs() > 0) { double quality = unitQualities[u.getXPos()][u.getYPos()]; if (quality > maxDiff) { maxDiff = quality; } if (quality < minDiff) { minDiff = quality; } } } catch (LayerAccessException e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(e.getMessage()); } } } maximumMatrixValue = maxDiff; minimumMatrixValue = minDiff; // create the image BufferedImage res = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) res.getGraphics(); int unitWidth = width / gsom.getLayer().getXSize(); int unitHeight = height / gsom.getLayer().getYSize(); int ci = 0; for (int y = 0; y < gsom.getLayer().getYSize(); y++) { for (int x = 0; x < gsom.getLayer().getXSize(); x++) { try { Unit u = gsom.getLayer().getUnit(x, y); if (u.getNumberOfMappedInputs() > 0) { double d = unitQualities[u.getXPos()][u.getYPos()]; ci = (int) Math.round(normalize(d, maxDiff, minDiff) * palette.maxColourIndex()); g.setPaint(palette.getColor(ci)); } else { g.setPaint(Color.WHITE); } g.setColor(null); g.fill(new Rectangle(x * unitWidth, y * unitHeight, unitWidth, unitHeight)); } catch (LayerAccessException e) { Logger.getLogger("at.tuwien.ifs.somtoolbox").severe(e.getMessage()); } } } return res; } }
37.937931
112
0.574805
91da78f185c41129c52d4b47f70f9e880b747ff4
1,367
package org.healtex.batch.writer; import org.healtex.model.AnnotatedDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemWriter; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.List; public class DeidentifiedDocumentWriter implements ItemWriter<AnnotatedDocument> { private static final Logger LOG = LoggerFactory.getLogger(DeidentifiedDocumentWriter.class); private String outputPath; private String gazetteersPath; public DeidentifiedDocumentWriter(String outputPath, String gazetteersPath) { this.outputPath = outputPath; this.gazetteersPath = gazetteersPath; } @Override public final void write(List<? extends AnnotatedDocument> documents) throws Exception { // Write results to documents for (AnnotatedDocument doc : documents) { try (BufferedWriter bw = new BufferedWriter(new FileWriter( new File(outputPath + File.separator + doc.getFileName().concat(".xml"))))) { bw.write(doc.toXml()); } try (BufferedWriter bw = new BufferedWriter(new FileWriter( new File(outputPath + File.separator + doc.getFileName())))) { bw.write(doc.getScrubbedText()); } } } }
32.547619
97
0.684711
a2fe749dbed69375932d8ceb0df5ddadfd0fec37
1,118
package fr.thesmyler.terramap.gui.screens; import fr.thesmyler.smylibgui.screen.Screen; import fr.thesmyler.smylibgui.widgets.buttons.TextButtonWidget; import fr.thesmyler.smylibgui.widgets.text.TextAlignment; import fr.thesmyler.smylibgui.widgets.text.TextWidget; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.common.FMLCommonHandler; public class TerraDependencyErrorScreen extends Screen { @Override public void initScreen() { String txt = ""; for(int i=1; I18n.hasKey("terramap.terraerror.warn." + i); i++) { txt += I18n.format("terramap.terraerror.warn." + i) + "\n"; // There will be a new line at the end, but this is fine } TextWidget txtWidget = new TextWidget(txt, this.width/2, this.height/2, 10, TextAlignment.CENTER, true, this.getFont()); txtWidget.setAnchorY((this.getHeight() - txtWidget.getHeight()) / 2); this.addWidget(txtWidget); this.addWidget(new TextButtonWidget(this.width / 2 - 75, txtWidget.getY() + txtWidget.getHeight(), 10, 150, I18n.format("terramap.terraerror.closegame"), () -> FMLCommonHandler.instance().exitJava(1, false))); } }
43
211
0.749553
96f34afd06a64c02ac8c0b2d5568ca4d777ef12f
3,180
/* * Copyright 2013 gitblit.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.gitblit.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gitblit.Keys; import com.gitblit.dagger.DaggerServlet; import com.gitblit.manager.IRuntimeManager; import dagger.ObjectGraph; /** * Handles requests for logo.png * * @author James Moger * */ public class LogoServlet extends DaggerServlet { private static final long serialVersionUID = 1L; private static final long lastModified = System.currentTimeMillis(); private IRuntimeManager runtimeManager; @Override protected void inject(ObjectGraph dagger) { this.runtimeManager = dagger.get(IRuntimeManager.class); } @Override protected long getLastModified(HttpServletRequest req) { File file = runtimeManager.getFileOrFolder(Keys.web.headerLogo, "${baseFolder}/logo.png"); if (file.exists()) { return Math.max(lastModified, file.lastModified()); } else { return lastModified; } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InputStream is = null; try { String contentType = null; File file = runtimeManager.getFileOrFolder(Keys.web.headerLogo, "${baseFolder}/logo.png"); if (file.exists()) { // custom logo ServletContext context = request.getSession().getServletContext(); contentType = context.getMimeType(file.getName()); response.setContentLength((int) file.length()); response.setDateHeader("Last-Modified", Math.max(lastModified, file.lastModified())); is = new FileInputStream(file); } else { // default logo response.setDateHeader("Last-Modified", lastModified); is = getClass().getResourceAsStream("/logo.png"); } if (contentType == null) { contentType = "image/png"; } response.setContentType(contentType); response.setHeader("Cache-Control", "public, max-age=3600, must-revalidate"); OutputStream os = response.getOutputStream(); byte[] buf = new byte[4096]; int bytesRead = is.read(buf); while (bytesRead != -1) { os.write(buf, 0, bytesRead); bytesRead = is.read(buf); } os.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { is.close(); } } } }
30.285714
94
0.701572
2262c81afaee11a2cda04d6b38f017854d0ffee0
287
package com.bounce.atlas.pojo; import java.util.List; import java.util.Map; public class FencePojo { public List<PointPojo> points; public String color = "red"; public String fillColor = "#f03"; public double fillOpacity = 0.5; public Map<String, Object> data; }
19.133333
37
0.69338
aa55eb5a1a497d2f2a50b9e7969f81eb90d384f9
61,978
package com.springboot.environment.serviceImpl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.springboot.environment.bean.*; import com.springboot.environment.dao.*; import com.springboot.environment.request.ComprehensiveQueryRequest; import com.springboot.environment.request.QuerydDataByStationAreaReq; import com.springboot.environment.request.QueryhDataByStationAreaReq; import com.springboot.environment.request.QuerymDataByStationsAreaReq; import com.springboot.environment.service.StationService; import com.springboot.environment.util.DateUtil; import com.springboot.environment.util.StationConstant; import com.springboot.environment.util.StringUtil; import org.hibernate.event.service.spi.EventListenerGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpSession; import java.util.*; import java.text.SimpleDateFormat; @Transactional @Service public class StationServiceImpl implements StationService { @Autowired StationDao stationDao; @Autowired MDataDao mDataDao; @Autowired DDataDao dDataDao; @Autowired NormDao normDao; @Autowired HDataDao hDataDao; @Autowired GatherDao gatherDao; @Autowired GatherDataDao gatherDataDao; @Autowired LogOffLineDao logOffLineDao; @Autowired UserServiceImpl userServiceImpl; @Autowired RedisTemplate<String, String> redisTemplate; @Autowired MDataBasicDao mDataBasicDao; private static final Logger logger = LoggerFactory.getLogger(StationServiceImpl.class); @Autowired WarningServiceImp warningServiceImp; @Override public List<Station> findALl() { return stationDao.findAll(); } @Override public List<Station> queryStationsByCountryCon(int isCountryCon) { if (isCountryCon != StationConstant.STATION_IS_COUNTRY_CON && isCountryCon != StationConstant.STATION_ISNOT_COUNTRY_CON){ throw new RuntimeException(); } List<Station> stations = stationDao.findByCountryCon(isCountryCon); return stations; } @Override public List<Station> queryStationsByStatus(int stationStatus) { if (stationStatus != StationConstant.STATION_RUN && stationStatus != StationConstant.STATION_DISABLE){ throw new RuntimeException(); } List<Station> stations = stationDao.findByStationStatus(stationStatus); return stations; } @Override public List<Station> queryStationsByOnlineFlag(int onlineFlag) { if (onlineFlag != StationConstant.STATION_ONLINE && onlineFlag != StationConstant.STATION_OFFLINE){ throw new RuntimeException(); } List<Station> stations = stationDao.findByOnlineFlag(onlineFlag); return stations; } @Override public List<Station> queryStationsByNameLike(String stationName) { List<Station> stations = stationDao.findByStationNameLike(stationName); return stations; } @Override public List<Station> queryStationsByCodeLike(String stationCode) { return stationDao.finByStationCodeLike(stationCode); } @Override public List<Station> queryStationsByDistrict(String district) { List<Station> stations = stationDao.findByDistrict(district); return stations; } @Override public List<Station> queryStationsByStreet(String street) { List<Station> stations = stationDao.findByStreetLike(street); return stations; } @Override public List<Station> queryStationsByCityCon(int isCityCon) { if (isCityCon != StationConstant.STATION_IS_CITY_CON && isCityCon != StationConstant.STATION_ISNOT_CITY_CON){ throw new RuntimeException(); } List<Station> stations = stationDao.findByCityCon(isCityCon); return stations; } @Override public List<Station> queryStationsByDomainCon(int isDomainCon) { if (isDomainCon != StationConstant.STATION_IS_DOMAIN_CON && isDomainCon != StationConstant.STATION_ISNOT_DOMAIN_CON){ throw new RuntimeException(); } List<Station> stations = stationDao.findByDomainCon(isDomainCon); return stations; } @Override public List<Station> queryStationsByArea(int area) { List<Station> stations = stationDao.findByArea(area); return stations; } @Override public List<Station> queryStationsByDomain(int domain) { List<Station> stations = stationDao.findByDomain(domain); return stations; } @Transactional @Override public String addStation(String stationId, String stationCode, String stationName, String stationStatus, String application, String onlineFlag, String stationIdDZ, String protocol, String protocolName, String position, String street, String district, String range, String countryCon, String cityCon, String domainCon, String area, String domain) { Station station = new Station(); station.setStationId(stationId); station.setStationCode(stationCode); station.setStationName(stationName); station.setStationStatus(Integer.parseInt(stationStatus)); station.setApplication(application); station.setOnlineFlag(Integer.parseInt(onlineFlag)); station.setStationIdDZ(stationIdDZ); station.setProtocol(Integer.parseInt(protocol)); station.setProtocolName(protocolName); station.setPosition(position); station.setStreet(street); station.setDistrict(district); station.setRange(range); station.setCountryCon(Integer.parseInt(countryCon)); station.setCityCon(Integer.parseInt(cityCon)); station.setDomainCon(Integer.parseInt(domainCon)); station.setArea(Integer.parseInt(area)); station.setDomainCon(Integer.parseInt(domain)); System.out.println(station.toString()); Station result = stationDao.save(station); if (result != null){ return "新增成功"; } return "新增失败"; } @Override public String deleteStationByStationId(String stationId) { Station station = stationDao.findStationByStationId(stationId); if (station == null){ return "该站点信息不存在"; } stationDao.deleteByStationId(stationId); return "删除成功"; } @Override public Map getDomainFromStation() { Map<String, List> map = new LinkedHashMap<String, List>(); List<String> funcCodes=stationDao.getFuncCodes(); map.put("funcCodes",funcCodes); return map; } @Override public Map getStationsByAreasAndFuncCodes(Map<String, Object> params, String operation_id) { Map<String, List> map = new LinkedHashMap<String, List>(); Map<String,Object> query=(Map<String, Object>) params.get("query"); System.out.println(query); ArrayList areas=(ArrayList) query.get("areas"); ArrayList funcCodes=(ArrayList) query.get("funcCodes"); System.out.println(areas+" "+funcCodes); String areas_checkedAll=query.get("areas_checkedAll")+""; String funcCodes_checkedAll=query.get("funcCodes_checkedAll")+""; System.out.println(areas_checkedAll+" "+funcCodes_checkedAll); //List<Station> stationss=userServiceImpl.GetStationListByUser(); List<Map> innerMapList=new ArrayList<Map>(); if(areas_checkedAll.equals("false")){ //循环列表中的areas--不是全部的areas,需要遍历,然后判断funcCodes--不是全部的func,需要遍历 if(funcCodes_checkedAll.equals("false")){ for(int i=0;i<areas.size();i++){ List<Station> stations=stationDao.getAreasByAreasName(areas.get(i)); for (Station station:stations) { if(operation_id.equals("0")){ for(int j=0;j<funcCodes.size();j++){//从获得的stationslist中查找功能让区为get(j)的站点,并把这个站点加入到list中 if(funcCodes.get(j).equals((station.getDomain()+""))){ Map<String, String> innerMap = new LinkedHashMap<String, String>(); innerMap.put("station_id",station.getStationCode()); innerMap.put("station_name",station.getStationName()); innerMapList.add(innerMap); } } }else{ if(station.getOperation_id().equals(operation_id)){ for(int j=0;j<funcCodes.size();j++){//从获得的stationslist中查找功能让区为get(j)的站点,并把这个站点加入到list中 if(funcCodes.get(j).equals((station.getDomain()+""))){ Map<String, String> innerMap = new LinkedHashMap<String, String>(); innerMap.put("station_id",station.getStationCode()); innerMap.put("station_name",station.getStationName()); innerMapList.add(innerMap); } } } } } } }else{//列表中不是全部的areas,但是是全部的func for(int i=0;i<areas.size();i++){ List<Station> stations=stationDao.getAreasByAreasName(areas.get(i)); for (Station station:stations) { if(operation_id.equals("0")){ Map<String, String> innerMap = new LinkedHashMap<String, String>(); innerMap.put("station_id",station.getStationCode()); innerMap.put("station_name",station.getStationName()); innerMapList.add(innerMap); }else{ if(station.getOperation_id().equals(operation_id)){ Map<String, String> innerMap = new LinkedHashMap<String, String>(); innerMap.put("station_id",station.getStationCode()); innerMap.put("station_name",station.getStationName()); innerMapList.add(innerMap); } } } } } }else { //获取所有的areas,然后再判断funcCodes List<Station> stations=stationDao.findAll(); if(funcCodes_checkedAll.equals("false")){ for (Station station:stations) { if(operation_id.equals("0")){ for(int j=0;j<funcCodes.size();j++){//从获得的stationslist中查找功能让区为get(j)的站点,并把这个站点加入到list中 if(funcCodes.get(j).equals((station.getDomain()+""))){ Map<String, String> innerMap = new LinkedHashMap<String, String>(); innerMap.put("station_id",station.getStationCode()); innerMap.put("station_name",station.getStationName()); innerMapList.add(innerMap); } } }else{ /*System.out.println("stationCode666:::"+station.getStationCode()); System.out.println(station.getOperation_id().equals(operation_id)); System.out.println(station.getOperation_id()); System.out.println(operation_id);*/ if(station.getOperation_id().equals(operation_id)){ for(int j=0;j<funcCodes.size();j++){//从获得的stationslist中查找功能让区为get(j)的站点,并把这个站点加入到list中 if(funcCodes.get(j).equals((station.getDomain()+""))){ Map<String, String> innerMap = new LinkedHashMap<String, String>(); innerMap.put("station_id",station.getStationCode()); innerMap.put("station_name",station.getStationName()); innerMapList.add(innerMap); } } } //System.out.println(innerMapList); } } }else{ for (Station station:stations) { if(operation_id.equals("0")){ Map<String, String> innerMap = new LinkedHashMap<String, String>(); innerMap.put("station_id",station.getStationCode()); innerMap.put("station_name",station.getStationName()); innerMapList.add(innerMap); }else{ if(station.getOperation_id().equals(operation_id)){ Map<String, String> innerMap = new LinkedHashMap<String, String>(); innerMap.put("station_id",station.getStationCode()); innerMap.put("station_name",station.getStationName()); innerMapList.add(innerMap); } } } } } System.out.println(innerMapList.size()); map.put("stations",innerMapList); return map; } @Override public String queryStationsByKey(String key) { JSONObject dataJSON = new JSONObject(); JSONArray stationArray = new JSONArray(); List<Station> stations = null; //没有输入模糊值则查询失败 if (key == null || key.equals("")){ return null; } stations = stationDao.findStationsByIdAndNameLike(key); if (!StringUtil.isNullOrEmpty(stations)){ for (Station station : stations){ JSONObject stationJSON = new JSONObject(); stationJSON.put("station_id", station.getStationId()); stationJSON.put("station_name", station.getStationName()); stationJSON.put("station_code", station.getStationCode()); stationArray.add(stationJSON); } } dataJSON.put("stations", stationArray); System.out.println(dataJSON.toJSONString()); System.out.println(stations.size()); return dataJSON.toJSONString(); } @Override public String querymDataByStationArea(Map<String, Object> params, HttpSession session) { //方法开始时间 long startTime = System.currentTimeMillis(); Date nowDate = new Date(); JSONObject dataJson = new JSONObject(); JSONObject siteData = new JSONObject(); JSONArray dataArray = new JSONArray(); ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet(); ComprehensiveQueryRequest request = buildReq(params, session); List<Station> stations = comprehensiveQueryStations(request); int count = getComprehensiveQueryNum(request); if (!StringUtil.isNullOrEmpty(stations)) { for (Station station : stations) { JSONObject stationJSON = new JSONObject(); //取得当天的数据条数 int thisDayCount = mDataDao.querymDataNumBetween(station.getStationCode(), DateUtil.getTodayStr(nowDate), DateUtil.getDateStr(nowDate)); //取得第一个数据 Set<String> maxScoreMdata = zSetOperations.reverseRange(station.getStationCode(), 0, 0); String maxDataTime = null; //如果redis中存在最新的数据 if (!maxScoreMdata.isEmpty()) { //最新数据的json格式 JSONObject maxMdataJson = JSONObject.parseObject(maxScoreMdata.iterator().next()); //最新数据的时间,格式为yyyy-MM-dd HH:mm:ss.000 //最新数据的时间戳 maxDataTime = (String) maxMdataJson.get("data_time"); maxDataTime = maxDataTime.split("\\.")[0]; maxDataTime = DateUtil.getTimeUntilMM(maxDataTime); String LA = null; String LEQ = null; String LMX = null; JSONArray data = maxMdataJson.getJSONArray("data"); for (int i = 0; i < data.size(); i++) { JSONObject indexData = data.getJSONObject(i); if (indexData.get("code").equals("n00000")) { LA = (String) indexData.get("Val"); } if (indexData.get("code").equals("n00006")) { LEQ = (String) indexData.get("Val"); } if (indexData.get("code").equals("n00010")) { LMX = (String) indexData.get("Val"); } } stationJSON.put("station_name", station.getStationName()); stationJSON.put("station_id", station.getStationId()); stationJSON.put("station_code", station.getStationCode()); stationJSON.put("area", station.getDistrict()); stationJSON.put("sim", station.getStationSim()); stationJSON.put("latest_time", maxDataTime); stationJSON.put("count_r", thisDayCount == 0 ? "" : thisDayCount); stationJSON.put("LA", LA); stationJSON.put("LEQ", LEQ); stationJSON.put("LMX", LMX); } else { stationJSON.put("station_name", station.getStationName()); stationJSON.put("station_id", station.getStationId()); stationJSON.put("station_code", station.getStationCode()); stationJSON.put("area", station.getDistrict()); stationJSON.put("sim", station.getStationSim()); stationJSON.put("latest_time", ""); stationJSON.put("count_r", thisDayCount == 0 ? "" : thisDayCount); stationJSON.put("LA", ""); stationJSON.put("LEQ", ""); stationJSON.put("LMX", ""); } dataArray.add(stationJSON); } } siteData.put("count", count); siteData.put("data", dataArray); dataJson.put("sitesDataReal", siteData); logger.info("返回数据 {}", dataJson.toJSONString()); logger.info("方法耗时 {}" , (System.currentTimeMillis() - startTime) + "毫秒"); return dataJson.toJSONString(); } @Override public String queryhDataByStationArea(Map<String, Object> params, HttpSession session) { long startTime = System.currentTimeMillis(); JSONObject dataJson = new JSONObject(); JSONObject siteData = new JSONObject(); JSONArray dataArray = new JSONArray(); ComprehensiveQueryRequest request = buildReq(params, session); List<Station> stations = comprehensiveQueryStations(request); int count = getComprehensiveQueryNum(request); if (!StringUtil.isNullOrEmpty(stations)) { for (Station station : stations) { JSONObject stationJSON = new JSONObject(); List<HData> hDatas = hDataDao.queryMaxTimeHdataByStationId(station.getStationCode()); if (StringUtil.isNullOrEmpty(hDatas)) { //没有该站点的数据记录 stationJSON.put("station_name", station.getStationName()); stationJSON.put("station_id", station.getStationId()); stationJSON.put("station_code", station.getStationCode()); stationJSON.put("area", station.getDistrict()); stationJSON.put("sim", station.getStationSim()); stationJSON.put("calibration_value", ""); stationJSON.put("flag", ""); stationJSON.put("latest_time_h", ""); stationJSON.put("count_h", ""); stationJSON.put("effective_rate_h", ""); stationJSON.put("LEQ_h", ""); stationJSON.put("LMX_h", ""); } else { //查询当天的小时数据的条数 Date date = new Date(); int nowdayHdataNum = hDataDao.queryhDataNumBetween(station.getStationCode(), DateUtil.getTodayStr(date), DateUtil.getDateStr(date)); String calibration_value = null; String flag = null; String effective_rate_h = null; String LEQ_h = null; String LMX_h = null; for (HData hdata : hDatas) { if (hdata.getNorm_code().equals("n00100")) { calibration_value = hdata.getNorm_val(); flag = hdata.getNorm_flag(); } if (hdata.getNorm_code().equals("n00006")) { LEQ_h = hdata.getNorm_val(); } if (hdata.getNorm_code().equals("n00010")) { LMX_h = hdata.getNorm_val(); effective_rate_h = hdata.getNorm_vdr(); } } stationJSON.put("station_name", station.getStationName()); stationJSON.put("station_id", station.getStationId()); stationJSON.put("station_code", station.getStationCode()); stationJSON.put("area", station.getDistrict()); stationJSON.put("calibration_value", calibration_value); stationJSON.put("sim", station.getStationSim()); stationJSON.put("flag", flag); stationJSON.put("latest_time_h", DateUtil.getDateBeforeSecond(hDatas.get(0).getData_time())); stationJSON.put("count_h", nowdayHdataNum); stationJSON.put("effective_rate_h", StringUtil.convertStringToInt(effective_rate_h)); stationJSON.put("LEQ_h", LEQ_h); stationJSON.put("LMX_h", LMX_h); } dataArray.add(stationJSON); } } siteData.put("count", count); siteData.put("data", dataArray); dataJson.put("sitesDataHour", siteData); logger.info("返回数据 {}", dataJson.toJSONString()); logger.info("方法耗时 {}" , (System.currentTimeMillis() - startTime) + "毫秒"); return dataJson.toJSONString(); } @Override public String querydDataByStationArea(Map<String, Object> params, HttpSession session) { long startTime = System.currentTimeMillis(); JSONObject dataJson = new JSONObject(); JSONObject siteData = new JSONObject(); JSONArray dataArray = new JSONArray(); ComprehensiveQueryRequest request = buildReq(params, session); List<Station> stations = comprehensiveQueryStations(request); int count = getComprehensiveQueryNum(request); if (!StringUtil.isNullOrEmpty(stations)) { for (Station station : stations) { JSONObject stationJSON = new JSONObject(); List<DData> dDatas = dDataDao.queryMaxTimeDdataByStationId(station.getStationCode()); if (StringUtil.isNullOrEmpty(dDatas)) { stationJSON.put("station_name", station.getStationName()); stationJSON.put("station_id", station.getStationId()); stationJSON.put("station_code", station.getStationCode()); stationJSON.put("area", station.getDistrict()); stationJSON.put("sim", station.getStationSim()); stationJSON.put("Ld", ""); stationJSON.put("effective_rate_Ld", ""); stationJSON.put("latest_time_d", ""); stationJSON.put("Ln", ""); stationJSON.put("effective_rate_Ln", ""); stationJSON.put("Lnm", ""); } else { //查询最新的日数据 String Ld = null; String effective_rate_Ld = null; String Ln = null; String effective_rate_Ln = null; String Lnm = null; for (DData dData : dDatas) { if (dData.getNorm_code().equals("n00008")) { Ld = dData.getNorm_val(); effective_rate_Ld = dData.getNorm_vdr(); } if (dData.getNorm_code().equals("n00009")) { Ln = dData.getNorm_val(); effective_rate_Ln = dData.getNorm_vdr(); } if (dData.getNorm_code().equals("n00021")) { Lnm = dData.getNorm_val(); } } stationJSON.put("station_name", station.getStationName()); stationJSON.put("station_id", station.getStationId()); stationJSON.put("station_code", station.getStationCode()); stationJSON.put("area", station.getDistrict()); stationJSON.put("sim", station.getStationSim()); stationJSON.put("Ld", Ld); stationJSON.put("latest_time_d", DateUtil.getDateBeforeHour(dDatas.get(0).getData_time())); stationJSON.put("effective_rate_Ld", StringUtil.convertStringToInt(effective_rate_Ld)); stationJSON.put("Ln", Ln); stationJSON.put("effective_rate_Ln", StringUtil.convertStringToInt(effective_rate_Ln)); stationJSON.put("Lnm", Lnm); } dataArray.add(stationJSON); } } siteData.put("count", count); siteData.put("data", dataArray); dataJson.put("sitesDataDay", siteData); logger.info("返回数据 {}", dataJson.toJSONString()); logger.info("方法耗时 {}" , (System.currentTimeMillis() - startTime) + "毫秒"); return dataJson.toJSONString(); } @Override public List<Station> comprehensiveQueryStations(ComprehensiveQueryRequest request) { //分页查询站点 int start = (request.getPageNum() - 1) * request.getPageSize(); int end = request.getPageSize(); //综合查询站点信息,不包含在线离线判断 List<Station> stations = stationDao.comprehensiveQueryByPage(request.getArea(), request.getEnvironment(), request.getIsCountry(), request.getIsCity(), request.getIsArea(), request.getAttribute(), request.getDistrict(), request.getStreet(), request.getUserOperationId(), start, end); //在线离线判断,如果为null则表示查询全部的站点信息 //查询在线标识,需要循环判断 List<Station> newList = new ArrayList<>(); if (request.getState() == null) { newList = stations; } else if (request.getState().equals("1")) { if (!StringUtil.isNullOrEmpty(stations)) { for (Station station : stations) { LogOffLine logOffLine = logOffLineDao.findByStationOrGatherID(station.getStationCode()); if (logOffLine == null || logOffLine.getFlag() == 1) { newList.add(station); } } } } else if (request.getState().equals("0")) { if (!StringUtil.isNullOrEmpty(stations)) { for (Station station : stations) { LogOffLine logOffLine = logOffLineDao.findByStationOrGatherID(station.getStationCode()); if (logOffLine != null && logOffLine.getFlag() == 0) { newList.add(station); } } } } //符合区域环境的总数 int count = newList.size(); logger.info("符合条件的站点信息={}, 总数={}", newList.toString(), count); return newList; } private ComprehensiveQueryRequest buildReq(Map<String, Object> params, HttpSession session) { ComprehensiveQueryRequest request = new ComprehensiveQueryRequest(); //area是区域环境 String area = (String)params.get("area"); String environment = (String)params.get("environment"); String control = (String) params.get("c"); String state = (String) params.get("s"); String attribute = (String)params.get("o"); List position = (List)params.get("street"); String district = (String)position.get(0); String street = (String)position.get(1); int pageSize = (Integer) params.get("each_page_num"); int pageNum = (Integer) params.get("current_page"); User user = (User) session.getAttribute("user"); if (area.equals("5")) { request.setArea(null); } else { request.setArea(area); } if (environment.equals("5")) { request.setEnvironment(null); }else { request.setEnvironment(environment); } //如果是全部则不做设置,默认的是初始化空值 if (control.equals("国控")) { request.setIsCountry("1"); } else if (control.equals("市控")) { request.setIsCity("1"); } else if (control.equals("区控")) { request.setIsArea("1"); } if (state.equals("在线")){ request.setState("1"); } else if (state.equals("离线")){ request.setState("0"); } if (attribute.equals("自动")){ request.setAttribute("1"); }else if (attribute.equals("手动")){ request.setAttribute("0"); } request.setDistrict(district); request.setStreet(street); request.setPageSize(pageSize); request.setPageNum(pageNum); if (user != null) { request.setUserOperationId(user.getOperation_id()); } logger.info("构造的参数为{}", request.toString()); return request; } private int getComprehensiveQueryNum(ComprehensiveQueryRequest request) { return stationDao.queryStationMunByComprehensiveQuery(request.getArea(), request.getEnvironment(), request.getIsCountry(), request.getIsCity(), request.getIsArea(), request.getAttribute(), request.getDistrict(), request.getStreet(), request.getUserOperationId()); } @Override public Station queryStatiionByCode(String stationCode) { return stationDao.findByStationCode(stationCode); } @Override public List<String> getAllStreet() { return stationDao.getAllStreet(); } public void insertStation(Station station,String setupdate) { String application=station.getApplication(); int area=station.getArea(); int city_con=station.getCityCon(); int country_con=station.getCountryCon(); String district=station.getDistrict(); int domain=station.getDomain(); int domain_con=station.getDomainCon(); String station_code=station.getStationCode(); String station_id=station.getStationId(); String station_id_dz=station.getStationIdDZ(); String station_name=station.getStationName(); int station_status=station.getStationStatus(); int online_flag=station.getOnlineFlag(); int protocol=station.getProtocol(); String protocol_name=station.getStationName(); String street=station.getStreet(); String station_major=station.getStation_major(); String station_setup=station.getStation_setup(); String station_setupdate=setupdate; String company_code=station.getCompany_code(); int climate=station.getClimate(); int radar=station.getRadar(); String station_position=station.getPosition(); String station_range=station.getRange(); int station_attribute=station.getStation_attribute(); String station_sim=station.getStationSim(); String operation_id=station.getOperation_id(); stationDao.insertStation(application,area,city_con,country_con,district,domain,domain_con,station_code, station_id,station_id_dz,station_name,station_status,online_flag,protocol,protocol_name,street,station_major, station_setup,station_setupdate,company_code,climate,radar,station_position,station_range,station_attribute,station_sim,operation_id); } @Override public void deleteStation(String station_id) { stationDao.deleteStation(station_id); } @Override public void updateStation(Station station, String setupdate, String target) { String application=station.getApplication(); int area=station.getArea(); int city_con=station.getCityCon(); int country_con=station.getCountryCon(); String district=station.getDistrict(); int domain=station.getDomain(); int domain_con=station.getDomainCon(); String station_code=station.getStationCode(); String station_id=station.getStationId(); String station_id_dz=station.getStationIdDZ(); String station_name=station.getStationName(); int station_status=station.getStationStatus(); int online_flag=station.getOnlineFlag(); int protocol=station.getProtocol(); String protocol_name=station.getStationName(); String street=station.getStreet(); String station_major=station.getStation_major(); String station_setup=station.getStation_setup(); String station_setupdate=setupdate; String company_code=station.getCompany_code(); int climate=station.getClimate(); int radar=station.getRadar(); String station_position=station.getPosition(); String station_range=station.getRange(); int station_attribute=station.getStation_attribute(); String station_sim=station.getStationSim(); String operation_id=station.getOperation_id(); stationDao.updateStation(area,application,city_con,country_con,district,domain,domain_con,station_code, station_id,station_id_dz,station_name,station_status,online_flag,protocol,protocol_name,street,station_major, station_setup,station_setupdate,company_code,climate,radar,station_position,station_range,station_attribute,station_sim,operation_id,target); } @Override public Station getByStationId(String station_id) { return stationDao.findByStationId(station_id); } @Override public Map GEOJson(Map params, String operation_id) { String type=params.get("type")+""; Map<String, Object> resultMap = new LinkedHashMap<String, Object>(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); List<Map> lists=new ArrayList<Map>(); Map<Object, Object> police = warningServiceImp.getRealWarning(); Map<Object, Object> realWarningData=(Map<Object, Object>) police.get("realWarningData"); List<Map> policeDatas = (List<Map>) realWarningData.get("data"); if(type.equals("all")){ //station List<Station> stations=stationDao.findAll(); String LeqAnorm_code=normDao.getLeqACode().toString(); for(int i=0;i<stations.size();i++){ if(operation_id.equals("0")){ //用户为admin或者无运营单位 为0,能看所有站点 Map<String,Object> map=new HashMap<String,Object>(); map.put("type","Feature"); map.put("id",stations.get(i).getStationCode()); map.put("name",stations.get(i).getStationName()); map.put("region",stations.get(i).getDistrict()); //map.put("OverLimit","否"); List<HData> hDatas= hDataDao.getLatestStationListByStationCode(stations.get(i).getStationCode()); if(hDatas!=null){ String time=(hDataDao.getLatestTimeByStationCode(stations.get(i).getStationCode().toString())); boolean flag= false; for(int tt=0;tt<hDatas.size();tt++){ if(hDatas.get(tt).getNorm_code().equals(LeqAnorm_code)){ flag=true; break; } } if(flag==true){ if(time!=null){ map.put("time",(time.substring(0,time.length()-2))); for (int j= 0;j<hDatas.size();j++){ if(hDatas.get(j).getNorm_code().equals(LeqAnorm_code)){ map.put("LeqA",hDatas.get(j).getNorm_val()); break; }else{ map.put("LeqA","0"); } } } }else{ System.out.println("不存在最新数据"); map.put("time",sdf.format(new Date())); map.put("LeqA","0"); } } List<String> MType_list=new ArrayList<String>(); MType_list.add("区域环境"); MType_list.add("功能区"); map.put("M_type",MType_list); List<String> MType_value_list=new ArrayList<String>(); MType_value_list.add(""+stations.get(i).getArea()); MType_value_list.add(""+stations.get(i).getDomain()); map.put("M_typeValue",MType_value_list); List<String> CType_list=new ArrayList<String>(); if(stations.get(i).getCountryCon()==1){ CType_list.add("国控"); } if(stations.get(i).getCityCon()==1){ CType_list.add("市控"); } if(stations.get(i).getDomainCon()==1){ CType_list.add("区控"); } map.put("C_type",CType_list); //待会修改 LogOffLine logOffLine=logOffLineDao.findByStationOrGatherID(stations.get(i).getStationCode()); if(logOffLine!=null){ if(logOffLine.getFlag()==1){ map.put("S_type","在线"); }else if(logOffLine.getFlag()==0){ map.put("S_type","离线"); } }else{ map.put("S_type","在线"); } if(stations.get(i).getStation_attribute()==1){ map.put("O_status","自动"); }else if(stations.get(i).getStation_attribute()==0){ map.put("O_status","手动"); } if(policeDatas.isEmpty()){ map.put("OverLimit","否"); }else{ //报警 是否超标 for (int p=0;p< policeDatas.size();p++) { Map<Object,Object> policeData= policeDatas.get(p); System.out.println(policeDatas.get(p)); System.out.println((policeData.get("station_id").equals(stations.get(i).getStationCode()))); System.out.println("police:"+policeData.get("station_id")); System.out.println("station:"+stations.get(i).getStationCode()); if((policeData.get("station_id").equals(stations.get(i).getStationCode()))){ //此站点有超标数据 System.out.println("ininini"); map.put("OverLimit","是"); break; }else{ map.put("OverLimit","否"); } } } Map<String,Object> mapGeometry=new HashMap<String,Object>(); mapGeometry.put("type","Point"); List<Float> coordinates=new ArrayList<>(); String[] coordinates_str=stations.get(i).getPosition().split(","); Float coordinates_strlat=Float.parseFloat(coordinates_str[0]); Float coordinates_strlon=Float.parseFloat(coordinates_str[1]); coordinates.add(coordinates_strlon); coordinates.add(coordinates_strlat); mapGeometry.put("coordinates",coordinates); map.put("geometry",mapGeometry); lists.add(map); } else{ //此用户存在运维单位,需要数据权限 if(stations.get(i).getOperation_id()!=null){ if(stations.get(i).getOperation_id().equals(operation_id)){ Map<String,Object> map=new HashMap<String,Object>(); map.put("type","Feature"); map.put("id",stations.get(i).getStationCode()); map.put("name",stations.get(i).getStationName()); map.put("region",stations.get(i).getDistrict()); //map.put("OverLimit","否"); List<HData> hDatas= hDataDao.getLatestStationListByStationCode(stations.get(i).getStationCode()); if(hDatas!=null){ String time=(hDataDao.getLatestTimeByStationCode(stations.get(i).getStationCode().toString())); if(time!=null){ map.put("time",(time.substring(0,(time.length()-2)))); for (int j= 0;j<hDatas.size();j++){ if(hDatas.get(j).getNorm_code().equals(LeqAnorm_code)){ map.put("LeqA",hDatas.get(j).getNorm_val()); } } }else{ System.out.println("不存在最新数据"); map.put("time",sdf.format(new Date())); map.put("LeqA","0"); } } List<String> MType_list=new ArrayList<String>(); MType_list.add("区域环境"); MType_list.add("功能区"); map.put("M_type",MType_list); List<String> MType_value_list=new ArrayList<String>(); MType_value_list.add(""+stations.get(i).getArea()); MType_value_list.add(""+stations.get(i).getDomain()); map.put("M_typeValue",MType_value_list); List<String> CType_list=new ArrayList<String>(); if(stations.get(i).getCountryCon()==1){ CType_list.add("国控"); } if(stations.get(i).getCityCon()==1){ CType_list.add("市控"); } if(stations.get(i).getDomainCon()==1){ CType_list.add("区控"); } map.put("C_type",CType_list); //待会修改 LogOffLine logOffLine=logOffLineDao.findByStationOrGatherID(stations.get(i).getStationCode()); if(logOffLine!=null){ if(logOffLine.getFlag()==1){ map.put("S_type","在线"); }else if(logOffLine.getFlag()==0){ map.put("S_type","离线"); } }else{ map.put("S_type","在线"); } if(stations.get(i).getStation_attribute()==1){ map.put("O_status","自动"); }else if(stations.get(i).getStation_attribute()==0){ map.put("O_status","手动"); } if(policeDatas==null){ map.put("OverLimit","否"); }else{ //报警 是否超标 for (int p=0;p< policeDatas.size();p++) { Map<Object,Object> policeData= policeDatas.get(p); System.out.println(policeDatas.get(p)); System.out.println((policeData.get("station_id").equals(stations.get(i).getStationCode()))); System.out.println("police:"+policeData.get("station_id")); System.out.println("station:"+stations.get(i).getStationCode()); if((policeData.get("station_id").equals(stations.get(i).getStationCode()))){ //此站点有超标数据 System.out.println("ininini"); map.put("OverLimit","是"); break; }else{ map.put("OverLimit","否"); } } } Map<String,Object> mapGeometry=new HashMap<String,Object>(); mapGeometry.put("type","Point"); List<Float> coordinates=new ArrayList<>(); String[] coordinates_str=stations.get(i).getPosition().split(","); Float coordinates_strlat=Float.parseFloat(coordinates_str[0]); Float coordinates_strlon=Float.parseFloat(coordinates_str[1]); coordinates.add(coordinates_strlon); coordinates.add(coordinates_strlat); mapGeometry.put("coordinates",coordinates); map.put("geometry",mapGeometry); lists.add(map); } } } } //gather List<Gather> gathers=gatherDao.findAll(); if(gathers!=null){ for(int i=0;i<gathers.size();i++){ if(operation_id.equals("0")){ Map<String,Object> map=new HashMap<String,Object>(); map.put("type","Feature"); map.put("id",gathers.get(i).getGather_id()); map.put("name",gathers.get(i).getGather_name()); map.put("region",gathers.get(i).getDistrict()); GatherData gatherDatas= gatherDataDao.getLaestDataByGather_id(gathers.get(i).getGather_id()); if(gatherDatas!=null){ String time = (gatherDataDao.getLaestDataByGather_id(gathers.get(i).getGather_id()).getData_time().toString()); if(time!=null){ if(gatherDatas.getNorm_code().equals(LeqAnorm_code)){ map.put("LeqA",gatherDatas.getNorm_val()); } map.put("time",(time.substring(0,(time.length()-2)))); }else{ System.out.println("不存在最新数据"); map.put("time",sdf.format(new Date())); map.put("LeqA","0"); } List<String> MType_list=new ArrayList<String>(); MType_list.add("区域环境"); MType_list.add("功能区"); map.put("M_type",MType_list); List<String> MType_value_list=new ArrayList<String>(); MType_value_list.add(""+stations.get(i).getArea()); MType_value_list.add(""+stations.get(i).getDomain()); map.put("M_typeValue",MType_value_list); List<String> CType_list=new ArrayList<String>(); if(gathers.get(i).getCountry_con()==1){ CType_list.add("国控"); } if(gathers.get(i).getCity_con()==1){ CType_list.add("市控"); } if(gathers.get(i).getDomain_con()==1){ CType_list.add("区控"); } map.put("C_type",CType_list); LogOffLine logOffLine=logOffLineDao.findByStationOrGatherID(gathers.get(i).getGather_code()); System.out.println("logoffline"+logOffLine); if(logOffLine!=null){ if(logOffLine.getFlag()==1){ map.put("S_type","在线"); }else if(logOffLine.getFlag()==0){ map.put("S_type","离线"); } }else{ map.put("S_type","在线"); } map.put("O_status","流动"); //采集车没有报警 map.put("OverLimit",""); Map<String,Object> mapGeometry=new HashMap<String,Object>(); mapGeometry.put("type","Point"); List<Float> coordinates=new ArrayList<>(); String pos=gatherDataDao.getLaestDataByGather_id(gathers.get(i).getGather_id()).getGather_position(); String gatherposition=pos.substring(1, pos.length()); String[] coordinates_str=gatherposition.substring(0,gatherposition.length()-1).split(","); Float coordinates_strlon=Float.parseFloat(coordinates_str[0]); Float coordinates_strlat=Float.parseFloat(coordinates_str[1]); coordinates.add(coordinates_strlon); coordinates.add(coordinates_strlat); mapGeometry.put("coordinates",coordinates); map.put("geometry",mapGeometry); lists.add(map); } }else{ if(gathers.get(i).getOperation_id()!=null){ if(gathers.get(i).getOperation_id().equals(operation_id)){ Map<String,Object> map=new HashMap<String,Object>(); map.put("type","Feature"); map.put("id",gathers.get(i).getGather_id()); map.put("name",gathers.get(i).getGather_name()); map.put("region",gathers.get(i).getDistrict()); GatherData gatherDatas= gatherDataDao.getLaestDataByGather_id(gathers.get(i).getGather_id()); if(gatherDatas!=null){ //System.out.println("ss"+gatherDataDao.getLaestDataByGather_id(gathers.get(i).getGather_id()).getData_time().toString()); String time = (gatherDataDao.getLaestDataByGather_id(gathers.get(i).getGather_id()).getData_time().toString()); if(time!=null){ if(gatherDatas.getNorm_code().equals(LeqAnorm_code)){ map.put("LeqA",gatherDatas.getNorm_val()); } map.put("time",(time.substring(0,(time.length()-2)))); }else{ System.out.println("不存在最新数据"); map.put("time",sdf.format(new Date())); map.put("LeqA","0"); } List<String> MType_list=new ArrayList<String>(); MType_list.add("区域环境"); MType_list.add("功能区"); map.put("M_type",MType_list); List<String> MType_value_list=new ArrayList<String>(); MType_value_list.add(""+stations.get(i).getArea()); MType_value_list.add(""+stations.get(i).getDomain()); map.put("M_typeValue",MType_value_list); List<String> CType_list=new ArrayList<String>(); if(gathers.get(i).getCountry_con()==1){ CType_list.add("国控"); } if(gathers.get(i).getCity_con()==1){ CType_list.add("市控"); } if(gathers.get(i).getDomain_con()==1){ CType_list.add("区控"); } map.put("C_type",CType_list); LogOffLine logOffLine=logOffLineDao.findByStationOrGatherID(gathers.get(i).getGather_code()); System.out.println("logoffline"+logOffLine); if(logOffLine!=null){ if(logOffLine.getFlag()==1){ map.put("S_type","在线"); }else if(logOffLine.getFlag()==0){ map.put("S_type","离线"); } }else{ map.put("S_type","在线"); } map.put("O_status","流动"); //采集车没有报警 map.put("OverLimit",""); Map<String,Object> mapGeometry=new HashMap<String,Object>(); mapGeometry.put("type","Point"); List<Float> coordinates=new ArrayList<>(); String pos=gatherDataDao.getLaestDataByGather_id(gathers.get(i).getGather_id()).getGather_position(); String gatherposition=pos.substring(1, pos.length()); String[] coordinates_str=gatherposition.substring(0,gatherposition.length()-1).split(","); Float coordinates_strlat=Float.parseFloat(coordinates_str[0]); Float coordinates_strlon=Float.parseFloat(coordinates_str[1]); coordinates.add(coordinates_strlon); coordinates.add(coordinates_strlat); mapGeometry.put("coordinates",coordinates); map.put("geometry",mapGeometry); lists.add(map); }else{//gather的某些站点没有数据,那么站点的很多数据都是空的,此站点数据返回空 map.put("time",sdf.format(new Date())); System.out.println(new Date()); map.put("LeqA","0"); List<String> MType_list=new ArrayList<String>(); MType_list.add("区域环境"); MType_list.add("功能区"); map.put("M_type",MType_list); List<String> MType_value_list=new ArrayList<String>(); MType_value_list.add(""+stations.get(i).getArea()); MType_value_list.add(""+stations.get(i).getDomain()); map.put("M_typeValue",MType_value_list); List<String> CType_list=new ArrayList<String>(); if(gathers.get(i).getCountry_con()==1){ CType_list.add("国控"); } if(gathers.get(i).getCity_con()==1){ CType_list.add("市控"); } if(gathers.get(i).getDomain_con()==1){ CType_list.add("区控"); } map.put("C_type",CType_list); LogOffLine logOffLine=logOffLineDao.findByStationOrGatherID(gathers.get(i).getGather_code()); System.out.println("logoffline"+logOffLine); if(logOffLine!=null){ if(logOffLine.getFlag()==1){ map.put("S_type","在线"); }else if(logOffLine.getFlag()==0){ map.put("S_type","离线"); } }else{ map.put("S_type","在线"); } map.put("O_status","流动"); //采集车没有报警 map.put("OverLimit",""); Map<String,Object> mapGeometry=new HashMap<String,Object>(); mapGeometry.put("type","Point"); List<Object> coordinates=new ArrayList<>(); coordinates.add(""); coordinates.add(""); mapGeometry.put("coordinates",coordinates); map.put("geometry",mapGeometry); lists.add(map); } } } } } } } resultMap.put("type","FeatureCollection"); resultMap.put("features",lists); System.out.println(lists.size()); return resultMap; } @Override public List<Station> queryStationsByCodeLikeAndArea(String area, String query) { List<Station> stations = stationDao.findByStationCodeNameLikeAndArea(area,query); return stations; } @Override public List<Station> queryStationsByNameLikeAndArea(String area, String query) { List<Station> stations = stationDao.findByStationCodeNameLikeAndArea(area,query); return stations; } @Override public void updateStationOperation(String operation_id,String station_code){ stationDao.updateStationOperation(operation_id,station_code); } @Override public List<Station> findByOperationId(String operatationId) { return stationDao.findByOperationId(operatationId); } @Override public List<Station> queryStationsByDistrictAndDomain(String district, int Domain) { List<Station> stations = stationDao.findByDistrictAndDomain(district, Domain); return stations; } @Override public List<Station> getOperationStationLike(String district,String operation_id,String key){ return stationDao.getOperationStationLike(district,operation_id,key); } @Override public List<Station> getOperationStationLikeAll(String operation_id,String key){ return stationDao.getOperationStationLikeAll(operation_id,key); } @Override public String findStationNameByStationId(String station_id) { return stationDao.findStationNameByStationId(station_id); } }
47.896445
351
0.5091
bf04385714cd6135e683140344c4542f6b52a1bf
1,243
package ch.jalu.configme.configurationdata.samples; import ch.jalu.configme.SettingsHolder; import ch.jalu.configme.configurationdata.CommentsConfiguration; /** * Contains SettingsHolder classes with wrong constructors. */ public final class IllegalSettingsHolderConstructorClasses { private IllegalSettingsHolderConstructorClasses() { } /** * Class doesn't have a no-args constructor. */ public final static class MissingNoArgsConstructor implements SettingsHolder { MissingNoArgsConstructor(String str) { } } /** * Constructor throws exception. */ public final static class ThrowingConstructor implements SettingsHolder { ThrowingConstructor() { throw new IllegalStateException("Exception for testing"); } } /** * Class is abstract. */ public static abstract class AbstractClass implements SettingsHolder { AbstractClass() { } } /** * Class is an interface. */ public interface InterfaceSettingsHolder extends SettingsHolder { @Override default void registerComments(CommentsConfiguration conf) { conf.setComment("path", "comment"); } } }
24.86
82
0.670957
5d009782fcc65433ec3daf185a445e23a24fe6a9
7,082
/* * (C) Copyright IBM Corp. 2014 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.ibm.portal.samples.mvc.controller; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.portlet.MimeResponse; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import javax.portlet.PortletURL; import com.ibm.portal.samples.common.Marshaller; import com.ibm.portal.samples.mvc.model.TemplateActions.ACTION; import com.ibm.portal.samples.mvc.model.TemplateActions.KEY; import com.ibm.portal.samples.mvc.model.TemplateModel; /** * Implementation of the controller that generates URLs to modify the model. * Each URL should work on a clone of the {@link TemplateModel} and modify the * cloned model. * * @author cleue */ public class TemplateController { /** * Representation to dependencies on external services */ public interface Dependencies { /** * Marshaller for private render parameters * * @return the marshaller */ Marshaller getPrivateParameterMarshaller(); /** * TODO add dependencies via parameterless getter methods */ } /** class name for the logger */ private static final String LOG_CLASS = TemplateController.class.getName(); /** logging level */ private static final Level LOG_LEVEL = Level.FINER; /** class logger */ private static final Logger LOGGER = Logger.getLogger(LOG_CLASS); /** * logging can be an instance variable, since the lifecycle of the * controller is the request */ private final boolean bIsLogging = LOGGER.isLoggable(LOG_LEVEL); /** * base model */ private final TemplateModel model; private final MimeResponse response; /** * controls how private parameters are marshalled */ private final Marshaller privateMarshaller; /** * Initializes the controller on top of a model * * @param aModel * the model * @param aRequest * the request * @param aResponse * the response * @param aDeps * the dependencies */ public TemplateController(final TemplateModel aModel, final PortletRequest aRequest, final MimeResponse aResponse, final Dependencies aDeps) { // sanity check assert aModel != null; assert aRequest != null; assert aResponse != null; assert aDeps != null; // logging support final String LOG_METHOD = "TemplateController(aModel, aBean, aDeps)"; if (bIsLogging) { LOGGER.entering(LOG_CLASS, LOG_METHOD); } // TODO copy dependencies from the interface into fields response = aResponse; model = aModel; privateMarshaller = aDeps.getPrivateParameterMarshaller(); // exit trace if (bIsLogging) { LOGGER.exiting(LOG_CLASS, LOG_METHOD); } } /** * Returns a clone of the current model * * @return the clone */ private final TemplateModel cloneModel() { // clones the current model return model.clone(); } /** * Constructs a render URL that encodes the given model * * @param aModel * the model * @return the render URL * * @throws PortletException * @throws IOException */ private final PortletURL createRenderURL(final TemplateModel aModel) throws PortletException, IOException { // sanity check assert aModel != null; // construct a new render URL final PortletURL url = response.createRenderURL(); aModel.encode(url); // ok return url; } /** * Performs a cleanup of resources held by the controller */ public void dispose() { // TODO cleanup here } /** * Returns the action URL that encodes the current model. We use the same * action URL for all actions, since the distinction of the individual * action is encoded as a hidden form data value. * * @return the action URL. * * @throws PortletException * @throws IOException */ public PortletURL getActionURL() throws PortletException, IOException { // construct a new render URL final PortletURL url = response.createActionURL(); model.encode(url); // ok return url; } /** * Creates a render URL that clears the model * * @return the render URL * * @throws PortletException * @throws IOException */ public PortletURL getClearURL() throws PortletException, IOException { // clone the model final TemplateModel clone = cloneModel(); // modify the cloned model clone.clear(); // represent the cloned model via a URL return createRenderURL(clone); } /** * TODO remove and replace by some more meaningful methods * * Creates a render URL that decrements the sample integer * * @return the render URL * * @throws PortletException * @throws IOException */ public PortletURL getDecSampleIntURL() throws PortletException, IOException { // clone the model final TemplateModel clone = cloneModel(); // modify the cloned model clone.decSampleInt(); // represent the cloned model via a URL return createRenderURL(clone); } /** * TODO remove and replace by some more meaningful methods * * Creates a render URL that increments the sample integer * * @return the render URL * * @throws PortletException * @throws IOException */ public PortletURL getIncSampleIntURL() throws PortletException, IOException { // clone the model final TemplateModel clone = cloneModel(); // modify the cloned model clone.incSampleInt(); // represent the cloned model via a URL return createRenderURL(clone); } /** * Returns the value of the form field that encodes the cancel action * * @return form field value */ public String getValueActionCancel() { return privateMarshaller.marshalEnum(ACTION.SAMPLE_FORM_CANCEL); } /** * Returns the value of the form field that encodes the save action * * @return form field value */ public String getValueActionSave() { return privateMarshaller.marshalEnum(ACTION.SAMPLE_FORM_SAVE); } /** * Returns the name of the form field that encodes the action * * @return form field name */ public String getKeyAction() { return privateMarshaller.marshalEnum(KEY.ACTION); } /** * Returns the name of the form field that encodes the sample text * * @return form field name */ public String getKeySampleText() { return privateMarshaller.marshalEnum(KEY.SAMPLE_TEXT); } }
26.62406
79
0.683846
7d2e64084631cd8b801c43612bfdff16a9a261b6
2,777
package com.example.android.bakingapp.Widget; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import com.example.android.bakingapp.R; import java.util.List; import static com.example.android.bakingapp.Widget.BakingAppWidget.ingredientsList; /* * Copyright 2017, Hamza Zyoud * * 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. */ /** * Created by Hamza Zyoud on 10/01/2017. * Project "Baking App"- created by Hamza Zyoud as part of the Udacity Android Nanodegree */ public class GridWidgetService extends RemoteViewsService { List<String> remoteViewsIngredients; @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new GridRemoteViewsFactory(this.getApplicationContext(), intent); } class GridRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { Context mContext = null; public GridRemoteViewsFactory(Context applicationContext, Intent intent) { mContext = applicationContext; } @Override public void onCreate() { } @Override public void onDataSetChanged() { remoteViewsIngredients = ingredientsList; } @Override public void onDestroy() { } @Override public int getCount() { return remoteViewsIngredients.size(); } @Override public RemoteViews getViewAt(int i) { RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.widget_grid_view_item); views.setTextViewText(R.id.widget_grid_view_item, remoteViewsIngredients.get(i)); Intent fillInIntent = new Intent(); views.setOnClickFillInIntent(R.id.widget_grid_view_item, fillInIntent); return views; } @Override public RemoteViews getLoadingView() { return null; } @Override public int getViewTypeCount() { return 1; } @Override public long getItemId(int i) { return i; } @Override public boolean hasStableIds() { return true; } } }
28.336735
107
0.666907
8a88041cbbcbc0bd034ba5f8eb784dec270ff78d
2,010
package net.dean.jraw.models.internal; import com.google.auto.value.AutoValue; import com.squareup.moshi.Json; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import net.dean.jraw.ApiException; import net.dean.jraw.http.NetworkException; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; /** * The model for a JSON-object based API error. Expected formats are: * * <pre> * { * "fields": ["multipath"], * "explanation": "you can't change that multireddit", * "message": "Forbidden", * "reason": "MULTI_CANNOT_EDIT" * } * </pre> * * <pre> * { * "message": "Forbidden", * "reason": 403 * } * </pre> */ @AutoValue public abstract class ObjectBasedApiExceptionStub implements RedditExceptionStub<ApiException> { @Nullable @Json(name = "fields") public abstract List<String> getRelevantFields(); @Nullable public abstract String getExplanation(); @Nullable public abstract String getMessage(); @Nullable @Json(name = "reason") public abstract String getCode(); @Nullable @Json(name = "error") public abstract Integer getHttpStatusCode(); @Override @Nullable public final ApiException create(NetworkException cause) { if (getRelevantFields() != null && getExplanation() != null && getMessage() != null && getCode() != null) return new ApiException(getCode(), getExplanation(), getRelevantFields(), cause); if (getMessage() != null && getHttpStatusCode() != null) return new ApiException(getHttpStatusCode().toString(), getMessage(), new ArrayList<String>(), cause); return null; } @Override public boolean containsError() { // Not exactly always true but close enough return getMessage() != null; } public static JsonAdapter<ObjectBasedApiExceptionStub> jsonAdapter(Moshi moshi) { return new AutoValue_ObjectBasedApiExceptionStub.MoshiJsonAdapter(moshi); } }
27.916667
114
0.683085
98b78458b13c56ccbe3075ba6f8545105530034b
818
package edu.mum.cs544.aop1.log; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class LogAdvice { private static Logger logger = LogManager.getLogger(LogAdvice.class.getName()); @Pointcut(value = "execution(* edu.mum.cs544.aop1.email.EmailSender.sendEmail(..)) && args(email, message)", argNames = "joinPoint,email,message") public void logAfterEmail(JoinPoint joinPoint, String email, String message) { System.out.println("method= " + joinPoint.getSignature().getName() + " address= " + email + " message= " + message); } }
37.181818
150
0.720049
3a8bc15bac0266acd68d77a8ff88af36bb28088a
2,901
package com.spade.ja.datalayer.local; import com.spade.ja.datalayer.pojo.response.DataResponse; import com.spade.ja.datalayer.pojo.response.allevents.AllEventsResponse; import com.spade.ja.datalayer.pojo.response.allnearby.AllNearByResponse; import com.spade.ja.datalayer.pojo.response.allvenues.AllVenuesResponse; import com.spade.ja.datalayer.pojo.response.category.Category; import com.spade.ja.datalayer.pojo.response.events.EventsResponse; import com.spade.ja.datalayer.pojo.response.login.User; import com.spade.ja.datalayer.pojo.response.profile.ProfileResponse; import com.spade.ja.datalayer.pojo.response.venues.VenuesResponse; import io.reactivex.Single; /** * Created by ehab on 12/2/17. */ public interface LocalSource { // all apis cached in the application DataResponse getData(); void saveData(DataResponse dataResponse); Single<EventsResponse> getTopEvents(); void saveTopEvents(EventsResponse eventsResponse); Single<EventsResponse> getNearByEvents(); void saveNearByEvents(EventsResponse eventsResponse); Single<VenuesResponse> getTopVenues(); Single<VenuesResponse> getTopAttractions(); Single<AllVenuesResponse> getAllVenues(); Single<AllVenuesResponse> getAllAttractions(); void saveTopVenues(VenuesResponse venuesResponse); void saveTopAttractions(VenuesResponse venuesResponse); void saveAllVenues(AllVenuesResponse venuesResponse); void saveAllAttractions(AllVenuesResponse venuesResponse); Single<VenuesResponse> getNearByVenues(); Single<VenuesResponse> getNearByAttractions(); void saveNearByVenues(VenuesResponse venuesResponse); void saveNearByAttractions(VenuesResponse venuesResponse); Single<AllNearByResponse> getNearByAll(); void saveAllNearBy(AllNearByResponse allNearByResponse); Single<Category> getCategories(); void saveCategories(Category categoriesResponse); void saveTodayEvents(EventsResponse eventsResponse); Single<EventsResponse> getTodayEvents(); void saveWeekEvents(EventsResponse eventsResponse); Single<EventsResponse> getWeekEvents(); Single<AllEventsResponse> getAllEvents(); void saveAllEvents(AllEventsResponse eventsResponse); Single<EventsResponse> getLikedEvents(); void saveLikedEvents(EventsResponse eventsResponse); Single<VenuesResponse> getLikedVenues(); void saveLikedVenues(VenuesResponse eventsResponse); Single<VenuesResponse> getLikedAttractions(); void saveLikedAttractions(VenuesResponse eventsResponse); void saveLoggedUser(User user); Single<User> getUserProfile(); void saveToken(String token); String getToken(); void clearToken(); Single<ProfileResponse> getProfile(); void saveProfile(ProfileResponse profileResponse); void clearProfile(); boolean isFirstInstall(); void walkThroughAppeared(); }
26.372727
72
0.779386
1c3d0bc78bf44fd35e2f6a1bf4e08d53a47d93a0
1,377
package zlc.season.rxjava2demo.demo; import android.content.Context; import android.util.Log; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import okhttp3.ResponseBody; import retrofit2.Response; import zlc.season.rxjava2demo.Api; import zlc.season.rxjava2demo.RetrofitProvider; import static zlc.season.rxjava2demo.MainActivity.TAG; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/12/14 * Time: 11:08 * FIXME */ public class RetrofitDemo { public static void demo1(final Context context) { final Api api = RetrofitProvider.get().create(Api.class); api.getTop250(0, 10) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Response<ResponseBody>>() { @Override public void accept(Response<ResponseBody> response) throws Exception { Log.d(TAG, response.body().string()); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { Log.w("Error", throwable); } }); } }
33.585366
91
0.602033
2d15525bdc3b90b1d6b8e9e871fc37b118eeb1d7
802
package ca.neilwhite.cloudfunctionlambda.models; import java.io.Serializable; public class Response implements Serializable { private String uppercaseMessage; private Integer characterCount; public Response() { } public Response(String uppercaseMessage, Integer characterCount) { this.uppercaseMessage = uppercaseMessage; this.characterCount = characterCount; } public String getUppercaseMessage() { return uppercaseMessage; } public void setUppercaseMessage(String uppercaseMessage) { this.uppercaseMessage = uppercaseMessage; } public Integer getCharacterCount() { return characterCount; } public void setCharacterCount(Integer characterCount) { this.characterCount = characterCount; } }
24.30303
70
0.715711
c7cbccea1cc6ee144475aea7f5b4b9f26f8dbaf3
1,402
/** */ package gluemodel.COSEM.COSEMObjects; import gluemodel.COSEM.InterfaceClasses.Auto_answer; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Auto Answer Object</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link gluemodel.COSEM.COSEMObjects.AutoAnswerObject#isAnswer <em>Answer</em>}</li> * </ul> * * @see gluemodel.COSEM.COSEMObjects.COSEMObjectsPackage#getAutoAnswerObject() * @model * @generated */ public interface AutoAnswerObject extends Auto_answer { /** * Returns the value of the '<em><b>Answer</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Answer</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Answer</em>' attribute. * @see #setAnswer(boolean) * @see gluemodel.COSEM.COSEMObjects.COSEMObjectsPackage#getAutoAnswerObject_Answer() * @model * @generated */ boolean isAnswer(); /** * Sets the value of the '{@link gluemodel.COSEM.COSEMObjects.AutoAnswerObject#isAnswer <em>Answer</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Answer</em>' attribute. * @see #isAnswer() * @generated */ void setAnswer(boolean value); } // AutoAnswerObject
27.490196
117
0.656205
8f00b3193621b6d4fd6ec00b0d3e036c2def6934
3,262
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.eagle.alert.engine.evaluator.absence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * Since 7/6/16. * To process each incoming event * internally maintain state machine to trigger alert when some attribute does not occur within this window */ public class AbsenceWindowProcessor { private static final Logger LOG = LoggerFactory.getLogger(AbsenceWindowProcessor.class); private List<Object> expectAttrs; private AbsenceWindow window; private boolean expired; // to mark if the time range has been went through private OccurStatus status = OccurStatus.not_sure; public enum OccurStatus { not_sure, occured, absent } public AbsenceWindowProcessor(List<Object> expectAttrs, AbsenceWindow window) { this.expectAttrs = expectAttrs; this.window = window; expired = false; } /** * return true if it is certain that expected attributes don't occur during startTime and endTime, else return false. */ public void process(List<Object> appearAttrs, long occurTime) { if (expired) { throw new IllegalStateException("Expired window can't recieve events"); } switch (status) { case not_sure: if (occurTime < window.startTime) { break; } else if (occurTime >= window.startTime && occurTime <= window.endTime) { if (expectAttrs.equals(appearAttrs)) { status = OccurStatus.occured; } break; } else { status = OccurStatus.absent; break; } case occured: if (occurTime > window.endTime) { expired = true; } break; default: break; } // reset status if (status == OccurStatus.absent) { expired = true; } } public OccurStatus checkStatus() { return status; } public boolean checkExpired() { return expired; } public AbsenceWindow currWindow() { return window; } public String toString() { return "expectAttrs=" + expectAttrs + ", status=" + status + ", expired=" + expired + ", window=[" + window + "]"; } }
33.285714
122
0.613427
34aa42af684eb99e0919775061bdcc153f6358c1
1,052
package learning.webapps; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CookieController extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher(req.getContextPath() + "/pages/cookies.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("cookie-name"); String value = req.getParameter("cookie-value"); Integer maxAge = Integer.parseInt(req.getParameter("cookie-max-age")); Cookie cookie = new Cookie(name, value); cookie.setMaxAge(maxAge); resp.addCookie(cookie); resp.sendRedirect(req.getContextPath() + "/cookies"); } }
37.571429
114
0.740494
de1144e4c3b95fb50ccff0160d246b20f946c37f
11,733
package jetbrains.mps.lang.typesystem.typesystem; /*Generated by MPS */ import jetbrains.mps.lang.typesystem.runtime.BaseHelginsDescriptor; import jetbrains.mps.lang.typesystem.runtime.InferenceRule_Runtime; import jetbrains.mps.lang.typesystem.runtime.NonTypesystemRule_Runtime; import jetbrains.mps.lang.typesystem.runtime.SubtypingRule_Runtime; import jetbrains.mps.lang.typesystem.runtime.ComparisonRule_Runtime; import jetbrains.mps.lang.typesystem.runtime.InequationReplacementRule_Runtime; public class TypesystemDescriptor extends BaseHelginsDescriptor { public TypesystemDescriptor() { { InferenceRule_Runtime inferenceRule = new typeOf_AssertStatement_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_CoerceExpression_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_ConceptReference_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_ImmediateSupertypes_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_IsSubtypeExpression_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_PatternCondition_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_ReportErrorStatement_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_TypeCheckerAccess_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_TypeOfExpression_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_TypeVarDeclaration_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_TypeVarReference_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_WhenConcreteStatement_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeOf_applicableNodeReference_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_AddDependencyStatement_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_AttributedNodeExpression_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_ComparisonRule_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_ErrorInfoExpression_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_GetOperationType_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_InfoStatement_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_LinkPatternVariableReference_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_MatchStatement_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_Node_InferTypeOperation_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_Node_TypeOperation_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_NormalTypeClause_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_OverloadedOpTypeRule_OneTypeSpecified_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_OverloadedOperatorTypeRule_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_PatternVariableReference_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_PrintToTrace_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_PropertyNameTarget_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_PropertyPatternVariableReference_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_QuickFixArgument_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_QuickFixArgumentReference_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_QuickFixField_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_QuickFixFieldReference_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_ReferenceRoleTarget_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_TypesystemIntentionArgument_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_WarningStatement_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_WhenConcreteVariableDeclaration_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_WhenConcreteVariableReference_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_leftOperandConcept_parameter_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_operationConcept_parameter_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { InferenceRule_Runtime inferenceRule = new typeof_rightOperandConcept_parameter_InferenceRule(); this.myInferenceRules.add(inferenceRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_AbstractCheckingRule_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_AbstractEquation_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_AbstractEquation_QuickFix_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_AbstractSubtypingRule_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_AttributedNodeExpression_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_ComparisonRule_ExpectedReturns_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_DuplicatedRules_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_ErrorInfoExpression_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_MessageStatementWithinCheckingRule_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_MessageStatement_QuickFix_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_MethodCall_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_MethodDeclaration_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_NodeInferTypeOperation_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_NodeTypeOperation_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_NonTypesystemRule_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_SubstituteTypeRule_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_SubtypingRule_ExpectedReturns_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_SupersedeConceptFunction_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_TypeofExpression_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_TypesystemIntentionWithoutDescription_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_VarRef_in_WhenConcreteStatement_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { NonTypesystemRule_Runtime nonTypesystemRule = new check_WhenConcreteStatement_NonTypesystemRule(); this.myNonTypesystemRules.add(nonTypesystemRule); } { SubtypingRule_Runtime subtypingRule = new erasure_SNodeType_SubtypingRule(); this.mySubtypingRules.add(subtypingRule); } { SubtypingRule_Runtime subtypingRule = new superTypesOfMeet_SubtypingRule(); this.mySubtypingRules.add(subtypingRule); } { ComparisonRule_Runtime comparisonRule = new MeetType_comparable_with_arguments_ComparisonRule(); this.myComparisonRules.add(comparisonRule); } { InequationReplacementRule_Runtime eliminationRule = new JoinType_supertypeOf_arguments_InequationReplacementRule(); this.myInequationReplacementRules.add(eliminationRule); } { InequationReplacementRule_Runtime eliminationRule = new MeetType_subtypeOf_arguments_InequationReplacementRule(); this.myInequationReplacementRules.add(eliminationRule); } } }
40.181507
121
0.763232
87c5fd624ada5fa352fef51f48e8c5d2c92b7295
372
package br.com.zupacademy.joao.mercadolivre.controller.utility.email; import org.springframework.stereotype.Component; @Component public class EnviarEmail implements Disparador { @Override public void enviar(String caminho, String mensagem) { System.out.println("Email enviado para: "+caminho); System.out.println("Mensagem: "+mensagem); } }
28.615385
69
0.741935
02316e678c2c4c9257fe49e8324ba73dc80e5127
377
package poc.debnathsupriyo.avengersportal.repository; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import poc.debnathsupriyo.avengersportal.entity.Agent; @Repository public interface AgentRepository extends MongoRepository<Agent, String> { public Agent findByAgentId(String agentId); }
29
74
0.822281
d65c798087b05142b26e8e529b249e67463e7a07
8,161
/* * (C) Copyright 2017 David Jennings * * 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. * * Contributors: * David Jennings */ /* * 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 org.jennings.rt.source.http; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.function.Function; import java.util.stream.Collectors; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.Header; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; /** * * @author david */ public class PollHttp { class Poll extends TimerTask { @Override public void run() { if (cnt > 0) { i += 1; } try { //System.out.println(System.currentTimeMillis()); SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } }}, new SecureRandom()); CloseableHttpClient httpclient = HttpClients .custom() .setSSLContext(sslContext) .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .build(); HttpGet request = new HttpGet(url); CloseableHttpResponse response = httpclient.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); Header contentType = response.getEntity().getContentType(); String ct = contentType.getValue().split(";")[0]; UUID uuid = UUID.randomUUID(); int responseCode = response.getStatusLine().getStatusCode(); int n = 0; if (responseCode != 200) { System.out.println("Problem connecting to url"); } else { String line; if (ct.equalsIgnoreCase("application/json")) { StringBuffer result = new StringBuffer(); while ((line = rd.readLine()) != null) { result.append(line); } String data = result.toString(); Object json = new JSONTokener(data).nextValue(); if (json instanceof JSONObject) { // Handle one JSONObject //System.out.println("JSONObject"); n += 1; producer.send(new ProducerRecord<String, String>(topic, uuid.toString(), result.toString())); } else if (json instanceof JSONArray) { // Handle as JSONArray //System.out.println("JSONArray"); JSONArray arr = new JSONArray(result.toString()); for (int i = 0; i < arr.length(); i++) { n += 1; producer.send(new ProducerRecord<String, String>(topic, uuid.toString(), arr.getJSONObject(i).toString())); } } } else { // Assume it's delimited text //System.out.println("Text"); while ((line = rd.readLine()) != null) { //System.out.println(line); n += 1; producer.send(new ProducerRecord<String, String>(topic, uuid.toString(), line)); } } } System.out.println(System.currentTimeMillis() + "," + n); request.abort(); response.close(); } catch (Exception e) { e.printStackTrace(); } if (i >= cnt && cnt > 0) { timer.cancel(); } } } Timer timer; Integer cnt; Integer i; String url; String brokers; String topic; private Producer<String, String> producer; public PollHttp(int cnt, long ms, String url, String brokers, String topic) { this.cnt = cnt; this.i = 0; this.url = url; this.brokers = brokers; this.topic = topic; try { Properties props = new Properties(); props.put("bootstrap.servers", brokers); props.put("client.id", PollHttp.class.getName()); props.put("acks", "1"); props.put("retries", 0); props.put("batch.size", 16384); props.put("linger.ms", 1); props.put("buffer.memory", 8192000); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); /* Addin Simple Partioner didn't help */ //props.put("partitioner.class", SimplePartitioner.class.getCanonicalName()); producer = new KafkaProducer<>(props); } catch (Exception e) { e.printStackTrace(); } timer = new Timer(); timer.schedule(new Poll(), 0, ms); } public static void main(String[] args) { // new PollHttp(20, 1000, "http://localhost:8080/websats/satellites?f=json&n=20", "k1:9092", "satellites"); int numargs = args.length; if (numargs != 5) { System.err.print("Usage: PollHttp numberTimes periodMS url brokers topic\n"); } else { new PollHttp(Integer.parseInt(args[0]), Integer.parseInt(args[1]), args[2], args[3], args[4]); } } }
35.329004
139
0.541355
5ecd75ef7c489769d18a598613926a97acff1ad7
3,959
/* * Created on Nov 28, 2005 */ package b01.foc.db.lock; import java.awt.GridBagConstraints; import java.awt.event.ActionEvent; import java.util.Iterator; import javax.swing.AbstractAction; import b01.foc.db.SQLFilter; import b01.foc.desc.FocDesc; import b01.foc.desc.FocObject; import b01.foc.desc.field.FField; import b01.foc.gui.FGButton; import b01.foc.gui.FPanel; import b01.foc.gui.FListPanel; import b01.foc.gui.table.FTableColumn; import b01.foc.gui.table.FTableView; import b01.foc.list.FocLinkSimple; import b01.foc.list.FocList; import b01.foc.property.FObject; /** * @author 01Barmaja */ public class LockableDescription { private FocDesc desc = null; private FocList listOfRecords = null; private FListPanel selectionPanel = null; public LockableDescription(FocDesc desc){ this.desc = desc; } public void dispose(){ desc = null; if(listOfRecords != null){ listOfRecords = null; } selectionPanel = null; } public FocList getListOfRecords(){ if(listOfRecords == null){ SQLFilter filter = new SQLFilter(null, SQLFilter.FILTER_ON_SELECTED); filter.setAdditionalWhere(new StringBuffer(FField.CONCURRENCY_LOCK_USER_FIELD_PREFIX + FField.REF_FIELD_NAME +">0")); listOfRecords = new FocList(null, new FocLinkSimple(desc), filter); } listOfRecords.loadIfNotLoadedFromDB(); return listOfRecords; } public void unlockAll(){ FocList list = getListOfRecords(); Iterator iter = list.focObjectIterator(); while(iter != null && iter.hasNext()){ FocObject obj = (FocObject) iter.next(); ((FObject)obj.getFocProperty(FField.LOCK_USER_FIELD_ID)).getObject_CreateIfNeeded(); obj.unlock(); obj.load(); } iter = list.focObjectIterator(); while(iter != null && iter.hasNext()){ FocObject obj = (FocObject) iter.next(); if(!obj.isLockedByConcurrence()){ getListOfRecords().removeCurrentObjectFromIterator(iter); } } } @SuppressWarnings("serial") public FPanel newRecordBrowsePanel(){ FPanel panel = new FPanel(); selectionPanel = new FListPanel(getListOfRecords()); panel.add(selectionPanel, 0, 0); FTableView tableView = selectionPanel.getTableView(); for(int i=0; i<desc.concurrenceLockView_FieldNumber(); i++){ FField field = desc.getFieldByID(desc.concurrenceLockView_FieldAt(i)); if(field != null){ FTableColumn col = tableView.addColumn(desc, desc.getFieldByID(field.getID())); col.setEditable(false); } } FTableColumn col = tableView.addColumn(desc, desc.getFieldByID(FField.LOCK_USER_FIELD_ID)); col.setEditable(false); selectionPanel.construct(); selectionPanel.setDirectlyEditable(false); selectionPanel.requestFocus(); selectionPanel.showEditButton(false); selectionPanel.showModificationButtons(false); FPanel totalsPanel = selectionPanel.getTotalsPanel(); FGButton unlockButton = new FGButton("Unlock"); totalsPanel.add(unlockButton, 0, 0, GridBagConstraints.WEST); unlockButton.addActionListener(new AbstractAction(){ public void actionPerformed(ActionEvent e) { FocObject obj = selectionPanel.getSelectedObject(); obj.unlock(); obj.load(); if(!obj.isLockedByConcurrence()){ getListOfRecords().remove(obj); } } }); FGButton unlockAllButton = new FGButton("Unlock all"); totalsPanel.add(unlockAllButton, 1, 0, GridBagConstraints.WEST); unlockAllButton.addActionListener(new AbstractAction(){ public void actionPerformed(ActionEvent e) { unlockAll(); } }); return panel; } public String getTitle(){ String title = desc.getTitle(); if(title.compareTo("") == 0){ title = desc.getStorageName(); }else{ title += " ("+desc.getStorageName()+")"; } return title; } }
28.89781
123
0.680222
fab1d14e0922326b387cebdde351e7ea07e49fb3
7,412
/** * Copyright (C) 2014 OpenTravel Alliance (info@opentravel.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opentravel.schemacompiler.codegen.html.writers.info; import org.opentravel.schemacompiler.codegen.html.Configuration; import org.opentravel.schemacompiler.codegen.html.Content; import org.opentravel.schemacompiler.codegen.html.LinkInfoImpl; import org.opentravel.schemacompiler.codegen.html.builders.FacetDocumentationBuilder; import org.opentravel.schemacompiler.codegen.html.builders.FacetOwnerDocumentationBuilder; import org.opentravel.schemacompiler.codegen.html.markup.HtmlStyle; import org.opentravel.schemacompiler.codegen.html.markup.HtmlTag; import org.opentravel.schemacompiler.codegen.html.markup.HtmlTree; import org.opentravel.schemacompiler.codegen.html.markup.RawHtml; import org.opentravel.schemacompiler.codegen.html.writers.SubWriterHolderWriter; import org.opentravel.schemacompiler.model.TLFacetType; import java.util.ArrayList; import java.util.List; /** * @author Eric.Bronson * */ public class FacetInfoWriter extends AbstractInheritedInfoWriter<FacetOwnerDocumentationBuilder<?>,FacetDocumentationBuilder> { /** * @param writer the writer for which to create an info-writer * @param owner the owner of the new info-writer */ public FacetInfoWriter(SubWriterHolderWriter writer, FacetOwnerDocumentationBuilder<?> owner) { super( writer, owner ); title = writer.getResource( "doclet.Facet_Summary" ); caption = writer.newConfiguration().getText( "doclet.Facets" ); } /** * Build the member summary for the given members. * * @param memberTree content trees to which the documentation will be added */ protected void addInfoSummary(Content memberTree) { Content label = getInfoLabel(); memberTree.addContent( label ); List<FacetDocumentationBuilder> facets = source.getFacets(); if (!facets.isEmpty()) { Content tableTree = getTableTree(); for (FacetDocumentationBuilder fdb : facets) { Content facetSummary = getInfo( fdb, facets.indexOf( fdb ), false ); tableTree.addContent( facetSummary ); } memberTree.addContent( tableTree ); } } /** * Add the member summary for the given class. * * @param member the member being documented * @param counter the counter for determing style for the table row * @param addCollapse flag indicating whether the content will be in a collapsable display */ protected Content getInfo(FacetDocumentationBuilder member, int counter, boolean addCollapse) { HtmlTree tdFacetName = new HtmlTree( HtmlTag.TD ); tdFacetName.setStyle( HtmlStyle.COL_FIRST ); addFacet( member, tdFacetName ); HtmlTree tdSummary = new HtmlTree( HtmlTag.TD ); setInfoColumnStyle( tdSummary ); addFacetType( member, tdSummary ); HtmlTree tr = HtmlTree.tr( tdFacetName ); tr.addContent( tdSummary ); addRowStyle( tr, counter ); return tr; } /** * {@inheritDoc} */ protected void addFacetType(FacetDocumentationBuilder member, Content tdSummary) { Content strong = HtmlTree.strong( new RawHtml( member.getType().name() ) ); Content code = HtmlTree.code( strong ); tdSummary.addContent( code ); } /** * {@inheritDoc} */ protected void addFacet(FacetDocumentationBuilder member, Content tdSummaryType) { HtmlTree code = new HtmlTree( HtmlTag.CODE ); code.addContent( new RawHtml( writer.getLink( new LinkInfoImpl( LinkInfoImpl.CONTEXT_SUMMARY_RETURN_TYPE, member ) ) ) ); Content strong = HtmlTree.strong( code ); tdSummaryType.addContent( strong ); } /** * Build the inherited member summary for the given methods. * * @param summaryTree tree to which the documentation will be added */ protected void addInheritedInfoSummary(Content summaryTree) { FacetOwnerDocumentationBuilder<?> ext = getParent( source ); while (ext != null) { List<FacetDocumentationBuilder> extFacets = ext.getFacets(); List<FacetDocumentationBuilder> inheritedFacets = new ArrayList<>(); for (FacetDocumentationBuilder fdb : extFacets) { if (!hasFacet( ext, fdb )) { inheritedFacets.add( fdb ); } } if (!inheritedFacets.isEmpty()) { addInheritedInfoHeader( ext, summaryTree, "doclet.Facets_Inherited_From" ); addInheritedInfo( inheritedFacets, ext, summaryTree ); } ext = getParent( ext ); } } private boolean hasFacet(FacetOwnerDocumentationBuilder<?> fodb, FacetDocumentationBuilder fdb) { boolean hasFacet = false; for (FacetDocumentationBuilder fdb2 : source.getFacets()) { TLFacetType extFacetType = fdb.getType(); if (extFacetType.equals( TLFacetType.ID ) || extFacetType.equals( TLFacetType.SUMMARY ) || extFacetType.equals( TLFacetType.DETAIL )) { if (fdb2.getType().equals( extFacetType )) { hasFacet = true; } } else { // should be a custom or query String extFacetName = fdb.getName(); // get the custom part String extName = extFacetName.substring( fodb.getName().length() ); if (fdb2.getName().contains( extName )) { hasFacet = true; } } if (hasFacet) { break; } } return hasFacet; } protected FacetOwnerDocumentationBuilder<?> getParent(FacetOwnerDocumentationBuilder<?> classDoc) { return (FacetOwnerDocumentationBuilder<?>) classDoc.getSuperType(); } /** * {@inheritDoc} */ protected void addInheritedInfoAnchor(FacetOwnerDocumentationBuilder<?> parent, Content inheritedTree) { inheritedTree .addContent( writer.getMarkerAnchor( "facets_inherited_from_object_" + parent.getQualifiedName() ) ); } protected String getInfoTableSummary() { Configuration config = writer.newConfiguration(); return config.getText( "doclet.Facet_Table_Summary", config.getText( "doclet.Facet_Summary" ), config.getText( "doclet.facets" ) ); } /** * @see org.opentravel.schemacompiler.codegen.html.writers.info.AbstractInfoWriter#getInfoTableHeader() */ @Override protected String[] getInfoTableHeader() { Configuration config = writer.newConfiguration(); return new String[] {config.getText( "doclet.Name" ), config.getText( "doclet.Type" )}; } }
38.010256
116
0.66082
3374e2673194d11a250c39653f7b69939a598fb1
245
package com.victor.player.library.data; public class FmtStreamMap { public String fallbackHost; public String s; public String itag; public String type; public String quality; public String url; public String sig; }
20.416667
39
0.710204
17e3a07c7b568789114425e91cc68ddfe61978e8
10,171
package com.meizhuang.controller; import com.meizhuang.entity.Article; import com.meizhuang.entity.ArticleQuery; import com.meizhuang.result.data.BaseResultInfo; import com.meizhuang.result.data.SuccessResult; import com.meizhuang.services.article.ArticleServiceImpl; import com.meizhuang.utils.PrintUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.io.UnsupportedEncodingException; import java.util.List; /** * Created by meizhuang on 03/02/17. */ @RestController public class ArticleController { public static String TAG = "ArticleController"; //http://localhost:8190/meizhuang/say @GetMapping(value = "/say") public BaseResultInfo say() { // return new ResultInfo(ResultInfo.SUCCESS_CODE,ResultInfo.SUCCESS_MSG,"Hello"); return new SuccessResult( "hello"); } //http://localhost:8189/meizhuang/test @GetMapping(value = "/test") public String test() { return articleService.test(); } @Autowired private ArticleServiceImpl articleService; /** * http://localhost:8190/meizhuang/addArticle?creatorId=1&createTimeMillis=1001&recordTimeMillis=1002&title=美妆&content=教你美妆&author=匿名&fromUrl=http://xxx.com&type=1&status=2 * 添加文章 * * @param creatorId * @param createTimeMillis * @param recordTimeMillis * @param title * @param content * @param author * @param fromUrl * @param type * @param recommendStatus * @return * @throws UnsupportedEncodingException */ @PostMapping(value = "/addArticleD", produces = "application/json; charset=utf-8") public BaseResultInfo articleAdd(@RequestParam("creatorId") Integer creatorId, @RequestParam("createTimeMillis") Long createTimeMillis, @RequestParam("recordTimeMillis") Long recordTimeMillis, @RequestParam("title") String title, @RequestParam("subTitle") String subTitle, @RequestParam("coverImgUrl") String coverImgUrl, @RequestParam("content") String content, @RequestParam("author") String author, @RequestParam("fromUrl") String fromUrl, @RequestParam("type") Integer type, @RequestParam("recommendStatus") Integer recommendStatus) throws UnsupportedEncodingException { Article article = articleService.addArticle(creatorId, createTimeMillis, recordTimeMillis, title, content, author, fromUrl, type, recommendStatus); SuccessResult resultInfo = new SuccessResult(article); return resultInfo; } @PostMapping(value = "/addArticle", produces = "application/json; charset=utf-8") public BaseResultInfo articleAdd(@RequestParam("creatorId") Integer creatorId, @RequestParam("title") String title, @RequestParam("subTitle") String subTitle, @RequestParam("coverImgUrl") String coverImgUrl, @RequestParam("content") String content, @RequestParam("author") String author, @RequestParam("fromUrl") String fromUrl, @RequestParam("type") Integer type, @RequestParam("recommendStatus") Integer recommendStatus) throws UnsupportedEncodingException { Article article = articleService.addArticle(creatorId, title, subTitle, content, author, fromUrl, coverImgUrl, type, recommendStatus); SuccessResult resultInfo = new SuccessResult(article); return resultInfo; } @PostMapping(value = "/postceshi", produces = "application/json; charset=utf-8") public BaseResultInfo postCeshi(@RequestParam("creatorId") Integer creatorId, @RequestParam("title") String title ) throws UnsupportedEncodingException { SuccessResult resultInfo = new SuccessResult("哈哈哈哈"); return resultInfo; } /** * http://localhost:8190/meizhuang/articles * 获取所有文章列表 * * @return */ @GetMapping(value = "/articles") public BaseResultInfo getArticleList() { PrintUtil.printTag(TAG, "articleList"); List<Article> articleList = articleService.getAllArticles(); SuccessResult resultInfo = new SuccessResult( articleList); return resultInfo; } /** * http://localhost:8189/meizhuang/article/id/2 * 通过文章id查询 * * @param id * @return */ @GetMapping(value = "/article/id/{id}") public BaseResultInfo getArticleById(@PathVariable("id") Long id) { PrintUtil.printTag(TAG, id); Article article = articleService.getArticleById(id); SuccessResult resultInfo = new SuccessResult(article); return resultInfo; } /** * post * http://localhost:8190/meizhuang/articleDeleteById?id=2 * 根据ID删除文章 * * @param id */ @PostMapping(value = "/articleDeleteById") public BaseResultInfo articleDeleteById(@RequestParam("id") Long id) { PrintUtil.printTag(TAG, id); articleService.deleteArticleById(id); SuccessResult resultInfo = new SuccessResult(""); return resultInfo; } /** * post * http://localhost:8190/meizhuang/article/recommendstatus?id=2&recommendStatus=1 * 根据ID设置文章推荐状态 * * @param id */ @PostMapping(value = "/article/recommendstatus") public BaseResultInfo articleRecommendById(@RequestParam("id") Long id, @RequestParam("recommendStatus") int recommendStatus) { Article article = articleService.getArticleById(id); article.setRecommendStatus(recommendStatus); Article articleNew = articleService.addArticle(article); SuccessResult resultInfo = new SuccessResult(articleNew); return resultInfo; } /** * http://localhost:8190/meizhuang/article/title/美妆3 * 通过文章title查询 * * @param title * @return */ @GetMapping(value = "/article/title/{title}") public BaseResultInfo articleFindByTitle(@PathVariable("title") String title) { List<Article> articleList = articleService.findByTitle(title); SuccessResult resultInfo = new SuccessResult(articleList); return resultInfo; } /** * http://localhost:8190/meizhuang/findarticlePages?page=0&size=4 * or * http://localhost:8190/meizhuang/findarticlepages * https://my.oschina.net/wangxincj/blog/820670 * 分页查询 * * @param modelMap * @param page * @param size * @return * @RequestMapping("/findarticlepages") //不区分get和post */ // @RequestMapping("/findarticlepages") @GetMapping("/findarticlepages") public BaseResultInfo findBookNoQuery(ModelMap modelMap, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size) { Page<Article> datas = articleService.findArticlesNoCriteria(page, size); modelMap.addAttribute("datas", datas); SuccessResult resultInfo = new SuccessResult( datas); return resultInfo; } /** * http://localhost:8190/meizhuang/findarticlePages?page=0&size=4 * or * http://localhost:8190/meizhuang/findarticlepagesquery * https://my.oschina.net/wangxincj/blog/820670 * 分页查询 * * @param modelMap * @param page * @param size * @return * @RequestMapping("/findarticlepages") //不区分get和post */ // @RequestMapping(value = "/findarticlepagesquery",method = {RequestMethod.GET,RequestMethod.POST}) @RequestMapping(value = "/findarticlepagesquery", method = {RequestMethod.GET}) public BaseResultInfo findBookQuery(ModelMap modelMap, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "2") Integer size, ArticleQuery bookQuery) { Page<Article> datas = articleService.findArticlesCriteria(page, size, bookQuery); modelMap.addAttribute("datas", datas); SuccessResult resultInfo = new SuccessResult(datas); return resultInfo; } // @RequestMapping("/findBookNoQuery") // public ModelMap findBookNoQuery(ModelMap modelMap,@RequestParam(value = "page", defaultValue = "0") Integer page, // @RequestParam(value = "size", defaultValue = "1") Integer size){ // Page<Article> datas = articleService.findArticleNoCriteria(page, size); // modelMap.addAttribute("datas", datas); // return modelMap; // } /** * @param modelMap * @param page * @param size * @param sortDirection * @param recommendStatus * @return */ @RequestMapping(value = "/findarticlepagesquery1", method = {RequestMethod.GET}) public BaseResultInfo findBookQuery1(ModelMap modelMap, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "2") Integer size, @RequestParam(value = "recommendStatus", defaultValue = "0") Integer recommendStatus, @RequestParam(value = "sortDirection", defaultValue = "0") Integer sortDirection ) { Page<Article> datas = articleService.findArticlesByRecommendStatus(page, size, recommendStatus, sortDirection); modelMap.addAttribute("datas", datas); SuccessResult resultInfo = new SuccessResult( datas); return resultInfo; } }
38.236842
176
0.626389
1a037161ff9bb8ee8373b0fb0c6fe96b54a5cd28
1,761
package org.apache.spark.sql.execution; /** * :: DeveloperApi :: * Performs an inner hash join of two child relations by first shuffling the data using the join * keys. */ public class ShuffledHashJoin extends org.apache.spark.sql.execution.SparkPlan implements org.apache.spark.sql.execution.BinaryNode, org.apache.spark.sql.execution.HashJoin, scala.Product, scala.Serializable { public scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression> leftKeys () { throw new RuntimeException(); } public scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression> rightKeys () { throw new RuntimeException(); } public org.apache.spark.sql.execution.BuildSide buildSide () { throw new RuntimeException(); } public org.apache.spark.sql.execution.SparkPlan left () { throw new RuntimeException(); } public org.apache.spark.sql.execution.SparkPlan right () { throw new RuntimeException(); } // not preceding public ShuffledHashJoin (scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression> leftKeys, scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression> rightKeys, org.apache.spark.sql.execution.BuildSide buildSide, org.apache.spark.sql.execution.SparkPlan left, org.apache.spark.sql.execution.SparkPlan right) { throw new RuntimeException(); } public org.apache.spark.sql.catalyst.plans.physical.Partitioning outputPartitioning () { throw new RuntimeException(); } public scala.collection.immutable.List<org.apache.spark.sql.catalyst.plans.physical.ClusteredDistribution> requiredChildDistribution () { throw new RuntimeException(); } public org.apache.spark.rdd.RDD<org.apache.spark.sql.catalyst.expressions.Row> execute () { throw new RuntimeException(); } }
92.684211
380
0.785917
f2981932429db4096447815944446b36bfac8b97
2,157
package fi.csc.chipster.sessionworker; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SmtpEmails { private String host; private String username; private String password; private boolean tls; private boolean auth; private String from; private String fromName; private int port; public SmtpEmails(String host, int port, String username, String password, boolean tls, boolean auth, String from, String fromName) { this.host = host; this.port = port; this.username = username; this.password = password; this.tls = tls; this.auth = auth; this.from = from; this.fromName = fromName; } public void send(String subject, String body, String to, String replyTo) throws MessagingException, UnsupportedEncodingException { Properties props = System.getProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.port", this.port); props.put("mail.smtp.starttls.enable", Boolean.toString(this.tls)); props.put("mail.smtp.auth", Boolean.toString(this.auth)); Session session = Session.getDefaultInstance(props); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(this.from, this.fromName)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setSubject(subject, StandardCharsets.UTF_8.name()); msg.setText(body, StandardCharsets.UTF_8.name()); if (replyTo != null) { msg.addHeader("Reply-To", replyTo); } Transport transport = session.getTransport(); try { transport.connect(this.host, this.username, this.password); transport.sendMessage(msg, msg.getAllRecipients()); System.out.println("Email sent!"); } finally { transport.close(); } } }
31.26087
131
0.686138
211026392675f47b4c0c223b313dd0c961088cb8
449
package org.perscholas.recipies.services; import java.util.List; import org.perscholas.recipies.daos.CategoryRepository; import org.perscholas.recipies.model.Category; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CategoryService { @Autowired CategoryRepository catRepo; public List<Category> findAll(){ return catRepo.findAll(); } }
23.631579
63
0.781737
a60560fef74db3d50d84f38c0bbb80bfd647a562
995
package com.zgrjb.utils; import java.util.List; import org.litepal.crud.DataSupport; import com.zgrjb.model.LastMsgRecord; import com.zgrjb.model.LocalUserInfo; public class LastMsgRecordDBUtil { private static final LastMsgRecordDBUtil instance= new LastMsgRecordDBUtil(); public static LastMsgRecordDBUtil getInstance(){ return instance; } private LastMsgRecordDBUtil(){ } public boolean insert(LastMsgRecord record){ return record.save(); } public void insert(List<LastMsgRecord> list){ DataSupport.saveAll(list); } public void deleteAll(){ DataSupport.deleteAll(LastMsgRecord.class); } public void delete(LocalUserInfo info){ DataSupport.delete(LastMsgRecord.class,info.getId()); } public List<LastMsgRecord> findAll(){ return DataSupport.findAll(LastMsgRecord.class); } public void updateMsg(LastMsgRecord newMsg,int id){ newMsg.update(id); } }
22.613636
78
0.691457
6eaf8a7784e9018fa564dfe3ebcd2189c13c287d
1,150
import java.io.PrintStream; import java.util.Scanner; /** * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) */ public class Ideal_gk { private static Scanner in; private static PrintStream out; private static class Solution { void run() { int n = in.nextInt(); long minX = Long.MAX_VALUE; long maxX = Long.MIN_VALUE; long minY = Long.MAX_VALUE; long maxY = Long.MIN_VALUE; for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); int h = in.nextInt(); minX = Math.min(minX, x - h); maxX = Math.max(maxX, x + h); minY = Math.min(minY, y - h); maxY = Math.max(maxY, y + h); } out.println((maxX + minX) / 2 + " " + (maxY + minY) / 2 + " " + (Math.max(maxY - minY, maxX - minX) + 1) / 2); } } public static void main(String[] args) { in = new Scanner(System.in); out = System.out; new Solution().run(); } }
29.487179
123
0.46
fbcc77b1bf17792de3eea00e45ccc3917668d324
10,224
package com.liwy.study.spring.spring4.controller; import com.fasterxml.jackson.annotation.JsonView; import com.liwy.study.spring.spring4.bean.User; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.datetime.DateFormatter; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import org.springframework.web.bind.annotation.SessionAttributes; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Date; /** * <b>模块:</b> <br/> * <b>名称:</b> <br/> * <b>描述:</b> <br/> * <b>作者:</b> wenyao02.li <br/> * <b>创建时间:</b> 2019/2/19 14:06 <br/> * <b>版本:</b> V1.0 <br/> */ @Controller //@RestController // rest风格接口,自动添加@ResponseBody注解 @RequestMapping("/user") @SessionAttributes(names = {"student","user"}) // 同Model与Session中的数据 public class UserController { /** * 使用@PathVariable方法参数上的注释将其绑定到URI模板变量的值 * 使用@RequestParam注释接收请求参数 * * @param id * @return java.lang.String */ @RequestMapping(path = "/group/{myGroup}/users/{id}", method = RequestMethod.GET, params = {"sex","type"}) public String getUser(@PathVariable("myGroup") String type, @PathVariable Long id, @RequestParam String sex, Model model) { System.out.println(type); System.out.println(id); System.out.println(sex); return "user"; } /** * 支持Ant样式(*) */ @RequestMapping("/group/*/users/{id}/{day}") public void handle(@PathVariable String id, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date day) { System.out.println(id); System.out.println(day); } /** * 通过正则配URI * * @param version * @param extension */ @RequestMapping("/myapp/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}") public void handle(@PathVariable String version, @PathVariable String extension) { System.out.println(version); System.out.println(extension); } /** * 通过params请求参数匹配URI: myParam", "!myParam" 或 "myParam=myValue" * 通过headers请求头匹配URI * */ @GetMapping(path = "/users", params = {"myParams","myParams1=myValue1"}, headers = "myHeader=myValue") public void findPet3() { System.out.println("成功匹配"); } /** * 指定消费媒体类型: 只有当请求头中 Content-Type 的值与指定可消费的媒体类型中有相同的时候,请求才会被匹配 * RequestBody注解 将请求主体绑定到方法参数 * * @param user * @param model */ @PostMapping(path = "/users", consumes = "application/json") public void addUser(@RequestBody User user, Model model) { System.out.println(user); } /** * 指定生产媒体类型: 只有当请求头中 Accept 的值与指定可生产的媒体类型中有相同的时候,请求才会被匹配。 * ResponseBody将返回值映射到响应正文 * * @param id * @param model * @return */ @GetMapping(path = "/usersjson/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User getUser(@PathVariable String id, Model model, HttpSession session, HttpServletResponse response) { User user = new User(); user.setUsername("name111"); user.setEmail("email@121.com"); System.out.println(user); session.setAttribute("user", user); Cookie cookie = new Cookie("myCookie","liwycookie"); cookie.setPath("/liwy-study-spring/user"); cookie.setMaxAge(60); response.addCookie(cookie); return user; } /** * 使用HttpEntity: * HttpEntity与@RequestBody和@ResponseBody很相似。除了能获得请求体和响应体中的内容之外,HttpEntity( * 以及专门负责处理响应的ResponseEntity子类)还可以存取请求头和响应头 * * @param requestEntity * @return * @throws UnsupportedEncodingException */ @RequestMapping("/something") public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException { String requestHeader = requestEntity.getHeaders().getFirst( "MyRequestHeader"); byte[] requestBody = requestEntity.getBody(); // do something with request header and body HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("MyResponseHeader", "MyValue"); return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED); } /** * <pre> * 在方法上使用@ModelAttribute * @ModelAttribute 说明了方法的作用是用于添加一个或多个属性到model上 * @ModelAttribute 的方法实际上会在@RequestMapping方法之前被调用 * * 该方法的返回值被添加到model中名字为"account",你也可以通过@ModelAttribute("myAccount")来自定义名字 * * <pre> * * @param number * @return */ // @ModelAttribute public User addAccount(@RequestParam String number) { User user = new User(); user.setUsername("在请求之前向model中添加属性"); return user; } /** * 添加多个属性到model * * @param number * @param model */ // @ModelAttribute public void populateModel(@RequestParam String number, Model model) { model.addAttribute("student","liwystu"); User user = new User(); user.setUsername("在请求之前向model中添加属性111"); model.addAttribute("user1", user); // add more ... } /** * <pre> * 注解在方法参数上的@ModelAttribute说明了该方法参数的值将由model中取得。如果model中找不到,那么该参数会先被实例化, * 然后被添加到model中。 * * 该参数实例可能来自以下几个地方: * 它可能因为@SessionAttributes注解的使用已经存在于model中 * 它可能因为在同个控制器中使用了@ModelAttribute方法已经存在于model中 * 它可能是由URI模板变量和类型转换中取得的 * 它可能是调用了自身的默认构造器被实例化出来的 * </pre> * * @param user * @return */ @GetMapping("/getModelAttri") public void processSubmit(@ModelAttribute User user,@ModelAttribute("user1") User user1, @ModelAttribute("student") String student) { System.out.println(user); System.out.println(user1); System.out.println(student); } /** * 使用@SessionAttribute来访问预先存在的全局会话属性 * * @param user * @return */ @RequestMapping("/hd1") public void handle(@SessionAttribute User user, HttpServletRequest request) { Cookie[] cookies = request.getCookies(); for (Cookie cookie: cookies) { System.out.println(cookie.getName()+":"+cookie.getValue()); } System.out.println(user); } /** * 使用@RequestAttribute来访问请求属性 * * @param parenet * @return */ @RequestMapping("/hd2") public void handle2(@RequestAttribute String parenet) { System.out.println(parenet); } /** * <pre> * 使用@CookieValue注解映射Cookie值 * JSESSIONID = 415A4AC178C59DACE0B2C9CA727CDD84 * </pre> * * @param cookie */ @RequestMapping("/cookie") public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) { System.out.println(cookie); } /** * <pre> * 使用@RequestHeader注解映射请求头属性 * Host localhost:8080 * Accept text/html,application/xhtml+xml,application/xml;q=0.9 * Accept-Language fr,en-gb;q=0.7,en;q=0.3 * Accept-Encoding gzip,deflate * Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 * Keep-Alive 300 * </pre> * * @param encoding * @param keepAlive */ @RequestMapping("/displayHeaderInfo") public void displayHeaderInfo( @RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive") long keepAlive) { System.out.println(encoding); System.out.println(keepAlive); } /** * 使用@InitBinder自定义数据绑定 * * @param binder */ @InitBinder protected void initBinder(WebDataBinder binder) { // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); // dateFormat.setLenient(false); // binder.registerCustomEditor(Date.class, new CustomDateEditor( // dateFormat, false)); binder.addCustomFormatter(new DateFormatter("yyyyMMdd")); } @RequestMapping("/getDate/{date}") public void getDate(@PathVariable Date date) { System.out.println(date); } @RequestMapping("/{id}") @ResponseBody @JsonView(User.WithNameEmailView.class) public User getUserView(@PathVariable Long id) { User user = new User(); user.setUsername("liwy"); user.setEmail("liwey@126.com"); user.setSex((byte) 1); user.setStatus((byte) 1); user.setRegisterTime(new Date()); return user; } //测试全局自定义类型转换器 @RequestMapping("/myConversion/{user}") public void testMyConversion(@PathVariable User user) { System.out.println(user); } // 测试自定义视图解析器 @RequestMapping("/myView") public String myView() { return "myView"; } }
31.361963
137
0.653756
8d10f76dd69fddcb12fc38448a5c79aa11938942
2,257
/* * Copyright (C) 2018 The ontology Authors * This file is part of The ontology library. * The ontology is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * The ontology is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with The ontology. If not, see <http://www.gnu.org/licenses/>. */ package com.github.ontio.explorersummary.model; import com.github.ontio.core.governance.PeerPoolItem; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Data @Builder @NoArgsConstructor @AllArgsConstructor @Table(name = "tbl_candidate_node_summary") public class CandidateNodeSummary { @Id @GeneratedValue(generator = "JDBC") private Long id; private String name; @Column(name = "node_rank") private Integer nodeRank; @Column(name = "current_stake") private Long currentStake; private String progress; @Column(name = "detail_url") private String detailUrl; @Column(name = "node_index") private Integer nodeIndex; @Column(name = "public_key") private String publicKey; private String address; private Integer status; @Column(name = "init_pos") private Long initPos; @Column(name = "total_pos") private Long totalPos; @Column(name = "max_authorize") private Long maxAuthorize; @Column(name = "node_proportion") private String nodeProportion; // Self-defined construct method. public CandidateNodeSummary(PeerPoolItem item) { name = ""; nodeIndex = item.index; publicKey = item.peerPubkey; address = item.address.toBase58(); status = item.status; initPos = item.initPos; totalPos = item.totalPos; nodeProportion = ""; } }
27.52439
78
0.708019
529e3eb615b587599cf04a9d26e0c73db9ba54c3
4,224
package ru.ok.technopolis.firedemoapp; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.support.annotation.ColorInt; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import java.util.Random; public class FireView extends View { private static final int[] firePalette = { 0xff070707, 0xff1F0707, 0xff2F0F07, 0xff470F07, 0xff571707, 0xff671F07, 0xff771F07, 0xff8F2707, 0xff9F2F07, 0xffAF3F07, 0xffBF4707, 0xffC74707, 0xffDF4F07, 0xffDF5707, 0xffDF5707, 0xffD75F07, 0xffD75F07, 0xffD7670F, 0xffCF6F0F, 0xffCF770F, 0xffCF7F0F, 0xffCF8717, 0xffC78717, 0xffC78F17, 0xffC7971F, 0xffBF9F1F, 0xffBF9F1F, 0xffBFA727, 0xffBFA727, 0xffBFAF2F, 0xffB7AF2F, 0xffB7B72F, 0xffB7B737, 0xffCFCF6F, 0xffDFDF9F, 0xffEFEFC7, 0xffFFFFFF }; private int[] firePixels; private int fireWidth; private int fireHeight; private int[] bitmapPixels; private int minHotY = -1; private final Paint paint = new Paint(); private final Random random = new Random(); private Bitmap bitmap; public FireView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { float aspectRatio = (float) w / h; fireWidth = 150; fireHeight = (int) (fireWidth / aspectRatio); firePixels = new int[fireWidth * fireHeight]; for (int x = 0; x < fireWidth; x ++) { firePixels[(fireHeight - 1) * fireWidth + x] = firePalette.length - 1; } bitmap = Bitmap.createBitmap(fireWidth, fireHeight, Bitmap.Config.RGB_565); } @Override protected void onDraw(Canvas canvas) { spreadFire(); drawFire(canvas); invalidate(); } private void drawFire(Canvas canvas) { final int pixelCount = fireWidth * fireHeight; if (bitmapPixels == null || bitmapPixels.length < pixelCount ) { bitmapPixels = new int[pixelCount]; } final int startY = this.minHotY < 0 ? 0 : minHotY; for (int y = startY; y < fireHeight; y++) { for (int x = 0; x < fireWidth; x++) { int temperature = firePixels[x + y * fireWidth]; if (temperature < 0) { temperature = 0; } if (temperature >= firePalette.length) { temperature = firePalette.length - 1; } @ColorInt int color = firePalette[temperature]; bitmapPixels[fireWidth * y + x] = color; } } bitmap.setPixels(bitmapPixels, 0, fireWidth, 0, 0, fireWidth, fireHeight); float scale = (float) getWidth() / fireWidth; canvas.scale(scale, scale); canvas.drawBitmap(bitmap, 0, 0, paint); } private void spreadFire() { final int startY = this.minHotY < 0 ? 0 : Math.max(0, minHotY - 5); int minHotY = -1; for (int y = startY; y < fireHeight - 1; y++) { for (int x = 0; x < fireWidth; x++) { int rand_x = random.nextInt(3); int rand_y = random.nextInt(6); int dst_x = Math.min(fireWidth - 1, Math.max(0, x + rand_x - 1)); int dst_y = Math.min(fireHeight - 1, y + rand_y); int deltaFire = -(rand_x & 1); int temp = Math.max(0, firePixels[dst_x + dst_y * fireWidth] + deltaFire); firePixels[x + y * fireWidth] = temp; if (minHotY == -1 && temp > 0) { minHotY = y; } } } this.minHotY = minHotY; } }
29.957447
90
0.533854
e4d5fd58cc1f7546fc88c722226a1382dec1a667
1,519
package org.gooru.nucleus.handlers.courses.processors.repositories.activejdbc.dbhelpers; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.gooru.nucleus.handlers.courses.app.components.DataSourceRegistry; import org.javalite.activejdbc.Base; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author ashish. */ public final class LanguageValidator { private static Set<Integer> languageIds; private static final Logger LOGGER = LoggerFactory.getLogger(LanguageValidator.class); private static final String LANG_QUERY = "select id from gooru_language where is_visible = true"; private LanguageValidator() {} public static boolean isValidLanguage(Integer id) { return id != null && languageIds.contains(id); } @SuppressWarnings("rawtypes") public static void initialize() { try { Base.open(DataSourceRegistry.getInstance().getDefaultDataSource()); List result = Base.firstColumn(LANG_QUERY); if (result == null || result.isEmpty()) { throw new AssertionError("No language values available"); } Set<Integer> foundIds = new HashSet<>(result.size()); for (Object o : result) { foundIds.add((Integer) o); } languageIds = Collections.unmodifiableSet(foundIds); } catch (Throwable e) { LOGGER.error("Caught exception while fetching language values", e); throw new IllegalStateException(e); } finally { Base.close(); } } }
30.38
99
0.714944
d30e52f0fee3701638cd53b8f93eb2319e7722d3
2,944
package com.vailsys.freeclimb.webhooks.percl; import com.vailsys.freeclimb.api.call.CallStatus; import com.vailsys.freeclimb.api.call.Direction; import com.vailsys.freeclimb.webhooks.RequestType; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; public class OutDialIfMachineCallbackTest { private OutDialIfMachineCallback omic; private static final String OMIC_JSON_fax = "{\"accountId\":\"AC766bc3fb87212042619f41ac6344feef2f1b0d00\",\"callId\":\"CA06d0eeb157c2322e3c44a19947eec2085e4be356\",\"callStatus\":\"inProgress\",\"conferenceId\":null,\"parentCallId\":\"CA694ec3a0eedfc8d62a96e3c97defc89371b1fdda\",\"direction\":\"outboundDial\",\"machineType\":\"faxMachine\",\"from\":\"+12248806205\",\"queueId\":null,\"requestType\":\"machineDetected\",\"to\":\"+18475978014\"}"; private static final String OMIC_JSON_answering = "{\"accountId\":\"AC766bc3fb87212042619f41ac6344feef2f1b0d00\",\"callId\":\"CA06d0eeb157c2322e3c44a19947eec2085e4be356\",\"callStatus\":\"inProgress\",\"conferenceId\":null,\"parentCallId\":\"CA694ec3a0eedfc8d62a96e3c97defc89371b1fdda\",\"direction\":\"outboundDial\",\"machineType\":\"answeringMachine\",\"from\":\"+12248806205\",\"queueId\":null,\"requestType\":\"machineDetected\",\"to\":\"+18475978014\"}"; @Given("^An OutDialIfMachineCallback object with machineType (faxMachine|answeringMachine)$") public void newOIMC(String machineType) throws Throwable { if(machineType.equals("faxMachine")){ this.omic = OutDialIfMachineCallback.createFromJson(OMIC_JSON_fax); } else{ this.omic = OutDialIfMachineCallback.createFromJson(OMIC_JSON_answering); } } @Then("^verify the OutDialIfMachineCallback's contents with machineType (faxMachine|answeringMachine)$") public void verifyContents(String machineType) throws Throwable { assertThat(this.omic.getAccountId(), is("AC766bc3fb87212042619f41ac6344feef2f1b0d00")); assertThat(this.omic.getCallId(), is("CA06d0eeb157c2322e3c44a19947eec2085e4be356")); assertThat(this.omic.getCallStatus(), is(CallStatus.IN_PROGRESS)); assertThat(this.omic.getConferenceId(), is(nullValue())); assertThat(this.omic.getDirection(), is(Direction.OUTBOUND_DIAL)); assertThat(this.omic.getFrom(), is("+12248806205")); if(machineType.equals("faxMachine")) { assertThat(this.omic.getMachineType(), is(MachineType.FAX)); }else { assertThat(this.omic.getMachineType(), is(MachineType.ANSWERING)); } assertThat(this.omic.getParentCallId(), is("CA694ec3a0eedfc8d62a96e3c97defc89371b1fdda")); assertThat(this.omic.getRequestType(), is(RequestType.MACHINE_DETECTED)); assertThat(this.omic.getTo(), is("+18475978014")); } }
62.638298
464
0.733356
72bd64d0c9d35a4f9355c4e14f52b50d1424ff91
1,721
package com.github.wz2cool.dynamic.mybatis.mapper.provider.factory; import com.github.wz2cool.dynamic.mybatis.db.model.entity.table.User; import com.github.wz2cool.dynamic.mybatis.db.model.entity.view.ProductView; import org.junit.Before; import org.junit.Test; public class DynamicCreateSqlFactoryTest { DynamicCreateSqlFactory sqlFactory; @Before public void getSqlFactory() { sqlFactory = DynamicCreateSqlFactory.getSqlFactory(ProviderTableHelper.getProviderTable(User.class)); } @Test public void getInsertSql() { System.out.println(sqlFactory.getInsertSql(true)); System.out.println(sqlFactory.getInsertSql(false)); } @Test public void getInsertSql2222() { DynamicCreateSqlFactory sqlFactory = DynamicCreateSqlFactory.getSqlFactory(ProviderTableHelper.getProviderTable(User.class)); DynamicCreateSqlFactory sqlFactory2 = DynamicCreateSqlFactory.getSqlFactory(ProviderTableHelper.getProviderTable(ProductView.class)); } @Test public void getDeleteSql() { System.out.println(sqlFactory.getDeleteSql(true)); System.out.println(sqlFactory.getDeleteSql(false)); } @Test public void getUpdateByPrimaryKeySql() { System.out.println(sqlFactory.getUpdateByPrimaryKeySql(true)); System.out.println(sqlFactory.getUpdateByPrimaryKeySql(false)); } @Test public void getDynamicDelete() { System.out.println(sqlFactory.getDynamicDelete()); } @Test public void getDynamicQuery() { System.out.println(sqlFactory.getDynamicQuery()); } @Test public void getDynamicCount() { System.out.println(sqlFactory.getDynamicCount()); } }
30.732143
141
0.728065
291f6660765ed53482208b46e6b6f2f37f0164e7
204
package com.newness.efficient.attendance.clockin.bo; import lombok.Data; @Data public class ClockInGridBo { private Integer pageSize; private Integer pageNum; private Integer analyzed; }
14.571429
52
0.754902
ff0920c7718b48804cf8521971c37f3ec7acd190
4,722
/* * Copyright 2011 gitblit.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.gitblit.models; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.eclipse.jgit.revwalk.RevCommit; import com.gitblit.utils.StringUtils; import com.gitblit.utils.TimeUtils; /** * Model class to represent the commit activity across many repositories. This * class is used by the Activity page. * * @author James Moger */ public class Activity implements Serializable, Comparable<Activity> { private static final long serialVersionUID = 1L; public final Date startDate; public final Date endDate; private final Set<RepositoryCommit> commits; private final Map<String, Metric> authorMetrics; private final Map<String, Metric> repositoryMetrics; private final Set<String> authorExclusions; /** * Constructor for one day of activity. * * @param date */ public Activity(Date date) { this(date, TimeUtils.ONEDAY - 1); } /** * Constructor for specified duration of activity from start date. * * @param date * the start date of the activity * @param duration * the duration of the period in milliseconds */ public Activity(Date date, long duration) { startDate = date; endDate = new Date(date.getTime() + duration); commits = new LinkedHashSet<RepositoryCommit>(); authorMetrics = new HashMap<String, Metric>(); repositoryMetrics = new HashMap<String, Metric>(); authorExclusions = new TreeSet<String>(); } /** * Exclude the specified authors from the metrics. * * @param authors */ public void excludeAuthors(Collection<String> authors) { for (String author : authors) { authorExclusions.add(author.toLowerCase()); } } /** * Adds a commit to the activity object as long as the commit is not a * duplicate. * * @param repository * @param branch * @param commit * @return a RepositoryCommit, if one was added. Null if this is duplicate * commit */ public RepositoryCommit addCommit(String repository, String branch, RevCommit commit) { RepositoryCommit commitModel = new RepositoryCommit(repository, branch, commit); return addCommit(commitModel); } /** * Adds a commit to the activity object as long as the commit is not a * duplicate. * * @param repository * @param branch * @param commit * @return a RepositoryCommit, if one was added. Null if this is duplicate * commit */ public RepositoryCommit addCommit(RepositoryCommit commitModel) { if (commits.add(commitModel)) { String author = StringUtils.removeNewlines(commitModel.getAuthorIdent().getName()); String authorName = author.toLowerCase(); String authorEmail = StringUtils.removeNewlines(commitModel.getAuthorIdent().getEmailAddress()).toLowerCase(); if (!repositoryMetrics.containsKey(commitModel.repository)) { repositoryMetrics.put(commitModel.repository, new Metric(commitModel.repository)); } repositoryMetrics.get(commitModel.repository).count++; if (!authorExclusions.contains(authorName) && !authorExclusions.contains(authorEmail)) { if (!authorMetrics.containsKey(author)) { authorMetrics.put(author, new Metric(author)); } authorMetrics.get(author).count++; } return commitModel; } return null; } public int getCommitCount() { return commits.size(); } public List<RepositoryCommit> getCommits() { List<RepositoryCommit> list = new ArrayList<RepositoryCommit>(commits); Collections.sort(list); return list; } public Map<String, Metric> getAuthorMetrics() { return authorMetrics; } public Map<String, Metric> getRepositoryMetrics() { return repositoryMetrics; } @Override public int compareTo(Activity o) { // reverse chronological order return o.startDate.compareTo(startDate); } }
28.792683
114
0.70288
5cb75feb99d72d4e66894afddf18fbd5d5baea64
34,817
package com.glitchcam.vepromei.edit; import android.content.Intent; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.glitchcam.vepromei.R; import com.glitchcam.vepromei.base.BaseActivity; import com.glitchcam.vepromei.edit.adapter.AssetRecyclerViewAdapter; import com.glitchcam.vepromei.edit.adapter.SpaceItemDecoration; import com.glitchcam.vepromei.edit.background.BackgroundActivity; import com.glitchcam.vepromei.edit.clipEdit.adjust.AdjustActivity; import com.glitchcam.vepromei.edit.clipEdit.speed.SpeedActivity; import com.glitchcam.vepromei.edit.clipEdit.spilt.SpiltActivity; import com.glitchcam.vepromei.edit.clipEdit.trim.TrimActivity; import com.glitchcam.vepromei.edit.clipEdit.volume.VolumeActivity; import com.glitchcam.vepromei.edit.data.AssetInfoDescription; import com.glitchcam.vepromei.edit.data.BackupData; import com.glitchcam.vepromei.edit.data.BitmapData; import com.glitchcam.vepromei.edit.interfaces.OnGrallyItemClickListener; import com.glitchcam.vepromei.edit.interfaces.OnItemClickListener; import com.glitchcam.vepromei.edit.interfaces.OnTitleBarClickListener; import com.glitchcam.vepromei.edit.view.CustomTitleBar; import com.glitchcam.vepromei.interfaces.TipsButtonClickListener; import com.glitchcam.vepromei.selectmedia.SelectMediaActivity; import com.glitchcam.vepromei.selectmedia.adapter.SelectedMediaDatasUI; import com.glitchcam.vepromei.selectmedia.bean.MediaData; import com.glitchcam.vepromei.utils.AppManager; import com.glitchcam.vepromei.utils.Constants; import com.glitchcam.vepromei.utils.TimelineUtil; import com.glitchcam.vepromei.utils.Util; import com.glitchcam.vepromei.utils.dataInfo.AnimationInfo; import com.glitchcam.vepromei.utils.dataInfo.ClipInfo; import com.glitchcam.vepromei.utils.dataInfo.TimelineData; import com.glitchcam.vepromei.utils.dataInfo.TransitionInfo; import com.meicam.sdk.NvsAudioTrack; import com.meicam.sdk.NvsStreamingContext; import com.meicam.sdk.NvsTimeline; import com.meicam.sdk.NvsVideoClip; import com.meicam.sdk.NvsVideoTrack; import java.util.ArrayList; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import static com.glitchcam.vepromei.utils.Constants.POINT3V4; import static com.glitchcam.vepromei.utils.Constants.POINT9V16; import static com.glitchcam.vepromei.utils.Constants.VIDEOVOLUME_MAXSEEKBAR_VALUE; import static com.glitchcam.vepromei.utils.Constants.VIDEOVOLUME_MAXVOLUMEVALUE; /** * VideoEditActivity class * * @author czl * @date 2018-05-28 */ public class VideoEditActivity extends BaseActivity { /* * 裁剪 * Clip trim * */ public static final int CLIPTRIM_REQUESTCODE = 101; /* * 分割 * Clip spilt * */ public static final int CLIPSPILTPOINT_REQUESTCODE = 102; /* * 调整 * Screen ratio * */ public static final int CLIPADJUST_REQUESTCODE = 104; /* * 速度 * speed * */ public static final int CLIPSPEED_REQUESTCODE = 105; /* * 音量 * volume * */ public static final int CLIPVOLUME_REQUESTCODE = 106; /* * 添加视频 * Add video * */ public static final int ADDVIDEO_REQUESTCODE = 107; public static final int REQUESTRESULT_BACKGROUND = 1012; int[] videoEditImageId = { R.drawable.trim, R.drawable.ratio, R.drawable.copy, R.drawable.background, R.drawable.speed, R.drawable.division, R.drawable.volume, }; String[] assetName; private AssetRecyclerViewAdapter mAssetRecycleAdapter; private ArrayList<AssetInfoDescription> mArrayAssetInfo; private ArrayList<TransitionInfo> mTransitionInfoArray; private ArrayList<ClipInfo> mClipInfoArray = new ArrayList<>(); private int mAddVideoPostion = 0, mCurrentPos = 0; private RecyclerView selectedRecyclerView; private SelectedMediaDatasUI selectedClipUI; private ImageView ivAddMedia; private CustomTitleBar mTitleBar; private RelativeLayout mBottomLayout; private RecyclerView mAssetRecycleView; private LinearLayout mVolumeUpLayout; private SeekBar mVideoVoiceSeekBar; private SeekBar mMusicVoiceSeekBar; private SeekBar mDubbingSeekBarSeekBar; private TextView mVideoVoiceSeekBarValue; private TextView mMusicVoiceSeekBarValue; private TextView mDubbingSeekBarSeekBarValue; private ImageView mSetVoiceFinish; private NvsStreamingContext mStreamingContext; private NvsTimeline mTimeline; private NvsVideoTrack mVideoTrack; private NvsAudioTrack mMusicTrack; private NvsAudioTrack mRecordAudioTrack; private VideoFragment mVideoFragment; private ClipInfo mCurrentClipInfo; private NvsVideoClip mCurrentNvsVideoClip; private CardView cvNext; private boolean m_waitFlag = false; /** * * clip 对应的动画集合 当前添加或删除 等操作 需要同步操作这个集合 以保证数据的同步 * 这个集合是当前页面级的 */ private ConcurrentHashMap<Integer, AnimationInfo> mVideoClipFxMap = new ConcurrentHashMap<>(); @Override protected int initRootView() { mStreamingContext = NvsStreamingContext.getInstance(); return R.layout.activity_video_edit; } @Override protected void initViews() { mTitleBar = findViewById(R.id.title_bar); mAssetRecycleView = findViewById(R.id.assetRecycleList); mBottomLayout = findViewById(R.id.bottomLayout); mVolumeUpLayout = findViewById(R.id.volumeUpLayout); mVideoVoiceSeekBar = findViewById(R.id.videoVoiceSeekBar); mMusicVoiceSeekBar = findViewById(R.id.musicVoiceSeekBar); mDubbingSeekBarSeekBar = findViewById(R.id.dubbingSeekBar); mVideoVoiceSeekBarValue = findViewById(R.id.videoVoiceSeekBarValue); mMusicVoiceSeekBarValue = findViewById(R.id.musicVoiceSeekBarValue); mDubbingSeekBarSeekBarValue = findViewById(R.id.dubbingSeekBarValue); mSetVoiceFinish = findViewById(R.id.finish); ivAddMedia = findViewById(R.id.iv_add_media); selectedRecyclerView = findViewById(R.id.ve_selected_media_rv); cvNext = findViewById(R.id.cv_next); } @Override protected void initTitle() { mTitleBar.setTextCenter(R.string.videoEdit); mTitleBar.setTextCenter(""); mTitleBar.setTextRightVisible(View.VISIBLE); } @Override protected void initData() { mTimeline = TimelineUtil.createTimeline(); if (mTimeline == null) { return; } mVideoTrack = mTimeline.getVideoTrackByIndex(0); if (mVideoTrack == null) { return; } NvsVideoClip nvsVideoClip = mVideoTrack.getClipByIndex(mCurrentPos); if (nvsVideoClip == null) { return; } mCurrentNvsVideoClip = nvsVideoClip; mTransitionInfoArray = TimelineData.instance().cloneTransitionsData(); mClipInfoArray = TimelineData.instance().cloneClipInfoData(); mCurrentPos = 0; BackupData.instance().setClipIndex(0); BackupData.instance().setClipInfoData(mClipInfoArray); setVideoClip(); //clip 对应的动画集合 ConcurrentHashMap<Integer, AnimationInfo> fxMap = TimelineData.instance().getmAnimationFxMap(); mVideoClipFxMap.putAll(fxMap); ivAddMedia.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { reAddMediaAsset(); } }); initVideoFragment(); initAssetInfo(); initAssetRecycleAdapter(); initVoiceSeekBar(); loadVideoClipFailTips(); initSelectedRecyclerView(); } private void setVideoClip() { if (mClipInfoArray.get(mCurrentPos) != null && mClipInfoArray.size() > 0) { mCurrentClipInfo = mClipInfoArray.get(mCurrentPos); } } @Override protected void onResume() { super.onResume(); m_waitFlag = false; if (mTimeline != null) { mMusicTrack = mTimeline.getAudioTrackByIndex(0); mRecordAudioTrack = mTimeline.getAudioTrackByIndex(1); } } @Override public void onBackPressed() { super.onBackPressed(); removeTimeline(); clearData(); AppManager.getInstance().finishActivity(); } private void initSelectedRecyclerView(){ LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); selectedRecyclerView.setLayoutManager(linearLayoutManager); selectedClipUI = new SelectedMediaDatasUI(getApplicationContext(), new ArrayList<MediaData>(), mClipInfoArray, false, new SelectedMediaDatasUI.OnClickSelectedItem() { @Override public void onClickCellData(int position) { mCurrentPos = position; BackupData.instance().setClipIndex(mCurrentPos); mCurrentClipInfo = mClipInfoArray.get(position); if (position >= 0 && position < mClipInfoArray.size()) { playCurrentClip(position); NvsVideoTrack videoTrack = mTimeline.getVideoTrackByIndex(mCurrentPos); if (videoTrack != null) { mCurrentNvsVideoClip = videoTrack.getClipByIndex(position); } mVideoFragment.setVideoClipInfo(mCurrentClipInfo, mCurrentNvsVideoClip); mVideoFragment.setTransformViewVisible(View.VISIBLE); } } @Override public void onClickRemoveData(int position) {} }); selectedRecyclerView.setAdapter(selectedClipUI); ItemTouchHelper.Callback callback = new com.glitchcam.vepromei.edit.grallyRecyclerView.ItemTouchHelper(selectedClipUI); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback); itemTouchHelper.attachToRecyclerView(selectedRecyclerView); selectedClipUI.setOnItemSelectedListener(new OnGrallyItemClickListener() { @Override public void onLeftItemClick(View view, int pos) {} @Override public void onRightItemClick(View view, int pos) {} @Override public void onItemMoved(int fromPosition, int toPosition) { mCurrentPos = toPosition; BackupData.instance().setClipIndex(mCurrentPos); mCurrentClipInfo = mClipInfoArray.get(mCurrentPos); Collections.swap(mClipInfoArray, fromPosition, toPosition); selectedClipUI.setClipInfoArray(mClipInfoArray); selectedClipUI.notifyDataSetChanged(); swapAnimationInfo(fromPosition,toPosition); } @Override public void onItemDismiss(int position) {} @Override public void removeall() {} }); } /** * 播放视频 * Play video */ private void playCurrentClip(int mSelectedClipPosition) { int clipCount = mTimeline.getVideoTrackByIndex(0).getClipCount(); long playStartPoint = 0; long playEndPoint = 0; if (mSelectedClipPosition >= 0 && mSelectedClipPosition < clipCount) { playStartPoint = getClipStartTime(mSelectedClipPosition); playEndPoint = getClipEndTime(mSelectedClipPosition); //播放时针对timeline 的 if (playEndPoint > playStartPoint) { //除了第一条片段,其他片段延0.5s播放时间,从开始向前 //设置进度条显示 0 - duration if (mSelectedClipPosition > 0) { playStartPoint -= 0.5 * 1000 * 1000; playEndPoint -= 0.5 * 1000 * 1000; } mVideoFragment.setmPlaySeekBarMaxAndCurrent(playStartPoint, playEndPoint, playStartPoint, mTimeline.getDuration()); mVideoFragment.playVideoButtonCilck(playStartPoint, playEndPoint); } } //播放全部视频 else if (mSelectedClipPosition == -1) { playStartPoint = mStreamingContext.getTimelineCurrentPosition(mTimeline); playEndPoint = mTimeline.getDuration(); //播放全部视频时 duration = end //设置进度条显示 mVideoFragment.setmPlaySeekBarMaxAndCurrent(0, playEndPoint, playStartPoint, playEndPoint); if (playEndPoint > playStartPoint) { mVideoFragment.playVideoButtonCilck(playStartPoint, playEndPoint); } } } /** * 获取当前选择的片段的起始位置 * * @param mSelectedClipPosition * @return */ private long getClipStartTime(int mSelectedClipPosition) { NvsVideoTrack nvsVideoTrack = mTimeline.getVideoTrackByIndex(0); if (nvsVideoTrack == null) { return 0; } NvsVideoClip nvsVideoClip = nvsVideoTrack.getClipByIndex(mSelectedClipPosition); if (nvsVideoClip == null) { return 0; } long clipInPoint = nvsVideoClip.getInPoint(); return clipInPoint; } /** * 获取当前选择的片段的起始位置 * * @param mSelectedClipPosition * @return */ private long getClipEndTime(int mSelectedClipPosition) { NvsVideoTrack nvsVideoTrack = mTimeline.getVideoTrackByIndex(0); if (nvsVideoTrack == null) { return 0; } NvsVideoClip nvsVideoClip = nvsVideoTrack.getClipByIndex(mSelectedClipPosition); if (nvsVideoClip == null) { return 0; } long clipOutPoint = nvsVideoClip.getOutPoint(); return clipOutPoint; } private void loadVideoClipFailTips() { /* * 导入视频无效,提示 * The imported video is invalid * */ if (mTimeline == null || (mTimeline.getDuration() <= 0)) { String[] versionName = getResources().getStringArray(R.array.clip_load_failed_tips); Util.showDialog(VideoEditActivity.this, versionName[0], versionName[1], new TipsButtonClickListener() { @Override public void onTipsButtoClick(View view) { removeTimeline(); AppManager.getInstance().finishActivity(); } }); } } /** * 清空数据 * Clear data */ private void clearData() { TimelineData.instance().clear(); BackupData.instance().clear(); BitmapData.instance().clear(); } private void removeTimeline() { TimelineUtil.removeTimeline(mTimeline); mTimeline = null; } private void initVoiceSeekBar() { mVideoVoiceSeekBar.setMax(VIDEOVOLUME_MAXSEEKBAR_VALUE); mMusicVoiceSeekBar.setMax(VIDEOVOLUME_MAXSEEKBAR_VALUE); mDubbingSeekBarSeekBar.setMax(VIDEOVOLUME_MAXSEEKBAR_VALUE); if (mVideoTrack == null) { return; } int volumeVal = (int) Math.floor(mVideoTrack.getVolumeGain().leftVolume / VIDEOVOLUME_MAXVOLUMEVALUE * VIDEOVOLUME_MAXSEEKBAR_VALUE + 0.5D); updateVideoVoiceSeekBar(volumeVal); updateMusicVoiceSeekBar(volumeVal); updateDubbingVoiceSeekBar(volumeVal); } private void updateVideoVoiceSeekBar(int volumeVal) { mVideoVoiceSeekBar.setProgress(volumeVal); mVideoVoiceSeekBarValue.setText(String.valueOf(volumeVal)); } private void updateMusicVoiceSeekBar(int volumeVal) { mMusicVoiceSeekBar.setProgress(volumeVal); mMusicVoiceSeekBarValue.setText(String.valueOf(volumeVal)); } private void updateDubbingVoiceSeekBar(int volumeVal) { mDubbingSeekBarSeekBar.setProgress(volumeVal); mDubbingSeekBarSeekBarValue.setText(String.valueOf(volumeVal)); } private void setVideoVoice(int voiceVal) { if (mVideoTrack == null) { return; } updateVideoVoiceSeekBar(voiceVal); float volumeVal = voiceVal * VIDEOVOLUME_MAXVOLUMEVALUE / VIDEOVOLUME_MAXSEEKBAR_VALUE; mVideoTrack.setVolumeGain(volumeVal, volumeVal); TimelineData.instance().setOriginVideoVolume(volumeVal); } private void setMusicVoice(int voiceVal) { if (mMusicTrack == null) { return; } updateMusicVoiceSeekBar(voiceVal); float volumeVal = voiceVal * VIDEOVOLUME_MAXVOLUMEVALUE / VIDEOVOLUME_MAXSEEKBAR_VALUE; mMusicTrack.setVolumeGain(volumeVal, volumeVal); TimelineData.instance().setMusicVolume(volumeVal); } private void setDubbingVoice(int voiceVal) { if (mRecordAudioTrack == null) { return; } updateDubbingVoiceSeekBar(voiceVal); float volumeVal = voiceVal * VIDEOVOLUME_MAXVOLUMEVALUE / VIDEOVOLUME_MAXSEEKBAR_VALUE; mRecordAudioTrack.setVolumeGain(volumeVal, volumeVal); TimelineData.instance().setRecordVolume(volumeVal); } private void initVideoFragment() { mVideoFragment = new VideoFragment(); mVideoFragment.setFragmentLoadFinisedListener(new VideoFragment.OnFragmentLoadFinisedListener() { @Override public void onLoadFinished() { mVideoFragment.seekTimeline(mStreamingContext.getTimelineCurrentPosition(mTimeline), 0); } }); mVideoFragment.setTimeline(mTimeline); mVideoFragment.setAutoPlay(true); Bundle bundle = new Bundle(); bundle.putInt("titleHeight", mTitleBar.getLayoutParams().height); bundle.putInt("bottomHeight", mBottomLayout.getLayoutParams().height); bundle.putInt("ratio", TimelineData.instance().getMakeRatio()); bundle.putBoolean("playBarVisible", true); bundle.putBoolean("voiceButtonVisible", true); mVideoFragment.setArguments(bundle); getFragmentManager().beginTransaction().add(R.id.video_layout, mVideoFragment).commit(); getFragmentManager().beginTransaction().show(mVideoFragment); } private void initAssetInfo() { mArrayAssetInfo = new ArrayList<>(); assetName = getResources().getStringArray(R.array.effectNamesVideo); for (int i = 0; i < assetName.length; i++) { mArrayAssetInfo.add(new AssetInfoDescription(assetName[i], videoEditImageId[i])); } } private void initAssetRecycleAdapter() { LinearLayoutManager layoutManager = new LinearLayoutManager(VideoEditActivity.this, LinearLayoutManager.HORIZONTAL, false); mAssetRecycleView.setLayoutManager(layoutManager); mAssetRecycleAdapter = new AssetRecyclerViewAdapter(VideoEditActivity.this); mAssetRecycleAdapter.updateData(mArrayAssetInfo); mAssetRecycleView.setAdapter(mAssetRecycleAdapter); mAssetRecycleView.addItemDecoration(new SpaceItemDecoration(8, 8)); mAssetRecycleAdapter.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(View view, int pos) { if (m_waitFlag) { return; } mStreamingContext.stop(); switch (pos) { case 0://trim m_waitFlag = true; AppManager.getInstance().jumpActivityForResult(AppManager.getInstance().currentActivity(), TrimActivity.class, null, VideoEditActivity.CLIPTRIM_REQUESTCODE); break; case 1: // ratio m_waitFlag = true; AppManager.getInstance().jumpActivityForResult(AppManager.getInstance().currentActivity(), AdjustActivity.class, null, VideoEditActivity.CLIPADJUST_REQUESTCODE); break; case 2: // copy media asset m_waitFlag = true; copyMediaAsset(); break; case 3: // background m_waitFlag = true; AppManager.getInstance().jumpActivityForResult(AppManager.getInstance().currentActivity(), BackgroundActivity.class, null, VideoEditActivity.REQUESTRESULT_BACKGROUND); break; case 4: // speed m_waitFlag = true; AppManager.getInstance().jumpActivityForResult(AppManager.getInstance().currentActivity(), SpeedActivity.class, null, VideoEditActivity.CLIPSPEED_REQUESTCODE); break; case 5: // split m_waitFlag = true; AppManager.getInstance().jumpActivityForResult(AppManager.getInstance().currentActivity(), SpiltActivity.class, null, VideoEditActivity.CLIPSPILTPOINT_REQUESTCODE); break; case 6: // volume AppManager.getInstance().jumpActivityForResult(AppManager.getInstance().currentActivity(), VolumeActivity.class, null, VideoEditActivity.CLIPVOLUME_REQUESTCODE); break; default: break; } } }); } private void copyMediaAsset() { if (mClipInfoArray.size() == 0) { return; } int count = mClipInfoArray.size(); if (mCurrentPos < 0 || mCurrentPos > count) { return; } mClipInfoArray.add(mCurrentPos, mClipInfoArray.get(mCurrentPos).clone()); mCurrentPos++; BackupData.instance().setClipIndex(mCurrentPos); //添加一个动画的对象 addNewAnimationInfo(true, mCurrentPos,1); /* * 添加转场 * Add transition * */ if (mTransitionInfoArray != null && mTransitionInfoArray.size() >= mCurrentPos) { mTransitionInfoArray.add(mCurrentPos, new TransitionInfo()); } selectedClipUI.setSelectPos(mCurrentPos); selectedClipUI.setClipInfoArray(mClipInfoArray); selectedClipUI.notifyDataSetChanged(); /* * 复制移动到下一个位置 * Copy move to next position * */ selectedRecyclerView.smoothScrollToPosition(mCurrentPos); BackupData.instance().setClipInfoData(mClipInfoArray); TimelineData.instance().setVideoResolution(Util.getVideoEditResolution(POINT9V16)); TimelineData.instance().setClipInfoData(mClipInfoArray); TimelineData.instance().setMakeRatio(POINT9V16); resetVideoFragment(); m_waitFlag = false; //添加一份 } /** * 添加一个动画item * 添加的逻辑就是构建一个新的集合,遍历旧的集合的数据,key+size 作为新的key * 如果需要添加一个动画特效对象,则添加到mCurrentPosition 位置 * * @param addItem 是否需要添加特效 * @param mCurrentPos 当前选择要添加的位置 * @param size 操作的数量 */ private void addNewAnimationInfo(boolean addItem ,int mCurrentPos,int size) { //如果当前就有动画效果,则复制一份 if(mVideoClipFxMap != null && mVideoClipFxMap.size()>0 ){ //构建一个新的集合存储新的数据; ConcurrentHashMap<Integer, AnimationInfo> tempMap = new ConcurrentHashMap<>(); Set<Integer> keySet = mVideoClipFxMap.keySet(); for(Integer key : keySet){ if(key >= mCurrentPos){ //遍历旧的集合的数据,key+size 作为新的key AnimationInfo animationInfo = mVideoClipFxMap.get(key); tempMap.put((key+size),animationInfo); }else{ AnimationInfo animationInfo = mVideoClipFxMap.get(key); tempMap.put(key,animationInfo); } } if(addItem){ AnimationInfo animationInfo = mVideoClipFxMap.get(mCurrentPos); AnimationInfo newOne = new AnimationInfo(); newOne.setmAssetType(animationInfo.getmAssetType()); newOne.setmAnimationIn(animationInfo.getmAnimationIn()); newOne.setmAnimationOut(animationInfo.getmAnimationOut()); newOne.setmPackageId(animationInfo.getmPackageId()); tempMap.put(mCurrentPos,newOne); } //然后重新赋值 mVideoClipFxMap.clear(); mVideoClipFxMap.putAll(tempMap); } } @Override protected void initListener() { mTitleBar.setOnTitleBarClickListener(new OnTitleBarClickListener() { @Override public void OnBackImageClick() { removeTimeline(); clearData(); } @Override public void OnCenterTextClick() { } @Override public void OnRightTextClick() { } }); mVideoVoiceSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { setVideoVoice(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mMusicVoiceSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { setMusicVoice(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mDubbingSeekBarSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { setDubbingVoice(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mSetVoiceFinish.setOnClickListener(this); if (mVideoFragment != null) { mVideoFragment.setVideoVolumeListener(new VideoFragment.VideoVolumeListener() { @Override public void onVideoVolume() { mVolumeUpLayout.setVisibility(View.VISIBLE); } }); } cvNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AppManager.getInstance().jumpActivity(VideoEditActivity.this, VideoEditActivity2.class, null); } }); mVolumeUpLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); } /** * 交换两个item 位置 * @param fromPosition 起点位置 * @param toPosition 终点位置 */ private void swapAnimationInfo(int fromPosition, int toPosition) { //如果当前就有动画效果,则复制一份 if(null != mVideoClipFxMap && mVideoClipFxMap.size()>0 && mVideoClipFxMap.containsKey(fromPosition) &&mVideoClipFxMap.containsKey(toPosition) ){ AnimationInfo animationInfoFrom = mVideoClipFxMap.get(fromPosition); AnimationInfo animationInfoTo = mVideoClipFxMap.get(toPosition); mVideoClipFxMap.put(fromPosition,animationInfoTo); mVideoClipFxMap.put(toPosition,animationInfoFrom); } } private void reAddMediaAsset() { mAddVideoPostion = mCurrentPos+1; Bundle bundle = new Bundle(); bundle.putInt("visitMethod", Constants.FROMCLIPEDITACTIVITYTOVISIT); BackupData.instance().clearAddClipInfoList(); AppManager.getInstance().jumpActivityForResult(VideoEditActivity.this, SelectMediaActivity.class, bundle, ADDVIDEO_REQUESTCODE); } private void processAddMediaResult(){ mClipInfoArray = BackupData.instance().getClipInfoData(); ArrayList<ClipInfo> addCipInfoList = BackupData.instance().getAddClipInfoList(); if (addCipInfoList.size() > 0) { //此处是从媒体库在选择资源 , 修改存储的动画的特效数据结构 addNewAnimationInfo(false, mAddVideoPostion, addCipInfoList.size()); mClipInfoArray.addAll(mAddVideoPostion, addCipInfoList); BackupData.instance().setClipInfoData(mClipInfoArray); BackupData.instance().clearAddClipInfoList(); TimelineData.instance().setVideoResolution(Util.getVideoEditResolution(POINT3V4)); TimelineData.instance().setClipInfoData(mClipInfoArray); TimelineData.instance().setMakeRatio(POINT3V4); TimelineData.instance().setClipInfoData(mClipInfoArray); /* * 为新增的素材添加默认转场 * Add default transitions for new material */ if (mTransitionInfoArray != null) { ArrayList<TransitionInfo> temp = new ArrayList<>(); int maxTransitionCount = mClipInfoArray.size() - mTransitionInfoArray.size() - 1; for (int i = 0; i < maxTransitionCount; i++) { TransitionInfo transitionInfo = new TransitionInfo(); temp.add(transitionInfo); } if (mAddVideoPostion <= mTransitionInfoArray.size()) { mTransitionInfoArray.addAll(mAddVideoPostion, temp); } } } mCurrentPos = mClipInfoArray.size()-1; selectedClipUI.setClipInfoArray(mClipInfoArray); selectedClipUI.setSelectPos(mCurrentPos); selectedClipUI.notifyDataSetChanged(); selectedRecyclerView.smoothScrollToPosition(mCurrentPos); BackupData.instance().setClipIndex(mCurrentPos); resetVideoFragment(); } private void resetVideoFragment() { mTimeline = TimelineUtil.createTimeline(); if (mTimeline == null) { return; } mVideoTrack = mTimeline.getVideoTrackByIndex(0); if (mVideoTrack == null) { return; } NvsVideoClip nvsVideoClip = mVideoTrack.getClipByIndex(mCurrentPos); if (nvsVideoClip == null) { return; } mCurrentNvsVideoClip = nvsVideoClip; mTransitionInfoArray = TimelineData.instance().cloneTransitionsData(); //clip 对应的动画集合 ConcurrentHashMap<Integer, AnimationInfo> fxMap = TimelineData.instance().getmAnimationFxMap(); mVideoClipFxMap.putAll(fxMap); initVideoFragment(); } private void refreshClipInfos(){ /* * 为新增的素材添加默认转场 * Add default transitions for new material */ if (mTransitionInfoArray != null) { ArrayList<TransitionInfo> temp = new ArrayList<>(); int maxTransitionCount = mClipInfoArray.size() - mTransitionInfoArray.size() - 1; for (int i = 0; i < maxTransitionCount; i++) { TransitionInfo transitionInfo = new TransitionInfo(); temp.add(transitionInfo); } if (mAddVideoPostion <= mTransitionInfoArray.size()) { mTransitionInfoArray.addAll(mAddVideoPostion, temp); } } selectedClipUI.setClipInfoArray(mClipInfoArray); selectedClipUI.setSelectPos(mCurrentPos); selectedClipUI.notifyDataSetChanged(); selectedRecyclerView.smoothScrollToPosition(mCurrentPos); resetVideoFragment(); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.finish) { mVolumeUpLayout.setVisibility(View.GONE); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) { return; } if (data == null) { return; } mClipInfoArray = BackupData.instance().getClipInfoData(); mCurrentPos = BackupData.instance().getClipIndex(); switch (requestCode) { case CLIPTRIM_REQUESTCODE: // trim result TimelineData.instance().setClipInfoData(mClipInfoArray); refreshClipInfos(); break; case CLIPADJUST_REQUESTCODE: // ratio result TimelineData.instance().setClipInfoData(mClipInfoArray); refreshClipInfos(); break; case ADDVIDEO_REQUESTCODE: // copy result processAddMediaResult(); break; case REQUESTRESULT_BACKGROUND: // background result TimelineData.instance().setClipInfoData(mClipInfoArray); refreshClipInfos(); break; case CLIPSPEED_REQUESTCODE: // speed result TimelineData.instance().setClipInfoData(mClipInfoArray); refreshClipInfos(); break; case CLIPSPILTPOINT_REQUESTCODE: // split result int spiltPosition = data.getIntExtra("spiltPosition", -1); if (spiltPosition != -1) { if ((mTransitionInfoArray != null) && (!mTransitionInfoArray.isEmpty())) { if (spiltPosition <= mTransitionInfoArray.size()) { mTransitionInfoArray.add(spiltPosition, new TransitionInfo()); } } mCurrentPos = spiltPosition; BackupData.instance().setClipIndex(mCurrentPos); TimelineData.instance().setClipInfoData(mClipInfoArray); refreshClipInfos(); } break; case CLIPVOLUME_REQUESTCODE: TimelineData.instance().setClipInfoData(mClipInfoArray); refreshClipInfos(); break; } } }
36.3814
174
0.631243
cffc9d09eef9575adfae90947b1e29d29df254fb
612
package ericminio.javaoracle.domain; import ericminio.javaoracle.domain.PlaceholderList; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; public class PlaceholderListTest { @Test public void emptyStringWhenEmpty() { assertThat(new PlaceholderList().please(0), equalTo("")); } @Test public void one() { assertThat(new PlaceholderList().please(1), equalTo("?")); } @Test public void two() { assertThat(new PlaceholderList().please(2), equalTo("?, ?")); } }
23.538462
70
0.650327
064bf2a2b5de012d2e01f4c00ea7f2b62abb5fb8
3,039
package org.haobtc.onekey.utils; import android.app.Activity; import android.graphics.Rect; import android.view.View; import android.view.ViewTreeObserver; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import java.security.InvalidParameterException; /** * 监听 View 的高度变化,达到一定阈值触发显示隐藏 View 的监听。 * * @author Onekey@QuincySx * @create 2020-12-29 12:15 PM */ public class ViewHeightStatusDetector { private int mViewMinHeight; private boolean visible = false; private VisibilityListener mVisibilityListener; private View mView; private final ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener = this::calculateHeight; public ViewHeightStatusDetector(int minHeight) { mViewMinHeight = minHeight; } public ViewHeightStatusDetector register(@NonNull Fragment fragment) { return register(fragment.getView()); } public ViewHeightStatusDetector register(@NonNull Activity activity) { return register(activity.getWindow().getDecorView().findViewById(android.R.id.content)); } public ViewHeightStatusDetector register(@Nullable final View view) { if (view == null) { throw new InvalidParameterException("The View cannot be null."); } mView = view; view.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener); return this; } public void unregister(@NonNull Activity activity) { unregister(activity.getWindow().getDecorView().findViewById(android.R.id.content)); } public void unregister(@NonNull Fragment fragment) { if (fragment.getView() != null) { unregister(fragment.getView()); } } public void unregister(@NonNull View view) { view.getViewTreeObserver().removeOnGlobalLayoutListener(mOnGlobalLayoutListener); } /** * 设置隐藏显示的监听。 * * @param listener 监听器 */ public void setVisibilityListener(VisibilityListener listener) { mVisibilityListener = listener; } /** * 实时修改触发阈值 * * @param minHeight 阈值 */ public void notification(int minHeight) { mViewMinHeight = minHeight; calculateHeight(); } private void calculateHeight() { Rect r = new Rect(); mView.getWindowVisibleDisplayFrame(r); int heightDiff = (r.bottom - r.top); if (heightDiff > mViewMinHeight) { if (!visible) { visible = true; if (mVisibilityListener != null) { mVisibilityListener.onVisibilityChanged(true); } } } else { if (visible) { visible = false; if (mVisibilityListener != null) { mVisibilityListener.onVisibilityChanged(false); } } } } public interface VisibilityListener { void onVisibilityChanged(boolean visible); } }
27.627273
106
0.645278
18a4acd01193b85f0b4f474072740da3f5205713
2,586
/** * Copyright (C) 2006-2016 INRIA and contributors * Spoon - http://spoon.gforge.inria.fr/ * * This software is governed by the CeCILL-C License under French law and * abiding by the rules of distribution of free software. You can use, modify * and/or redistribute the software under the terms of the CeCILL-C license as * circulated by CEA, CNRS and INRIA at http://www.cecill.info. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the CeCILL-C License for more details. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C license and that you accept its terms. */ package spoon.reflect.cu; import spoon.compiler.Environment; import spoon.reflect.cu.position.NoSourcePosition; import java.io.File; import java.io.Serializable; /** * This interface represents the position of a program element in a source file. */ public interface SourcePosition extends Serializable { SourcePosition NOPOSITION = new NoSourcePosition(); /** * Returns a string representation of this position in the form * "sourcefile:line", or "sourcefile" if no line number is available. */ String toString(); /** * Gets the file for this position. */ File getFile(); /** * Gets the compilation unit for this position. */ CompilationUnit getCompilationUnit(); /** * Gets the line in the source file (1 indexed). Prefer using * {@link #getSourceStart()}}. * For CtNamedElement the line is where the name is declared. */ int getLine(); /** * Gets the end line in the source file (1 indexed). Prefer using * {@link #getSourceEnd()}}. */ int getEndLine(); /** * Gets the column in the source file (1 indexed). This method is slow * because it has to calculate the column number depending on * {@link Environment#getTabulationSize()} and * {@link CompilationUnit#getOriginalSourceCode()}. Prefer {@link #getSourceStart()}. */ int getColumn(); /** * Gets the end column in the source file (1 indexed). This method is slow * because it has to calculate the column number depending on * {@link Environment#getTabulationSize()} and * {@link CompilationUnit#getOriginalSourceCode()}. Prefer {@link #getSourceEnd()}. */ int getEndColumn(); /** * Gets the index at which the position ends in the source file. */ int getSourceEnd(); /** * Gets the index at which the position starts in the source file. */ int getSourceStart(); }
29.724138
86
0.716164
d3ce1a046bede41f642aadbfabf8f84ba2ebfc76
144
package fruit; public class Apple extends Fruit { @Override public String howToEat() { return "Apple could be slided"; } }
16
39
0.638889
7e1fbeba28f610c4404893fcbcc84e78c6d26f0b
5,143
/* * 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.algorithm.recreate; import com.graphhopper.jsprit.core.problem.driver.Driver; import com.graphhopper.jsprit.core.problem.vehicle.Vehicle; import java.util.ArrayList; import java.util.List; /** * Data object that collects insertion information. It collects insertionCosts, insertionIndeces, vehicle and driver to be employed * and departureTime of vehicle at vehicle's start location (e.g. depot). * * @author stefan */ public class InsertionData { public static class NoInsertionFound extends InsertionData { public NoInsertionFound() { super(Double.MAX_VALUE, NO_INDEX, NO_INDEX, null, null); } } private static InsertionData noInsertion = new NoInsertionFound(); /** * Returns an instance of InsertionData that represents an EmptyInsertionData (which might indicate * that no insertion has been found). It is internally instantiated as follows:<br> * <code>new InsertionData(Double.MAX_VALUE, NO_INDEX, NO_INDEX, null, null);</code><br> * where NO_INDEX=-1. * * @return */ public static InsertionData createEmptyInsertionData() { return noInsertion; } static int NO_INDEX = -1; private double insertionCost; private final int pickupInsertionIndex; private final int deliveryInsertionIndex; private final Vehicle selectedVehicle; private final Driver selectedDriver; private double departureTime; private double additionalTime; private List<Event> events = new ArrayList<Event>(); List<Event> getEvents() { return events; } private List<String> reasons = new ArrayList<>(); /** * @return the additionalTime */ public double getAdditionalTime() { return additionalTime; } public void addFailedConstrainName(String name) { reasons.add(name); } public List<String> getFailedConstraintNames() { return reasons; } /** * @param additionalTime the additionalTime to set */ public void setAdditionalTime(double additionalTime) { this.additionalTime = additionalTime; } public InsertionData(double insertionCost, int pickupInsertionIndex, int deliveryInsertionIndex, Vehicle vehicle, Driver driver) { this.insertionCost = insertionCost; this.pickupInsertionIndex = pickupInsertionIndex; this.deliveryInsertionIndex = deliveryInsertionIndex; this.selectedVehicle = vehicle; this.selectedDriver = driver; } @Override public String toString() { return "[iCost=" + insertionCost + "][pickupIndex=" + pickupInsertionIndex + "][deliveryIndex=" + deliveryInsertionIndex + "][depTime=" + departureTime + "][vehicle=" + selectedVehicle + "][driver=" + selectedDriver + "]"; } /** * Returns insertionIndex of deliveryActivity. If no insertionPosition is found, it returns NO_INDEX (=-1). * * @return */ public int getDeliveryInsertionIndex() { return deliveryInsertionIndex; } /** * Returns insertionIndex of pickkupActivity. If no insertionPosition is found, it returns NO_INDEX (=-1). * * @return */ public int getPickupInsertionIndex() { return pickupInsertionIndex; } /** * Returns insertion costs (which might be the additional costs of inserting the corresponding job). * * @return */ public double getInsertionCost() { return insertionCost; } /** * Returns the vehicle to be employed. * * @return */ public Vehicle getSelectedVehicle() { return selectedVehicle; } /** * Returns the vehicle to be employed. * * @return */ public Driver getSelectedDriver() { return selectedDriver; } /** * @return the departureTime */ public double getVehicleDepartureTime() { return departureTime; } /** * @param departureTime the departureTime to set */ public void setVehicleDepartureTime(double departureTime) { this.departureTime = departureTime; } /** * @param insertionCost the insertionCost to set */ public void setInsertionCost(double insertionCost) { this.insertionCost = insertionCost; } }
28.258242
230
0.678009
ac1f1c2ca26d37520762efa4caf039ebed070aec
1,396
package be.ac.ulb.infof307.g01.client.model.map; import be.ac.ulb.infof307.g01.client.model.app.ClientConfiguration; import be.ac.ulb.infof307.g01.common.model.PokemonSendableModel; /** * Represents a Pokemon. * A pokemon is the generic pokemon entity, such as "Pikachu". A pokemon * spotted on the map is represented by MarkerModel. */ public class PokemonModel extends PokemonSendableModel { public PokemonModel(final PokemonSendableModel pokemon) { super(pokemon); // Convert all types to client model instances for(int i = 0; i < _types.length; ++i) { _types[i] = new PokemonTypeModel(_types[i]); } } @Override public String getImagePath() { return getImagePath(false); } /** * Gets the path to the pokemon's image. * During test, all folders don't exist, therefore the * path to some assets is not the same. * * @param isTest true if the path is requested during a test * @return the image's path */ public String getImagePath(final boolean isTest) { String assetFolder; if(isTest) { assetFolder = ClientConfiguration.getTestInstance().getSpritePath(); } else { assetFolder = ClientConfiguration.getInstance().getSpritePath(); } return assetFolder + super.getImagePath(); } }
31.022222
80
0.646848
a09beb7e9c0e7d1c5e699d5092313d6f9821427c
11,258
package eu.verdelhan.ansluta; import com.pi4j.io.gpio.*; import com.pi4j.io.spi.SpiChannel; import com.pi4j.io.spi.SpiDevice; import com.pi4j.io.spi.SpiFactory; import com.pi4j.io.spi.SpiMode; import java.io.IOException; /** * An Ikea Ansluta remote. * * CC2500 : http://www.ti.com/lit/ds/swrs040c/swrs040c.pdf */ public class AnslutaRemote { public static final boolean DEBUG = true; /** GPIO controller */ private static final GpioController gpio = GpioFactory.getInstance(); /** * Some SPI pins. */ private static Pin spiMiso = RaspiPin.GPIO_13; private static Pin spiCs = RaspiPin.GPIO_10; private static GpioPinDigitalInput misoInput = null; private static GpioPinDigitalOutput chipSelectOutput = null; /** The SPI device */ private SpiDevice spi; /** * Inits the remote. */ public void initAnsluta() throws IOException{ chipSelectOutput = gpio.provisionDigitalOutputPin(spiCs, "CS"); misoInput = gpio.provisionDigitalInputPin(spiMiso, "MISO"); if(DEBUG) { System.out.println("Debug mode"); System.out.print("Initialisation"); } spi = SpiFactory.getInstance(SpiChannel.CS0, 6000000, SpiMode.MODE_0); //Faster SPI mode, maximal speed for the CC2500 without the need for extra delays chipSelectOutput.high(); sendStrobe(CC2500.CC2500_SRES); //0x30 SRES Reset chip. initCC2500(); // sendStrobe(CC2500.CC2500_SPWD); //Enter power down mode - Not used in the prototype writeReg((byte) 0x3E, (byte) 0xFF); //Maximum transmit power - write 0xFF to 0x3E (PATABLE) if (DEBUG) { System.out.println(" - Done"); } Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.out.println("Shutting down."); gpio.shutdown(); })); } /** * Reads the address bytes from a remote (by sniffing its packets wireless). */ public void readAddressBytes() throws IOException { byte tries = 0; boolean AddressFound = false; if (DEBUG) { System.out.print("Listening for an Address"); } while ((tries<2000)&&(!AddressFound)) { //Try to listen for the address 2000 times if (DEBUG){ System.out.print("."); } sendStrobe(CC2500.CC2500_SRX); writeReg(CC2500.REG_IOCFG1, (byte) 0x01); // Switch MISO to output if a packet has been received or not delay(5); if (misoInput.isHigh()) { // TODO check condition //byte readStatus = readRegister(CC2500.REG_RXBYTES); // TODO: test3 //System.out.println("read status: " + bytesToHexString(readStatus)); byte PacketLength = readRegister(CC2500.CC2500_FIFO); byte[] recvPacket = new byte[PacketLength]; if(DEBUG) { System.out.print("\nPacket received: " + PacketLength + " bytes"); } if (PacketLength <= 8) { // A packet from the remote cant be longer than 8 bytes // Read the received data from CC2500 for (byte i = 0; i < PacketLength; i++) { recvPacket[i] = readRegister(CC2500.CC2500_FIFO); } if (DEBUG) { System.out.println(bytesToHexString(recvPacket)); } } // Search for the start of the sequence byte start=0; while ((recvPacket[start]!=0x55) && (start < PacketLength)) { start++; } if (recvPacket[start+1]==0x01 && recvPacket[start+5]==0xAA) { // The bytes match an Ikea remote sequence AddressFound = true; byte AddressByteA = recvPacket[start+2]; // Extract the addressbytes byte AddressByteB = recvPacket[start+3]; byte RecvCommand = recvPacket[start+4]; if (DEBUG) { System.out.println("Address Bytes found: " + bytesToHexString(AddressByteA, AddressByteB)); System.out.println("Hex command: " + bytesToHexString(RecvCommand)); if(RecvCommand==AnslutaCommand.LIGHT_OFF.command){System.out.println("Command:OFF");} if(RecvCommand==AnslutaCommand.LIGHT_ON_50.command){System.out.println("Command:50%");} if(RecvCommand==AnslutaCommand.LIGHT_ON_100.command){System.out.println("Command:100%");} if(RecvCommand==AnslutaCommand.LIGHT_PAIR.command){System.out.println("Command:Pair");} } } sendStrobe(CC2500.CC2500_SIDLE); // Needed to flush RX FIFO sendStrobe(CC2500.CC2500_SFRX); // Flush RX FIFO } tries++; //Another try has passed } if (DEBUG) { System.out.println(" - Done"); } } /** * Sends a command like a real Ansluta remote. * @param addressByteA the first byte of the address * @param addressByteB the second byte of the address * @param command the command to be sent */ public void sendCommand(byte addressByteA, byte addressByteB, byte command) throws IOException{ if (DEBUG) { System.out.print("Send command " + bytesToHexString(addressByteA, addressByteB, command)); } for (byte i=0;i<50;i++) { // Send 50 times System.out.print("."); sendStrobe(CC2500.CC2500_SIDLE); // 0x36 SIDLE Exit RX / TX, turn off frequency synthesizer and exit Wake-On-Radio mode if applicable. sendStrobe(CC2500.CC2500_SFTX); // 0x3B SFTX Flush the TX FIFO buffer. Only issue SFTX in IDLE or TXFIFO_UNDERFLOW states. chipSelectOutput.low(); while (misoInput.isHigh()) { }; // Wait untill MISO low //Command 0x01=Light OFF 0x02=50% 0x03=100% 0xFF=Pairing spi.write((byte) 0x7F, (byte) 0x06, (byte) 0x55, (byte) 0x01, addressByteA, addressByteB, command, (byte) 0xAA, (byte) 0xFF); chipSelectOutput.high(); sendStrobe(CC2500.CC2500_STX); //0x35 STX In IDLE state: Enable TX. Perform calibration first if MCSM0.FS_AUTOCAL=1. If in RX state and CCA is enabled: Only go to TX if channel is clear delay(1); } if (DEBUG) { System.out.println(" - Done"); } } /** * Reads a CC2500 register. * @param addr the CC2500 register address * @return the read value */ private byte readRegister(byte addr) throws IOException { chipSelectOutput.low(); while (misoInput.isHigh()) { }; byte[] readStatus = spi.write((byte) (addr + 0x80), (byte) 0); chipSelectOutput.high(); return readStatus[0]; } /** * Sends a strobe to the CC2500 * @param strobe the strobe to be sent */ private void sendStrobe(byte strobe) throws IOException { chipSelectOutput.low(); while (misoInput.isHigh()) { }; spi.write(strobe); chipSelectOutput.high(); delay(20); } /** * Writes a value to a CC2500 register. * @param addr the CC2500 register address * @param value the value to be written */ private void writeReg(byte addr, byte value) throws IOException { chipSelectOutput.low(); while (misoInput.isHigh()) { }; byte[] writeStatus = spi.write(addr, value); chipSelectOutput.high(); } /** * Inits the TI CC2500 like in a real Ansluta remote. */ private void initCC2500() throws IOException { writeReg(CC2500.REG_IOCFG2, (byte) 0x29); writeReg(CC2500.REG_IOCFG0, (byte) 0x06); writeReg(CC2500.REG_PKTLEN, (byte) 0xFF); // Max packet length writeReg(CC2500.REG_PKTCTRL1, (byte) 0x04); writeReg(CC2500.REG_PKTCTRL0, (byte) 0x05); // variable packet length; CRC enabled writeReg(CC2500.REG_ADDR, (byte) 0x01); // Device address writeReg(CC2500.REG_CHANNR, (byte) 0x10); // Channel number writeReg(CC2500.REG_FSCTRL1, (byte) 0x09); writeReg(CC2500.REG_FSCTRL0, (byte) 0x00); writeReg(CC2500.REG_FREQ2, (byte) 0x5D); // RF frequency 2433.000000 MHz writeReg(CC2500.REG_FREQ1, (byte) 0x93); // RF frequency 2433.000000 MHz writeReg(CC2500.REG_FREQ0, (byte) 0xB1); // RF frequency 2433.000000 MHz writeReg(CC2500.REG_MDMCFG4, (byte) 0x2D); writeReg(CC2500.REG_MDMCFG3, (byte) 0x3B); // Data rate 250.000000 kbps writeReg(CC2500.REG_MDMCFG2, (byte) 0x73); // MSK, (byte) No Manchester; 30/32 sync mode writeReg(CC2500.REG_MDMCFG1, (byte) 0xA2); writeReg(CC2500.REG_MDMCFG0, (byte) 0xF8); // Channel spacing 199.9500 kHz writeReg(CC2500.REG_DEVIATN, (byte) 0x01); writeReg(CC2500.REG_MCSM2, (byte) 0x07); writeReg(CC2500.REG_MCSM1, (byte) 0x30); writeReg(CC2500.REG_MCSM0, (byte) 0x18); writeReg(CC2500.REG_FOCCFG, (byte) 0x1D); writeReg(CC2500.REG_BSCFG, (byte) 0x1C); writeReg(CC2500.REG_AGCCTRL2, (byte) 0xC7); writeReg(CC2500.REG_AGCCTRL1, (byte) 0x00); writeReg(CC2500.REG_AGCCTRL0, (byte) 0xB2); writeReg(CC2500.REG_WOREVT1, (byte) 0x87); writeReg(CC2500.REG_WOREVT0, (byte) 0x6B); writeReg(CC2500.REG_WORCTRL, (byte) 0xF8); writeReg(CC2500.REG_FREND1, (byte) 0xB6); writeReg(CC2500.REG_FREND0, (byte) 0x10); writeReg(CC2500.REG_FSCAL3, (byte) 0xEA); writeReg(CC2500.REG_FSCAL2, (byte) 0x0A); writeReg(CC2500.REG_FSCAL1, (byte) 0x00); writeReg(CC2500.REG_FSCAL0, (byte) 0x11); writeReg(CC2500.REG_RCCTRL1, (byte) 0x41); writeReg(CC2500.REG_RCCTRL0, (byte) 0x00); writeReg(CC2500.REG_FSTEST, (byte) 0x59); writeReg(CC2500.REG_TEST2, (byte) 0x88); writeReg(CC2500.REG_TEST1, (byte) 0x31); writeReg(CC2500.REG_TEST0, (byte) 0x0B); writeReg(CC2500.REG_DAFUQ, (byte) 0xFF); } /** * Ugly delay method. * @param delay the delay (in milliseconds) */ private static void delay(long delay) { try { Thread.sleep(delay); } catch (InterruptedException ie) { } } /** Array of all hexadecimal chars */ private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray(); /** * @param bytes a byte array * @return a hex string */ private static String bytesToHexString(byte... bytes) { char[] hexChars = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { int v = bytes[i] & 0xFF; hexChars[i * 2] = HEX_CHARS[v >>> 4]; hexChars[i * 2 + 1] = HEX_CHARS[v & 0x0F]; } return new String(hexChars); } /** * Test entry point. */ public static void main(String[] args) throws Exception{ AnslutaRemote r = new AnslutaRemote(); r.initAnsluta(); r.readAddressBytes(); } }
40.351254
197
0.593622
b5e4207c7d0f0dd0adffce533d8d12f42fdcc415
12,373
/* * * Copyright 2005 Sun Microsystems, 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 net.jini.space; import net.jini.core.entry.Entry; import net.jini.core.entry.UnusableEntryException; import net.jini.core.event.EventRegistration; import net.jini.core.event.RemoteEventListener; import net.jini.core.lease.Lease; import net.jini.core.transaction.Transaction; import net.jini.core.transaction.TransactionException; import java.rmi.MarshalledObject; import java.rmi.RemoteException; /** * This interface is implemented by servers that export a JavaSpaces(TM) technology service. The * operations in this interface are the public methods that all such spaces support. * * @author Sun Microsystems, Inc. * @see Entry */ public interface JavaSpace { /** * Write a new entry into the space. * * Equivalent to calling {@link com.j_spaces.core.IJSpace#write(Object, Transaction, long, long, * int)} with {@link com.j_spaces.core.client.UpdateModifiers#WRITE_ONLY}. * * @param entry the entry to write * @param txn the transaction object, if any, under which to perform the write * @param lease the requested lease time, in milliseconds * @return a lease for the entry that was written to the space * @throws TransactionException if a transaction error occurs * @throws RemoteException if a communication error occurs */ Lease write(Entry entry, Transaction txn, long lease) throws TransactionException, RemoteException; /** * Wait for no time at all. This is used as a timeout value in various read and take calls. * * @see #read * @see #readIfExists * @see #take * @see #takeIfExists */ long NO_WAIT = 0; /** * Read any matching entry from the space, blocking until one exists. Return <code>null</code> * if the timeout expires. * * @param tmpl The template used for matching. Matching is done against <code>tmpl</code> * with <code>null</code> fields being wildcards ("match anything") other fields * being values ("match exactly on the serialized form"). * @param txn The transaction (if any) under which to work. * @param timeout How long the client is willing to wait for a transactionally proper matching * entry. A timeout of <code>NO_WAIT</code> means to wait no time at all; this * is equivalent to a wait of zero. * @return a copy of the entry read from the space * @throws UnusableEntryException if any serialized field of the entry being read cannot be * deserialized for any reason * @throws TransactionException if a transaction error occurs * @throws InterruptedException if the thread in which the read occurs is interrupted * @throws RemoteException if a communication error occurs * @throws IllegalArgumentException if a negative timeout value is used */ Entry read(Entry tmpl, Transaction txn, long timeout) throws UnusableEntryException, TransactionException, InterruptedException, RemoteException; /** * Read any matching entry from the space, returning <code>null</code> if there is currently is * none. Matching and timeouts are done as in <code>read</code>, except that blocking in this * call is done only if necessary to wait for transactional state to settle. * * @param tmpl The template used for matching. Matching is done against <code>tmpl</code> * with <code>null</code> fields being wildcards ("match anything") other fields * being values ("match exactly on the serialized form"). * @param txn The transaction (if any) under which to work. * @param timeout How long the client is willing to wait for a transactionally proper matching * entry. A timeout of <code>NO_WAIT</code> means to wait no time at all; this * is equivalent to a wait of zero. * @return a copy of the entry read from the space * @throws UnusableEntryException if any serialized field of the entry being read cannot be * deserialized for any reason * @throws TransactionException if a transaction error occurs * @throws InterruptedException if the thread in which the read occurs is interrupted * @throws RemoteException if a communication error occurs * @throws IllegalArgumentException if a negative timeout value is used * @see #read */ Entry readIfExists(Entry tmpl, Transaction txn, long timeout) throws UnusableEntryException, TransactionException, InterruptedException, RemoteException; /** * Take a matching entry from the space, waiting until one exists. Matching is and timeout done * as for <code>read</code>. * * @param tmpl The template used for matching. Matching is done against <code>tmpl</code> * with <code>null</code> fields being wildcards ("match anything") other fields * being values ("match exactly on the serialized form"). * @param txn The transaction (if any) under which to work. * @param timeout How long the client is willing to wait for a transactionally proper matching * entry. A timeout of <code>NO_WAIT</code> means to wait no time at all; this * is equivalent to a wait of zero. * @return the entry taken from the space * @throws UnusableEntryException if any serialized field of the entry being read cannot be * deserialized for any reason * @throws TransactionException if a transaction error occurs * @throws InterruptedException if the thread in which the take occurs is interrupted * @throws RemoteException if a communication error occurs * @throws IllegalArgumentException if a negative timeout value is used * @see #read */ Entry take(Entry tmpl, Transaction txn, long timeout) throws UnusableEntryException, TransactionException, InterruptedException, RemoteException; /** * Take a matching entry from the space, returning <code>null</code> if there is currently is * none. Matching is and timeout done as for <code>read</code>, except that blocking in this * call is done only if necessary to wait for transactional state to settle. * * @param tmpl The template used for matching. Matching is done against <code>tmpl</code> * with <code>null</code> fields being wildcards ("match anything") other fields * being values ("match exactly on the serialized form"). * @param txn The transaction (if any) under which to work. * @param timeout How long the client is willing to wait for a transactionally proper matching * entry. A timeout of <code>NO_WAIT</code> means to wait no time at all; this * is equivalent to a wait of zero. * @return the entry taken from the space * @throws UnusableEntryException if any serialized field of the entry being read cannot be * deserialized for any reason * @throws TransactionException if a transaction error occurs * @throws InterruptedException if the thread in which the take occurs is interrupted * @throws RemoteException if a communication error occurs * @throws IllegalArgumentException if a negative timeout value is used * @see #read */ Entry takeIfExists(Entry tmpl, Transaction txn, long timeout) throws UnusableEntryException, TransactionException, InterruptedException, RemoteException; /** * When entries are written that match this template notify the given <code>listener</code> with * a <code>RemoteEvent</code> that includes the <code>handback</code> object. Matching is done * as for <code>read</code>. * * @param tmpl The template used for matching. Matching is done against <code>tmpl</code> * with <code>null</code> fields being wildcards ("match anything") other fields * being values ("match exactly on the serialized form"). * @param txn The transaction (if any) under which to work. * @param listener The remote event listener to notify. * @param lease the requested lease time, in milliseconds * @param handback An object to send to the listener as part of the event notification. * @return the event registration to the the registrant * @throws TransactionException if a transaction error occurs * @throws RemoteException if a communication error occurs * @throws IllegalArgumentException if the lease time requested is not Lease.ANY and is * negative * @see #read * @see net.jini.core.event.EventRegistration */ EventRegistration notify(Entry tmpl, Transaction txn, RemoteEventListener listener, long lease, MarshalledObject handback) throws TransactionException, RemoteException; /** * The process of serializing an entry for transmission to a JavaSpaces service will be * identical if the same entry is used twice. This is most likely to be an issue with templates * that are used repeatedly to search for entries with <code>read</code> or <code>take</code>. * The client-side implementations of <code>read</code> and <code>take</code> cannot reasonably * avoid this duplicated effort, since they have no efficient way of checking whether the same * template is being used without intervening modification. * * The <code>snapshot</code> method gives the JavaSpaces service implementor a way to reduce the * impact of repeated use of the same entry. Invoking <code>snapshot</code> with an * <code>Entry</code> will return another <code>Entry</code> object that contains a * <i>snapshot</i> of the original entry. Using the returned snapshot entry is equivalent to * using the unmodified original entry in all operations on the same JavaSpaces service. * Modifications to the original entry will not affect the snapshot. You can * <code>snapshot</code> a <code>null</code> template; <code>snapshot</code> may or may not * return null given a <code>null</code> template. * * The entry returned from <code>snapshot</code> will be guaranteed equivalent to the original * unmodified object only when used with the space. Using the snapshot with any other JavaSpaces * service will generate an <code>IllegalArgumentException</code> unless the other space can use * it because of knowledge about the JavaSpaces service that generated the snapshot. The * snapshot will be a different object from the original, may or may not have the same hash * code, and <code>equals</code> may or may not return <code>true</code> when invoked with the * original object, even if the original object is unmodified. * * A snapshot is guaranteed to work only within the virtual machine in which it was generated. * If a snapshot is passed to another virtual machine (for example, in a parameter of an RMI * call), using it--even with the same JavaSpaces service--may generate an * <code>IllegalArgumentException</code>. * * @param e the entry to take a snapshot of. * @return a snapshot of the entry. * @throws RemoteException if a communication error occurs */ Entry snapshot(Entry e) throws RemoteException; }
55.236607
100
0.680029
767674c158d8be3a45495ec8c5097fec55d132ab
11,307
/* * This software is distributed under following license based on modified BSD * style license. * ---------------------------------------------------------------------- * * Copyright 2003 The Nimbus Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NIMBUS PROJECT ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL THE NIMBUS PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the Nimbus Project. */ package jp.ossc.nimbus.core; import java.lang.reflect.*; import java.io.*; /** * サービスプロキシファクトリ。<p> * {@link ServiceManager}に登録されるサービスは、{@link Service}インタフェースを実装すべきである。しかし、既存のリソースをそのままサービスとして使用したい場合、Serviceインタフェースを実装していない。また、既存のリソースを継承してサービスを新規に作成する場合は、{@link ServiceBase}を継承する事ができない。そのような場合に、サービスとして登録したい任意のオブジェクトを、Serviceインタフェースを実装したプロキシでラップする事で、サービスとして使用可能にする。<br> * このクラスは、そのようなサービスのプロキシを作成するためのファクトリクラスである。<br> * * @author M.Takata */ public class ServiceProxyFactory{ private static final long serialVersionUID = 4530900231794013688L; private ServiceProxyFactory(){ } /** * {@link ServiceBaseSupport}インタフェースを実装したクラスをラップするサービスプロキシを作成する。<p> * * @param support {@link ServiceBaseSupport}インタフェースを実装したクラスのインスタンス * @return サービスプロキシ */ public static ServiceBase createServiceBaseProxy( ServiceBaseSupport support ) throws Exception{ return new GenericsServiceProxy(support); } /** * {@link Service}、{@link ServiceBaseSupport}インタフェースを実装しない任意のクラスをラップするサービスプロキシを作成する。<p> * * @param obj サービスでない任意のクラスのインスタンス * @return サービスプロキシ */ public static ServiceBase createServiceBaseProxy( final Object obj ) throws Exception{ ServiceBaseSupport support = null; final Class[] interfaces = obj.getClass().getInterfaces(); if(interfaces == null || interfaces.length == 0){ support = new ServiceBaseSupportAdapter(obj); }else{ final Class[] newInterfaces = new Class[interfaces.length + 2]; newInterfaces[0] = ServiceBaseSupport.class; newInterfaces[1] = ServiceProxy.class; System.arraycopy( interfaces, 0, newInterfaces, 2, interfaces.length ); support = (ServiceBaseSupport)Proxy.newProxyInstance( NimbusClassLoader.getInstance(), newInterfaces, new ServiceBaseSupportProxyHandler(obj) ); } return createServiceBaseProxy(support); } private static class ServiceBaseSupportProxyHandler implements InvocationHandler, Serializable{ private static final long serialVersionUID = 4726647102748613673L; private final static String GET_TARGET = "getTarget"; private final Object targetObj; public ServiceBaseSupportProxyHandler(Object target){ targetObj = target; } public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable{ if(GET_TARGET.equals(method.getName()) && method.getParameterTypes().length == 0){ return targetObj; } try{ Method targetMethod = findTargetMethod(targetObj.getClass(), method); if(targetMethod == null){ return null; } return targetMethod.invoke(targetObj, args); }catch(InvocationTargetException e){ throw e.getTargetException(); } } private Method findTargetMethod(Class targetClass, Method method){ Method targetMethod = null; if(isAccessableClass(targetClass)){ try{ targetMethod = targetClass.getMethod( method.getName(), method.getParameterTypes() ); if(Modifier.isNative(targetMethod.getModifiers())){ targetMethod = null; } }catch(NoSuchMethodException e){ return null; } } if(targetMethod == null){ final Class[] interfaces = targetClass.getInterfaces(); for(int i = 0; i < interfaces.length; i++){ if(isAccessableClass(interfaces[i])){ targetMethod = findTargetMethod(interfaces[i], method); if(targetMethod != null){ return targetMethod; } } } final Class superClass = targetClass.getSuperclass(); if(superClass == null){ return null; }else{ return findTargetMethod(superClass, method); } } return targetMethod; } private boolean isAccessableClass(Class clazz){ final int modifier = clazz.getModifiers(); return Modifier.isPublic(modifier); } public Object getTarget(){ return targetObj; } } private static class ServiceBaseSupportAdapter implements ServiceBaseSupport, ServiceProxy, Serializable{ private static final long serialVersionUID = -6078404516516929266L; private final static String SET_SERVICEBASE = "setServiceBase"; private final static String CREATE = "create"; private final static String START = "start"; private final static String STOP = "stop"; private final static String DESTROY = "destroy"; private final Method setServiceBase; private final Method create; private final Method start; private final Method stop; private final Method destroy; private final Object obj; public ServiceBaseSupportAdapter(Object obj){ this.obj = obj; final Class clazz = obj.getClass(); setServiceBase = findMethod(clazz, SET_SERVICEBASE, new Class[]{ServiceBase.class}); create = findMethod(clazz, CREATE, null); start = findMethod(clazz, START, null); stop = findMethod(clazz, STOP, null); destroy = findMethod(clazz, DESTROY, null); } private Method findMethod(Class clazz, String name, Class[] params){ try{ return clazz.getMethod(name, params); }catch(Exception e){ return null; } } public void setServiceBase(ServiceBase service){ if(setServiceBase == null){ return; } try{ setServiceBase.invoke(obj, new Object[]{service}); }catch(InvocationTargetException e){ final Throwable th = e.getTargetException(); if(th instanceof RuntimeException){ throw (RuntimeException)th; }else{ throw (Error)th; } }catch(IllegalAccessException e){ }catch(IllegalArgumentException e){ } } public void createService() throws Exception{ if(create == null){ return; } try{ create.invoke(obj, (Object[])null); }catch(InvocationTargetException e){ final Throwable th = e.getTargetException(); if(th instanceof Exception){ throw (Exception)th; }else{ throw (Error)th; } }catch(Exception e){ throw e; } } public void startService() throws Exception{ if(start == null){ return; } try{ start.invoke(obj, (Object[])null); }catch(InvocationTargetException e){ final Throwable th = e.getTargetException(); if(th instanceof Exception){ throw (Exception)th; }else{ throw (Error)th; } }catch(Exception e){ throw e; } } public void stopService() throws Exception{ if(stop == null){ return; } try{ stop.invoke(obj, (Object[])null); }catch(InvocationTargetException e){ final Throwable th = e.getTargetException(); if(th instanceof Exception){ throw (Exception)th; }else{ throw (Error)th; } }catch(Exception e){ throw e; } } public void destroyService() throws Exception{ if(destroy == null){ return; } try{ destroy.invoke(obj, (Object[])null); }catch(InvocationTargetException e){ final Throwable th = e.getTargetException(); if(th instanceof Exception){ throw (Exception)th; }else{ throw (Error)th; } }catch(Exception e){ throw e; } } public Object getTarget(){ return obj; } } }
37.69
269
0.541788
eeab3f22cf16b4a22f1091f8aa9382785a22fc24
3,924
package com.example.macromanager.constraintdialoguefragment; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.DialogFragment; import androidx.lifecycle.ViewModelProvider; import com.example.macromanager.R; import com.example.macromanager.viewmodel; import java.util.ArrayList; import java.util.Arrays; public class Month extends DialogFragment { Boolean[] months = {false, false, false, false, false, false, false, false, false, false, false, false}; CheckBox jan, feb, mar, apr, may, jun, jul, aug, sept, oct, nov, dec; viewmodel res; public Month(ArrayList<Boolean> constraintmonth) { months = constraintmonth.toArray(months); } public Month() { } @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { res = new ViewModelProvider(requireActivity()).get(viewmodel.class); LayoutInflater inflater = requireActivity().getLayoutInflater(); View v = inflater.inflate(R.layout.monthconstraintdialogue, null); AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity()); jan = v.findViewById(R.id.jan); feb = v.findViewById(R.id.feb); mar = v.findViewById(R.id.mar); apr = v.findViewById(R.id.apr); may = v.findViewById(R.id.may); jun = v.findViewById(R.id.jun); jul = v.findViewById(R.id.jul); aug = v.findViewById(R.id.aug); sept = v.findViewById(R.id.sept); oct = v.findViewById(R.id.oct); nov = v.findViewById(R.id.nov); dec = v.findViewById(R.id.dec); jan.setChecked(months[0]); feb.setChecked(months[1]); mar.setChecked(months[2]); apr.setChecked(months[3]); may.setChecked(months[4]); jun.setChecked(months[5]); jul.setChecked(months[6]); aug.setChecked(months[7]); sept.setChecked(months[8]); oct.setChecked(months[9]); nov.setChecked(months[10]); dec.setChecked(months[11]); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int j) { months[0] = jan.isChecked(); months[1] = feb.isChecked(); months[2] = mar.isChecked(); months[3] = apr.isChecked(); months[4] = may.isChecked(); months[5] = jun.isChecked(); months[6] = jul.isChecked(); months[7] = aug.isChecked(); months[8] = sept.isChecked(); months[9] = oct.isChecked(); months[10] = nov.isChecked(); months[11] = dec.isChecked(); ArrayList<Boolean> y = new ArrayList<>(Arrays.asList(months)); for (int i = 0; i < res.getConstraintselected().size(); i++) { if (res.getConstraintselected().get(i).equals("Month")) { res.getConstraintselected().remove(i); } } res.getConstraintselected().add("Month"); res.setConstraintmonth(y); res.getConstraintupdate().setValue(!res.getConstraintupdate().getValue()); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .setView(v) .setTitle("Month"); return builder.create(); } }
32.97479
108
0.595056
b4c07b6333ec878e920a8f2ed375d815b55d847b
43,379
/******************************************************************************* * Copyright (c) 2008 SAP AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * SAP AG - initial API and implementation *******************************************************************************/ package org.eclipse.mat.parser.index; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.lang.ref.SoftReference; import java.util.Arrays; import java.util.NoSuchElementException; import org.eclipse.mat.collect.ArrayInt; import org.eclipse.mat.collect.ArrayIntCompressed; import org.eclipse.mat.collect.ArrayLong; import org.eclipse.mat.collect.ArrayLongCompressed; import org.eclipse.mat.collect.ArrayUtils; import org.eclipse.mat.collect.BitField; import org.eclipse.mat.collect.HashMapIntLong; import org.eclipse.mat.collect.HashMapIntObject; import org.eclipse.mat.collect.IteratorInt; import org.eclipse.mat.collect.IteratorLong; import org.eclipse.mat.collect.SetInt; import org.eclipse.mat.parser.index.IIndexReader.IOne2LongIndex; import org.eclipse.mat.parser.index.IIndexReader.IOne2OneIndex; import org.eclipse.mat.parser.io.BitInputStream; import org.eclipse.mat.parser.io.BitOutputStream; import org.eclipse.mat.util.IProgressListener; public abstract class IndexWriter { public static final int PAGE_SIZE_INT = 1000000; public static final int PAGE_SIZE_LONG = 500000; public interface KeyWriter { public void storeKey(int index, Serializable key); } // ////////////////////////////////////////////////////////////// // integer based indices // ////////////////////////////////////////////////////////////// public static class Identifier implements IIndexReader.IOne2LongIndex { long[] identifiers; int size; public void add(long id) { if (identifiers == null) { identifiers = new long[10000]; size = 0; } if (size + 1 > identifiers.length) { int newCapacity = (identifiers.length * 3) / 2 + 1; if (newCapacity < size + 1) newCapacity = size + 1; identifiers = copyOf(identifiers, newCapacity); } identifiers[size++] = id; } public void sort() { Arrays.sort(identifiers, 0, size); } public int size() { return size; } public long get(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException(); return identifiers[index]; } public int reverse(long val) { int a, c; for (a = 0, c = size; a < c; ) { // Avoid overflow problems by using unsigned divide by 2 int b = (a + c) >>> 1; long probeVal = get(b); if (val < probeVal) { c = b; } else if (probeVal < val) { a = b + 1; } else { return b; } } // Negative index indicates not found (and where to insert) return -1 - a; } public IteratorLong iterator() { return new IteratorLong() { int index = 0; public boolean hasNext() { return index < size; } public long next() { return identifiers[index++]; } }; } public long[] getNext(int index, int length) { long answer[] = new long[length]; for (int ii = 0; ii < length; ii++) answer[ii] = identifiers[index + ii]; return answer; } public void close() throws IOException { } public void delete() { identifiers = null; } public void unload() throws IOException { throw new UnsupportedOperationException(); } } public static class IntIndexCollectorUncompressed { int[] dataElements; public IntIndexCollectorUncompressed(int size) { dataElements = new int[size]; } public void set(int index, int value) { dataElements[index] = value; } public int get(int index) { return dataElements[index]; } public IIndexReader.IOne2OneIndex writeTo(File indexFile) throws IOException { return new IntIndexStreamer().writeTo(indexFile, dataElements); } } static class Pages<V> { int size; Object[] elements; public Pages(int initialSize) { elements = new Object[initialSize]; size = 0; } private void ensureCapacity(int minCapacity) { int oldCapacity = elements.length; if (minCapacity > oldCapacity) { int newCapacity = (oldCapacity * 3) / 2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; Object[] copy = new Object[newCapacity]; System.arraycopy(elements, 0, copy, 0, Math.min(elements.length, newCapacity)); elements = copy; } } @SuppressWarnings("unchecked") public V get(int key) { return (key >= elements.length) ? null : (V) elements[key]; } public void put(int key, V value) { ensureCapacity(key + 1); elements[key] = value; size = Math.max(size, key + 1); } public int size() { return size; } } abstract static class IntIndex<V> { int pageSize; int size; Pages<V> pages; protected IntIndex() { } protected IntIndex(int size) { init(size, PAGE_SIZE_INT); } protected void init(int size, int pageSize) { this.size = size; this.pageSize = pageSize; this.pages = new Pages<V>(size / pageSize + 1); } public int get(int index) { ArrayIntCompressed array = getPage(index / pageSize); return array.get(index % pageSize); } public int[] getNext(int index, int length) { int answer[] = new int[length]; int page = index / pageSize; int pageIndex = index % pageSize; ArrayIntCompressed array = getPage(page); for (int ii = 0; ii < length; ii++) { answer[ii] = array.get(pageIndex++); if (pageIndex >= pageSize) { array = getPage(++page); pageIndex = 0; } } return answer; } @SuppressWarnings("null") public int[] getAll(int index[]) { int[] answer = new int[index.length]; int page = -1; ArrayIntCompressed array = null; for (int ii = 0; ii < answer.length; ii++) { int p = index[ii] / pageSize; if (p != page) array = getPage(page = p); answer[ii] = array.get(index[ii] % pageSize); } return answer; } public void set(int index, int value) { ArrayIntCompressed array = getPage(index / pageSize); array.set(index % pageSize, value); } protected abstract ArrayIntCompressed getPage(int page); public synchronized void unload() { this.pages = new Pages<V>(size / pageSize + 1); } public int size() { return size; } public IteratorInt iterator() { return new IntIndexIterator(this); } } static class IntIndexIterator implements IteratorInt { IntIndex<?> intArray; int nextIndex = 0; public IntIndexIterator(IntIndex<?> intArray) { this.intArray = intArray; } public int next() { return intArray.get(nextIndex++); } public boolean hasNext() { return nextIndex < intArray.size(); } } public static class IntIndexCollector extends IntIndex<ArrayIntCompressed> implements IOne2OneIndex { int mostSignificantBit; public IntIndexCollector(int size, int mostSignificantBit) { super(size); this.mostSignificantBit = mostSignificantBit; } @Override protected ArrayIntCompressed getPage(int page) { ArrayIntCompressed array = pages.get(page); if (array == null) { int ps = page < (size / pageSize) ? pageSize : size % pageSize; array = new ArrayIntCompressed(ps, 31 - mostSignificantBit, 0); pages.put(page, array); } return array; } public IIndexReader.IOne2OneIndex writeTo(File indexFile) throws IOException { // needed to re-compress return new IntIndexStreamer().writeTo(indexFile, this.iterator()); } public IIndexReader.IOne2OneIndex writeTo(DataOutputStream out, long position) throws IOException { return new IntIndexStreamer().writeTo(out, position, this.iterator()); } public void close() throws IOException { } public void delete() { pages = null; } } public static class IntIndexStreamer extends IntIndex<SoftReference<ArrayIntCompressed>> { DataOutputStream out; ArrayLong pageStart; int[] page; int left; public IIndexReader.IOne2OneIndex writeTo(File indexFile, IteratorInt iterator) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile))); openStream(out, 0); addAll(iterator); closeStream(); out.close(); return getReader(indexFile); } public IIndexReader.IOne2OneIndex writeTo(File indexFile, int[] array) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile))); openStream(out, 0); addAll(array); closeStream(); out.close(); return getReader(indexFile); } public IIndexReader.IOne2OneIndex writeTo(DataOutputStream out, long position, IteratorInt iterator) throws IOException { openStream(out, position); addAll(iterator); closeStream(); return getReader(null); } public IIndexReader.IOne2OneIndex writeTo(DataOutputStream out, long position, int[] array) throws IOException { openStream(out, position); addAll(array); closeStream(); return getReader(null); } void openStream(DataOutputStream out, long position) { this.out = out; init(0, PAGE_SIZE_INT); this.page = new int[pageSize]; this.pageStart = new ArrayLong(); this.pageStart.add(position); this.left = page.length; } /** * @return total bytes written to index file */ long closeStream() throws IOException { if (left < page.length) addPage(); // write header information for (int jj = 0; jj < pageStart.size(); jj++) out.writeLong(pageStart.get(jj)); out.writeInt(pageSize); out.writeInt(size); this.page = null; this.out = null; return this.pageStart.lastElement() + (8 * pageStart.size()) + 8 - this.pageStart.firstElement(); } IndexReader.IntIndexReader getReader(File indexFile) { return new IndexReader.IntIndexReader(indexFile, pages, size, pageSize, pageStart.toArray()); } void addAll(IteratorInt iterator) throws IOException { while (iterator.hasNext()) add(iterator.next()); } void add(int value) throws IOException { if (left == 0) addPage(); page[page.length - left--] = value; size++; } void addAll(int[] values) throws IOException { addAll(values, 0, values.length); } void addAll(int[] values, int offset, int length) throws IOException { while (length > 0) { if (left == 0) addPage(); int chunk = Math.min(left, length); System.arraycopy(values, offset, page, page.length - left, chunk); left -= chunk; size += chunk; length -= chunk; offset += chunk; } } private void addPage() throws IOException { ArrayIntCompressed array = new ArrayIntCompressed(page, 0, page.length - left); byte[] buffer = array.toByteArray(); out.write(buffer); int written = buffer.length; pages.put(pages.size(), new SoftReference<ArrayIntCompressed>(array)); pageStart.add(pageStart.lastElement() + written); left = page.length; } @Override protected ArrayIntCompressed getPage(int page) { throw new UnsupportedOperationException(); } } public static class IntArray1NWriter { int[] header; File indexFile; DataOutputStream out; IntIndexStreamer body; public IntArray1NWriter(int size, File indexFile) throws IOException { this.header = new int[size]; this.indexFile = indexFile; this.out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile))); this.body = new IntIndexStreamer(); this.body.openStream(this.out, 0); } public void log(Identifier identifer, int index, ArrayLong references) throws IOException { // remove duplicates and convert to identifiers // keep pseudo reference as first one long pseudo = references.firstElement(); references.sort(); int[] objectIds = new int[references.size()]; int length = 1; long current = 0, last = references.firstElement() - 1; for (int ii = 0; ii < objectIds.length; ii++) { current = references.get(ii); if (last != current) { int objectId = identifer.reverse(current); if (objectId >= 0) { int jj = (current == pseudo) ? 0 : length++; objectIds[jj] = objectId; } } last = current; } this.set(index, objectIds, 0, length); } /** * must not contain duplicates! */ public void log(int index, ArrayInt references) throws IOException { this.set(index, references.toArray(), 0, references.size()); } public void log(int index, int[] values) throws IOException { this.set(index, values, 0, values.length); } protected void set(int index, int[] values, int offset, int length) throws IOException { header[index] = body.size(); body.add(length); body.addAll(values, offset, length); } public IIndexReader.IOne2ManyIndex flush() throws IOException { long divider = body.closeStream(); IIndexReader.IOne2OneIndex headerIndex = new IntIndexStreamer().writeTo(out, divider, header); out.writeLong(divider); out.close(); out = null; return createReader(headerIndex, body.getReader(null)); } /** * @throws IOException */ protected IIndexReader.IOne2ManyIndex createReader(IIndexReader.IOne2OneIndex headerIndex, IIndexReader.IOne2OneIndex bodyIndex) throws IOException { return new IndexReader.IntIndex1NReader(this.indexFile, headerIndex, bodyIndex); } public void cancel() { try { if (out != null) { out.close(); body = null; out = null; } } catch (IOException ignore) { } finally { if (indexFile.exists()) indexFile.delete(); } } public File getIndexFile() { return indexFile; } } public static class IntArray1NSortedWriter extends IntArray1NWriter { public IntArray1NSortedWriter(int size, File indexFile) throws IOException { super(size, indexFile); } protected void set(int index, int[] values, int offset, int length) throws IOException { header[index] = body.size() + 1; body.addAll(values, offset, length); } protected IIndexReader.IOne2ManyIndex createReader(IIndexReader.IOne2OneIndex headerIndex, IIndexReader.IOne2OneIndex bodyIndex) throws IOException { return new IndexReader.IntIndex1NSortedReader(this.indexFile, headerIndex, bodyIndex); } } public static class InboundWriter { int size; File indexFile; int bitLength; int pageSize; BitOutputStream[] segments; int[] segmentSizes; /** * @throws IOException */ public InboundWriter(int size, File indexFile) throws IOException { this.size = size; this.indexFile = indexFile; int requiredSegments = (size / 500000) + 1; int segments = 1; while (segments < requiredSegments) segments <<= 1; this.bitLength = mostSignificantBit(size) + 1; this.pageSize = (size / segments) + 1; this.segments = new BitOutputStream[segments]; this.segmentSizes = new int[segments]; } public void log(int objectIndex, int refIndex, boolean isPseudo) throws IOException { int segment = objectIndex / pageSize; if (segments[segment] == null) { File segmentFile = new File(this.indexFile.getAbsolutePath() + segment + ".log");//$NON-NLS-1$ segments[segment] = new BitOutputStream(new FileOutputStream(segmentFile)); } segments[segment].writeBit(isPseudo ? 1 : 0); segments[segment].writeInt(objectIndex, bitLength); segments[segment].writeInt(refIndex, bitLength); segmentSizes[segment]++; } public IIndexReader.IOne2ManyObjectsIndex flush(IProgressListener monitor, KeyWriter keyWriter) throws IOException { close(); int[] header = new int[size]; DataOutputStream index = new DataOutputStream(new BufferedOutputStream( new FileOutputStream(this.indexFile), 1024 * 256)); BitInputStream segmentIn = null; try { IntIndexStreamer body = new IntIndexStreamer(); body.openStream(index, 0); for (int segment = 0; segment < segments.length; segment++) { if (monitor.isCanceled()) throw new IProgressListener.OperationCanceledException(); File segmentFile = new File(this.indexFile.getAbsolutePath() + segment + ".log");//$NON-NLS-1$ if (!segmentFile.exists()) continue; // read & sort payload segmentIn = new BitInputStream(new FileInputStream(segmentFile)); int objIndex[] = new int[segmentSizes[segment]]; int refIndex[] = new int[segmentSizes[segment]]; for (int ii = 0; ii < segmentSizes[segment]; ii++) { boolean isPseudo = segmentIn.readBit() == 1; objIndex[ii] = segmentIn.readInt(bitLength); refIndex[ii] = segmentIn.readInt(bitLength); if (isPseudo) refIndex[ii] = -1 - refIndex[ii]; // 0 is a valid! } segmentIn.close(); segmentIn = null; if (monitor.isCanceled()) throw new IProgressListener.OperationCanceledException(); // delete segment log segmentFile.delete(); segmentFile = null; processSegment(monitor, keyWriter, header, body, objIndex, refIndex); } // write header long divider = body.closeStream(); IIndexReader.IOne2OneIndex headerIndex = new IntIndexStreamer().writeTo(index, divider, header); index.writeLong(divider); index.flush(); index.close(); index = null; // return index reader return new IndexReader.InboundReader(this.indexFile, headerIndex, body.getReader(null)); } finally { try { if (index != null) index.close(); } catch (IOException ignore) { } try { if (segmentIn != null) segmentIn.close(); } catch (IOException ignore) { } if (monitor.isCanceled()) cancel(); } } private void processSegment(IProgressListener monitor, KeyWriter keyWriter, int[] header, IntIndexStreamer body, int[] objIndex, int[] refIndex) throws IOException { // sort (only by objIndex though) ArrayUtils.sort(objIndex, refIndex); // write index body int start = 0; int previous = -1; for (int ii = 0; ii <= objIndex.length; ii++) { if (ii == 0) { start = ii; previous = objIndex[ii]; } else if (ii == objIndex.length || previous != objIndex[ii]) { if (monitor.isCanceled()) throw new IProgressListener.OperationCanceledException(); header[previous] = body.size() + 1; processObject(keyWriter, header, body, previous, refIndex, start, ii); if (ii < objIndex.length) { previous = objIndex[ii]; start = ii; } } } } private void processObject(KeyWriter keyWriter, int[] header, IntIndexStreamer body, int objectId, int[] refIndex, int fromIndex, int toIndex) throws IOException { Arrays.sort(refIndex, fromIndex, toIndex); int endPseudo = fromIndex; if ((toIndex - fromIndex) > 100000) { BitField duplicates = new BitField(size); int jj = fromIndex; for (; jj < toIndex; jj++) // pseudo references { if (refIndex[jj] >= 0) break; endPseudo++; refIndex[jj] = -refIndex[jj] - 1; if (!duplicates.get(refIndex[jj])) { body.add(refIndex[jj]); duplicates.set(refIndex[jj]); } } for (; jj < toIndex; jj++) // other references { if ((jj == fromIndex || refIndex[jj - 1] != refIndex[jj]) && !duplicates.get(refIndex[jj])) { body.add(refIndex[jj]); } } } else { SetInt duplicates = new SetInt(toIndex - fromIndex); int jj = fromIndex; for (; jj < toIndex; jj++) // pseudo references { if (refIndex[jj] >= 0) break; endPseudo++; refIndex[jj] = -refIndex[jj] - 1; if (duplicates.add(refIndex[jj])) body.add(refIndex[jj]); } for (; jj < toIndex; jj++) // other references { if ((jj == fromIndex || refIndex[jj - 1] != refIndex[jj]) && !duplicates.contains(refIndex[jj])) { body.add(refIndex[jj]); } } } if (endPseudo > fromIndex) { keyWriter.storeKey(objectId, new int[]{header[objectId] - 1, endPseudo - fromIndex}); } } public synchronized void cancel() { try { close(); if (segments != null) { for (int ii = 0; ii < segments.length; ii++) { new File(this.indexFile.getAbsolutePath() + ii + ".log").delete();//$NON-NLS-1$ } } } catch (IOException ignore) { } finally { indexFile.delete(); } } public synchronized void close() throws IOException { if (segments != null) { for (int ii = 0; ii < segments.length; ii++) { if (segments[ii] != null) { segments[ii].flush(); segments[ii].close(); segments[ii] = null; } } } } public File getIndexFile() { return indexFile; } } public static class IntArray1NUncompressedCollector { int[][] elements; File indexFile; /** * @throws IOException */ public IntArray1NUncompressedCollector(int size, File indexFile) throws IOException { this.elements = new int[size][]; this.indexFile = indexFile; } public void log(int classId, int methodId) { if (elements[classId] == null) { elements[classId] = new int[]{methodId}; } else { int[] newChildren = new int[elements[classId].length + 1]; System.arraycopy(elements[classId], 0, newChildren, 0, elements[classId].length); newChildren[elements[classId].length] = methodId; elements[classId] = newChildren; } } public File getIndexFile() { return indexFile; } public IIndexReader.IOne2ManyIndex flush() throws IOException { IntArray1NSortedWriter writer = new IntArray1NSortedWriter(elements.length, indexFile); for (int ii = 0; ii < elements.length; ii++) { if (elements[ii] != null) writer.log(ii, elements[ii]); } return writer.flush(); } } // ////////////////////////////////////////////////////////////// // long based indices // ////////////////////////////////////////////////////////////// public static class LongIndexCollectorUncompressed { long[] dataElements; public LongIndexCollectorUncompressed(int size) { dataElements = new long[size]; } public void set(int index, long value) { dataElements[index] = value; } public long get(int index) { return dataElements[index]; } public IIndexReader.IOne2LongIndex writeTo(File indexFile) throws IOException { return new LongIndexStreamer().writeTo(indexFile, dataElements); } } abstract static class LongIndex { private static final int DEPTH = 10; int pageSize; int size; // pages are either IntArrayCompressed or // SoftReference<IntArrayCompressed> HashMapIntObject<Object> pages; HashMapIntLong binarySearchCache = new HashMapIntLong(1 << DEPTH); protected LongIndex() { } protected LongIndex(int size) { init(size, PAGE_SIZE_LONG); } protected void init(int size, int pageSize) { this.size = size; this.pageSize = pageSize; this.pages = new HashMapIntObject<Object>(size / pageSize + 1); } public long get(int index) { ArrayLongCompressed array = getPage(index / pageSize); return array.get(index % pageSize); } public long[] getNext(int index, int length) { long answer[] = new long[length]; int page = index / pageSize; int pageIndex = index % pageSize; ArrayLongCompressed array = getPage(page); for (int ii = 0; ii < length; ii++) { answer[ii] = array.get(pageIndex++); if (pageIndex >= pageSize) { array = getPage(++page); pageIndex = 0; } } return answer; } @SuppressWarnings("null") public int reverse(long value) { int low = 0; int high = size - 1; int depth = 0; int page = -1; ArrayLongCompressed array = null; while (low <= high) { int mid = (low + high) >> 1; long midVal; if (depth++ < DEPTH) { try { midVal = binarySearchCache.get(mid); } catch (NoSuchElementException e) { int p = mid / pageSize; if (p != page) array = getPage(page = p); midVal = array.get(mid % pageSize); binarySearchCache.put(mid, midVal); } } else { int p = mid / pageSize; if (p != page) array = getPage(page = p); midVal = array.get(mid % pageSize); } if (midVal < value) low = mid + 1; else if (midVal > value) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } public void set(int index, long value) { ArrayLongCompressed array = getPage(index / pageSize); array.set(index % pageSize, value); } protected abstract ArrayLongCompressed getPage(int page); public synchronized void unload() { pages = new HashMapIntObject<Object>(size / pageSize + 1); binarySearchCache = new HashMapIntLong(1 << DEPTH); } public int size() { return size; } public IteratorLong iterator() { return new LongIndexIterator(this); } } static class LongIndexIterator implements IteratorLong { LongIndex longArray; int nextIndex = 0; public LongIndexIterator(LongIndex longArray) { this.longArray = longArray; } public long next() { return longArray.get(nextIndex++); } public boolean hasNext() { return nextIndex < longArray.size(); } } public static class LongIndexCollector extends LongIndex { int mostSignificantBit; public LongIndexCollector(int size, int mostSignificantBit) { super(size); this.mostSignificantBit = mostSignificantBit; } @Override protected ArrayLongCompressed getPage(int page) { ArrayLongCompressed array = (ArrayLongCompressed) pages.get(page); if (array == null) { int ps = page < (size / pageSize) ? pageSize : size % pageSize; array = new ArrayLongCompressed(ps, 63 - mostSignificantBit, 0); pages.put(page, array); } return array; } public IIndexReader.IOne2LongIndex writeTo(File indexFile) throws IOException { // needed to re-compress return new LongIndexStreamer().writeTo(indexFile, this.size, this.pages, this.pageSize); } } public static class LongIndexStreamer extends LongIndex { DataOutputStream out; ArrayLong pageStart; long[] page; int left; public LongIndexStreamer() { } public LongIndexStreamer(File indexFile) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile))); openStream(out, 0); } public void close() throws IOException { DataOutputStream out = this.out; closeStream(); out.close(); } public IOne2LongIndex writeTo(File indexFile, int size, HashMapIntObject<Object> pages, int pageSize) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile))); openStream(out, 0); int noOfPages = size / pageSize + (size % pageSize > 0 ? 1 : 0); for (int ii = 0; ii < noOfPages; ii++) { ArrayLongCompressed a = (ArrayLongCompressed) pages.get(ii); int len = (ii + 1) < noOfPages ? pageSize : (size % pageSize); if (a == null) addAll(new long[len]); else for (int jj = 0; jj < len; jj++) { add(a.get(jj)); } } closeStream(); out.close(); return getReader(indexFile); } public IOne2LongIndex writeTo(File indexFile, long[] array) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile))); openStream(out, 0); addAll(array); closeStream(); out.close(); return getReader(indexFile); } public IOne2LongIndex writeTo(File indexFile, IteratorLong iterator) throws IOException { FileOutputStream fos = new FileOutputStream(indexFile); try { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(fos)); openStream(out, 0); addAll(iterator); closeStream(); out.flush(); return getReader(indexFile); } finally { try { fos.close(); } catch (IOException ignore) { } } } public IOne2LongIndex writeTo(File indexFile, ArrayLong array) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile))); openStream(out, 0); addAll(array); closeStream(); out.close(); return getReader(indexFile); } void openStream(DataOutputStream out, long position) { this.out = out; init(0, PAGE_SIZE_LONG); this.page = new long[pageSize]; this.pageStart = new ArrayLong(); this.pageStart.add(position); this.left = page.length; } /** * @return total bytes written to index file */ long closeStream() throws IOException { if (left < page.length) addPage(); // write header information for (int jj = 0; jj < pageStart.size(); jj++) out.writeLong(pageStart.get(jj)); out.writeInt(pageSize); out.writeInt(size); this.page = null; this.out = null; return this.pageStart.lastElement() + (8 * pageStart.size()) + 8 - this.pageStart.firstElement(); } IndexReader.LongIndexReader getReader(File indexFile) throws IOException { return new IndexReader.LongIndexReader(indexFile, pages, size, pageSize, pageStart.toArray()); } public void addAll(IteratorLong iterator) throws IOException { while (iterator.hasNext()) add(iterator.next()); } public void addAll(ArrayLong array) throws IOException { for (IteratorLong e = array.iterator(); e.hasNext(); ) add(e.next()); } public void add(long value) throws IOException { if (left == 0) addPage(); page[page.length - left--] = value; size++; } public void addAll(long[] values) throws IOException { addAll(values, 0, values.length); } public void addAll(long[] values, int offset, int length) throws IOException { while (length > 0) { if (left == 0) addPage(); int chunk = Math.min(left, length); System.arraycopy(values, offset, page, page.length - left, chunk); left -= chunk; size += chunk; length -= chunk; offset += chunk; } } private void addPage() throws IOException { ArrayLongCompressed array = new ArrayLongCompressed(page, 0, page.length - left); byte[] buffer = array.toByteArray(); out.write(buffer); int written = buffer.length; pages.put(pages.size(), new SoftReference<ArrayLongCompressed>(array)); pageStart.add(pageStart.lastElement() + written); left = page.length; } @Override protected ArrayLongCompressed getPage(int page) { throw new UnsupportedOperationException(); } } public static class LongArray1NWriter { int[] header; File indexFile; DataOutputStream out; LongIndexStreamer body; public LongArray1NWriter(int size, File indexFile) throws IOException { this.header = new int[size]; this.indexFile = indexFile; this.out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexFile))); this.body = new LongIndexStreamer(); this.body.openStream(this.out, 0); } public void log(int index, long[] values) throws IOException { this.set(index, values, 0, values.length); } protected void set(int index, long[] values, int offset, int length) throws IOException { header[index] = body.size() + 1; body.add(length); body.addAll(values, offset, length); } public void flush() throws IOException { long divider = body.closeStream(); new IntIndexStreamer().writeTo(out, divider, header).close(); out.writeLong(divider); out.close(); out = null; } public void cancel() { try { if (out != null) { out.close(); body = null; out = null; } } catch (IOException ignore) { } finally { if (indexFile.exists()) indexFile.delete(); } } public File getIndexFile() { return indexFile; } } // ////////////////////////////////////////////////////////////// // mama's little helpers // ////////////////////////////////////////////////////////////// public static long[] copyOf(long[] original, int newLength) { long[] copy = new long[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } public static int mostSignificantBit(int x) { int length = 0; if ((x & 0xffff0000) != 0) { length += 16; x >>= 16; } if ((x & 0xff00) != 0) { length += 8; x >>= 8; } if ((x & 0xf0) != 0) { length += 4; x >>= 4; } if ((x & 0xc) != 0) { length += 2; x >>= 2; } if ((x & 0x2) != 0) { length += 1; x >>= 1; } if ((x & 0x1) != 0) { length += 1; // x >>= 1; } return length - 1; } public static int mostSignificantBit(long x) { long lead = x >>> 32; return lead == 0x0 ? mostSignificantBit((int) x) : 32 + mostSignificantBit((int) lead); } }
32.348248
121
0.495885
11d9cb032a099b561c262c442d7391f57f3031d7
243
package com.v7lin.android.env.widget; import android.graphics.drawable.Drawable; /** * * * @author v7lin Email:v7lin@qq.com */ public interface XAbsSeekBarCall extends XProgressBarCall { public void scheduleThumb(Drawable thumb); }
17.357143
59
0.753086
f85fa1b26d1789d0c1fc3237e90c64f5daaa6bab
3,044
package me.melijn.jda.commands.music; import me.melijn.jda.Helpers; import me.melijn.jda.blub.Category; import me.melijn.jda.blub.Command; import me.melijn.jda.blub.CommandEvent; import me.melijn.jda.blub.Need; import me.melijn.jda.music.MusicManager; import me.melijn.jda.music.MusicPlayer; import me.melijn.jda.utils.MessageHelper; import static me.melijn.jda.Melijn.PREFIX; public class SpeedCommand extends Command { public SpeedCommand() { this.commandName = "speed"; this.description = "Change the playback speed of bot"; this.usage = PREFIX + this.commandName + " [value]"; this.category = Category.MUSIC; this.extra = "1.0 is normal speed"; this.needs = new Need[] {Need.GUILD}; } @Override protected void execute(CommandEvent event) { if (Helpers.hasPerm(event.getGuild().getMember(event.getAuthor()), this.commandName, 0)) { String[] args = event.getArgs().split("\\s+"); MusicPlayer player = MusicManager.getManagerInstance().getPlayer(event.getGuild()); if (args.length > 0 && !args[0].equalsIgnoreCase("")) { if (event.getGuild().getSelfMember().getVoiceState().getChannel() != null) { if (event.getMember().getVoiceState().getChannel() == event.getGuild().getSelfMember().getVoiceState().getChannel()) { if (args[0].matches("[0-9]{1,2}|100|[0-9]{1,2}\\.[0-9]{1,5}")) { if (player != null && player.getAudioPlayer().getPlayingTrack() != null) { if (Double.parseDouble(args[0]) > 0) { player.getAudioPlayer().setPaused(false); player.setSpeed(Double.parseDouble(args[0])); player.updateFilters(); } else { player.setSpeed(0); player.getAudioPlayer().setPaused(true); player.updateFilters(); } event.reply("The music speed has been set to **" + args[0] + "** by **" + event.getFullAuthorName() + "**"); } else { event.reply("There is no music playing"); } } else { MessageHelper.sendUsage(this, event); } } else { event.reply("You have to be in the same voice channel as me to change the speed"); } } else { event.reply("I'm not in a voiceChannel"); } } else { event.reply("The configured speed is **" + player.getSpeed() + "**"); } } else { event.reply("You need the permission `" + commandName + "` to execute this command."); } } }
46.121212
140
0.503285
dcf8a22bdcb041deb34f919406108ab1fe121bb9
5,654
/* * RED5 Open Source Media Server - https://github.com/Red5/ Copyright 2006-2016 by respective authors (see below). All rights reserved. Licensed under the Apache License, Version * 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless * required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.red5.server.net.rtmp.message; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.apache.mina.core.buffer.IoBuffer; import org.red5.server.net.protocol.ProtocolException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * RTMP chunk header * * <pre> * rtmp_specification_1.0.pdf (5.3.1.1 page 12) * </pre> */ public class ChunkHeader implements Constants, Cloneable, Externalizable { protected static final Logger log = LoggerFactory.getLogger(ChunkHeader.class); /** * Chunk format */ private byte format; /** * Chunk size */ private byte size; /** * Channel */ private int channelId; /** * Getter for format * * @return chunk format */ public byte getFormat() { return format; } /** * Setter for format * * @param format * format */ public void setFormat(byte format) { this.format = format; } /** * Getter for channel id * * @return Channel id */ public int getChannelId() { return channelId; } /** * Setter for channel id * * @param channelId * Header channel id */ public void setChannelId(int channelId) { this.channelId = channelId; } /** * Getter for size * * @return size */ public byte getSize() { return size; } /** * Setter for size * * @param size * Header size */ public void setSize(byte size) { this.size = size; } /** * Read chunk header from the buffer. * * @param in * buffer * @return ChunkHeader instance */ public static ChunkHeader read(IoBuffer in) { int remaining = in.remaining(); if (remaining > 0) { byte headerByte = in.get(); ChunkHeader h = new ChunkHeader(); // going to check highest 2 bits h.format = (byte) ((0b11000000 & headerByte) >> 6); int fmt = headerByte & 0x3f; switch (fmt) { case 0: // two byte header h.size = 2; if (remaining < 2) { throw new ProtocolException("Bad chunk header, at least 2 bytes are expected"); } h.channelId = 64 + (in.get() & 0xff); break; case 1: // three byte header h.size = 3; if (remaining < 3) { throw new ProtocolException("Bad chunk header, at least 3 bytes are expected"); } byte b1 = in.get(); byte b2 = in.get(); h.channelId = 64 + ((b2 & 0xff) << 8 | (b1 & 0xff)); break; default: // single byte header h.size = 1; h.channelId = 0x3f & headerByte; break; } // check channel id is valid if (h.channelId < 0) { throw new ProtocolException("Bad channel id: " + h.channelId); } log.trace("CHUNK header byte {}, count {}, header {}, channel {}", String.format("%02x", headerByte), h.size, 0, h.channelId); return h; } else { // at least one byte for valid decode throw new ProtocolException("Bad chunk header, at least 1 byte is expected"); } } /** {@inheritDoc} */ @Override public boolean equals(Object other) { if (other instanceof ChunkHeader) { final ChunkHeader header = (ChunkHeader) other; return (header.getChannelId() == channelId && header.getFormat() == format); } return false; } /** {@inheritDoc} */ @Override public ChunkHeader clone() { final ChunkHeader header = new ChunkHeader(); header.setChannelId(channelId); header.setSize(size); header.setFormat(format); return header; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { format = in.readByte(); channelId = in.readInt(); size = (byte) (channelId > 319 ? 3 : (channelId > 63 ? 2 : 1)); } public void writeExternal(ObjectOutput out) throws IOException { out.writeByte(format); out.writeInt(channelId); } @Override public String toString() { // if its new and props are un-set, just return that message if ((channelId + format) > 0d) { return "ChunkHeader [type=" + format + ", channelId=" + channelId + ", size=" + size + "]"; } else { return "empty"; } } }
28.700508
178
0.542978
44fa918cfe7cef742ada39b3c9c73f1ef294baca
1,447
package no.ks.eslite.esjc; import com.github.msemys.esjc.CatchUpSubscription; import com.github.msemys.esjc.CatchUpSubscriptionListener; import com.github.msemys.esjc.CatchUpSubscriptionSettings; import com.github.msemys.esjc.EventStore; import org.junit.jupiter.api.Test; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; class EsjcEventSubscriberTest { @Test void testSubscriberGeneration() { EsjcEventSubscriber subscriber; final EventStore eventstoreMock = mock(EventStore.class); final CatchUpSubscription catchUpSubscription = mock(CatchUpSubscription.class); when(eventstoreMock.subscribeToStreamFrom(anyString(), anyLong(), any(CatchUpSubscriptionSettings.class), any(CatchUpSubscriptionListener.class))) .thenReturn(catchUpSubscription); subscriber = new EsjcEventSubscriber(eventstoreMock); String category = UUID.randomUUID().toString(); long hwm = ThreadLocalRandom.current().nextLong(); CatchUpSubscriptionListener listener = mock(CatchUpSubscriptionListener.class); subscriber.subscribeByCategory(category, hwm, listener); verify(eventstoreMock).subscribeToStreamFrom(eq("$ce-" + category), eq(hwm), any(CatchUpSubscriptionSettings.class), eq(listener)); verifyNoMoreInteractions(catchUpSubscription); } }
40.194444
154
0.76434
383092b39cb1d74dcdf1b7e25b8a57a96a272374
7,205
/** * pwlf: Piecewise Linearization of Arbitrary First Order Loss Functions * * MIT License * * Copyright (c) 2020 Roberto Rossi * * 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 lossfunction; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartFrame; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import umontreal.ssj.charts.XYLineChart; import umontreal.ssj.probdist.Distribution; import umontreal.ssj.probdist.EmpiricalDist; import umontreal.ssj.probdist.NormalDist; import umontreal.ssj.probdist.PoissonDist; import umontreal.ssj.probdist.ExponentialDist; public class PiecewiseComplementaryFirstOrderLossFunction extends ComplementaryFirstOrderLossFunction { public PiecewiseComplementaryFirstOrderLossFunction(Distribution[] distributions, long[] seed){ super(distributions, seed); } public double[] getConditionalExpectations(double[] probabilityMasses, int nbSamples){ double[] conditionalExpectations = new double[probabilityMasses.length]; EmpiricalDist empDistribution = this.getEmpiricalDistribution(nbSamples); double probabilityMass = 0; int conditionalExpectationIndex = 0; for(int i = 0; i < empDistribution.getN(); i++){ if(probabilityMass < 1 && probabilityMass < probabilityMasses[conditionalExpectationIndex]){ conditionalExpectations[conditionalExpectationIndex] += empDistribution.getObs(i)/empDistribution.getN(); probabilityMass += 1.0/empDistribution.getN(); }else{ conditionalExpectations[conditionalExpectationIndex] /= probabilityMasses[conditionalExpectationIndex]; probabilityMass = 0; conditionalExpectationIndex++; } } conditionalExpectations[conditionalExpectationIndex] /= probabilityMasses[conditionalExpectationIndex]; return conditionalExpectations; } public XYSeries getLossFunctionXYSeriesForSegment(int segmentIndex, double[] probabilityMasses, double[] conditionalExpectations, double min, double max, double minYValue, double precision){ XYSeries series = new XYSeries("Piecewise complementary loss function"); for(double x = min; x <= max; x+= precision){ double value = getPiecewiseLossFunctionValue(segmentIndex, x, probabilityMasses, conditionalExpectations); if(value >= minYValue) series.add(x, value); } return series; } public double getPiecewiseLossFunctionValue(int segmentIndex, double x, double[] probabilityMasses, double[] conditionalExpectations){ double value = 0; for(int i = 1; i <= segmentIndex; i++){ value += (x-conditionalExpectations[i-1])*probabilityMasses[i-1]; } return value; } public XYSeries getPiecewiseErrorXYSeries(double min, double max, int nbSamples, double[] probabilityMasses, double[] conditionalExpectations, double precision){ XYSeries series = new XYSeries("Piecewise complementary loss function error"); for(double x = min; x <= max; x+= precision){ series.add(x, getPiecewiseErrorValue(x, nbSamples, probabilityMasses, conditionalExpectations)); } return series; } public double getPiecewiseErrorValue(double x, int nbSamples, double[] probabilityMasses, double[] conditionalExpectations){ double lossFunctionValue = this.getLossFunctionValue(x, nbSamples); double maxValue = 0; for(int j = 0; j <= probabilityMasses.length; j++){ double value = 0; for(int i = 1; i <= j; i++){ value += (x-conditionalExpectations[i-1])*probabilityMasses[i-1]; } maxValue = Math.max(maxValue, value); } return lossFunctionValue-maxValue; } public void plotPiecewiseLossFunction(double min, double max, double minYValue, double[] probabilityMasses, int nbSamples, double precision, boolean saveToDisk){ int segments = probabilityMasses.length + 1; double[] conditionalExpectations = this.getConditionalExpectations(probabilityMasses, nbSamples); XYSeriesCollection xyDataset = new XYSeriesCollection(); xyDataset.addSeries(this.getLossFunctionXYSeries(min, max, nbSamples, precision)); for(int i = 0; i < segments; i++) xyDataset.addSeries(this.getLossFunctionXYSeriesForSegment(i, probabilityMasses, conditionalExpectations, min, max, minYValue, precision)); xyDataset.addSeries(this.getPiecewiseErrorXYSeries(min, max, nbSamples, probabilityMasses, conditionalExpectations, precision)); JFreeChart chart = ChartFactory.createXYLineChart("Empirical complementary loss function", "x", "CL(x)", xyDataset, PlotOrientation.VERTICAL, false, true, false); ChartFrame frame = new ChartFrame("Empirical complementary loss function",chart); frame.setVisible(true); frame.setSize(500,400); if(saveToDisk){ XYLineChart lc = new XYLineChart("Piecewise linearization", "x", "CL(x)", xyDataset); try { File latexFolder = new File("./latex"); if(!latexFolder.exists()){ latexFolder.mkdir(); } Writer file = new FileWriter("./latex/graph.tex"); file.write(lc.toLatex(8, 5)); file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public double[] getApproximationErrors(double[] probabilityMasses, int nbSamples){ double[] conditionalExpectations = this.getConditionalExpectations(probabilityMasses, nbSamples); double[] approximationErrors = new double[conditionalExpectations.length]; for(int i = 0; i < probabilityMasses.length; i++){ approximationErrors[i] = getLossFunctionValue(conditionalExpectations[i], nbSamples)- getPiecewiseLossFunctionValue(i, conditionalExpectations[i], probabilityMasses, conditionalExpectations); } return approximationErrors; } public double getMaxApproximationError(double[] probabilityMasses, int nbSamples){ double[] approximationErrors = this.getApproximationErrors(probabilityMasses, nbSamples); double maxApproximationError = 0; for(int i = 0; i < probabilityMasses.length; i++){ maxApproximationError = Math.max(maxApproximationError, approximationErrors[i]); } return maxApproximationError; } }
39.80663
162
0.764885
75e1355c42067df50b8fcb657f32ce65b8f91752
449
package com.homies.app.web.rest.errors.Task; import com.homies.app.web.rest.errors.BadRequestAlertException; import com.homies.app.web.rest.errors.ErrorConstants; public class TaskWasNotSpecifyIdTask extends BadRequestAlertException { private static final long serialVersionUID = 1L; public TaskWasNotSpecifyIdTask() { super(ErrorConstants.TASK_ID_NOT_SPECIFY, "Id was not specify", "userManagement", "idWasNotSpecify"); } }
32.071429
109
0.783964
d109e56d0a35cf3916f423942f179b8aeb5486e5
789
package net.ugolok.providers; import java.util.Iterator; import net.ugolok.dto.BarrierState; import net.ugolok.generation.providers.api.AbstractRandomProvider; import net.ugolok.generation.providers.api.Provider; public class BarrierStateProvider extends AbstractRandomProvider<BarrierState> implements Provider<BarrierState> { public BarrierStateProvider() { super(); } @Override public Iterator<BarrierState> iterator() { return new Iterator<>() { @Override public boolean hasNext() { return true; } @Override public BarrierState next() { return BarrierState.values()[randomGenerator.nextInt(BarrierState.values().length)]; } }; } }
26.3
114
0.647655
87935b40139477cc08829bc3875900a3c0531b42
162
package Exceptions; public class InvalidGameMovement extends Exception { public InvalidGameMovement(String message) { super(message); } }
20.25
53
0.697531
7fb70ad4a3ed051ccc10cb004297555b47ec7bfb
1,514
package restx.description; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Lists; import java.util.List; /** * User: xavierhanin * Date: 2/7/13 * Time: 10:53 AM */ public class ResourceDescription { public String path; public String stdPath; public String description = ""; public List<OperationDescription> operations = Lists.newArrayList(); public static class Matcher implements Predicate<ResourceDescription> { private Predicate<String> pathMatcher = Predicates.alwaysTrue(); private Predicate<String> stdPathMatcher = Predicates.alwaysTrue(); private Predicate<String> descriptionMatcher = Predicates.alwaysTrue(); public Matcher withPathMatcher(Predicate<String> pathMatcher) { this.pathMatcher = pathMatcher; return this; } public Matcher withStdPathMatcher(Predicate<String> stdPathMatcher) { this.stdPathMatcher = stdPathMatcher; return this; } public Matcher withDescriptionMatcher(Predicate<String> descriptionMatcher) { this.descriptionMatcher = descriptionMatcher; return this; } public boolean apply(ResourceDescription description) { return pathMatcher.apply(description.path) && stdPathMatcher.apply(description.stdPath) && descriptionMatcher.apply(description.description); } } }
31.541667
85
0.679657
f074f65c1dd950c4ab7f1ca15419478e57d25faf
813
package com.udb.dsm.helpets; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import com.google.firebase.auth.FirebaseAuth; import java.util.Timer; import java.util.TimerTask; public class SplashScreen extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); TimerTask task = new TimerTask() { @Override public void run() { Intent intent = new Intent(SplashScreen.this, LoginActivity.class); startActivity(intent); finish(); } }; Timer time = new Timer(); time.schedule(task, 3000); } }
26.225806
83
0.653137
9057cecf869d5f05e7dfc932bb508c5148a33380
5,898
/* * Fabric3 * Copyright (c) 2009-2015 Metaform Systems * * 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. * * Portions originally based on Apache Tuscany 2007 * licensed under the Apache 2.0 license. */ package org.fabric3.implementation.pojo.manager; import java.util.HashSet; import java.util.Set; import java.util.function.Supplier; import org.fabric3.api.host.Fabric3Exception; import org.fabric3.api.model.type.java.Injectable; import org.fabric3.implementation.pojo.spi.reflection.LifecycleInvoker; import org.fabric3.spi.container.injection.Injector; import org.fabric3.spi.container.invocation.Message; import org.fabric3.spi.container.invocation.MessageCache; /** * */ public class ImplementationManagerImpl implements ImplementationManager { private final Supplier<?> constructor; private Injectable[] injectables; private final Injector<Object>[] injectors; private final LifecycleInvoker initInvoker; private final LifecycleInvoker destroyInvoker; private final ClassLoader cl; private final boolean reinjectable; private Set<Injector<Object>> updatedInjectors; public ImplementationManagerImpl(Supplier<?> constructor, Injectable[] injectables, Injector<Object>[] injectors, LifecycleInvoker initInvoker, LifecycleInvoker destroyInvoker, boolean reinjectable, ClassLoader cl) { this.constructor = constructor; this.injectables = injectables; this.injectors = injectors; this.initInvoker = initInvoker; this.destroyInvoker = destroyInvoker; this.reinjectable = reinjectable; this.cl = cl; if (reinjectable) { this.updatedInjectors = new HashSet<>(); } else { this.updatedInjectors = null; } } public Object newInstance() throws Fabric3Exception { ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(cl); try { // FABRIC-40: if a component invokes services from a setter, the message content will be over-written. Save so it can be restored after instance // injection. Message message = MessageCache.getMessage(); Object content = message.getBody(); Object instance = constructor.get(); if (injectors != null) { for (Injector<Object> injector : injectors) { injector.inject(instance); } } // restore the original contents message.setBody(content); return instance; } finally { Thread.currentThread().setContextClassLoader(oldCl); } } public void start(Object instance) throws Fabric3Exception { if (initInvoker != null) { ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(cl); initInvoker.invoke(instance); } finally { Thread.currentThread().setContextClassLoader(oldCl); } } } public void stop(Object instance) throws Fabric3Exception { if (destroyInvoker != null) { ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(cl); destroyInvoker.invoke(instance); } finally { Thread.currentThread().setContextClassLoader(oldCl); } } } public void reinject(Object instance) throws Fabric3Exception { if (!reinjectable) { throw new IllegalStateException("Implementation is not reinjectable:" + instance.getClass().getName()); } for (Injector<Object> injector : updatedInjectors) { injector.inject(instance); } updatedInjectors.clear(); } public void updated(Object instance, String name) { if (instance != null && !reinjectable) { throw new IllegalStateException("Implementation is not reinjectable: " + instance.getClass().getName()); } for (int i = 0; i < injectables.length; i++) { Injectable attribute = injectables[i]; if (attribute.getName().equals(name)) { Injector<Object> injector = injectors[i]; if (instance != null) { updatedInjectors.add(injector); } } } } public void removed(Object instance, String name) { if (instance != null && !reinjectable) { throw new IllegalStateException("Implementation is not reinjectable: " + instance.getClass().getName()); } for (int i = 0; i < injectables.length; i++) { Injectable attribute = injectables[i]; if (attribute.getName().equals(name)) { Injector<Object> injector = injectors[i]; injector.clearSupplier(); if (instance != null) { updatedInjectors.add(injector); } } } } }
37.807692
156
0.610207
9050adde2a73352948deffa697c40907b3d3217c
1,217
package org.edx.mobile.core; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.inject.Inject; import com.google.inject.Provider; import com.jakewharton.retrofit.Ok3Client; import org.edx.mobile.discussion.RetroHttpExceptionHandler; import org.edx.mobile.util.Config; import org.edx.mobile.util.DateUtil; import okhttp3.OkHttpClient; import retrofit.RestAdapter; import retrofit.converter.GsonConverter; public class RestAdapterProvider implements Provider<RestAdapter> { @Inject Config config; @Inject OkHttpClient client; @Override public RestAdapter get() { Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setDateFormat(DateUtil.ISO_8601_DATE_TIME_FORMAT) .serializeNulls() .create(); return new RestAdapter.Builder() .setClient(new Ok3Client(client)) .setEndpoint(config.getApiHostURL()) .setConverter(new GsonConverter(gson)) .setErrorHandler(new RetroHttpExceptionHandler()) .build(); } }
28.97619
84
0.695974
31d4dccf5d3e6ba708c9600a6f81293dfd3a58aa
27,753
/* * 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.facebook.presto.hive; import com.facebook.presto.hive.HiveWriteUtils.FieldSetter; import com.facebook.presto.hive.metastore.HiveMetastore; import com.facebook.presto.spi.ConnectorPageSink; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.PageIndexer; import com.facebook.presto.spi.PageIndexerFactory; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; import io.airlift.json.JsonCodec; import io.airlift.slice.Slice; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.common.FileUtils; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.MetaStoreUtils; import org.apache.hadoop.hive.metastore.api.Partition; import org.apache.hadoop.hive.metastore.api.StorageDescriptor; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter; import org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.hive.serde2.Serializer; import org.apache.hadoop.hive.serde2.columnar.OptimizedLazyBinaryColumnarSerde; import org.apache.hadoop.hive.serde2.objectinspector.SettableStructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.DefaultCodec; import org.apache.hadoop.mapred.JobConf; import org.apache.hive.common.util.ReflectionUtil; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import static com.facebook.presto.hive.HiveColumnHandle.SAMPLE_WEIGHT_COLUMN_NAME; import static com.facebook.presto.hive.HiveErrorCode.HIVE_INVALID_METADATA; import static com.facebook.presto.hive.HiveErrorCode.HIVE_PARTITION_READ_ONLY; import static com.facebook.presto.hive.HiveErrorCode.HIVE_PARTITION_SCHEMA_MISMATCH; import static com.facebook.presto.hive.HiveErrorCode.HIVE_PATH_ALREADY_EXISTS; import static com.facebook.presto.hive.HiveErrorCode.HIVE_TOO_MANY_OPEN_PARTITIONS; import static com.facebook.presto.hive.HiveErrorCode.HIVE_UNSUPPORTED_FORMAT; import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_ERROR; import static com.facebook.presto.hive.HivePartitionKey.HIVE_DEFAULT_DYNAMIC_PARTITION; import static com.facebook.presto.hive.HiveType.toHiveTypes; import static com.facebook.presto.hive.HiveWriteUtils.createFieldSetter; import static com.facebook.presto.hive.HiveWriteUtils.getField; import static com.facebook.presto.hive.HiveWriteUtils.getRowColumnInspectors; import static com.facebook.presto.spi.StandardErrorCode.NOT_FOUND; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static io.airlift.slice.Slices.wrappedBuffer; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static java.util.UUID.randomUUID; import static java.util.stream.Collectors.toList; import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.COMPRESSRESULT; import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMNS; import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_COLUMN_TYPES; import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardStructObjectInspector; public class HivePageSink implements ConnectorPageSink { private final String schemaName; private final String tableName; private final int[] dataColumns; private final List<String> dataColumnNames; private final List<Type> dataColumnTypes; private final int[] partitionColumns; private final List<String> partitionColumnNames; private final List<Type> partitionColumnTypes; private final HiveStorageFormat tableStorageFormat; private final LocationHandle locationHandle; private final LocationService locationService; private final String filePrefix; private final HiveMetastore metastore; private final PageIndexer pageIndexer; private final TypeManager typeManager; private final HdfsEnvironment hdfsEnvironment; private final JobConf conf; private final int maxOpenPartitions; private final JsonCodec<PartitionUpdate> partitionUpdateCodec; private final List<Object> partitionRow; private final Table table; private final boolean immutablePartitions; private final boolean respectTableFormat; private HiveRecordWriter[] writers = new HiveRecordWriter[0]; public HivePageSink( String schemaName, String tableName, boolean isCreateTable, List<HiveColumnHandle> inputColumns, HiveStorageFormat tableStorageFormat, LocationHandle locationHandle, LocationService locationService, String filePrefix, HiveMetastore metastore, PageIndexerFactory pageIndexerFactory, TypeManager typeManager, HdfsEnvironment hdfsEnvironment, boolean respectTableFormat, int maxOpenPartitions, boolean immutablePartitions, JsonCodec<PartitionUpdate> partitionUpdateCodec) { this.schemaName = requireNonNull(schemaName, "schemaName is null"); this.tableName = requireNonNull(tableName, "tableName is null"); requireNonNull(inputColumns, "inputColumns is null"); this.tableStorageFormat = requireNonNull(tableStorageFormat, "tableStorageFormat is null"); this.locationHandle = requireNonNull(locationHandle, "locationHandle is null"); this.locationService = requireNonNull(locationService, "locationService is null"); this.filePrefix = requireNonNull(filePrefix, "filePrefix is null"); this.metastore = requireNonNull(metastore, "metastore is null"); requireNonNull(pageIndexerFactory, "pageIndexerFactory is null"); this.typeManager = requireNonNull(typeManager, "typeManager is null"); this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null"); this.respectTableFormat = respectTableFormat; this.maxOpenPartitions = maxOpenPartitions; this.immutablePartitions = immutablePartitions; this.partitionUpdateCodec = requireNonNull(partitionUpdateCodec, "partitionUpdateCodec is null"); // divide input columns into partition and data columns ImmutableList.Builder<String> partitionColumnNames = ImmutableList.builder(); ImmutableList.Builder<Type> partitionColumnTypes = ImmutableList.builder(); ImmutableList.Builder<String> dataColumnNames = ImmutableList.builder(); ImmutableList.Builder<Type> dataColumnTypes = ImmutableList.builder(); for (HiveColumnHandle column : inputColumns) { if (column.isPartitionKey()) { partitionColumnNames.add(column.getName()); partitionColumnTypes.add(typeManager.getType(column.getTypeSignature())); } else { dataColumnNames.add(column.getName()); dataColumnTypes.add(typeManager.getType(column.getTypeSignature())); } } this.partitionColumnNames = partitionColumnNames.build(); this.partitionColumnTypes = partitionColumnTypes.build(); this.dataColumnNames = dataColumnNames.build(); this.dataColumnTypes = dataColumnTypes.build(); // determine the input index of the partition columns and data columns ImmutableList.Builder<Integer> partitionColumns = ImmutableList.builder(); ImmutableList.Builder<Integer> dataColumns = ImmutableList.builder(); // sample weight column is passed separately, so index must be calculated without this column List<HiveColumnHandle> inputColumnsWithoutSample = inputColumns.stream() .filter(column -> !column.getName().equals(SAMPLE_WEIGHT_COLUMN_NAME)) .collect(toList()); for (int inputIndex = 0; inputIndex < inputColumnsWithoutSample.size(); inputIndex++) { HiveColumnHandle column = inputColumnsWithoutSample.get(inputIndex); if (column.isPartitionKey()) { partitionColumns.add(inputIndex); } else { dataColumns.add(inputIndex); } } this.partitionColumns = Ints.toArray(partitionColumns.build()); this.dataColumns = Ints.toArray(dataColumns.build()); this.pageIndexer = pageIndexerFactory.createPageIndexer(this.partitionColumnTypes); // preallocate temp space for partition and data this.partitionRow = Arrays.asList(new Object[this.partitionColumnNames.size()]); if (isCreateTable) { this.table = null; Optional<Path> writePath = locationService.writePathRoot(locationHandle); checkArgument(writePath.isPresent(), "CREATE TABLE must have a write path"); conf = new JobConf(hdfsEnvironment.getConfiguration(writePath.get())); } else { Optional<Table> table = metastore.getTable(schemaName, tableName); if (!table.isPresent()) { throw new PrestoException(HIVE_INVALID_METADATA, format("Table %s.%s was dropped during insert", schemaName, tableName)); } this.table = table.get(); Path hdfsEnvironmentPath = locationService.writePathRoot(locationHandle).orElseGet(() -> locationService.targetPathRoot(locationHandle)); conf = new JobConf(hdfsEnvironment.getConfiguration(hdfsEnvironmentPath)); } } @Override public Collection<Slice> finish() { ImmutableList.Builder<Slice> partitionUpdates = ImmutableList.builder(); for (HiveRecordWriter writer : writers) { if (writer != null) { writer.commit(); PartitionUpdate partitionUpdate = writer.getPartitionUpdate(); partitionUpdates.add(wrappedBuffer(partitionUpdateCodec.toJsonBytes(partitionUpdate))); } } return partitionUpdates.build(); } @Override public void abort() { for (HiveRecordWriter writer : writers) { if (writer != null) { writer.rollback(); } } } @Override public void appendPage(Page page, Block sampleWeightBlock) { if (page.getPositionCount() == 0) { return; } Block[] dataBlocks = getDataBlocks(page, sampleWeightBlock); Block[] partitionBlocks = getPartitionBlocks(page); int[] indexes = pageIndexer.indexPage(new Page(page.getPositionCount(), partitionBlocks)); if (pageIndexer.getMaxIndex() >= maxOpenPartitions) { throw new PrestoException(HIVE_TOO_MANY_OPEN_PARTITIONS, "Too many open partitions"); } if (pageIndexer.getMaxIndex() >= writers.length) { writers = Arrays.copyOf(writers, pageIndexer.getMaxIndex() + 1); } for (int position = 0; position < page.getPositionCount(); position++) { int writerIndex = indexes[position]; HiveRecordWriter writer = writers[writerIndex]; if (writer == null) { for (int field = 0; field < partitionBlocks.length; field++) { Object value = getField(partitionColumnTypes.get(field), partitionBlocks[field], position); partitionRow.set(field, value); } writer = createWriter(partitionRow); writers[writerIndex] = writer; } writer.addRow(dataBlocks, position); } } private HiveRecordWriter createWriter(List<Object> partitionRow) { checkArgument(partitionRow.size() == partitionColumnNames.size(), "size of partitionRow is different from partitionColumnNames"); List<String> partitionValues = partitionRow.stream() .map(value -> (value == null) ? HIVE_DEFAULT_DYNAMIC_PARTITION : value.toString()) .collect(toList()); Optional<String> partitionName; if (!partitionColumnNames.isEmpty()) { partitionName = Optional.of(FileUtils.makePartName(partitionColumnNames, partitionValues)); } else { partitionName = Optional.empty(); } // attempt to get the existing partition (if this is an existing partitioned table) Optional<Partition> partition = Optional.empty(); if (!partitionRow.isEmpty() && table != null) { partition = metastore.getPartition(schemaName, tableName, partitionName.get()); } boolean isNew; Properties schema; Path target; Path write; String outputFormat; String serDe; if (!partition.isPresent()) { if (table == null) { // Write to: a new partition in a new partitioned table, // or a new unpartitioned table. isNew = true; schema = new Properties(); schema.setProperty(META_TABLE_COLUMNS, Joiner.on(',').join(dataColumnNames)); schema.setProperty(META_TABLE_COLUMN_TYPES, dataColumnTypes.stream() .map(HiveType::toHiveType) .map(HiveType::getHiveTypeName) .collect(Collectors.joining(":"))); target = locationService.targetPath(locationHandle, partitionName); write = locationService.writePath(locationHandle, partitionName).get(); if (partitionName.isPresent()) { // verify the target directory for the partition does not already exist if (HiveWriteUtils.pathExists(hdfsEnvironment, target)) { throw new PrestoException(HIVE_PATH_ALREADY_EXISTS, format("Target directory for new partition '%s' of table '%s.%s' already exists: %s", partitionName, schemaName, tableName, target)); } } outputFormat = tableStorageFormat.getOutputFormat(); serDe = tableStorageFormat.getSerDe(); } else { // Write to: a new partition in an existing partitioned table, // or an existing unpartitioned table if (partitionName.isPresent()) { isNew = true; } else { if (immutablePartitions) { throw new PrestoException(HIVE_PARTITION_READ_ONLY, "Unpartitioned Hive tables are immutable"); } isNew = false; } schema = MetaStoreUtils.getSchema( table.getSd(), table.getSd(), table.getParameters(), schemaName, tableName, table.getPartitionKeys()); target = locationService.targetPath(locationHandle, partitionName); write = locationService.writePath(locationHandle, partitionName).orElse(target); if (respectTableFormat) { outputFormat = table.getSd().getOutputFormat(); } else { outputFormat = tableStorageFormat.getOutputFormat(); } serDe = table.getSd().getSerdeInfo().getSerializationLib(); } } else { // Write to: an existing partition in an existing partitioned table, if (immutablePartitions) { throw new PrestoException(HIVE_PARTITION_READ_ONLY, "Hive partitions are immutable"); } isNew = false; // Append to an existing partition HiveWriteUtils.checkPartitionIsWritable(partitionName.get(), partition.get()); StorageDescriptor storageDescriptor = partition.get().getSd(); outputFormat = storageDescriptor.getOutputFormat(); serDe = storageDescriptor.getSerdeInfo().getSerializationLib(); schema = MetaStoreUtils.getSchema(partition.get(), table); target = locationService.targetPath(locationHandle, partition.get(), partitionName.get()); write = locationService.writePath(locationHandle, partitionName).orElse(target); } return new HiveRecordWriter( schemaName, tableName, partitionName.orElse(""), isNew, dataColumnNames, dataColumnTypes, outputFormat, serDe, schema, generateRandomFileName(outputFormat), write.toString(), target.toString(), typeManager, conf); } private String generateRandomFileName(String outputFormat) { // text format files must have the correct extension when compressed String extension = ""; if (HiveConf.getBoolVar(conf, COMPRESSRESULT) && HiveIgnoreKeyTextOutputFormat.class.getName().equals(outputFormat)) { extension = new DefaultCodec().getDefaultExtension(); String compressionCodecClass = conf.get("mapred.output.compression.codec"); if (compressionCodecClass != null) { try { Class<? extends CompressionCodec> codecClass = conf.getClassByName(compressionCodecClass).asSubclass(CompressionCodec.class); extension = ReflectionUtil.newInstance(codecClass, conf).getDefaultExtension(); } catch (ClassNotFoundException e) { throw new PrestoException(HIVE_UNSUPPORTED_FORMAT, "Compression codec not found: " + compressionCodecClass, e); } catch (RuntimeException e) { throw new PrestoException(HIVE_UNSUPPORTED_FORMAT, "Failed to load compression codec: " + compressionCodecClass, e); } } } return filePrefix + "_" + randomUUID() + extension; } private Block[] getDataBlocks(Page page, Block sampleWeightBlock) { Block[] blocks = new Block[dataColumns.length + (sampleWeightBlock != null ? 1 : 0)]; for (int i = 0; i < dataColumns.length; i++) { int dataColumn = dataColumns[i]; blocks[i] = page.getBlock(dataColumn); } if (sampleWeightBlock != null) { // sample weight block is always last blocks[blocks.length - 1] = sampleWeightBlock; } return blocks; } private Block[] getPartitionBlocks(Page page) { Block[] blocks = new Block[partitionColumns.length]; for (int i = 0; i < partitionColumns.length; i++) { int dataColumn = partitionColumns[i]; blocks[i] = page.getBlock(dataColumn); } return blocks; } private static class HiveRecordWriter { private final String partitionName; private final boolean isNew; private final String fileName; private final String writePath; private final String targetPath; private final int fieldCount; @SuppressWarnings("deprecation") private final Serializer serializer; private final RecordWriter recordWriter; private final SettableStructObjectInspector tableInspector; private final List<StructField> structFields; private final Object row; private final FieldSetter[] setters; public HiveRecordWriter( String schemaName, String tableName, String partitionName, boolean isNew, List<String> inputColumnNames, List<Type> inputColumnTypes, String outputFormat, String serDe, Properties schema, String fileName, String writePath, String targetPath, TypeManager typeManager, JobConf conf) { this.partitionName = partitionName; this.isNew = isNew; this.fileName = fileName; this.writePath = writePath; this.targetPath = targetPath; // existing tables may have columns in a different order List<String> fileColumnNames = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(schema.getProperty(META_TABLE_COLUMNS, "")); List<Type> fileColumnTypes = toHiveTypes(schema.getProperty(META_TABLE_COLUMN_TYPES, "")).stream() .map(hiveType -> hiveType.getType(typeManager)) .collect(toList()); // verify we can write all input columns to the file Set<Object> missingColumns = Sets.difference(new HashSet<>(inputColumnNames), new HashSet<>(fileColumnNames)); if (!missingColumns.isEmpty()) { throw new PrestoException(NOT_FOUND, format("Table %s.%s does not have columns %s", schema, tableName, missingColumns)); } if (fileColumnNames.size() != fileColumnTypes.size()) { throw new PrestoException(HIVE_INVALID_METADATA, format("Partition '%s' in table '%s.%s' has metadata for column names or types", partitionName, schemaName, tableName)); } // verify the file types match the input type // todo adapt input types to the file types as Hive does for (int fileIndex = 0; fileIndex < fileColumnNames.size(); fileIndex++) { String columnName = fileColumnNames.get(fileIndex); Type fileColumnType = fileColumnTypes.get(fileIndex); int inputIndex = inputColumnNames.indexOf(columnName); Type inputType = inputColumnTypes.get(inputIndex); if (!inputType.equals(fileColumnType)) { // todo this should be moved to a helper throw new PrestoException(HIVE_PARTITION_SCHEMA_MISMATCH, format("" + "There is a mismatch between the table and partition schemas. " + "The column '%s' in table '%s.%s' is declared as type '%s', " + "but partition '%s' declared column '%s' as type '%s'.", columnName, schemaName, tableName, inputType, partitionName, columnName, fileColumnType)); } } fieldCount = fileColumnNames.size(); if (serDe.equals(org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe.class.getName())) { serDe = OptimizedLazyBinaryColumnarSerde.class.getName(); } serializer = initializeSerializer(conf, schema, serDe); recordWriter = HiveWriteUtils.createRecordWriter(new Path(writePath, fileName), conf, schema, outputFormat); tableInspector = getStandardStructObjectInspector(fileColumnNames, getRowColumnInspectors(fileColumnTypes)); // reorder (and possibly reduce) struct fields to match input structFields = ImmutableList.copyOf(inputColumnNames.stream() .map(tableInspector::getStructFieldRef) .collect(toList())); row = tableInspector.create(); setters = new FieldSetter[structFields.size()]; for (int i = 0; i < setters.length; i++) { setters[i] = createFieldSetter(tableInspector, row, structFields.get(i), inputColumnTypes.get(i)); } } public void addRow(Block[] columns, int position) { for (int field = 0; field < fieldCount; field++) { if (columns[field].isNull(position)) { tableInspector.setStructFieldData(row, structFields.get(field), null); } else { setters[field].setField(columns[field], position); } } try { recordWriter.write(serializer.serialize(row, tableInspector)); } catch (SerDeException | IOException e) { throw new PrestoException(HIVE_WRITER_ERROR, e); } } public void commit() { try { recordWriter.close(false); } catch (IOException e) { throw new PrestoException(HIVE_WRITER_ERROR, "Error committing write to Hive", e); } } public void rollback() { try { recordWriter.close(true); } catch (IOException e) { throw new PrestoException(HIVE_WRITER_ERROR, "Error rolling back write to Hive", e); } } public PartitionUpdate getPartitionUpdate() { return new PartitionUpdate( partitionName, isNew, writePath, targetPath, ImmutableList.of(fileName)); } @SuppressWarnings("deprecation") private static Serializer initializeSerializer(Configuration conf, Properties properties, String serializerName) { try { Serializer result = (Serializer) Class.forName(serializerName).getConstructor().newInstance(); result.initialize(conf, properties); return result; } catch (SerDeException | ReflectiveOperationException e) { throw Throwables.propagate(e); } } @Override public String toString() { return toStringHelper(this) .add("partitionName", partitionName) .add("writePath", writePath) .add("fileName", fileName) .toString(); } } }
44.122417
161
0.632076
c028342994f035ac760f7c679b59be5cdd30c909
4,633
package org.batfish.minesweeper.question; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.service.AutoService; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.batfish.common.Answerer; import org.batfish.common.plugin.IBatfish; import org.batfish.common.plugin.Plugin; import org.batfish.datamodel.answers.AnswerElement; import org.batfish.datamodel.answers.StringAnswerElement; import org.batfish.datamodel.questions.Question; import org.batfish.minesweeper.nv.CompilerOptions; import org.batfish.minesweeper.nv.CompilerOptions.NVFlags; import org.batfish.minesweeper.nv.CompilerResult; import org.batfish.minesweeper.nv.NVCompiler; import org.batfish.question.QuestionPlugin; @AutoService(Plugin.class) public class CompilerQuestionPlugin extends QuestionPlugin { public static class CompileAnswerer extends Answerer { public CompileAnswerer(Question question, IBatfish batfish) { super(question, batfish); } @Override public AnswerElement answer() { CompileQuestion q = (CompileQuestion) _question; CompilerOptions flags = new CompilerOptions(); if (((CompileQuestion) _question).getNextHop()) { flags.setFlag(NVFlags.nexthop); } if (((CompileQuestion) _question).getOrigin()) { flags.setFlag(NVFlags.origin); } if (((CompileQuestion) _question).getData()) { flags.setFlag(NVFlags.dataplane); } if (((CompileQuestion) _question).getNodeFaults()) { flags.setFlag(NVFlags.nodeFaults); } NVCompiler c = new NVCompiler(_batfish, q.getFile() + "_control.nv", flags); CompilerResult f = c.compile(q.getSinglePrefix()); String cpComment = "(* models bgp, ospf, static routes" + (flags.doNextHop() ? ", nexthop" : "") + (flags.doOrigin() ? ", route-origin" : "") + " *)\n\n"; writeFile(q.getFile() + "_control.nv", f.getControlPlane(), cpComment); if (flags.doDataplane()) { writeFile(q.getFile() + "_data.nv", f.getDataPlane(), ""); } if (flags.doNodeFaults()) { writeFile(q.getFile() + "_nodeFaults.nv", f.getAllNodeFaults(), ""); } return new StringAnswerElement(); } private void writeFile(String name, String contents, String comments) { try { File file = new File(name); FileWriter fileWriter = new FileWriter(file); fileWriter.write(comments); fileWriter.write(contents); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { System.out.println("An error occurred: could not write file."); e.printStackTrace(); } } } public static class CompileQuestion extends HeaderQuestion { private static final String PROP_NEXTHOP = "doNextHop"; private static final String PROP_ORIGIN = "doOrigin"; private static final String PROP_DATA = "doData"; private static final String PROP_DO_NODE_FAULTS = "doNodeFaults"; private static final String PROP_FILE = "file"; private boolean _nextHop = false; private boolean _origin = false; private boolean _doNodeFaults = false; private boolean _data = false; private String _file = ""; @JsonProperty(PROP_NEXTHOP) public boolean getNextHop() { return _nextHop; } @JsonProperty(PROP_ORIGIN) public boolean getOrigin() { return _origin; } @JsonProperty(PROP_DO_NODE_FAULTS) public boolean getNodeFaults() { return _doNodeFaults; } @JsonProperty(PROP_DATA) public boolean getData() { return _data; } @JsonProperty(PROP_FILE) public String getFile() { return _file; } @JsonProperty(PROP_NEXTHOP) public void setNextHop(boolean x) { this._nextHop = x; } @JsonProperty(PROP_ORIGIN) public void setOrigin(boolean x) { this._origin = x; } @JsonProperty(PROP_DATA) public void setData(boolean x) { this._data = x; } @JsonProperty(PROP_DO_NODE_FAULTS) public void setDoNodeFaults(boolean x) { this._doNodeFaults = x; } @JsonProperty(PROP_FILE) public void setFile(String x) { this._file = x; } @Override public boolean getDataPlane() { return false; } @Override public String getName() { return "compile"; } } @Override protected Answerer createAnswerer(Question question, IBatfish batfish) { return new CompileAnswerer(question, batfish); } @Override protected Question createQuestion() { return new CompileQuestion(); } }
28.776398
82
0.67343
5f6286583d4ac9b8a06e19e845ed362619481eb7
444
package com.binlee.design.command; import com.binlee.util.Logger; /** * @author binli sleticalboy@gmail.com * created by IDEA 2020/11/16 */ public final class AudioPlayer { private final Logger logger = Logger.get(AudioPlayer.class); public void play() { logger.i("play() ..."); } public void pause() { logger.i("pause() ..."); } public void resume() { logger.i("resume() ..."); } }
17.76
64
0.59009
b1f454d67f8f26fe775121d6104c4d4939510f40
29,760
package vv3ird.populatecard.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTree; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.MutableTreeNode; import vv3ird.populatecard.CardCreator; import vv3ird.populatecard.control.FieldEditor; import vv3ird.populatecard.control.FieldEditor.Corner; import vv3ird.populatecard.data.Field; import vv3ird.populatecard.data.Field.CardSide; import vv3ird.populatecard.data.FieldPackage; import javax.swing.JCheckBox; /** * Panel to map Fields to the front and rear image of the card. * @author wkiv894 * */ public class JFieldMappingPanel extends JPanel { private static final long serialVersionUID = 6755160427559608684L; private JPanel contentPane; private JScrollPane spFront; private JLabel pnFront; private JLabel pnRear; private DefaultMutableTreeNode fieldRoot = null; private BufferedImage front = null; private BufferedImage frontBuffer1 = null; private BufferedImage frontBuffer2 = null; private BufferedImage frontPreview = null; private BufferedImage rear = null; private BufferedImage rearBuffer1 = null; private BufferedImage rearBuffer2 = null; private BufferedImage rearPreview = null; private boolean previewMode = false; Dimension frontPos1 = null; Dimension backPos1 = null; private List<Field> fields = new LinkedList<>(); private FieldEditor editor = null; private Corner editCorner = Corner.NONE; private Color rectColor = Color.GREEN; private JScrollPane spBack; private JTree treeFields; private JFieldEditorPanel fieldEditior; private JCheckBox chckbxPreview; /** * @wbp.parser.constructor */ public JFieldMappingPanel() { this(true); } public JFieldMappingPanel(boolean frontPanel) { BufferedImage frontImage = CardCreator.getFrontImage(); BufferedImage rearImage = CardCreator.getRearImage(); int preferredWidth = frontImage.getWidth() < rearImage.getWidth() ? frontImage.getWidth() : rearImage.getWidth(); preferredWidth = preferredWidth < 1000 ? preferredWidth : 1000; int preferredHeight = frontImage.getHeight() < rearImage.getHeight() ? frontImage.getHeight() : rearImage.getHeight(); preferredHeight = preferredHeight < 1000 ? preferredHeight : 800; setBounds(100, 100, 600, 400); setMinimumSize(new Dimension(400, 400)); setSize(new Dimension(400, 400)); setPreferredSize(new Dimension(preferredWidth, preferredHeight)); setMaximumSize(new Dimension(1000, 800)); contentPane = this; contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); this.fields.addAll(CardCreator.getFields().stream().map(f -> f.clone()).collect(Collectors.toList())); this.editor = new FieldEditor(this.fields); contentPane.setLayout(new BorderLayout(0, 0)); // Front image this.front = frontImage; this.frontBuffer1 = new BufferedImage(frontImage.getWidth(), frontImage.getHeight(), frontImage.getType()); this.frontBuffer2 = new BufferedImage(frontImage.getWidth(), frontImage.getHeight(), frontImage.getType()); Graphics g = frontBuffer1.getGraphics(); Graphics g2 = frontBuffer2.getGraphics(); g.drawImage(frontImage, 0, 0, null); g.dispose(); g2.drawImage(frontImage, 0, 0, null); g2.dispose(); // Back image this.rear = rearImage; this.rearBuffer1 = new BufferedImage(rearImage.getWidth(), rearImage.getHeight(), rearImage.getType()); this.rearBuffer2 = new BufferedImage(rearImage.getWidth(), rearImage.getHeight(), rearImage.getType()); g = frontBuffer1.getGraphics(); g2 = frontBuffer2.getGraphics(); g.drawImage(rearImage, 0, 0, null); g.dispose(); g2.drawImage(rearImage, 0, 0, null); g2.dispose(); JPanel panel_1 = new JPanel(); contentPane.add(panel_1, BorderLayout.SOUTH); JButton btnSaveDimensions = new JButton("Export CM File"); btnSaveDimensions.setAlignmentY(Component.TOP_ALIGNMENT); btnSaveDimensions.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String cmDir = System.getProperty("user.dir") + File.separator + "projects"; try { if (!Files.exists(Paths.get(cmDir))) Files.createDirectories(Paths.get(cmDir)); JFileChooser chooser = new JFileChooserCheckExisting(cmDir); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setAcceptAllFileFilterUsed(false); chooser.setDialogTitle("Choose a filename"); chooser.setFileFilter(new FileNameExtensionFilter("CardMapper Files", new String[] { "cm" })); int res = chooser.showSaveDialog(JFieldMappingPanel.this); if (res == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); FieldPackage fPackage = new FieldPackage(front, rear); fPackage.addFields(fields); fPackage.setAlternateRearImage(CardCreator.getAlternateRearImage()); if (!f.getAbsolutePath().endsWith(".cm")) f = new File(f.getAbsolutePath() + ".cm"); FieldPackage.save(fPackage, f.toPath()); } } catch (Exception e) { e.printStackTrace(); } } }); panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.X_AXIS)); Component horizontalGlue_1 = Box.createHorizontalGlue(); panel_1.add(horizontalGlue_1); panel_1.add(btnSaveDimensions); JLabel label = new JLabel(""); panel_1.add(label); JButton btnChangeRectColor = new JButton("Change rect color"); btnChangeRectColor.setAlignmentY(Component.TOP_ALIGNMENT); btnChangeRectColor.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Color nColor = JColorChooser.showDialog(null, "Change Button Background", rectColor); if (nColor != null) { rectColor = nColor; } } }); Component horizontalStrut_1 = Box.createHorizontalStrut(5); panel_1.add(horizontalStrut_1); panel_1.add(btnChangeRectColor); Component horizontalStrut = Box.createHorizontalStrut(15); panel_1.add(horizontalStrut); JButton btnSaveResize = new JButton("Save resize"); btnSaveResize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFieldMappingPanel.this.editor.saveField(); JFieldMappingPanel.this.setImage(front, rear); JFieldMappingPanel.this.repaintImage(CardSide.FRONT); JFieldMappingPanel.this.repaintImage(CardSide.REAR); btnSaveResize.setEnabled(false); } }); btnSaveResize.setEnabled(false); btnSaveResize.setAlignmentY(Component.TOP_ALIGNMENT); panel_1.add(btnSaveResize); JLabel label_2 = new JLabel(" "); panel_1.add(label_2); Component horizontalStrut_2 = Box.createHorizontalStrut(15); panel_1.add(horizontalStrut_2); chckbxPreview = new JCheckBox("Preview"); chckbxPreview.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { previewMode = chckbxPreview.isSelected(); updatePreviewMode(); } }); chckbxPreview.setAlignmentY(Component.TOP_ALIGNMENT); panel_1.add(chckbxPreview); Component horizontalGlue = Box.createHorizontalGlue(); panel_1.add(horizontalGlue); Box horizontalBox = Box.createHorizontalBox(); horizontalBox.setAlignmentX(Component.RIGHT_ALIGNMENT); panel_1.add(horizontalBox); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); contentPane.add(tabbedPane, BorderLayout.CENTER); pnFront = new JLabel(new ImageIcon(frontBuffer2)); pnFront.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { JFieldMappingPanel.this.editCorner = Corner.NONE; if (JFieldMappingPanel.this.editor.isEditMode()) { if (!JFieldMappingPanel.this.editor.editFieldContains(e.getPoint())) { JFieldMappingPanel.this.editor.discardEdits(); JFieldMappingPanel.this.setImage(front, rear); JFieldMappingPanel.this.repaintImage(CardSide.FRONT); btnSaveResize.setEnabled(false); } } else if (!JFieldMappingPanel.this.editor.isEditMode()) { if (JFieldMappingPanel.this.editor.editFieldContaining(e.getPoint(), CardSide.FRONT)) { JFieldMappingPanel.this.setImage(front, rear); JFieldMappingPanel.this.repaintImage(CardSide.FRONT); btnSaveResize.setEnabled(true); } else handleFieldCreation(e.getX(), e.getY(), Field.CardSide.FRONT); } } @Override public void mousePressed(MouseEvent e) { if (JFieldMappingPanel.this.editor.isEditMode()) { editCorner = JFieldMappingPanel.this.editor.getCornerOnEditField(e.getPoint()); if(editCorner != Corner.NONE) { System.out.println("Corner selected: " + editCorner); } } } public void mouseExited(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} }); pnFront.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent arg0) { repaintImage(CardSide.FRONT); } @Override public void mouseDragged(MouseEvent arg0) { repaintImage(CardSide.FRONT); } }); pnRear = new JLabel(new ImageIcon(rearBuffer2)); pnRear.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { JFieldMappingPanel.this.editCorner = Corner.NONE; if (JFieldMappingPanel.this.editor.isEditMode()) { if (!JFieldMappingPanel.this.editor.editFieldContains(e.getPoint())) { JFieldMappingPanel.this.editor.discardEdits(); JFieldMappingPanel.this.setImage(front, rear); JFieldMappingPanel.this.repaintImage(CardSide.REAR); btnSaveResize.setEnabled(false); } } else if (!JFieldMappingPanel.this.editor.isEditMode()) { if (JFieldMappingPanel.this.editor.editFieldContaining(e.getPoint(), CardSide.REAR)) { JFieldMappingPanel.this.setImage(front, rear); JFieldMappingPanel.this.repaintImage(CardSide.REAR); btnSaveResize.setEnabled(true); } else handleFieldCreation(e.getX(), e.getY(), Field.CardSide.REAR); } } @Override public void mousePressed(MouseEvent e) { if (JFieldMappingPanel.this.editor.isEditMode()) { editCorner = JFieldMappingPanel.this.editor.getCornerOnEditField(e.getPoint()); if(editCorner != Corner.NONE) { System.out.println("Corner selected: " + editCorner); } } } public void mouseExited(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} }); pnRear.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent arg0) { repaintImage(CardSide.REAR); } @Override public void mouseDragged(MouseEvent arg0) { repaintImage(CardSide.REAR); } }); // imgPanel.setLayout(null); // panel.setSize(new Dimension(860, 1800)); spFront = new JScrollPane(pnFront); tabbedPane.addTab("Front", null, spFront, null); spFront.getVerticalScrollBar().setUnitIncrement(16); spFront.setMaximumSize(new Dimension(frontBuffer1.getWidth(), frontBuffer1.getHeight() < 600 ? frontBuffer1.getHeight() : 600)); spBack = new JScrollPane(pnRear); spBack.setSize(new Dimension(rearBuffer1.getWidth(), rearBuffer1.getHeight() < 600 ? rearBuffer1.getHeight() : 600)); spBack.setMaximumSize(new Dimension(rearBuffer1.getWidth(), rearBuffer1.getHeight() < 600 ? rearBuffer1.getHeight() : 600)); spBack.getVerticalScrollBar().setUnitIncrement(16); tabbedPane.addTab("Rear", null, spBack, null); JPanel pnFields = new JPanel(); tabbedPane.addTab("Fields", null, pnFields, null); pnFields.setLayout(new BorderLayout(0, 0)); tabbedPane.setSelectedIndex(frontPanel ? 0 : 1); fieldRoot = new DefaultMutableTreeNode("root"); JScrollPane spTree = new JScrollPane(); spTree.getVerticalScrollBar().setUnitIncrement(16); pnFields.add(spTree, BorderLayout.WEST); JSplitPane splitPane = new JSplitPane(); splitPane.setResizeWeight(0.3); pnFields.add(splitPane, BorderLayout.CENTER); treeFields = new JTree(fieldRoot); treeFields.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent tse) { Object obj = ((DefaultMutableTreeNode) tse.getPath().getLastPathComponent()).getUserObject(); if (obj instanceof Field) { fieldEditior.setField((Field) obj); } } }); treeFields.setRootVisible(false); treeFields.setShowsRootHandles(true); treeFields.expandRow(0); splitPane.setLeftComponent(treeFields); JPanel panel = new JPanel(); splitPane.setRightComponent(panel); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); Component verticalGlue_1 = Box.createVerticalGlue(); panel.add(verticalGlue_1); Box horizontalBox_1 = Box.createHorizontalBox(); panel.add(horizontalBox_1); fieldEditior = new JFieldEditorPanel(new Field("<none>", new Dimension(0, 0), new Dimension(10, 10), rectColor)); horizontalBox_1.add(fieldEditior); Component horizontalGlue_2 = Box.createHorizontalGlue(); horizontalBox_1.add(horizontalGlue_2); Component verticalGlue = Box.createVerticalGlue(); panel.add(verticalGlue); Box horizontalBox_2 = Box.createHorizontalBox(); panel.add(horizontalBox_2); JButton btnOkEditField = new JButton("Ok"); btnOkEditField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fieldEditior.getField(); treeFields.repaint(); setImage(front, rear); updatePreviewMode(); } }); Component horizontalGlue_6 = Box.createHorizontalGlue(); horizontalBox_2.add(horizontalGlue_6); Component horizontalGlue_3 = Box.createHorizontalGlue(); horizontalBox_2.add(horizontalGlue_3); horizontalBox_2.add(btnOkEditField); Component rigidArea = Box.createRigidArea(new Dimension(10, 20)); horizontalBox_2.add(rigidArea); JButton btnDiscardChanges = new JButton("Discard changes"); btnDiscardChanges.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fieldEditior.resetField(); } }); horizontalBox_2.add(btnDiscardChanges); Component horizontalGlue_4 = Box.createHorizontalGlue(); horizontalBox_2.add(horizontalGlue_4); Component horizontalGlue_5 = Box.createHorizontalGlue(); horizontalBox_2.add(horizontalGlue_5); JButton btnDeleteField = new JButton("Delete field"); btnDeleteField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean approve = JOptionPane.showConfirmDialog(JFieldMappingPanel.this, "Delete field " + fieldEditior.getFieldName() + "?", "Delete field", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION; if(approve) { fieldEditior.resetField(); JFieldMappingPanel.this.fields.remove(getFieldByName(fieldEditior.getFieldName())); setImage(frontImage, rearImage); populateFieldTree(); } } }); horizontalBox_2.add(btnDeleteField); this.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent evt) { if (JFieldMappingPanel.this.getWidth() > (frontBuffer1.getWidth() < rearBuffer1.getWidth() ? frontBuffer1.getWidth() : rearBuffer1.getWidth())) JFieldMappingPanel.this.setSize(new Dimension( (frontBuffer1.getWidth() < rearBuffer1.getWidth() ? frontBuffer1.getWidth() : rearBuffer1.getWidth()), JFieldMappingPanel.this.getHeight())); if (JFieldMappingPanel.this.getHeight() > (frontBuffer1.getHeight() < rearBuffer1.getHeight() ? frontBuffer1.getHeight() : rearBuffer1.getHeight())) JFieldMappingPanel.this.setSize(new Dimension(JFieldMappingPanel.this.getWidth(), (frontBuffer1.getHeight() < rearBuffer1.getHeight() ? frontBuffer1.getHeight() : rearBuffer1.getHeight()))); } }); setImage(frontImage, rearImage); populateFieldTree(); revalidate(); } protected void handleFieldCreation(int x, int y, Field.CardSide side) { Dimension pos1 = (side == Field.CardSide.FRONT ? this.frontPos1 : this.backPos1); if (pos1 == null) { pos1 = new Dimension(x, y); if (side == Field.CardSide.FRONT) frontPos1 = pos1; else backPos1 = pos1; System.out.println(side + " X|Y Point 1: " + x + "|" + y); } else { System.out.println(side + " X|Y Point 2: " + x + "|" + y); System.out.println(); String name = JOptionPane.showInputDialog(JFieldMappingPanel.this, "Enter a name"); // Aborted if (name == null) return; name = name.trim(); boolean link = false; while (checkNameForDuplicate(name) && !link || name.isEmpty()) { if (name.isEmpty()) name = JOptionPane.showInputDialog(JFieldMappingPanel.this, "Enter a valid name"); else { int approve = JOptionPane.showConfirmDialog(JFieldMappingPanel.this, "Name already taken, link this field to the existing?", "Choose an option", JOptionPane.YES_NO_OPTION); if (approve == JOptionPane.YES_OPTION) link = true; else name = JOptionPane.showInputDialog(JFieldMappingPanel.this, "Name already taken, enter a new name") .trim(); } if (name == null) return; name = name.trim(); } // FieldType type = (FieldType) JOptionPane.showInputDialog(CardMapper.this, "Choose the field type", // "Field type", JOptionPane.QUESTION_MESSAGE, null, // Use // // default // // icon // Field.FieldType.values(), // Array of choices // Field.FieldType.values()[0]); // Initial choice Field newField = new Field(name, pos1, new Dimension(x, y), rectColor, side); JFieldEditorPanel fe = new JFieldEditorPanel(newField); boolean ok = JOptionPane.showConfirmDialog(JFieldMappingPanel.this, fe, "Create Field", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION; if(ok) { fe.getField(); if (link) { Field field = JFieldMappingPanel.this.getFieldByName(name); if (field != null) field.setLinkedField(newField); else JFieldMappingPanel.this.fields.add(newField); } else JFieldMappingPanel.this.fields.add(newField); Graphics2D g = side == Field.CardSide.FRONT ? frontBuffer1.createGraphics() : rearBuffer1.createGraphics(); g.setColor(rectColor); newField.drawRect(g, CardCreator.getFont(newField.getFont())); g.dispose(); repaintImage(side); } // imgPanel.setIcon(new ImageIcon(PositionGeneratorMagicCards.this.cPicture)); if (side == Field.CardSide.FRONT) frontPos1 = null; else backPos1 = null; populateFieldTree(); revalidate(); } } private void setImage(BufferedImage frontImage, BufferedImage backImage) { // List<Field> frontFields = new ArrayList<>(getFrontFields()); // List<Field> backFields = new ArrayList<>(getRearFields()); // List<Field> frontAdditions = new ArrayList<>(); // List<Field> backAdditions = new ArrayList<>(); // // for (Field field : frontFields) { // Field linked = field; // while((linked = linked.getLinkedField()) != null) { // if (linked.getSide() == Field.CardSide.FRONT) // frontAdditions.add(linked); // else // backAdditions.add(linked); // } // } // for (Field field : backFields) { // Field linked = field; // while((linked = linked.getLinkedField()) != null) { // if (linked.getSide() == Field.CardSide.FRONT) // frontAdditions.add(linked); // else // backAdditions.add(linked); // } // } // frontFields.addAll(frontAdditions); // backFields.addAll(backAdditions); // Front if (frontImage != null) { this.front = frontImage; this.frontBuffer1 = new BufferedImage(frontImage.getWidth(), frontImage.getHeight(), frontImage.getType()); this.frontBuffer2 = new BufferedImage(frontImage.getWidth(), frontImage.getHeight(), frontImage.getType()); Graphics g = frontBuffer1.getGraphics(); Graphics g2 = frontBuffer2.getGraphics(); g.drawImage(frontImage, 0, 0, null); // for (Field f : frontFields) { // g.setColor(f.getColor()); // f.drawRect(g, ProjectManager.getFont(JCardMapperPanel.this.p, f.getFont())); // } g.dispose(); this.editor.drawFields(frontBuffer1, CardSide.FRONT, true, false); g2.drawImage(frontBuffer1, 0, 0, null); g2.dispose(); this.editor.drawFields(frontBuffer2, CardSide.FRONT, false, true); this.pnFront.setIcon(new ImageIcon(frontBuffer2)); pnFront.setPreferredSize(new Dimension(frontBuffer2.getWidth(), frontBuffer2.getHeight())); pnFront.setMaximumSize(new Dimension(frontBuffer2.getWidth(), frontBuffer2.getHeight())); pnFront.setSize(new Dimension(frontBuffer2.getWidth(), frontBuffer2.getHeight())); this.setMaximumSize(new Dimension(frontBuffer2.getWidth(), frontBuffer2.getHeight())); // this.setSize(new Dimension(b2Front.getWidth(), b2Front.getHeight())); spFront.setMaximumSize(new Dimension(frontBuffer1.getWidth(), frontBuffer2.getHeight() < 600 ? frontBuffer2.getHeight() : 600)); spFront.setSize(new Dimension(frontBuffer1.getWidth(), frontBuffer2.getHeight() < 600 ? frontBuffer2.getHeight() : 600)); pnFront.setSize(new Dimension(frontBuffer2.getWidth(), frontBuffer2.getHeight())); // Adjust size if (JFieldMappingPanel.this.getWidth() > frontBuffer1.getWidth()) JFieldMappingPanel.this.setSize(new Dimension(frontBuffer1.getWidth(), JFieldMappingPanel.this.getHeight())); if (JFieldMappingPanel.this.getHeight() > frontBuffer1.getHeight()) JFieldMappingPanel.this.setSize(new Dimension(JFieldMappingPanel.this.getWidth(), frontBuffer1.getHeight())); } // Back if (backImage != null) { this.rear = backImage; this.rearBuffer1 = new BufferedImage(backImage.getWidth(), backImage.getHeight(), backImage.getType()); this.rearBuffer2 = new BufferedImage(backImage.getWidth(), backImage.getHeight(), backImage.getType()); Graphics g = rearBuffer1.getGraphics(); Graphics g2 = rearBuffer2.getGraphics(); g.drawImage(backImage, 0, 0, null); // for (Field f : backFields) { // g.setColor(f.getColor()); // f.drawRect(g, ProjectManager.getFont(JCardMapperPanel.this.p, f.getFont())); // } g.dispose(); this.editor.drawFields(rearBuffer1, CardSide.REAR, true, false); g2.drawImage(rearBuffer1, 0, 0, null); g2.dispose(); this.pnRear.setIcon(new ImageIcon(rearBuffer2)); pnRear.setPreferredSize(new Dimension(rearBuffer2.getWidth(), rearBuffer2.getHeight())); pnRear.setMaximumSize(new Dimension(rearBuffer2.getWidth(), rearBuffer2.getHeight())); pnRear.setSize(new Dimension(rearBuffer2.getWidth(), rearBuffer2.getHeight())); this.setMaximumSize(new Dimension(rearBuffer2.getWidth(), rearBuffer2.getHeight())); // this.setSize(new Dimension(b2Rear.getWidth(), b2Rear.getHeight())); spBack.setMaximumSize(new Dimension(rearBuffer1.getWidth(), rearBuffer2.getHeight() < 600 ? rearBuffer2.getHeight() : 600)); spBack.setSize(new Dimension(rearBuffer1.getWidth(), rearBuffer2.getHeight() < 600 ? rearBuffer2.getHeight() : 600)); pnRear.setSize(new Dimension(rearBuffer2.getWidth(), rearBuffer2.getHeight())); if (JFieldMappingPanel.this.getWidth() > rearBuffer1.getWidth()) JFieldMappingPanel.this.setSize(new Dimension(rearBuffer1.getWidth(), JFieldMappingPanel.this.getHeight())); if (JFieldMappingPanel.this.getHeight() > rearBuffer1.getHeight()) JFieldMappingPanel.this.setSize(new Dimension(JFieldMappingPanel.this.getWidth(), rearBuffer1.getHeight())); } revalidate(); } private void repaintImage(CardSide side) { if (previewMode) return; boolean front = side == CardSide.FRONT; Point m = front ? pnFront.getMousePosition() : pnRear.getMousePosition(); Graphics g = front ? this.frontBuffer2.createGraphics() : this.rearBuffer2.createGraphics(); g.drawImage(front ? this.frontBuffer1 : this.rearBuffer1, 0, 0, null); if (m != null) { g.setColor(rectColor); g.drawLine(0, m.y, front ? pnFront.getWidth() : pnRear.getWidth(), m.y); g.drawLine(m.x, 0, m.x, front ? pnFront.getHeight() : pnRear.getHeight()); g.dispose(); if (editor.isEditMode()) { int width = editor.getWidth(); int height = editor.getHeight(); int x = editor.getX(); int y = editor.getY(); if (width != -1 && height != -1 && x != -1 && y != -1) { switch (editCorner) { case TOP_LEFT: width = width + (x - m.x); height = height + (y - m.y); x = m.x; y = m.y; editor.setPos(x, y); editor.setWidth(width); editor.setHeight(height); break; case TOP_RIGHT: width = m.x - x; height = (height + y) - m.y; y = m.y; editor.setPos(x, y); editor.setWidth(width); editor.setHeight(height); break; case BOTTOM_LEFT: System.out.println("Old Rect: Point (" + x + "|" + y + "), Dimension ("+width+"x"+height+")"); width = (width + x) - m.x; height = (m.y-y); x = m.x; System.out.println("New Rect: Point (" + x + "|" + y + "), Dimension ("+width+"x"+height+")"); System.out.println(); editor.setPos(x, y); editor.setWidth(width); editor.setHeight(height); break; case BOTTOM_RIGHT: width = m.x - x; height = m.y - y; editor.setWidth(width); editor.setHeight(height); break; default: break; } } } // System.out.println("Edit mode: " + this.editor.isEditMode()); // System.out.println("X|Y: " + m.x + "|" + m.y); } this.editor.drawFields(front ? this.frontBuffer2 : this.rearBuffer2, side, false, true); if (front) pnFront.repaint(); else pnRear.repaint(); } private void populateFieldTree() { treeFields.setRootVisible(true); this.fieldRoot.removeAllChildren(); DefaultMutableTreeNode frontNode = new DefaultMutableTreeNode("Front"); DefaultMutableTreeNode backNode = new DefaultMutableTreeNode("Back"); List<Field> frontFields = this.getFrontFields(); List<Field> backFields = this.getRearFields(); for (Field field : frontFields) { System.out.println(field); frontNode.add(createFieldNode(field)); } for (Field field : backFields) { backNode.add(createFieldNode(field)); } this.fieldRoot.add(frontNode); this.fieldRoot.add(backNode); ((DefaultTreeModel)this.treeFields.getModel()).setRoot(fieldRoot); treeFields.expandRow(100); this.treeFields.setRootVisible(false); } private MutableTreeNode createFieldNode(Field field) { DefaultMutableTreeNode fieldNode = new DefaultMutableTreeNode(field); if (field.hasLinkedField()) { fieldNode.add(createFieldNode(field.getLinkedField())); } return fieldNode; } public List<Field> getFrontFields() { return this.fields.stream().filter(f -> f.getSide() == CardSide.FRONT).collect(Collectors.toList()); } public List<Field> getRearFields() { return this.fields.stream().filter(f -> f.getSide() == CardSide.REAR).collect(Collectors.toList()); } public boolean checkNameForDuplicate(final String name) { return fields.stream().anyMatch(f -> f.getName().equalsIgnoreCase(name)); } public Field getFieldByName(final String name) { return fields.stream().filter(f -> f.getName().equalsIgnoreCase(name)).findFirst().orElse(null); } public List<Field> getFields() { return fields; } private void updatePreviewMode() { if (previewMode) { BufferedImage[] images = CardCreator.createCard(0, null, this.fields); if (images != null) { this.frontPreview = images[0]; this.rearPreview = images[1]; } else { this.frontPreview = null; this.rearPreview = null; this.previewMode = false; this.chckbxPreview.setSelected(false); } if (this.frontPreview != null) { pnFront.setIcon(new ImageIcon(this.frontPreview)); pnRear.setIcon(new ImageIcon(this.rearPreview)); } } else { pnFront.setIcon(new ImageIcon(this.frontBuffer2)); pnRear.setIcon(new ImageIcon(this.rearBuffer2)); } } }
37.959184
153
0.697009
d885c891e5f66f4dc0eeb47e31544444d85e7c76
133
package com.book.vero.c3_6_boundservice2; /** * Created by vero on 2016/3/11. */ interface IService{ MyService getService(); }
16.625
41
0.706767
a8092e5a4b904b94bb022c83791ebca56d6b14b8
3,618
package main; import javax.swing.*; import java.awt.*; /** * Contains post-game info about one car and how has it placed in the race. */ public class ScorePanel extends JPanel { /** * Displays how has the player placed in the race. */ private JLabel place; /** * Displays the name of the player. */ private JLabel playerName; /** * Displays the name of the AI if there was one controlling the car. */ private JLabel aiName; /** * Displays the number of turns it took to the player to finish the race. */ private JLabel turnCount; /** * ScorePanel constructor. Initializes the Swing components of the ScorePanel. * @param place the place on which the car whose information this ScorePanel shows has finished. * @param playerName the player name of the player driving the car whose information this ScorePanel shows. * @param aiName the name of the AI which has been driving the car. * @param turnCount the turn on which has the car finished. */ ScorePanel(int place, String playerName, String aiName, int turnCount) { setMinimumSize(new Dimension(480, 50)); setPreferredSize(new Dimension(480, 50)); setMaximumSize(new Dimension(480, 50)); setBackground(Color.darkGray); setBorder(BorderFactory.createLineBorder(Color.gray)); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); if (place == -1) { this.place = new JLabel("DQ"); this.place.setForeground(Color.red); } else { this.place = new JLabel(place + "."); this.place.setForeground(Color.orange); } this.place.setHorizontalAlignment(SwingConstants.CENTER); this.place.setMinimumSize(new Dimension(80, 50)); this.place.setMaximumSize(new Dimension(80, 50)); add(this.place); this.playerName = new JLabel(playerName); this.playerName.setForeground(Color.white); this.playerName.setHorizontalAlignment(SwingConstants.CENTER); this.playerName.setMinimumSize(new Dimension(160, 50)); this.playerName.setMaximumSize(new Dimension(160, 50)); add(this.playerName); if (aiName == "HUMAN") { this.aiName = new JLabel("HUMAN"); } else { this.aiName = new JLabel(aiName); } this.aiName.setForeground(Color.white); this.aiName.setHorizontalAlignment(SwingConstants.CENTER); this.aiName.setMinimumSize(new Dimension(160, 50)); this.aiName.setMaximumSize(new Dimension(160, 50)); add(this.aiName); if (place == -1) { this.turnCount = new JLabel("DQ"); } else { this.turnCount = new JLabel(Integer.toString(turnCount)); } this.turnCount.setForeground(Color.white); this.turnCount.setHorizontalAlignment(SwingConstants.CENTER); this.turnCount.setMinimumSize(new Dimension(80, 50)); this.turnCount.setMaximumSize(new Dimension(80, 50)); add(this.turnCount); } /** * Transforms the CarPanel into a special CarPanels used as the heading for the carMainPanel. */ public void makeIntoHeading() { setBackground(Color.black); place.setText("PLACE"); playerName.setText("PLAYER NAME"); aiName.setText("AI NAME"); turnCount.setText("TURNS"); place.setForeground(Color.orange); playerName.setForeground(Color.orange); aiName.setForeground(Color.orange); turnCount.setForeground(Color.orange); } }
35.821782
111
0.641791
b3dd5e6182cdbd6df5af121cba721babae0faf1e
552
package shell; import ibm.wjx.osserver.shell.ShellCommandResult; import ibm.wjx.osserver.shell.oc.AdminLoginCommand; import org.junit.Assert; import org.junit.Test; /** * Create Date: 12/20/17 * Author: <a href="mailto:wu812730157@gmail.com">Wujunxian</a> * Description: */ public class AdminLoginCommandTest { @Test public void testLogin() { ShellCommandResult<Boolean> result = new AdminLoginCommand().execute(); Assert.assertTrue(result.getData().isPresent()); Assert.assertTrue(result.getData().get()); } }
27.6
79
0.711957
7205754cb957a83f4b3787c710eac5621d12d06b
41,069
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 com.google.cloud.recommendationengine.v1beta1; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.longrunning.OperationFuture; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.recommendationengine.v1beta1.stub.CatalogServiceStub; import com.google.cloud.recommendationengine.v1beta1.stub.CatalogServiceStubSettings; import com.google.common.util.concurrent.MoreExecutors; import com.google.longrunning.Operation; import com.google.longrunning.OperationsClient; import com.google.protobuf.Empty; import com.google.protobuf.FieldMask; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Service for ingesting catalog information of the customer's website. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * CatalogName parent = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]"); * CatalogItem catalogItem = CatalogItem.newBuilder().build(); * CatalogItem response = catalogServiceClient.createCatalogItem(parent, catalogItem); * } * }</pre> * * <p>Note: close() needs to be called on the CatalogServiceClient object to clean up resources such * as threads. In the example above, try-with-resources is used, which automatically calls close(). * * <p>The surface of this class includes several types of Java methods for each of the API's * methods: * * <ol> * <li>A "flattened" method. With this type of method, the fields of the request type have been * converted into function parameters. It may be the case that not all fields are available as * parameters, and not every API method will have a flattened method entry point. * <li>A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. * <li>A "callable" method. This type of method takes no parameters and returns an immutable API * callable object, which can be used to initiate calls to the service. * </ol> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of CatalogServiceSettings to * create(). For example: * * <p>To customize credentials: * * <pre>{@code * CatalogServiceSettings catalogServiceSettings = * CatalogServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * CatalogServiceClient catalogServiceClient = CatalogServiceClient.create(catalogServiceSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * CatalogServiceSettings catalogServiceSettings = * CatalogServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * CatalogServiceClient catalogServiceClient = CatalogServiceClient.create(catalogServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @BetaApi @Generated("by gapic-generator-java") public class CatalogServiceClient implements BackgroundResource { private final CatalogServiceSettings settings; private final CatalogServiceStub stub; private final OperationsClient operationsClient; /** Constructs an instance of CatalogServiceClient with default settings. */ public static final CatalogServiceClient create() throws IOException { return create(CatalogServiceSettings.newBuilder().build()); } /** * Constructs an instance of CatalogServiceClient, using the given settings. The channels are * created based on the settings passed in, or defaults for any settings that are not set. */ public static final CatalogServiceClient create(CatalogServiceSettings settings) throws IOException { return new CatalogServiceClient(settings); } /** * Constructs an instance of CatalogServiceClient, using the given stub for making calls. This is * for advanced usage - prefer using create(CatalogServiceSettings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final CatalogServiceClient create(CatalogServiceStub stub) { return new CatalogServiceClient(stub); } /** * Constructs an instance of CatalogServiceClient, using the given settings. This is protected so * that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected CatalogServiceClient(CatalogServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((CatalogServiceStubSettings) settings.getStubSettings()).createStub(); this.operationsClient = OperationsClient.create(this.stub.getOperationsStub()); } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") protected CatalogServiceClient(CatalogServiceStub stub) { this.settings = null; this.stub = stub; this.operationsClient = OperationsClient.create(this.stub.getOperationsStub()); } public final CatalogServiceSettings getSettings() { return settings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public CatalogServiceStub getStub() { return stub; } /** * Returns the OperationsClient that can be used to query the status of a long-running operation * returned by another API method call. */ public final OperationsClient getOperationsClient() { return operationsClient; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates a catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * CatalogName parent = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]"); * CatalogItem catalogItem = CatalogItem.newBuilder().build(); * CatalogItem response = catalogServiceClient.createCatalogItem(parent, catalogItem); * } * }</pre> * * @param parent Required. The parent catalog resource name, such as * `projects/&#42;/locations/global/catalogs/default_catalog`. * @param catalogItem Required. The catalog item to create. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final CatalogItem createCatalogItem(CatalogName parent, CatalogItem catalogItem) { CreateCatalogItemRequest request = CreateCatalogItemRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setCatalogItem(catalogItem) .build(); return createCatalogItem(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates a catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * String parent = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString(); * CatalogItem catalogItem = CatalogItem.newBuilder().build(); * CatalogItem response = catalogServiceClient.createCatalogItem(parent, catalogItem); * } * }</pre> * * @param parent Required. The parent catalog resource name, such as * `projects/&#42;/locations/global/catalogs/default_catalog`. * @param catalogItem Required. The catalog item to create. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final CatalogItem createCatalogItem(String parent, CatalogItem catalogItem) { CreateCatalogItemRequest request = CreateCatalogItemRequest.newBuilder().setParent(parent).setCatalogItem(catalogItem).build(); return createCatalogItem(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates a catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * CreateCatalogItemRequest request = * CreateCatalogItemRequest.newBuilder() * .setParent(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString()) * .setCatalogItem(CatalogItem.newBuilder().build()) * .build(); * CatalogItem response = catalogServiceClient.createCatalogItem(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final CatalogItem createCatalogItem(CreateCatalogItemRequest request) { return createCatalogItemCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates a catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * CreateCatalogItemRequest request = * CreateCatalogItemRequest.newBuilder() * .setParent(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString()) * .setCatalogItem(CatalogItem.newBuilder().build()) * .build(); * ApiFuture<CatalogItem> future = * catalogServiceClient.createCatalogItemCallable().futureCall(request); * // Do something. * CatalogItem response = future.get(); * } * }</pre> */ public final UnaryCallable<CreateCatalogItemRequest, CatalogItem> createCatalogItemCallable() { return stub.createCatalogItemCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a specific catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * CatalogItemPathName name = * CatalogItemPathName.of("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]"); * CatalogItem response = catalogServiceClient.getCatalogItem(name); * } * }</pre> * * @param name Required. Full resource name of catalog item, such as * `projects/&#42;/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_id`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final CatalogItem getCatalogItem(CatalogItemPathName name) { GetCatalogItemRequest request = GetCatalogItemRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return getCatalogItem(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a specific catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * String name = * CatalogItemPathName.of("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]") * .toString(); * CatalogItem response = catalogServiceClient.getCatalogItem(name); * } * }</pre> * * @param name Required. Full resource name of catalog item, such as * `projects/&#42;/locations/global/catalogs/default_catalog/catalogitems/some_catalog_item_id`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final CatalogItem getCatalogItem(String name) { GetCatalogItemRequest request = GetCatalogItemRequest.newBuilder().setName(name).build(); return getCatalogItem(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a specific catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * GetCatalogItemRequest request = * GetCatalogItemRequest.newBuilder() * .setName( * CatalogItemPathName.of( * "[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]") * .toString()) * .build(); * CatalogItem response = catalogServiceClient.getCatalogItem(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final CatalogItem getCatalogItem(GetCatalogItemRequest request) { return getCatalogItemCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a specific catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * GetCatalogItemRequest request = * GetCatalogItemRequest.newBuilder() * .setName( * CatalogItemPathName.of( * "[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]") * .toString()) * .build(); * ApiFuture<CatalogItem> future = * catalogServiceClient.getCatalogItemCallable().futureCall(request); * // Do something. * CatalogItem response = future.get(); * } * }</pre> */ public final UnaryCallable<GetCatalogItemRequest, CatalogItem> getCatalogItemCallable() { return stub.getCatalogItemCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a list of catalog items. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * CatalogName parent = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]"); * String filter = "filter-1274492040"; * for (CatalogItem element : * catalogServiceClient.listCatalogItems(parent, filter).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The parent catalog resource name, such as * `projects/&#42;/locations/global/catalogs/default_catalog`. * @param filter Optional. A filter to apply on the list results. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListCatalogItemsPagedResponse listCatalogItems(CatalogName parent, String filter) { ListCatalogItemsRequest request = ListCatalogItemsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setFilter(filter) .build(); return listCatalogItems(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a list of catalog items. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * String parent = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString(); * String filter = "filter-1274492040"; * for (CatalogItem element : * catalogServiceClient.listCatalogItems(parent, filter).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The parent catalog resource name, such as * `projects/&#42;/locations/global/catalogs/default_catalog`. * @param filter Optional. A filter to apply on the list results. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListCatalogItemsPagedResponse listCatalogItems(String parent, String filter) { ListCatalogItemsRequest request = ListCatalogItemsRequest.newBuilder().setParent(parent).setFilter(filter).build(); return listCatalogItems(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a list of catalog items. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * ListCatalogItemsRequest request = * ListCatalogItemsRequest.newBuilder() * .setParent(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .setFilter("filter-1274492040") * .build(); * for (CatalogItem element : catalogServiceClient.listCatalogItems(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListCatalogItemsPagedResponse listCatalogItems(ListCatalogItemsRequest request) { return listCatalogItemsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a list of catalog items. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * ListCatalogItemsRequest request = * ListCatalogItemsRequest.newBuilder() * .setParent(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .setFilter("filter-1274492040") * .build(); * ApiFuture<CatalogItem> future = * catalogServiceClient.listCatalogItemsPagedCallable().futureCall(request); * // Do something. * for (CatalogItem element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListCatalogItemsRequest, ListCatalogItemsPagedResponse> listCatalogItemsPagedCallable() { return stub.listCatalogItemsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets a list of catalog items. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * ListCatalogItemsRequest request = * ListCatalogItemsRequest.newBuilder() * .setParent(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .setFilter("filter-1274492040") * .build(); * while (true) { * ListCatalogItemsResponse response = * catalogServiceClient.listCatalogItemsCallable().call(request); * for (CatalogItem element : response.getResponsesList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListCatalogItemsRequest, ListCatalogItemsResponse> listCatalogItemsCallable() { return stub.listCatalogItemsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a catalog item. Partial updating is supported. Non-existing items will be created. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * CatalogItemPathName name = * CatalogItemPathName.of("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]"); * CatalogItem catalogItem = CatalogItem.newBuilder().build(); * FieldMask updateMask = FieldMask.newBuilder().build(); * CatalogItem response = catalogServiceClient.updateCatalogItem(name, catalogItem, updateMask); * } * }</pre> * * @param name Required. Full resource name of catalog item, such as * "projects/&#42;/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". * @param catalogItem Required. The catalog item to update/create. The 'catalog_item_id' field has * to match that in the 'name'. * @param updateMask Optional. Indicates which fields in the provided 'item' to update. If not * set, will by default update all fields. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final CatalogItem updateCatalogItem( CatalogItemPathName name, CatalogItem catalogItem, FieldMask updateMask) { UpdateCatalogItemRequest request = UpdateCatalogItemRequest.newBuilder() .setName(name == null ? null : name.toString()) .setCatalogItem(catalogItem) .setUpdateMask(updateMask) .build(); return updateCatalogItem(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a catalog item. Partial updating is supported. Non-existing items will be created. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * String name = * CatalogItemPathName.of("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]") * .toString(); * CatalogItem catalogItem = CatalogItem.newBuilder().build(); * FieldMask updateMask = FieldMask.newBuilder().build(); * CatalogItem response = catalogServiceClient.updateCatalogItem(name, catalogItem, updateMask); * } * }</pre> * * @param name Required. Full resource name of catalog item, such as * "projects/&#42;/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id". * @param catalogItem Required. The catalog item to update/create. The 'catalog_item_id' field has * to match that in the 'name'. * @param updateMask Optional. Indicates which fields in the provided 'item' to update. If not * set, will by default update all fields. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final CatalogItem updateCatalogItem( String name, CatalogItem catalogItem, FieldMask updateMask) { UpdateCatalogItemRequest request = UpdateCatalogItemRequest.newBuilder() .setName(name) .setCatalogItem(catalogItem) .setUpdateMask(updateMask) .build(); return updateCatalogItem(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a catalog item. Partial updating is supported. Non-existing items will be created. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * UpdateCatalogItemRequest request = * UpdateCatalogItemRequest.newBuilder() * .setName( * CatalogItemPathName.of( * "[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]") * .toString()) * .setCatalogItem(CatalogItem.newBuilder().build()) * .setUpdateMask(FieldMask.newBuilder().build()) * .build(); * CatalogItem response = catalogServiceClient.updateCatalogItem(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final CatalogItem updateCatalogItem(UpdateCatalogItemRequest request) { return updateCatalogItemCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Updates a catalog item. Partial updating is supported. Non-existing items will be created. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * UpdateCatalogItemRequest request = * UpdateCatalogItemRequest.newBuilder() * .setName( * CatalogItemPathName.of( * "[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]") * .toString()) * .setCatalogItem(CatalogItem.newBuilder().build()) * .setUpdateMask(FieldMask.newBuilder().build()) * .build(); * ApiFuture<CatalogItem> future = * catalogServiceClient.updateCatalogItemCallable().futureCall(request); * // Do something. * CatalogItem response = future.get(); * } * }</pre> */ public final UnaryCallable<UpdateCatalogItemRequest, CatalogItem> updateCatalogItemCallable() { return stub.updateCatalogItemCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes a catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * CatalogItemPathName name = * CatalogItemPathName.of("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]"); * catalogServiceClient.deleteCatalogItem(name); * } * }</pre> * * @param name Required. Full resource name of catalog item, such as * `projects/&#42;/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void deleteCatalogItem(CatalogItemPathName name) { DeleteCatalogItemRequest request = DeleteCatalogItemRequest.newBuilder() .setName(name == null ? null : name.toString()) .build(); deleteCatalogItem(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes a catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * String name = * CatalogItemPathName.of("[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]") * .toString(); * catalogServiceClient.deleteCatalogItem(name); * } * }</pre> * * @param name Required. Full resource name of catalog item, such as * `projects/&#42;/locations/global/catalogs/default_catalog/catalogItems/some_catalog_item_id`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void deleteCatalogItem(String name) { DeleteCatalogItemRequest request = DeleteCatalogItemRequest.newBuilder().setName(name).build(); deleteCatalogItem(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes a catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * DeleteCatalogItemRequest request = * DeleteCatalogItemRequest.newBuilder() * .setName( * CatalogItemPathName.of( * "[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]") * .toString()) * .build(); * catalogServiceClient.deleteCatalogItem(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void deleteCatalogItem(DeleteCatalogItemRequest request) { deleteCatalogItemCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes a catalog item. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * DeleteCatalogItemRequest request = * DeleteCatalogItemRequest.newBuilder() * .setName( * CatalogItemPathName.of( * "[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]") * .toString()) * .build(); * ApiFuture<Empty> future = * catalogServiceClient.deleteCatalogItemCallable().futureCall(request); * // Do something. * future.get(); * } * }</pre> */ public final UnaryCallable<DeleteCatalogItemRequest, Empty> deleteCatalogItemCallable() { return stub.deleteCatalogItemCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Bulk import of multiple catalog items. Request processing may be synchronous. No partial * updating supported. Non-existing items will be created. * * <p>Operation.response is of type ImportResponse. Note that it is possible for a subset of the * items to be successfully updated. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * CatalogName parent = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]"); * String requestId = "requestId693933066"; * InputConfig inputConfig = InputConfig.newBuilder().build(); * ImportErrorsConfig errorsConfig = ImportErrorsConfig.newBuilder().build(); * ImportCatalogItemsResponse response = * catalogServiceClient * .importCatalogItemsAsync(parent, requestId, inputConfig, errorsConfig) * .get(); * } * }</pre> * * @param parent Required. `projects/1234/locations/global/catalogs/default_catalog` * @param requestId Optional. Unique identifier provided by client, within the ancestor dataset * scope. Ensures idempotency and used for request deduplication. Server-generated if * unspecified. Up to 128 characters long. This is returned as * google.longrunning.Operation.name in the response. * @param inputConfig Required. The desired input location of the data. * @param errorsConfig Optional. The desired location of errors incurred during the Import. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<ImportCatalogItemsResponse, ImportMetadata> importCatalogItemsAsync( CatalogName parent, String requestId, InputConfig inputConfig, ImportErrorsConfig errorsConfig) { ImportCatalogItemsRequest request = ImportCatalogItemsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setRequestId(requestId) .setInputConfig(inputConfig) .setErrorsConfig(errorsConfig) .build(); return importCatalogItemsAsync(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Bulk import of multiple catalog items. Request processing may be synchronous. No partial * updating supported. Non-existing items will be created. * * <p>Operation.response is of type ImportResponse. Note that it is possible for a subset of the * items to be successfully updated. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * String parent = CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString(); * String requestId = "requestId693933066"; * InputConfig inputConfig = InputConfig.newBuilder().build(); * ImportErrorsConfig errorsConfig = ImportErrorsConfig.newBuilder().build(); * ImportCatalogItemsResponse response = * catalogServiceClient * .importCatalogItemsAsync(parent, requestId, inputConfig, errorsConfig) * .get(); * } * }</pre> * * @param parent Required. `projects/1234/locations/global/catalogs/default_catalog` * @param requestId Optional. Unique identifier provided by client, within the ancestor dataset * scope. Ensures idempotency and used for request deduplication. Server-generated if * unspecified. Up to 128 characters long. This is returned as * google.longrunning.Operation.name in the response. * @param inputConfig Required. The desired input location of the data. * @param errorsConfig Optional. The desired location of errors incurred during the Import. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<ImportCatalogItemsResponse, ImportMetadata> importCatalogItemsAsync( String parent, String requestId, InputConfig inputConfig, ImportErrorsConfig errorsConfig) { ImportCatalogItemsRequest request = ImportCatalogItemsRequest.newBuilder() .setParent(parent) .setRequestId(requestId) .setInputConfig(inputConfig) .setErrorsConfig(errorsConfig) .build(); return importCatalogItemsAsync(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Bulk import of multiple catalog items. Request processing may be synchronous. No partial * updating supported. Non-existing items will be created. * * <p>Operation.response is of type ImportResponse. Note that it is possible for a subset of the * items to be successfully updated. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * ImportCatalogItemsRequest request = * ImportCatalogItemsRequest.newBuilder() * .setParent(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString()) * .setRequestId("requestId693933066") * .setInputConfig(InputConfig.newBuilder().build()) * .setErrorsConfig(ImportErrorsConfig.newBuilder().build()) * .build(); * ImportCatalogItemsResponse response = * catalogServiceClient.importCatalogItemsAsync(request).get(); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<ImportCatalogItemsResponse, ImportMetadata> importCatalogItemsAsync( ImportCatalogItemsRequest request) { return importCatalogItemsOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Bulk import of multiple catalog items. Request processing may be synchronous. No partial * updating supported. Non-existing items will be created. * * <p>Operation.response is of type ImportResponse. Note that it is possible for a subset of the * items to be successfully updated. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * ImportCatalogItemsRequest request = * ImportCatalogItemsRequest.newBuilder() * .setParent(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString()) * .setRequestId("requestId693933066") * .setInputConfig(InputConfig.newBuilder().build()) * .setErrorsConfig(ImportErrorsConfig.newBuilder().build()) * .build(); * OperationFuture<ImportCatalogItemsResponse, ImportMetadata> future = * catalogServiceClient.importCatalogItemsOperationCallable().futureCall(request); * // Do something. * ImportCatalogItemsResponse response = future.get(); * } * }</pre> */ public final OperationCallable< ImportCatalogItemsRequest, ImportCatalogItemsResponse, ImportMetadata> importCatalogItemsOperationCallable() { return stub.importCatalogItemsOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Bulk import of multiple catalog items. Request processing may be synchronous. No partial * updating supported. Non-existing items will be created. * * <p>Operation.response is of type ImportResponse. Note that it is possible for a subset of the * items to be successfully updated. * * <p>Sample code: * * <pre>{@code * try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) { * ImportCatalogItemsRequest request = * ImportCatalogItemsRequest.newBuilder() * .setParent(CatalogName.of("[PROJECT]", "[LOCATION]", "[CATALOG]").toString()) * .setRequestId("requestId693933066") * .setInputConfig(InputConfig.newBuilder().build()) * .setErrorsConfig(ImportErrorsConfig.newBuilder().build()) * .build(); * ApiFuture<Operation> future = * catalogServiceClient.importCatalogItemsCallable().futureCall(request); * // Do something. * Operation response = future.get(); * } * }</pre> */ public final UnaryCallable<ImportCatalogItemsRequest, Operation> importCatalogItemsCallable() { return stub.importCatalogItemsCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class ListCatalogItemsPagedResponse extends AbstractPagedListResponse< ListCatalogItemsRequest, ListCatalogItemsResponse, CatalogItem, ListCatalogItemsPage, ListCatalogItemsFixedSizeCollection> { public static ApiFuture<ListCatalogItemsPagedResponse> createAsync( PageContext<ListCatalogItemsRequest, ListCatalogItemsResponse, CatalogItem> context, ApiFuture<ListCatalogItemsResponse> futureResponse) { ApiFuture<ListCatalogItemsPage> futurePage = ListCatalogItemsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListCatalogItemsPagedResponse(input), MoreExecutors.directExecutor()); } private ListCatalogItemsPagedResponse(ListCatalogItemsPage page) { super(page, ListCatalogItemsFixedSizeCollection.createEmptyCollection()); } } public static class ListCatalogItemsPage extends AbstractPage< ListCatalogItemsRequest, ListCatalogItemsResponse, CatalogItem, ListCatalogItemsPage> { private ListCatalogItemsPage( PageContext<ListCatalogItemsRequest, ListCatalogItemsResponse, CatalogItem> context, ListCatalogItemsResponse response) { super(context, response); } private static ListCatalogItemsPage createEmptyPage() { return new ListCatalogItemsPage(null, null); } @Override protected ListCatalogItemsPage createPage( PageContext<ListCatalogItemsRequest, ListCatalogItemsResponse, CatalogItem> context, ListCatalogItemsResponse response) { return new ListCatalogItemsPage(context, response); } @Override public ApiFuture<ListCatalogItemsPage> createPageAsync( PageContext<ListCatalogItemsRequest, ListCatalogItemsResponse, CatalogItem> context, ApiFuture<ListCatalogItemsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListCatalogItemsFixedSizeCollection extends AbstractFixedSizeCollection< ListCatalogItemsRequest, ListCatalogItemsResponse, CatalogItem, ListCatalogItemsPage, ListCatalogItemsFixedSizeCollection> { private ListCatalogItemsFixedSizeCollection( List<ListCatalogItemsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListCatalogItemsFixedSizeCollection createEmptyCollection() { return new ListCatalogItemsFixedSizeCollection(null, 0); } @Override protected ListCatalogItemsFixedSizeCollection createCollection( List<ListCatalogItemsPage> pages, int collectionSize) { return new ListCatalogItemsFixedSizeCollection(pages, collectionSize); } } }
39.413628
102
0.68794
6d689288aa4c063f1839f73f97fdc5eb9470692d
1,580
/* * 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 cafe.tool; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; /** * * @author rudolf */ public class MsgBox { public static void info(String infoMessage) { JOptionPane.showMessageDialog(null, infoMessage, "Info", JOptionPane.INFORMATION_MESSAGE); } public static void info(String infoMessage, String title) { JOptionPane.showMessageDialog(null, infoMessage, title, JOptionPane.INFORMATION_MESSAGE); } // ref : http://stackoverflow.com/questions/16511039/is-there-a-way-to-only-have-the-ok-button-in-a-joptionpane-showinputdialog-and public static String input(String inputMessage, String title) { String[] options = {"OK"}; JPanel pane = new JPanel(); JLabel lb = new JLabel(inputMessage); JTextField tf = new JTextField(10); pane.add(lb); pane.add(tf); int selected = JOptionPane.showOptionDialog(null, pane, title, JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); return tf.getText(); } // ref : http://stackoverflow.com/a/15853127 public static boolean ask(String askMessage) { if (JOptionPane.showConfirmDialog(null, askMessage, "CONFIRM", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) return true; return false; } }
32.244898
144
0.696835
1c386202632fb3504faa4546eeaa88ba6168f0dc
3,488
package gov.usds.case_issues.controllers; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import gov.usds.case_issues.db.model.projections.CaseSnoozeSummary; import gov.usds.case_issues.model.CaseDetails; import gov.usds.case_issues.model.CaseSnoozeSummaryFacade; import gov.usds.case_issues.model.AttachmentRequest; import gov.usds.case_issues.model.SnoozeRequest; import gov.usds.case_issues.services.CaseDetailsService; @RestController @RequestMapping("/api/caseDetails/{caseManagementSystemTag}/{receiptNumber}") @PreAuthorize("hasAuthority(T(gov.usds.case_issues.authorization.CaseIssuePermission).READ_CASES.name())") public class CaseDetailsApiController { @Autowired private CaseDetailsService _caseDetailsService; @GetMapping public CaseDetails getCaseDetails(@PathVariable String caseManagementSystemTag, @PathVariable String receiptNumber) { return _caseDetailsService.findCaseDetails(caseManagementSystemTag, receiptNumber); } @GetMapping("activeSnooze") public ResponseEntity<CaseSnoozeSummary> getActiveSnooze(@PathVariable String caseManagementSystemTag, @PathVariable String receiptNumber) { Optional<CaseSnoozeSummary> snooze = _caseDetailsService.findActiveSnooze(caseManagementSystemTag, receiptNumber); if (snooze.isPresent()) { return ResponseEntity.of(snooze); } else { return ResponseEntity.noContent().build(); } } @DeleteMapping("activeSnooze") @PreAuthorize("hasAuthority(T(gov.usds.case_issues.authorization.CaseIssuePermission).UPDATE_CASES.name())") public ResponseEntity<Void> endActiveSnooze(@PathVariable String caseManagementSystemTag, @PathVariable String receiptNumber) { // e-tag could be added here with the end-time of the snooze if (_caseDetailsService.endActiveSnooze(caseManagementSystemTag, receiptNumber)) { return new ResponseEntity<>(HttpStatus.OK); } else { return ResponseEntity.noContent().build(); } } @PutMapping("activeSnooze") @PreAuthorize("hasAuthority(T(gov.usds.case_issues.authorization.CaseIssuePermission).UPDATE_CASES.name())") public ResponseEntity<CaseSnoozeSummaryFacade> changeActiveSnooze( @PathVariable String caseManagementSystemTag, @PathVariable String receiptNumber, @RequestBody @Valid SnoozeRequest requestedSnooze) { CaseSnoozeSummaryFacade replacement = _caseDetailsService.updateSnooze(caseManagementSystemTag, receiptNumber, requestedSnooze); return ResponseEntity.ok(replacement); } @PostMapping("activeSnooze/notes") public ResponseEntity<?> addNote(@PathVariable String caseManagementSystemTag, @PathVariable String receiptNumber, @RequestBody AttachmentRequest newNote) { _caseDetailsService.annotateActiveSnooze(caseManagementSystemTag, receiptNumber, newNote); return ResponseEntity.accepted().build(); } }
44.717949
141
0.830275
1f8330a56a96dec230fc25d693d6c629399b70e7
2,780
/** * Copyright 2012 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.geoar.utils; import java.io.Serializable; import android.os.Parcel; import android.os.Parcelable; /** * Holding Geolocation information. * @author Arne de Wall * */ public class GeoLocation implements Serializable, Parcelable { /*********************** * Statics **********************/ private static final long serialVersionUID = 1L; /*********************** * Variables **********************/ public int mLatitudeE6; public int mLongitudeE6; public int mAltitude; /*********************** * Constructors **********************/ public GeoLocation(final int latitudeE6, final int longitudeE6, final int altitude) { this.mLatitudeE6 = latitudeE6; this.mLongitudeE6 = longitudeE6; this.mAltitude = altitude; } public GeoLocation(final int latitudeE6, final int longitudeE6){ this(latitudeE6, longitudeE6, 0); } public GeoLocation(final double latitude, final double longitude){ this((int)(latitude * 1E6), (int)(longitude * 1E6), 0); } public GeoLocation(final double latitude, final double longitude, final int altitude){ this((int)(latitude * 1E6), (int)(longitude * 1E6), altitude); } public int getAltitude() { return mAltitude; } public int getLatitudeE6() { return mLatitudeE6; } public int getLongitudeE6() { return mLongitudeE6; } /** * * @param in */ public GeoLocation(Parcel in){ this.mLatitudeE6 = in.readInt(); this.mLongitudeE6 = in.readInt(); this.mAltitude = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeInt(mLatitudeE6); out.writeInt(mLongitudeE6); out.writeInt(mAltitude); } public static final Parcelable.Creator<GeoLocation> CREATOR = new Parcelable.Creator<GeoLocation>() { @Override public GeoLocation createFromParcel(final Parcel in) { return new GeoLocation(in); } @Override public GeoLocation[] newArray(final int size) { return new GeoLocation[size]; } }; }
25.740741
103
0.656475
a19dd4bbb22eeee4ac8be850c4e0facae24d7514
63
package com.gm.chatie.common; public interface Constents { }
10.5
29
0.761905
bef97424b1c961b2ed97d42dd0cc389531ae305c
1,005
package fr.takebook.library.infrastructure.in.transport.wrapper; import fr.takebook.library.domain.model.Library; import fr.takebook.library.infrastructure.in.transport.object.LibraryDTO; import fr.takebook.library.infrastructure.out.persistence.entity.LibraryEntity; import org.springframework.stereotype.Component; import java.util.UUID; @Component public class LibraryDTOWrapper { public LibraryDTO fromModel(Library model) { LibraryDTO dto = new LibraryDTO(); dto.setId(model.getId().toString()); dto.setName(model.getName()); return dto; } public LibraryDTO fromEntity(LibraryEntity entity) { LibraryDTO dto = new LibraryDTO(); dto.setId(entity.getId().toString()); dto.setName(entity.getName()); return dto; } public Library toModel(LibraryDTO dto) { Library model = new Library(); model.setId(UUID.fromString(dto.getId())); model.setName(dto.getName()); return model; } }
29.558824
79
0.695522
868fed48c73e7314d358bb1e207fd7845dfd0e47
919
package com.zhixiao.wanandroid.app; import java.io.File; /** * @ClassName: Constants * @Description: * @Author: zhixiao * @CreateDate: 2019/9/4 */ public class Constants { /** * 数据库名 */ public static final String DATABASE_NAME = "zhixiao_wanandroid.db"; /** * 数据缓存文件夹路径 */ public static final String PATH_DATA = APP.getInstance().getCacheDir().getAbsolutePath() + "/data"; /** * http缓存的路径 */ public static final String PATH_HTTP_CACHE = PATH_DATA + "/HttpCache"; /** * http超时时间,ms */ public static final long HTTP_TIME_OUT = 5000; /** * http连接超时时间,m */ public static final long HTTP_CONNECT_TIME_OUT = 30; /** * http读写超时时间,m */ public static final long HTTP_RW_TIME_OUT = 30; /** * ShredPreferenceRepository库的文件 */ public static final String SHARED_PREFERENCE_REPOSITORY = "zhixiao"; }
22.414634
103
0.624592
12243734160f25040849c35222890ce947653b08
1,805
package spreadsheet.mapper.w2o.process; import spreadsheet.mapper.model.core.Sheet; import spreadsheet.mapper.model.core.Workbook; import spreadsheet.mapper.model.meta.SheetMeta; import spreadsheet.mapper.model.meta.WorkbookMeta; import java.util.ArrayList; import java.util.List; /** * Created by hanwen on 2017/1/4. */ public class DefaultWorkbookProcessHelper implements WorkbookProcessHelper { private List<SheetProcessHelper> sheetProcessHelpers = new ArrayList<>(); @Override public WorkbookProcessHelper addSheetProcessHelper(SheetProcessHelper sheetProcessHelper) { if (sheetProcessHelper == null) { throw new IllegalArgumentException("sheet process helper can not be null"); } sheetProcessHelpers.add(sheetProcessHelper); return this; } @Override public List<List> process(Workbook workbook, WorkbookMeta workbookMeta) { int sizeOfSheets = workbook.sizeOfSheets(); int sizeOfSheetMetas = workbookMeta.sizeOfSheetMetas(); int sizeOfHelper = sheetProcessHelpers.size(); if (sizeOfSheets != sizeOfSheetMetas) { throw new WorkbookProcessException("workbook's sheet size[" + sizeOfSheets + "] not equals workbook meta's sheet meta size[" + sizeOfSheetMetas + "]"); } if (sizeOfSheets != sizeOfHelper) { throw new WorkbookProcessException("workbook's sheet size[" + sizeOfSheets + "] not equals sheet process helper size[" + sizeOfHelper + "]"); } List<List> objects = new ArrayList<>(); for (int i = 1; i <= sizeOfSheets; i++) { SheetProcessHelper sheetProcessHelper = sheetProcessHelpers.get(i - 1); Sheet sheet = workbook.getSheet(i); SheetMeta sheetMeta = workbookMeta.getSheetMeta(i); objects.add(sheetProcessHelper.process(sheet, sheetMeta)); } return objects; } }
32.818182
157
0.73241
8163b93b53fd6693011e3b77eb24a7922703386c
823
package com.acme.example.archunit.lang.archrule.area; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; import com.tngtech.archunit.core.importer.ImportOption; import com.tngtech.archunit.junit.AnalyzeClasses; import com.tngtech.archunit.junit.ArchTest; import com.tngtech.archunit.lang.ArchRule; //@RunWith(ArchUnitRunner.class) // Important: Only for JUnit 4 and not needed JUnit5 @AnalyzeClasses(packages = "com.acme.example", importOptions = { ImportOption.DoNotIncludeTests.class, ImportOption.DoNotIncludeJars.class, ImportOption.DoNotIncludeArchives.class }) public class CheckMethodsArchRuleAreaTest { @ArchTest static final ArchRule utility_methods_should_be_static = methods().that().areDeclaredInClassesThat() .haveSimpleNameEndingWith("Util").should().beStatic(); }
35.782609
101
0.811665
aa1e4e80d32324d2ef172b7ba271cf2d01d4bceb
9,319
package s3fx; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.S3ObjectSummary; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.util.StringConverter; import s3fx.client.S3Adapter; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URL; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import java.util.function.Supplier; /** * @author irof */ public class S3BucketController implements Initializable { private final S3Adapter client; private final Stage stage; private final Map<S3ObjectIdentifier, Stage> objectWindows = new HashMap<>(); public ComboBox<Bucket> bucket; public Button refreshBucketsButton; public Button createBucketButton; public Button deleteBucketButton; public ProgressIndicator progress; public Button deleteButton; public Button uploadButton; public TextField filterText; public TableView<S3ObjectSummary> objectList; public TableColumn<S3ObjectSummary, String> tableNameColumn; public TableColumn<S3ObjectSummary, Long> tableSizeColumn; public TableColumn<S3ObjectSummary, Date> tableLastModifiedColumn; private final Service<ObservableList<Bucket>> listBucketsService; private final Service<ObservableList<S3ObjectSummary>> listObjectsService; public S3BucketController(Stage stage, S3Adapter client) { this.stage = stage; this.client = client; this.listBucketsService = createS3Service(() -> FXCollections.observableArrayList(client.listBuckets())); this.listObjectsService = createS3Service(() -> FXCollections.observableArrayList( client.listObjects(bucket.getValue(), filterText.getText()))); } private <T> Service<T> createS3Service(Supplier<T> task) { return new Service<T>() { @Override protected Task<T> createTask() { return new Task<T>() { @Override protected T call() throws Exception { return task.get(); } }; } }; } public void getBuckets() { listBucketsService.restart(); } public void createBucket() { TextInputDialog dialog = new TextInputDialog(); dialog.setTitle("新しいBucketの作成"); dialog.setHeaderText("作りたいBucketの名前を入力してください"); dialog.setContentText("new Bucket Name :"); dialog.showAndWait().ifPresent(name -> bucket.getItems().add(client.createBucket(name))); } public void deleteBucket() { client.deleteBucket(bucket.getValue()); bucket.getItems().remove(bucket.getValue()); bucket.getSelectionModel().clearSelection(); } public void uploadFile() { // ファイルを選択してもらう FileChooser fileChooser = new FileChooser(); File file = fileChooser.showOpenDialog(stage); if (file == null) return; TextInputDialog dialog = new TextInputDialog(file.getName()); dialog.setTitle("Bucketに格納するキーを入力してください"); dialog.setHeaderText(file.getPath()); dialog.setContentText("Key :"); dialog.showAndWait().ifPresent(name -> { client.putObject(bucket.getValue(), name, file); listObjectsService.restart(); }); } public void deleteFile() { S3ObjectSummary selectedItem = objectList.getSelectionModel().getSelectedItem(); client.deleteObject(selectedItem); objectList.getItems().remove(selectedItem); S3ObjectIdentifier id = new S3ObjectIdentifier(selectedItem); if (objectWindows.containsKey(id)) { objectWindows.remove(id).close(); } } @Override public void initialize(URL location, ResourceBundle resources) { // サービス実行中はインジケーター表示 progress.visibleProperty().bind(listBucketsService.runningProperty() .or(listObjectsService.runningProperty())); bucket.itemsProperty().bind(listBucketsService.valueProperty()); bucket.setCellFactory(this::createBucketCell); bucket.setConverter(new StringConverter<Bucket>() { @Override public String toString(Bucket object) { return object.getName(); } @Override public Bucket fromString(String string) { // StringからBucketへの変換はしない throw new UnsupportedOperationException(); } }); bucket.valueProperty().addListener((observable, oldValue, newValue) -> { listObjectsService.restart(); }); objectList.itemsProperty().bind(listObjectsService.valueProperty()); objectList.setRowFactory(table -> { TableRow<S3ObjectSummary> row = new TableRow<>(); row.setOnMouseClicked(event -> { S3ObjectSummary item = row.getItem(); if (item == null || event.getClickCount() != 2) return; S3ObjectIdentifier id = new S3ObjectIdentifier(item); if (objectWindows.containsKey(id)) { objectWindows.get(id).requestFocus(); } else { Stage objectWindow = createS3ObjectWindow(item); // 上を合わせて右に並べて出す objectWindow.setX(stage.getX() + stage.getWidth()); objectWindow.setY(stage.getY()); objectWindow.show(); objectWindows.put(id, objectWindow); objectWindow.setOnCloseRequest(e -> objectWindows.remove(id)); } }); return row; }); tableNameColumn.setCellValueFactory(new PropertyValueFactory<>("key")); tableSizeColumn.setCellValueFactory(new PropertyValueFactory<>("size")); tableSizeColumn.setCellFactory(data -> new TableCell<S3ObjectSummary, Long>() { @Override protected void updateItem(Long item, boolean empty) { super.updateItem(item, empty); setText(empty ? "" : NumberFormat.getNumberInstance().format(item)); } }); tableLastModifiedColumn.setCellValueFactory(new PropertyValueFactory<>("lastModified")); tableLastModifiedColumn.setCellFactory(data -> new TableCell<S3ObjectSummary, Date>() { @Override protected void updateItem(Date item, boolean empty) { super.updateItem(item, empty); setText(empty ? "" : new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(item)); } }); // 活性条件をバインディング bucket.disableProperty().bind(progress.visibleProperty()); refreshBucketsButton.disableProperty().bind(progress.visibleProperty()); createBucketButton.disableProperty().bind(progress.visibleProperty()); BooleanBinding bucketNotSelected = Bindings.isNull(bucket.valueProperty()); deleteBucketButton.disableProperty().bind(bucketNotSelected.or(progress.visibleProperty())); uploadButton.disableProperty().bind(bucketNotSelected.or(progress.visibleProperty())); deleteButton.disableProperty().bind(bucketNotSelected.or(progress.visibleProperty()) .or(objectList.getSelectionModel().selectedItemProperty().isNull())); // 一旦bucket窓閉じたら全部閉じるようにしとく stage.setOnCloseRequest(event -> objectWindows.values().stream().forEach(Stage::close)); // Bucket一覧は最初に取得しとく listBucketsService.start(); } private ListCell<Bucket> createBucketCell(ListView<Bucket> listView) { return new ListCell<Bucket>() { @Override protected void updateItem(Bucket item, boolean empty) { super.updateItem(item, empty); setText(empty ? "" : item.getName()); } }; } private Stage createS3ObjectWindow(S3ObjectSummary item) { try { Stage stage = new Stage(StageStyle.DECORATED); FXMLLoader loader = new FXMLLoader(getClass().getResource("s3object.fxml")); loader.setControllerFactory(clz -> new S3ObjectController(stage, client, item)); Parent root = loader.load(); stage.setScene(new Scene(root)); return stage; } catch (IOException e) { throw new UncheckedIOException(e); } } public void searchObjects(KeyEvent event) { if (KeyCode.ENTER == event.getCode()) listObjectsService.restart(); } }
38.192623
100
0.645992
0b3718573c3b33d5d14f5ef1b1eb6af143846fdf
1,391
package com.github.ros.roxanne_sa.platform.rosbridge; import com.fasterxml.jackson.databind.JsonNode; import it.cnr.istc.pst.platinum.control.acting.GoalOrientedActingAgent; import it.cnr.istc.pst.platinum.control.lang.AgentTaskDescription; import it.cnr.istc.pst.platinum.control.lang.ex.PlatformCommunicationException; import ros.RosListenDelegate; /** * * @author alessandroumbrico * */ public abstract class RosBridgeGoalListener extends RosBridgeTopicHandler implements RosListenDelegate { private GoalOrientedActingAgent agent; /** * * @param agent */ protected RosBridgeGoalListener(GoalOrientedActingAgent agent) { // set agent this.agent = agent; } /** * */ @Override public void receive(JsonNode data, String stringRep) { try { // extract task description from goal AgentTaskDescription task = this.doHandleMessage(data, stringRep); // buffer task this.agent.buffer(task); } catch (Exception ex) { // error while extracting goal System.err.println("Error while extracting taks description from goal request:\n" + "\t- message: " + ex.getMessage() + "\n"); } } /** * * @param data * @param stringRep * @return * @throws PlatformCommunicationException */ protected abstract AgentTaskDescription doHandleMessage(JsonNode data, String stringRep) throws PlatformCommunicationException; }
23.183333
103
0.734723
3c4deb525bfcbf3dc892e8f3ab1f58337b700cf9
1,256
package org.societies.comm.xmpp.xc.impl; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.List; import org.dom4j.Element; import org.societies.api.comm.xmpp.datatypes.XMPPInfo; import org.societies.api.comm.xmpp.datatypes.XMPPNode; public class ParsingUtils { public static SimpleEntry<String, XMPPInfo> parseInfoResult(Element element) { // TODO Auto-generated method stub return null; } public static byte[] getInfoQueryRequestBytes(String node) { String nodePart = ""; if (node!=null) nodePart = "node='"+node+"' "; return ("<query xmlns='"+XMPPInfo.INFO_NAMESPACE+"' "+nodePart+"/>\n").getBytes(); } public static SimpleEntry<String, List<String>> parseItemsResult(Element element) { String node = element.attributeValue("node"); List<String> list = new ArrayList<String>(); for (Object o : element.elements()) { Element e = (Element) o; list.add(e.attributeValue("node")); } return new SimpleEntry<String, List<String>>(node, list); } public static byte[] getItemsQueryRequestBytes(String node) { String nodePart = ""; if (node!=null) nodePart = "node='"+node+"' "; return ("<query xmlns='"+XMPPNode.ITEM_NAMESPACE+"' "+nodePart+"/>\n").getBytes(); } }
29.904762
84
0.70621
807daef88d42f430b762cdc2147f003d2e503af0
19,484
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.util.bkd; import java.io.IOException; import java.util.Arrays; import org.apache.lucene.store.Directory; import org.apache.lucene.tests.util.LuceneTestCase; import org.apache.lucene.tests.util.TestUtil; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.NumericUtils; public class TestBKDRadixSelector extends LuceneTestCase { public void testBasic() throws IOException { int values = 4; Directory dir = getDirectory(values); int middle = 2; int dimensions = 1; int bytesPerDimensions = Integer.BYTES; BKDConfig config = new BKDConfig( dimensions, dimensions, bytesPerDimensions, BKDConfig.DEFAULT_MAX_POINTS_IN_LEAF_NODE); PointWriter points = getRandomPointWriter(config, dir, values); byte[] value = new byte[config.packedBytesLength]; NumericUtils.intToSortableBytes(1, value, 0); points.append(value, 0); NumericUtils.intToSortableBytes(2, value, 0); points.append(value, 1); NumericUtils.intToSortableBytes(3, value, 0); points.append(value, 2); NumericUtils.intToSortableBytes(4, value, 0); points.append(value, 3); points.close(); PointWriter copy = copyPoints(config, dir, points); verify(config, dir, copy, 0, values, middle, 0); dir.close(); } public void testRandomBinaryTiny() throws Exception { doTestRandomBinary(10); } public void testRandomBinaryMedium() throws Exception { doTestRandomBinary(25000); } @Nightly public void testRandomBinaryBig() throws Exception { doTestRandomBinary(500000); } private void doTestRandomBinary(int count) throws IOException { BKDConfig config = getRandomConfig(); int values = TestUtil.nextInt(random(), count, count * 2); Directory dir = getDirectory(values); int start; int end; if (random().nextBoolean()) { start = 0; end = values; } else { start = TestUtil.nextInt(random(), 0, values - 3); end = TestUtil.nextInt(random(), start + 2, values); } int partitionPoint = TestUtil.nextInt(random(), start + 1, end - 1); int sortedOnHeap = random().nextInt(5000); PointWriter points = getRandomPointWriter(config, dir, values); byte[] value = new byte[config.packedBytesLength]; for (int i = 0; i < values; i++) { random().nextBytes(value); points.append(value, i); } points.close(); verify(config, dir, points, start, end, partitionPoint, sortedOnHeap); dir.close(); } public void testRandomAllDimensionsEquals() throws IOException { int dimensions = TestUtil.nextInt(random(), 1, BKDConfig.MAX_INDEX_DIMS); int bytesPerDimensions = TestUtil.nextInt(random(), 2, 30); BKDConfig config = new BKDConfig( dimensions, dimensions, bytesPerDimensions, BKDConfig.DEFAULT_MAX_POINTS_IN_LEAF_NODE); int values = TestUtil.nextInt(random(), 15000, 20000); Directory dir = getDirectory(values); int partitionPoint = random().nextInt(values); int sortedOnHeap = random().nextInt(5000); PointWriter points = getRandomPointWriter(config, dir, values); byte[] value = new byte[config.packedBytesLength]; random().nextBytes(value); for (int i = 0; i < values; i++) { if (random().nextBoolean()) { points.append(value, i); } else { points.append(value, random().nextInt(values)); } } points.close(); verify(config, dir, points, 0, values, partitionPoint, sortedOnHeap); dir.close(); } public void testRandomLastByteTwoValues() throws IOException { int values = random().nextInt(15000) + 1; Directory dir = getDirectory(values); int partitionPoint = random().nextInt(values); int sortedOnHeap = random().nextInt(5000); BKDConfig config = getRandomConfig(); PointWriter points = getRandomPointWriter(config, dir, values); byte[] value = new byte[config.packedBytesLength]; random().nextBytes(value); for (int i = 0; i < values; i++) { if (random().nextBoolean()) { points.append(value, 1); } else { points.append(value, 2); } } points.close(); verify(config, dir, points, 0, values, partitionPoint, sortedOnHeap); dir.close(); } public void testRandomAllDocsEquals() throws IOException { int values = random().nextInt(15000) + 1; Directory dir = getDirectory(values); int partitionPoint = random().nextInt(values); int sortedOnHeap = random().nextInt(5000); BKDConfig config = getRandomConfig(); PointWriter points = getRandomPointWriter(config, dir, values); byte[] value = new byte[config.packedBytesLength]; random().nextBytes(value); for (int i = 0; i < values; i++) { points.append(value, 0); } points.close(); verify(config, dir, points, 0, values, partitionPoint, sortedOnHeap); dir.close(); } public void testRandomFewDifferentValues() throws IOException { BKDConfig config = getRandomConfig(); int values = atLeast(15000); Directory dir = getDirectory(values); int partitionPoint = random().nextInt(values); int sortedOnHeap = random().nextInt(5000); PointWriter points = getRandomPointWriter(config, dir, values); int numberValues = random().nextInt(8) + 2; byte[][] differentValues = new byte[numberValues][config.packedBytesLength]; for (int i = 0; i < numberValues; i++) { random().nextBytes(differentValues[i]); } for (int i = 0; i < values; i++) { points.append(differentValues[random().nextInt(numberValues)], i); } points.close(); verify(config, dir, points, 0, values, partitionPoint, sortedOnHeap); dir.close(); } public void testRandomDataDimDiffValues() throws IOException { BKDConfig config = getRandomConfig(); int values = atLeast(15000); Directory dir = getDirectory(values); int partitionPoint = random().nextInt(values); int sortedOnHeap = random().nextInt(5000); PointWriter points = getRandomPointWriter(config, dir, values); byte[] value = new byte[config.packedBytesLength]; int dataOnlyDims = config.numDims - config.numIndexDims; byte[] dataValue = new byte[dataOnlyDims * config.bytesPerDim]; random().nextBytes(value); for (int i = 0; i < values; i++) { random().nextBytes(dataValue); System.arraycopy( dataValue, 0, value, config.numIndexDims * config.bytesPerDim, dataOnlyDims * config.bytesPerDim); points.append(value, i); } points.close(); verify(config, dir, points, 0, values, partitionPoint, sortedOnHeap); dir.close(); } private void verify( BKDConfig config, Directory dir, PointWriter points, long start, long end, long middle, int sortedOnHeap) throws IOException { BKDRadixSelector radixSelector = new BKDRadixSelector(config, sortedOnHeap, dir, "test"); int dataOnlyDims = config.numDims - config.numIndexDims; // we only split by indexed dimension so we check for each only those dimension for (int splitDim = 0; splitDim < config.numIndexDims; splitDim++) { // We need to make a copy of the data as it is deleted in the process BKDRadixSelector.PathSlice inputSlice = new BKDRadixSelector.PathSlice(copyPoints(config, dir, points), 0, points.count()); int commonPrefixLengthInput = getRandomCommonPrefix(config, inputSlice, splitDim); BKDRadixSelector.PathSlice[] slices = new BKDRadixSelector.PathSlice[2]; byte[] partitionPoint = radixSelector.select( inputSlice, slices, start, end, middle, splitDim, commonPrefixLengthInput); assertEquals(middle - start, slices[0].count); assertEquals(end - middle, slices[1].count); // check that left and right slices contain the correct points byte[] max = getMax(config, slices[0], splitDim); byte[] min = getMin(config, slices[1], splitDim); int cmp = Arrays.compareUnsigned(max, 0, config.bytesPerDim, min, 0, config.bytesPerDim); assertTrue(cmp <= 0); if (cmp == 0) { byte[] maxDataDim = getMaxDataDimension(config, slices[0], max, splitDim); byte[] minDataDim = getMinDataDimension(config, slices[1], min, splitDim); cmp = Arrays.compareUnsigned( maxDataDim, 0, dataOnlyDims * config.bytesPerDim, minDataDim, 0, dataOnlyDims * config.bytesPerDim); assertTrue(cmp <= 0); if (cmp == 0) { int maxDocID = getMaxDocId(config, slices[0], splitDim, partitionPoint, maxDataDim); int minDocId = getMinDocId(config, slices[1], splitDim, partitionPoint, minDataDim); assertTrue(minDocId >= maxDocID); } } assertTrue(Arrays.equals(partitionPoint, min)); slices[0].writer.destroy(); slices[1].writer.destroy(); } points.destroy(); } private PointWriter copyPoints(BKDConfig config, Directory dir, PointWriter points) throws IOException { try (PointWriter copy = getRandomPointWriter(config, dir, points.count()); PointReader reader = points.getReader(0, points.count())) { while (reader.next()) { copy.append(reader.pointValue()); } return copy; } } /** returns a common prefix length equal or lower than the current one */ private int getRandomCommonPrefix( BKDConfig config, BKDRadixSelector.PathSlice inputSlice, int splitDim) throws IOException { byte[] pointsMax = getMax(config, inputSlice, splitDim); byte[] pointsMin = getMin(config, inputSlice, splitDim); int commonPrefixLength = Arrays.mismatch(pointsMin, 0, config.bytesPerDim, pointsMax, 0, config.bytesPerDim); if (commonPrefixLength == -1) { commonPrefixLength = config.bytesPerDim; } return (random().nextBoolean()) ? commonPrefixLength : commonPrefixLength == 0 ? 0 : random().nextInt(commonPrefixLength); } private PointWriter getRandomPointWriter(BKDConfig config, Directory dir, long numPoints) throws IOException { if (numPoints < 4096 && random().nextBoolean()) { return new HeapPointWriter(config, Math.toIntExact(numPoints)); } else { return new OfflinePointWriter(config, dir, "test", "data", numPoints); } } private Directory getDirectory(int numPoints) { Directory dir; if (numPoints > 100000) { dir = newFSDirectory(createTempDir("TestBKDTRadixSelector")); } else { dir = newDirectory(); } return dir; } private byte[] getMin(BKDConfig config, BKDRadixSelector.PathSlice pathSlice, int dimension) throws IOException { byte[] min = new byte[config.bytesPerDim]; Arrays.fill(min, (byte) 0xff); try (PointReader reader = pathSlice.writer.getReader(pathSlice.start, pathSlice.count)) { byte[] value = new byte[config.bytesPerDim]; while (reader.next()) { PointValue pointValue = reader.pointValue(); BytesRef packedValue = pointValue.packedValue(); System.arraycopy( packedValue.bytes, packedValue.offset + dimension * config.bytesPerDim, value, 0, config.bytesPerDim); if (Arrays.compareUnsigned(min, 0, config.bytesPerDim, value, 0, config.bytesPerDim) > 0) { System.arraycopy(value, 0, min, 0, config.bytesPerDim); } } } return min; } private int getMinDocId( BKDConfig config, BKDRadixSelector.PathSlice p, int dimension, byte[] partitionPoint, byte[] dataDim) throws IOException { int docID = Integer.MAX_VALUE; try (PointReader reader = p.writer.getReader(p.start, p.count)) { while (reader.next()) { PointValue pointValue = reader.pointValue(); BytesRef packedValue = pointValue.packedValue(); int offset = dimension * config.bytesPerDim; int dataOffset = config.packedIndexBytesLength; int dataLength = (config.numDims - config.numIndexDims) * config.bytesPerDim; if (Arrays.compareUnsigned( packedValue.bytes, packedValue.offset + offset, packedValue.offset + offset + config.bytesPerDim, partitionPoint, 0, config.bytesPerDim) == 0 && Arrays.compareUnsigned( packedValue.bytes, packedValue.offset + dataOffset, packedValue.offset + dataOffset + dataLength, dataDim, 0, dataLength) == 0) { int newDocID = pointValue.docID(); if (newDocID < docID) { docID = newDocID; } } } } return docID; } private byte[] getMinDataDimension( BKDConfig config, BKDRadixSelector.PathSlice p, byte[] minDim, int splitDim) throws IOException { final int numDataDims = config.numDims - config.numIndexDims; byte[] min = new byte[numDataDims * config.bytesPerDim]; Arrays.fill(min, (byte) 0xff); int offset = splitDim * config.bytesPerDim; try (PointReader reader = p.writer.getReader(p.start, p.count)) { byte[] value = new byte[numDataDims * config.bytesPerDim]; while (reader.next()) { PointValue pointValue = reader.pointValue(); BytesRef packedValue = pointValue.packedValue(); if (Arrays.mismatch( minDim, 0, config.bytesPerDim, packedValue.bytes, packedValue.offset + offset, packedValue.offset + offset + config.bytesPerDim) == -1) { System.arraycopy( packedValue.bytes, packedValue.offset + config.numIndexDims * config.bytesPerDim, value, 0, numDataDims * config.bytesPerDim); if (Arrays.compareUnsigned( min, 0, numDataDims * config.bytesPerDim, value, 0, numDataDims * config.bytesPerDim) > 0) { System.arraycopy(value, 0, min, 0, numDataDims * config.bytesPerDim); } } } } return min; } private byte[] getMax(BKDConfig config, BKDRadixSelector.PathSlice p, int dimension) throws IOException { byte[] max = new byte[config.bytesPerDim]; Arrays.fill(max, (byte) 0); try (PointReader reader = p.writer.getReader(p.start, p.count)) { byte[] value = new byte[config.bytesPerDim]; while (reader.next()) { PointValue pointValue = reader.pointValue(); BytesRef packedValue = pointValue.packedValue(); System.arraycopy( packedValue.bytes, packedValue.offset + dimension * config.bytesPerDim, value, 0, config.bytesPerDim); if (Arrays.compareUnsigned(max, 0, config.bytesPerDim, value, 0, config.bytesPerDim) < 0) { System.arraycopy(value, 0, max, 0, config.bytesPerDim); } } } return max; } private byte[] getMaxDataDimension( BKDConfig config, BKDRadixSelector.PathSlice p, byte[] maxDim, int splitDim) throws IOException { final int numDataDims = config.numDims - config.numIndexDims; byte[] max = new byte[numDataDims * config.bytesPerDim]; Arrays.fill(max, (byte) 0); int offset = splitDim * config.bytesPerDim; try (PointReader reader = p.writer.getReader(p.start, p.count)) { byte[] value = new byte[numDataDims * config.bytesPerDim]; while (reader.next()) { PointValue pointValue = reader.pointValue(); BytesRef packedValue = pointValue.packedValue(); if (Arrays.mismatch( maxDim, 0, config.bytesPerDim, packedValue.bytes, packedValue.offset + offset, packedValue.offset + offset + config.bytesPerDim) == -1) { System.arraycopy( packedValue.bytes, packedValue.offset + config.packedIndexBytesLength, value, 0, numDataDims * config.bytesPerDim); if (Arrays.compareUnsigned( max, 0, numDataDims * config.bytesPerDim, value, 0, numDataDims * config.bytesPerDim) < 0) { System.arraycopy(value, 0, max, 0, numDataDims * config.bytesPerDim); } } } } return max; } private int getMaxDocId( BKDConfig config, BKDRadixSelector.PathSlice p, int dimension, byte[] partitionPoint, byte[] dataDim) throws IOException { int docID = Integer.MIN_VALUE; try (PointReader reader = p.writer.getReader(p.start, p.count)) { while (reader.next()) { PointValue pointValue = reader.pointValue(); BytesRef packedValue = pointValue.packedValue(); int offset = dimension * config.bytesPerDim; int dataOffset = config.packedIndexBytesLength; int dataLength = (config.numDims - config.numIndexDims) * config.bytesPerDim; if (Arrays.compareUnsigned( packedValue.bytes, packedValue.offset + offset, packedValue.offset + offset + config.bytesPerDim, partitionPoint, 0, config.bytesPerDim) == 0 && Arrays.compareUnsigned( packedValue.bytes, packedValue.offset + dataOffset, packedValue.offset + dataOffset + dataLength, dataDim, 0, dataLength) == 0) { int newDocID = pointValue.docID(); if (newDocID > docID) { docID = newDocID; } } } } return docID; } private BKDConfig getRandomConfig() { int numIndexDims = TestUtil.nextInt(random(), 1, BKDConfig.MAX_INDEX_DIMS); int numDims = TestUtil.nextInt(random(), numIndexDims, BKDConfig.MAX_DIMS); int bytesPerDim = TestUtil.nextInt(random(), 2, 30); int maxPointsInLeafNode = TestUtil.nextInt(random(), 50, 2000); return new BKDConfig(numDims, numIndexDims, bytesPerDim, maxPointsInLeafNode); } }
37.32567
99
0.626976
31c815cc6163e89bb4f3b2969cf8a0a2a9aa3bc1
7,548
package org.librairy.service.nlp.service; import com.google.common.base.CharMatcher; import com.google.common.base.Strings; import com.google.common.io.Files; import eus.ixa.ixa.pipe.pos.Annotate; import eus.ixa.ixa.pipe.pos.CLI; import ixa.kaflib.KAFDocument; import ixa.kaflib.Term; import ixa.kaflib.WF; import org.apache.avro.AvroRemoteException; import org.librairy.service.nlp.facade.model.Annotation; import org.librairy.service.nlp.facade.model.Form; import org.librairy.service.nlp.facade.model.PoS; import org.librairy.service.nlp.facade.model.Token; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import java.io.*; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es> */ public class IXAService { private static final Logger LOG = LoggerFactory.getLogger(org.librairy.service.nlp.service.IXAService.class); @Value("#{environment['RESOURCE_FOLDER']?:'${resource.folder}'}") String resourceFolder; String model ; String lemmatizerModel ; String language ; String multiwords ; String dictag ; // String binDictMorphoTaggerURL; String kafVersion ; String normalize ; String untokenizable ; String hardParagraph ; String noseg ; private Properties annotateProperties; private Annotate posAnnotator; public IXAService(String resourceFolder){ this.resourceFolder = resourceFolder; } public void setup() { model = Paths.get(resourceFolder,"morph-models-1.5.0/en/en-pos-perceptron-autodict01-conll09.bin").toFile().getAbsolutePath(); lemmatizerModel = Paths.get(resourceFolder,"morph-models-1.5.0/en/en-lemma-perceptron-conll09.bin").toFile().getAbsolutePath(); language = "en"; multiwords = "false"; dictag = "false"; // binDictMorphoTaggerURL = Paths.get(resourceFolder,"nerc-models-1.5.4/en/conll03").toFile().getAbsolutePath(); kafVersion = "1.5.0"; normalize = "true"; // false untokenizable = "false"; hardParagraph = "false"; noseg = "false"; // this.annotateProperties = new Properties(); annotateProperties.setProperty("normalize", normalize); annotateProperties.setProperty("untokenizable", untokenizable); annotateProperties.setProperty("hardParagraph", hardParagraph); annotateProperties.setProperty("noseg",noseg); annotateProperties.setProperty("model", model); annotateProperties.setProperty("lemmatizerModel", lemmatizerModel); annotateProperties.setProperty("language", language); annotateProperties.setProperty("multiwords", multiwords); annotateProperties.setProperty("dictag", dictag); try { this.posAnnotator = new Annotate(annotateProperties); } catch (IOException e) { throw new RuntimeException("Error initializing IXA Pipes", e); } } public String tokens(String text, List<PoS> filter, Form form) throws AvroRemoteException { return analyze(text,filter).stream() .map(term-> { switch (form){ case LEMMA: return Strings.isNullOrEmpty(term.getLemma())? term.getStr() : term.getLemma().toLowerCase(); default: return term.getStr().toLowerCase(); } }) .collect(Collectors.joining(" ")); } public List<Annotation> annotations(String text, List<PoS> filter) throws AvroRemoteException { List<Term> terms = new ArrayList<>(); Matcher matcher = Pattern.compile(".{1,1000}(,|.$)").matcher(text); int groupIndex = 0; while (matcher.find()){ String group = matcher.group(); List<Term> groupTerms = analyze(group, filter); for(Term term: groupTerms){ WF target = term.getSpan().getTargets().get(0); target.setOffset((groupIndex*1000)+target.getOffset()); } terms.addAll(groupTerms); groupIndex++; } return terms.stream() .map(term -> { Token token = new Token(); token.setTarget(term.getStr()); token.setLemma(!Strings.isNullOrEmpty(term.getLemma())?term.getLemma():""); if ((CharMatcher.javaLetter().matchesAllOf(term.getStr())) && CharMatcher.javaDigit().matchesAllOf(term.getLemma())){ // special case: // target = first // lemma = 1 token.setLemma(term.getStr()); } token.setMorphoFeat(!Strings.isNullOrEmpty(term.getMorphofeat())?term.getMorphofeat():""); token.setPos(!Strings.isNullOrEmpty(term.getPos())?PoSTranslator.toPoSTag(term.getPos()):PoS.NOUN); token.setType(!Strings.isNullOrEmpty(term.getType())?term.getType():""); Annotation annotation = new Annotation(); if (term.getSentiment() != null) annotation.setSentiment(term.getSentiment().getPolarity()); annotation.setToken(token); annotation.setOffset(Long.valueOf(term.getSpan().getTargets().get(0).getOffset())); return annotation; }) .collect(Collectors.toList()); } private List<Term> analyze(String text, List<PoS> filter){ List<Term> terms = Collections.emptyList(); final KAFDocument kaf; try { InputStream is = new ByteArrayInputStream(text.getBytes()); BufferedReader breader = new BufferedReader(new InputStreamReader(is)); kaf = new KAFDocument(language, kafVersion); final String version = CLI.class.getPackage().getImplementationVersion(); final String commit = CLI.class.getPackage().getSpecificationVersion(); final eus.ixa.ixa.pipe.tok.Annotate tokAnnotator = new eus.ixa.ixa.pipe.tok.Annotate(breader, annotateProperties); // Tokenization tokAnnotator.tokenizeToKAF(kaf); // PosTagging final KAFDocument.LinguisticProcessor newLp = kaf.addLinguisticProcessor("terms", "ixa-pipe-pos-" + Files.getNameWithoutExtension(model), version + "-" + commit); newLp.setBeginTimestamp(); posAnnotator.annotatePOSToKAF(kaf); // Filtering List<String> postags = filter.stream().flatMap( type -> PoSTranslator.toTermPoS(type).stream()).collect(Collectors.toList()); terms = kaf.getAnnotations(KAFDocument.AnnotationType.TERM).stream() .map(annotation -> (Term) annotation) .filter(term -> postags.isEmpty() || postags.contains(term.getPos())) .collect(Collectors.toList()); breader.close(); } catch (IOException e) { LOG.error("Error analyzing text", e); } return terms; } }
39.108808
174
0.612083
b0bee48ee92449dadefdeb5e6e12b3029c4885ab
283
package com.example.backend.services.interfaces.openapi; import java.util.concurrent.ExecutionException; public interface OpenApiConnectable extends JsonDataAccessible { int INTERVAL = 1_000; void updateByOpenApiData() throws ExecutionException, InterruptedException; }
23.583333
79
0.819788
6c9eaa758b2a9c4033d458f6a3156b53154f3a12
23,347
package com.bullhornsdk.data.model.entity.customfields; import java.math.BigDecimal; import javax.validation.constraints.Size; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** * Common custom fields for Placement and PlacementChangeRequest: * * customDate 1-3 * * customFloat 1-3 * * customInt 1-3 * * customText 1-40 * * customTextBlock 1-5 * * correlatedCustomDate 1-3 * * correlatedCustomFloat 1-3 * * correlatedCustomInt 1-3 * * correlatedCustomText 1-10 * * correlatedCustomTextBlock 1-3 * * customBillRate 1-10 * * customPayRate 1-10 * * @author magnus.palm * */ public class CustomFieldsD extends CustomFieldsC { private BigDecimal customBillRate1; private BigDecimal customBillRate10; private BigDecimal customBillRate2; private BigDecimal customBillRate3; private BigDecimal customBillRate4; private BigDecimal customBillRate5; private BigDecimal customBillRate6; private BigDecimal customBillRate7; private BigDecimal customBillRate8; private BigDecimal customBillRate9; private BigDecimal customPayRate1; private BigDecimal customPayRate10; private BigDecimal customPayRate2; private BigDecimal customPayRate3; private BigDecimal customPayRate4; private BigDecimal customPayRate5; private BigDecimal customPayRate6; private BigDecimal customPayRate7; private BigDecimal customPayRate8; private BigDecimal customPayRate9; @JsonIgnore @Size(max = 100) private String customText21; @JsonIgnore @Size(max = 100) private String customText22; @JsonIgnore @Size(max = 100) private String customText23; @JsonIgnore @Size(max = 100) private String customText24; @JsonIgnore @Size(max = 100) private String customText25; @JsonIgnore @Size(max = 100) private String customText26; @JsonIgnore @Size(max = 100) private String customText27; @JsonIgnore @Size(max = 100) private String customText28; @JsonIgnore @Size(max = 100) private String customText29; @JsonIgnore @Size(max = 100) private String customText30; @JsonIgnore @Size(max = 100) private String customText31; @JsonIgnore @Size(max = 100) private String customText32; @JsonIgnore @Size(max = 100) private String customText33; @JsonIgnore @Size(max = 100) private String customText34; @JsonIgnore @Size(max = 100) private String customText35; @JsonIgnore @Size(max = 100) private String customText36; @JsonIgnore @Size(max = 100) private String customText37; @JsonIgnore @Size(max = 100) private String customText38; @JsonIgnore @Size(max = 100) private String customText39; @JsonIgnore @Size(max = 100) private String customText40; @JsonProperty("customBillRate1") public BigDecimal getCustomBillRate1() { return customBillRate1; } @JsonProperty("customBillRate1") public void setCustomBillRate1(BigDecimal customBillRate1) { this.customBillRate1 = customBillRate1; } @JsonProperty("customBillRate10") public BigDecimal getCustomBillRate10() { return customBillRate10; } @JsonProperty("customBillRate10") public void setCustomBillRate10(BigDecimal customBillRate10) { this.customBillRate10 = customBillRate10; } @JsonProperty("customBillRate2") public BigDecimal getCustomBillRate2() { return customBillRate2; } @JsonProperty("customBillRate2") public void setCustomBillRate2(BigDecimal customBillRate2) { this.customBillRate2 = customBillRate2; } @JsonProperty("customBillRate3") public BigDecimal getCustomBillRate3() { return customBillRate3; } @JsonProperty("customBillRate3") public void setCustomBillRate3(BigDecimal customBillRate3) { this.customBillRate3 = customBillRate3; } @JsonProperty("customBillRate4") public BigDecimal getCustomBillRate4() { return customBillRate4; } @JsonProperty("customBillRate4") public void setCustomBillRate4(BigDecimal customBillRate4) { this.customBillRate4 = customBillRate4; } @JsonProperty("customBillRate5") public BigDecimal getCustomBillRate5() { return customBillRate5; } @JsonProperty("customBillRate5") public void setCustomBillRate5(BigDecimal customBillRate5) { this.customBillRate5 = customBillRate5; } @JsonProperty("customBillRate6") public BigDecimal getCustomBillRate6() { return customBillRate6; } @JsonProperty("customBillRate6") public void setCustomBillRate6(BigDecimal customBillRate6) { this.customBillRate6 = customBillRate6; } @JsonProperty("customBillRate7") public BigDecimal getCustomBillRate7() { return customBillRate7; } @JsonProperty("customBillRate7") public void setCustomBillRate7(BigDecimal customBillRate7) { this.customBillRate7 = customBillRate7; } @JsonProperty("customBillRate8") public BigDecimal getCustomBillRate8() { return customBillRate8; } @JsonProperty("customBillRate8") public void setCustomBillRate8(BigDecimal customBillRate8) { this.customBillRate8 = customBillRate8; } @JsonProperty("customBillRate9") public BigDecimal getCustomBillRate9() { return customBillRate9; } @JsonProperty("customBillRate9") public void setCustomBillRate9(BigDecimal customBillRate9) { this.customBillRate9 = customBillRate9; } @JsonProperty("customPayRate1") public BigDecimal getCustomPayRate1() { return customPayRate1; } @JsonProperty("customPayRate1") public void setCustomPayRate1(BigDecimal customPayRate1) { this.customPayRate1 = customPayRate1; } @JsonProperty("customPayRate10") public BigDecimal getCustomPayRate10() { return customPayRate10; } @JsonProperty("customPayRate10") public void setCustomPayRate10(BigDecimal customPayRate10) { this.customPayRate10 = customPayRate10; } @JsonProperty("customPayRate2") public BigDecimal getCustomPayRate2() { return customPayRate2; } @JsonProperty("customPayRate2") public void setCustomPayRate2(BigDecimal customPayRate2) { this.customPayRate2 = customPayRate2; } @JsonProperty("customPayRate3") public BigDecimal getCustomPayRate3() { return customPayRate3; } @JsonProperty("customPayRate3") public void setCustomPayRate3(BigDecimal customPayRate3) { this.customPayRate3 = customPayRate3; } @JsonProperty("customPayRate4") public BigDecimal getCustomPayRate4() { return customPayRate4; } @JsonProperty("customPayRate4") public void setCustomPayRate4(BigDecimal customPayRate4) { this.customPayRate4 = customPayRate4; } @JsonProperty("customPayRate5") public BigDecimal getCustomPayRate5() { return customPayRate5; } @JsonProperty("customPayRate5") public void setCustomPayRate5(BigDecimal customPayRate5) { this.customPayRate5 = customPayRate5; } @JsonProperty("customPayRate6") public BigDecimal getCustomPayRate6() { return customPayRate6; } @JsonProperty("customPayRate6") public void setCustomPayRate6(BigDecimal customPayRate6) { this.customPayRate6 = customPayRate6; } @JsonProperty("customPayRate7") public BigDecimal getCustomPayRate7() { return customPayRate7; } @JsonProperty("customPayRate7") public void setCustomPayRate7(BigDecimal customPayRate7) { this.customPayRate7 = customPayRate7; } @JsonProperty("customPayRate8") public BigDecimal getCustomPayRate8() { return customPayRate8; } @JsonProperty("customPayRate8") public void setCustomPayRate8(BigDecimal customPayRate8) { this.customPayRate8 = customPayRate8; } @JsonProperty("customPayRate9") public BigDecimal getCustomPayRate9() { return customPayRate9; } @JsonProperty("customPayRate9") public void setCustomPayRate9(BigDecimal customPayRate9) { this.customPayRate9 = customPayRate9; } @JsonProperty("customText21") public String getCustomText21() { return customText21; } @JsonIgnore public void setCustomText21(String customText21) { this.customText21 = customText21; } @JsonProperty("customText22") public String getCustomText22() { return customText22; } @JsonIgnore public void setCustomText22(String customText22) { this.customText22 = customText22; } @JsonProperty("customText23") public String getCustomText23() { return customText23; } @JsonIgnore public void setCustomText23(String customText23) { this.customText23 = customText23; } @JsonProperty("customText24") public String getCustomText24() { return customText24; } @JsonIgnore public void setCustomText24(String customText24) { this.customText24 = customText24; } @JsonProperty("customText25") public String getCustomText25() { return customText25; } @JsonIgnore public void setCustomText25(String customText25) { this.customText25 = customText25; } @JsonProperty("customText26") public String getCustomText26() { return customText26; } @JsonIgnore public void setCustomText26(String customText26) { this.customText26 = customText26; } @JsonProperty("customText27") public String getCustomText27() { return customText27; } @JsonIgnore public void setCustomText27(String customText27) { this.customText27 = customText27; } @JsonProperty("customText28") public String getCustomText28() { return customText28; } @JsonIgnore public void setCustomText28(String customText28) { this.customText28 = customText28; } @JsonProperty("customText29") public String getCustomText29() { return customText29; } @JsonIgnore public void setCustomText29(String customText29) { this.customText29 = customText29; } @JsonProperty("customText30") public String getCustomText30() { return customText30; } @JsonIgnore public void setCustomText30(String customText30) { this.customText30 = customText30; } @JsonProperty("customText31") public String getCustomText31() { return customText31; } @JsonIgnore public void setCustomText31(String customText31) { this.customText31 = customText31; } @JsonProperty("customText32") public String getCustomText32() { return customText32; } @JsonIgnore public void setCustomText32(String customText32) { this.customText32 = customText32; } @JsonProperty("customText33") public String getCustomText33() { return customText33; } @JsonIgnore public void setCustomText33(String customText33) { this.customText33 = customText33; } @JsonProperty("customText34") public String getCustomText34() { return customText34; } @JsonIgnore public void setCustomText34(String customText34) { this.customText34 = customText34; } @JsonProperty("customText35") public String getCustomText35() { return customText35; } @JsonIgnore public void setCustomText35(String customText35) { this.customText35 = customText35; } @JsonProperty("customText36") public String getCustomText36() { return customText36; } @JsonIgnore public void setCustomText36(String customText36) { this.customText36 = customText36; } @JsonProperty("customText37") public String getCustomText37() { return customText37; } @JsonIgnore public void setCustomText37(String customText37) { this.customText37 = customText37; } @JsonProperty("customText38") public String getCustomText38() { return customText38; } @JsonIgnore public void setCustomText38(String customText38) { this.customText38 = customText38; } @JsonProperty("customText39") public String getCustomText39() { return customText39; } @JsonIgnore public void setCustomText39(String customText39) { this.customText39 = customText39; } @JsonProperty("customText40") public String getCustomText40() { return customText40; } @JsonIgnore public void setCustomText40(String customText40) { this.customText40 = customText40; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((customBillRate1 == null) ? 0 : customBillRate1.hashCode()); result = prime * result + ((customBillRate10 == null) ? 0 : customBillRate10.hashCode()); result = prime * result + ((customBillRate2 == null) ? 0 : customBillRate2.hashCode()); result = prime * result + ((customBillRate3 == null) ? 0 : customBillRate3.hashCode()); result = prime * result + ((customBillRate4 == null) ? 0 : customBillRate4.hashCode()); result = prime * result + ((customBillRate5 == null) ? 0 : customBillRate5.hashCode()); result = prime * result + ((customBillRate6 == null) ? 0 : customBillRate6.hashCode()); result = prime * result + ((customBillRate7 == null) ? 0 : customBillRate7.hashCode()); result = prime * result + ((customBillRate8 == null) ? 0 : customBillRate8.hashCode()); result = prime * result + ((customBillRate9 == null) ? 0 : customBillRate9.hashCode()); result = prime * result + ((customPayRate1 == null) ? 0 : customPayRate1.hashCode()); result = prime * result + ((customPayRate10 == null) ? 0 : customPayRate10.hashCode()); result = prime * result + ((customPayRate2 == null) ? 0 : customPayRate2.hashCode()); result = prime * result + ((customPayRate3 == null) ? 0 : customPayRate3.hashCode()); result = prime * result + ((customPayRate4 == null) ? 0 : customPayRate4.hashCode()); result = prime * result + ((customPayRate5 == null) ? 0 : customPayRate5.hashCode()); result = prime * result + ((customPayRate6 == null) ? 0 : customPayRate6.hashCode()); result = prime * result + ((customPayRate7 == null) ? 0 : customPayRate7.hashCode()); result = prime * result + ((customPayRate8 == null) ? 0 : customPayRate8.hashCode()); result = prime * result + ((customPayRate9 == null) ? 0 : customPayRate9.hashCode()); result = prime * result + ((customText21 == null) ? 0 : customText21.hashCode()); result = prime * result + ((customText22 == null) ? 0 : customText22.hashCode()); result = prime * result + ((customText23 == null) ? 0 : customText23.hashCode()); result = prime * result + ((customText24 == null) ? 0 : customText24.hashCode()); result = prime * result + ((customText25 == null) ? 0 : customText25.hashCode()); result = prime * result + ((customText26 == null) ? 0 : customText26.hashCode()); result = prime * result + ((customText27 == null) ? 0 : customText27.hashCode()); result = prime * result + ((customText28 == null) ? 0 : customText28.hashCode()); result = prime * result + ((customText29 == null) ? 0 : customText29.hashCode()); result = prime * result + ((customText30 == null) ? 0 : customText30.hashCode()); result = prime * result + ((customText31 == null) ? 0 : customText31.hashCode()); result = prime * result + ((customText32 == null) ? 0 : customText32.hashCode()); result = prime * result + ((customText33 == null) ? 0 : customText33.hashCode()); result = prime * result + ((customText34 == null) ? 0 : customText34.hashCode()); result = prime * result + ((customText35 == null) ? 0 : customText35.hashCode()); result = prime * result + ((customText36 == null) ? 0 : customText36.hashCode()); result = prime * result + ((customText37 == null) ? 0 : customText37.hashCode()); result = prime * result + ((customText38 == null) ? 0 : customText38.hashCode()); result = prime * result + ((customText39 == null) ? 0 : customText39.hashCode()); result = prime * result + ((customText40 == null) ? 0 : customText40.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; CustomFieldsD other = (CustomFieldsD) obj; if (customBillRate1 == null) { if (other.customBillRate1 != null) return false; } else if (!customBillRate1.equals(other.customBillRate1)) return false; if (customBillRate10 == null) { if (other.customBillRate10 != null) return false; } else if (!customBillRate10.equals(other.customBillRate10)) return false; if (customBillRate2 == null) { if (other.customBillRate2 != null) return false; } else if (!customBillRate2.equals(other.customBillRate2)) return false; if (customBillRate3 == null) { if (other.customBillRate3 != null) return false; } else if (!customBillRate3.equals(other.customBillRate3)) return false; if (customBillRate4 == null) { if (other.customBillRate4 != null) return false; } else if (!customBillRate4.equals(other.customBillRate4)) return false; if (customBillRate5 == null) { if (other.customBillRate5 != null) return false; } else if (!customBillRate5.equals(other.customBillRate5)) return false; if (customBillRate6 == null) { if (other.customBillRate6 != null) return false; } else if (!customBillRate6.equals(other.customBillRate6)) return false; if (customBillRate7 == null) { if (other.customBillRate7 != null) return false; } else if (!customBillRate7.equals(other.customBillRate7)) return false; if (customBillRate8 == null) { if (other.customBillRate8 != null) return false; } else if (!customBillRate8.equals(other.customBillRate8)) return false; if (customBillRate9 == null) { if (other.customBillRate9 != null) return false; } else if (!customBillRate9.equals(other.customBillRate9)) return false; if (customPayRate1 == null) { if (other.customPayRate1 != null) return false; } else if (!customPayRate1.equals(other.customPayRate1)) return false; if (customPayRate10 == null) { if (other.customPayRate10 != null) return false; } else if (!customPayRate10.equals(other.customPayRate10)) return false; if (customPayRate2 == null) { if (other.customPayRate2 != null) return false; } else if (!customPayRate2.equals(other.customPayRate2)) return false; if (customPayRate3 == null) { if (other.customPayRate3 != null) return false; } else if (!customPayRate3.equals(other.customPayRate3)) return false; if (customPayRate4 == null) { if (other.customPayRate4 != null) return false; } else if (!customPayRate4.equals(other.customPayRate4)) return false; if (customPayRate5 == null) { if (other.customPayRate5 != null) return false; } else if (!customPayRate5.equals(other.customPayRate5)) return false; if (customPayRate6 == null) { if (other.customPayRate6 != null) return false; } else if (!customPayRate6.equals(other.customPayRate6)) return false; if (customPayRate7 == null) { if (other.customPayRate7 != null) return false; } else if (!customPayRate7.equals(other.customPayRate7)) return false; if (customPayRate8 == null) { if (other.customPayRate8 != null) return false; } else if (!customPayRate8.equals(other.customPayRate8)) return false; if (customPayRate9 == null) { if (other.customPayRate9 != null) return false; } else if (!customPayRate9.equals(other.customPayRate9)) return false; if (customText21 == null) { if (other.customText21 != null) return false; } else if (!customText21.equals(other.customText21)) return false; if (customText22 == null) { if (other.customText22 != null) return false; } else if (!customText22.equals(other.customText22)) return false; if (customText23 == null) { if (other.customText23 != null) return false; } else if (!customText23.equals(other.customText23)) return false; if (customText24 == null) { if (other.customText24 != null) return false; } else if (!customText24.equals(other.customText24)) return false; if (customText25 == null) { if (other.customText25 != null) return false; } else if (!customText25.equals(other.customText25)) return false; if (customText26 == null) { if (other.customText26 != null) return false; } else if (!customText26.equals(other.customText26)) return false; if (customText27 == null) { if (other.customText27 != null) return false; } else if (!customText27.equals(other.customText27)) return false; if (customText28 == null) { if (other.customText28 != null) return false; } else if (!customText28.equals(other.customText28)) return false; if (customText29 == null) { if (other.customText29 != null) return false; } else if (!customText29.equals(other.customText29)) return false; if (customText30 == null) { if (other.customText30 != null) return false; } else if (!customText30.equals(other.customText30)) return false; if (customText31 == null) { if (other.customText31 != null) return false; } else if (!customText31.equals(other.customText31)) return false; if (customText32 == null) { if (other.customText32 != null) return false; } else if (!customText32.equals(other.customText32)) return false; if (customText33 == null) { if (other.customText33 != null) return false; } else if (!customText33.equals(other.customText33)) return false; if (customText34 == null) { if (other.customText34 != null) return false; } else if (!customText34.equals(other.customText34)) return false; if (customText35 == null) { if (other.customText35 != null) return false; } else if (!customText35.equals(other.customText35)) return false; if (customText36 == null) { if (other.customText36 != null) return false; } else if (!customText36.equals(other.customText36)) return false; if (customText37 == null) { if (other.customText37 != null) return false; } else if (!customText37.equals(other.customText37)) return false; if (customText38 == null) { if (other.customText38 != null) return false; } else if (!customText38.equals(other.customText38)) return false; if (customText39 == null) { if (other.customText39 != null) return false; } else if (!customText39.equals(other.customText39)) return false; if (customText40 == null) { if (other.customText40 != null) return false; } else if (!customText40.equals(other.customText40)) return false; return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(", \ncustomText21="); builder.append(customText21); builder.append(", \ncustomText22="); builder.append(customText22); builder.append(", \ncustomText23="); builder.append(customText23); builder.append(", \ncustomText24="); builder.append(customText24); builder.append(", \ncustomText25="); builder.append(customText25); builder.append(", \ncustomText26="); builder.append(customText26); builder.append(", \ncustomText27="); builder.append(customText27); builder.append(", \ncustomText28="); builder.append(customText28); builder.append(", \ncustomText29="); builder.append(customText29); builder.append(", \ncustomText30="); builder.append(customText30); builder.append(", \ncustomText31="); builder.append(customText31); builder.append(", \ncustomText32="); builder.append(customText32); builder.append(", \ncustomText33="); builder.append(customText33); builder.append(", \ncustomText34="); builder.append(customText34); builder.append(", \ncustomText35="); builder.append(customText35); builder.append(", \ncustomText36="); builder.append(customText36); builder.append(", \ncustomText37="); builder.append(customText37); builder.append(", \ncustomText38="); builder.append(customText38); builder.append(", \ncustomText39="); builder.append(customText39); builder.append(", \ncustomText40="); builder.append(customText40); return builder.toString(); } }
26.897465
91
0.723305
1e0420e5f0e9906d0c798de92b1d6460cd38e518
3,634
package datawave.query.tables; import com.google.common.hash.BloomFilter; import com.google.common.hash.Funnel; import com.google.common.hash.PrimitiveSink; import java.io.Serializable; import java.util.HashSet; import java.util.Iterator; import java.util.Map.Entry; import org.apache.accumulo.core.data.ArrayByteSequence; import org.apache.accumulo.core.data.ByteSequence; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Value; /** * Created on 9/13/16. */ class DedupingIterator implements Iterator<Entry<Key,Value>> { private Iterator<Entry<Key,Value>> delegate; private Entry<Key,Value> next; private BloomFilter<byte[]> bloom = null; private HashSet<ByteSequence> seen; private final boolean DEBUG = true; public DedupingIterator(Iterator<Entry<Key,Value>> iterator) { this.delegate = iterator; this.bloom = BloomFilter.create(new ByteFunnel(), 500000, 1e-15); if (DEBUG) { this.seen = new HashSet<>(); } getNext(); } private void getNext() { next = null; while (next == null && delegate.hasNext()) { next = delegate.next(); if (isDuplicate(next)) { next = null; } } } private byte[] getBytes(Entry<Key,Value> entry) { ByteSequence row = entry.getKey().getRowData(); ByteSequence cf = entry.getKey().getColumnFamilyData(); // only append the last 2 tokens (the datatype and uid) // we are expecting that they may be prefixed with a count (see sortedUIDs in the DefaultQueryPlanner / QueryIterator) int nullCount = 0; int index = -1; for (int i = 0; i < cf.length() && nullCount < 2; i++) { if (cf.byteAt(i) == 0) { nullCount++; if (index == -1) { index = i; } } } int dataTypeOffset = index + 1; int offset = cf.offset() + dataTypeOffset; int length = cf.length() - dataTypeOffset; byte[] bytes = new byte[row.length() + length + 1]; System.arraycopy(row.getBackingArray(), row.offset(), bytes, 0, row.length()); System.arraycopy(cf.getBackingArray(), offset, bytes, row.length() + 1, length); return bytes; } @Override public boolean hasNext() { return next != null; } @Override public Entry<Key,Value> next() { Entry<Key,Value> nextReturn = next; if (next != null) { getNext(); } return nextReturn; } @Override public void remove() { throw new UnsupportedOperationException("Remove not supported on DedupingIterator"); } private boolean isDuplicate(Entry<Key,Value> entry) { byte[] bytes = getBytes(entry); ByteSequence byteSeq = new ArrayByteSequence(bytes); if (bloom.mightContain(bytes)) { if (DEBUG && !seen.contains(byteSeq)) { throw new IllegalStateException("This event is 1 in 1Q!"); } else { return true; } } bloom.put(bytes); if (DEBUG) { seen.add(byteSeq); } return false; } public static class ByteFunnel implements Funnel<byte[]>, Serializable { private static final long serialVersionUID = -2126172579955897986L; @Override public void funnel(byte[] from, PrimitiveSink into) { into.putBytes(from); } } }
30.79661
126
0.577876
10ffe6cbf89a4803795ae16f38f70cd8d8429085
2,461
package io.graversen.minecraft.rcon.commands.title; import io.graversen.minecraft.rcon.commands.base.ICommandBuilder; import io.graversen.minecraft.rcon.commands.base.ITargetingCommandBuilder; import io.graversen.minecraft.rcon.util.Colors; import io.graversen.minecraft.rcon.util.Selectors; import io.graversen.minecraft.rcon.util.Target; import io.graversen.minecraft.rcon.util.TitlePositions; public class TitleCommandBuilder implements ITargetingCommandBuilder<TitleCommandBuilder>, ICommandBuilder<TitleCommand> { private Target target; private String position; private String text; private boolean bold; private boolean italic; private boolean underlined; private boolean striketrough; private boolean obfuscated; private String color; @Override public TitleCommandBuilder targeting(String playerName) { this.target = Target.player(playerName); return this; } @Override public TitleCommandBuilder targeting(Selectors usingSelector) { this.target = Target.selector(usingSelector); return this; } public TitleCommandBuilder atPosition(TitlePositions titlePosition) { this.position = titlePosition.getTitlePositionValue(); return this; } public TitleCommandBuilder withColor(Colors color) { this.color = color.getColorName(); return this; } public TitleCommandBuilder withText(String text) { this.text = text; return this; } public TitleCommandBuilder bold() { this.bold = true; return this; } public TitleCommandBuilder italic() { this.italic = true; return this; } public TitleCommandBuilder underlined() { this.underlined = true; return this; } public TitleCommandBuilder strikethrough() { this.striketrough = true; return this; } public TitleCommandBuilder obfuscated() { this.obfuscated = true; return this; } @Override public boolean validate() { return (target != null) && (text != null) && (position != null); } @Override public TitleCommand build() { if (validate()) { return new TitleCommand(target, text, position, bold, italic, underlined, striketrough, obfuscated, color); } else { throw new IllegalArgumentException("Could not construct valid Title Command"); } } }
28.287356
122
0.679399
853fde4097935b57fb8c78e135913e3f7aaa4da6
1,079
import java.util.*; public class JavaGregorianCalendarDemo { public static void main(String args[]) { String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; int year; // 初始化 Gregorian日历 // 使用当前时间和日期 // 默认为本地时间和时区 GregorianCalendar gcalendar = new GregorianCalendar(); // 显示当前时间和日期的信息 System.out.print("Date: "); System.out.print(months[gcalendar.get(Calendar.MONTH)]); System.out.print("" + gcalendar.get(Calendar.DATE) +""); System.out.println(year = gcalendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(gcalendar.get(Calendar.HOUR) + ":"); System.out.print(gcalendar.get(Calendar.MINUTE) + ":"); System.out.print(gcalendar.get(Calendar.SECOND)); // 测试当前年份是否为闰年 if (gcalendar.isLeapYear(year)) { System.out.println("当前年份是闰年"); } else { System.out.println("当前年份不是闰年"); } } }
32.69697
64
0.55051
c331e6cc0054087214f5698906fdf3ee1f4dda16
3,365
/* * Copyright (c) 2017 Michael Krotscheck * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ package net.krotscheck.kangaroo.common.response; import net.krotscheck.kangaroo.common.hibernate.entity.AbstractEntity; import java.util.List; /** * This POJO describes an API list response. As it is insecure for us to * return raw arrays of data (See OWASP), we instead wrap the list response * in this pojo. * * @param <T> The data type returned. * @author Michael Krotscheck */ public final class ListResponseEntity<T extends AbstractEntity> { /** * The total # of records available. */ private Number total; /** * The page offset. */ private Number offset; /** * The page size limit. */ private Number limit; /** * The sort key. */ private String sort; /** * The sort order. */ private SortOrder order; /** * The results. */ private List<T> results; /** * The total # of records available. * * @return The total # of records available. */ public Number getTotal() { return total; } /** * Set the total. * * @param total The new total. */ protected void setTotal(final Number total) { this.total = total; } /** * The page offset. * * @return The page offset. */ public Number getOffset() { return offset; } /** * Set the offset. * * @param offset The new offset. */ protected void setOffset(final Number offset) { this.offset = offset; } /** * The page size limit. * * @return The page size limit. */ public Number getLimit() { return limit; } /** * Set the limit. * * @param limit The new limit. */ protected void setLimit(final Number limit) { this.limit = limit; } /** * The sort key. * * @return The sort key. */ public String getSort() { return sort; } /** * Set the sort. * * @param sort The new sort. */ protected void setSort(final String sort) { this.sort = sort; } /** * The sort order. * * @return The sort order. */ public SortOrder getOrder() { return order; } /** * Set the order. * * @param order The new order. */ protected void setOrder(final SortOrder order) { this.order = order; } /** * The results. * * @return The results. */ public List<T> getResults() { return results; } /** * Set the results. * * @param results The new results. */ protected void setResults(final List<T> results) { this.results = results; } }
19.450867
78
0.567608
08b0fe9404624ffc0500eba964743841567cf7e8
18,583
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.serialization.DocumentWriter; import com.yahoo.vespa.objects.Ids; import com.yahoo.vespa.objects.ObjectVisitor; import com.yahoo.vespa.objects.Serializer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; /** * <p>A document definition is a list of fields. Documents may inherit other documents, * implicitly acquiring their fields as it's own. If a document is not set to inherit * any document, it will always inherit the document "document.0".</p> * * @author Thomas Gundersen * @author bratseth */ // TODO: Remove header/body concept on Vespa 8 public class DocumentType extends StructuredDataType { private static final String ALL = "[all]"; public static final String DOCUMENT = "[document]"; public static final int classId = registerClass(Ids.document + 58, DocumentType.class); private StructDataType headerType; private StructDataType bodyType; private List<DocumentType> inherits = new ArrayList<>(1); private Map<String, Set<Field>> fieldSets = new HashMap<>(); /** * Creates a new document type and registers it with the document type manager. * This will be created as version 0 of this document type. * Implicitly registers this with the document type manager. * The document type id will be generated as a hash from the document type name. * * @param name The name of the new document type */ public DocumentType(String name) { this(name, new StructDataType(name + ".header"), new StructDataType(name + ".body")); } /** * Creates a new document type and registers it with the document type manager. * Implicitly registers this with the document type manager. * The document type id will be generated as a hash from the document type name. * * @param name The name of the new document type * @param headerType The type of the header struct * @param bodyType The type of the body struct */ public DocumentType(String name, StructDataType headerType, StructDataType bodyType) { super(name); this.headerType = headerType; this.bodyType = bodyType; } @Override public DocumentType clone() { DocumentType type = (DocumentType) super.clone(); type.headerType = headerType.clone(); type.bodyType = bodyType.clone(); type.inherits = new ArrayList<>(inherits.size()); type.inherits.addAll(inherits); return type; } @Override public Document createFieldValue() { return new Document(this, (DocumentId) null); } @Override public Class getValueClass() { return Document.class; } @Override public boolean isValueCompatible(FieldValue value) { if (!(value instanceof Document)) { return false; } Document doc = (Document) value; if (doc.getDataType().inherits(this)) { //the value is of this type; or the supertype of the value is of this type, etc.... return true; } return false; } /** * Provides the Struct describing the fields in the document. * * @return a struct describing the document fields. */ public StructDataType contentStruct() { return headerType; } /** @deprecated use contentStruct instead */ @Deprecated // TODO: Remove on Vespa 8 public StructDataType getHeaderType() { return contentStruct(); } @Deprecated // TODO: Remove on Vespa 8 /** @deprecated use contentStruct instead */ public StructDataType getBodyType() { return bodyType; } @Override @SuppressWarnings("deprecation") protected void register(DocumentTypeManager manager, List<DataType> seenTypes) { seenTypes.add(this); for (DocumentType type : getInheritedTypes()) { if (!seenTypes.contains(type)) { type.register(manager, seenTypes); } } // Get parent fields into fields specified in this type StructDataType header = headerType.clone(); StructDataType body = bodyType.clone(); header.clearFields(); body.clearFields(); for (Field field : getAllUniqueFields()) { (field.isHeader() ? header : body).addField(field); } headerType.assign(header); bodyType.assign(body); if (!seenTypes.contains(headerType)) { headerType.register(manager, seenTypes); } if (!seenTypes.contains(bodyType)) { bodyType.register(manager, seenTypes); } manager.registerSingleType(this); } /** * Check if this document type has the given name, * or inherits from a type with that name. */ public boolean isA(String docTypeName) { if (getName().equalsIgnoreCase(docTypeName)) { return true; } for (DocumentType parent : inherits) { if (parent.isA(docTypeName)) { return true; } } return false; } /** * Adds an field that can be used with this document type. * * @param field the field to add */ @SuppressWarnings("deprecation") public void addField(Field field) { if (isRegistered()) { throw new IllegalStateException("You cannot add fields to a document type that is already registered."); } StructDataType struct = (field.isHeader() ? headerType : bodyType); struct.addField(field); } // Do not use, public only for testing public void addFieldSets(Map<String, Collection<String>> fieldSets) { for (Map.Entry<String, Collection<String>> entry : fieldSets.entrySet()) { Set<Field> fields = new LinkedHashSet<>(entry.getValue().size()); for (DocumentType parent : inherits) { Set<Field> parentFieldSet = parent.fieldSet(entry.getKey()); if (parentFieldSet != null) { fields.addAll(parentFieldSet); } } for (Field orderedField : getAllUniqueFields()) { if (entry.getValue().contains(orderedField.getName())) { fields.add(orderedField); } } this.fieldSets.put(entry.getKey(), ImmutableSet.copyOf(fields)); } if ( ! this.fieldSets.containsKey(ALL)) { this.fieldSets.put(ALL, getAllUniqueFields()); } } /** * Adds a new body field to this document type and returns the new field object * * @param name The name of the field to add * @param type The datatype of the field to add * @return The field created * TODO Fix searchdefinition so that exception can be thrown if filed is already registerd. */ public Field addField(String name, DataType type) { if (isRegistered()) { throw new IllegalStateException("You cannot add fields to a document type that is already registered."); } Field field = new Field(name, type, false); bodyType.addField(field); return field; } /** * Adds a new header field to this document type and returns the new field object * * @param name The name of the field to add * @param type The datatype of the field to add * @return The field created * TODO Fix searchdefinition so that exception can be thrown if filed is already registerd */ public Field addHeaderField(String name, DataType type) { if (isRegistered()) { throw new IllegalStateException("You cannot add fields to a document type that is already registered."); } Field field = new Field(name, type, true); headerType.addField(field); return field; } /** * Adds a document to the inherited document types of this. * If this type is already directly inherited, nothing is done * * @param type An already DocumentType object. */ public void inherit(DocumentType type) { //TODO: There is also a check like the following in SDDocumentType addField(), try to move that to this class' addField() to get it proper, // as this method is called only when the doc types are exported. verifyTypeConsistency(type); if (isRegistered()) { throw new IllegalStateException("You cannot add inheritance to a document type that is already registered."); } if (type == null) { throw new IllegalArgumentException("The document type cannot be null in inherit()"); } // If it inherits the exact same type if (inherits.contains(type)) return; // If we inherit a type, don't inherit the supertype if (inherits.size() == 1 && inherits.get(0).getDataTypeName().equals(new DataTypeName("document"))) { inherits.clear(); } inherits.add(type); } /** * Fail if the subtype changes the type of any equally named field. * * @param superType The supertype to verify against * TODO Add strict type checking no duplicate fields are allowed */ private void verifyTypeConsistency(DocumentType superType) { for (Field f : getAllUniqueFields()) { Field supField = superType.getField(f.getName()); if (supField != null) { if (!f.getDataType().equals(supField.getDataType())) { throw new IllegalArgumentException("Inheritance type mismatch: field \"" + f.getName() + "\" in datatype \"" + getName() + "\"" + " must have same datatype as in parent document type \"" + superType.getName() + "\""); } } } } /** * Returns the DocumentNames which are directly inherited by this * as a read-only collection. * If this document type does not explicitly inherit anything, the list will * contain the root type 'Document' * * @return a read-only list iterator containing the name Strings of the directly * inherited document types of this */ public Collection<DocumentType> getInheritedTypes() { return Collections.unmodifiableCollection(inherits); } public ListIterator<DataTypeName> inheritedIterator() { List<DataTypeName> names = new ArrayList<>(inherits.size()); for (DocumentType type : inherits) { names.add(type.getDataTypeName()); } return ImmutableList.copyOf(names).listIterator(); } /** * Return whether this document type inherits the given document type. * * @param superType The documenttype to check if it inherits. * @return true if it inherits the superType, false if not */ public boolean inherits(DocumentType superType) { if (equals(superType)) return true; for (DocumentType type : inherits) { if (type.inherits(superType)) return true; } return false; } /** * Gets the field matching a given name. * * @param name The name of a field. * @return Returns the matching field, or null if not found. */ public Field getField(String name) { Field field = headerType.getField(name); if (field == null) { field = bodyType.getField(name); } if (field == null && !isRegistered()) { for (DocumentType inheritedType : inherits) { field = inheritedType.getField(name); if (field != null) break; } } return field; } @Override public Field getField(int id) { Field field = headerType.getField(id); if (field == null) { field = bodyType.getField(id); } if (field == null && !isRegistered()) { for (DocumentType inheritedType : inherits) { field = inheritedType.getField(id); if (field != null) break; } } return field; } /** * Returns whether this type defines the given field name * * @param name The name of the field to check if it has * @return True if there is a field with the given name. */ public boolean hasField(String name) { return getField(name) != null; } public int getFieldCount() { return headerType.getFieldCount() + bodyType.getFieldCount(); } /** * Removes an field from the DocumentType. * * @param name The name of the field. * @return The field that was removed or null if it did not exist. */ public Field removeField(String name) { if (isRegistered()) { throw new IllegalStateException("You cannot remove fields from a document type that is already registered."); } Field field = headerType.removeField(name); if (field == null) { field = bodyType.removeField(name); } if (field == null) { for (DocumentType inheritedType : inherits) { field = inheritedType.removeField(name); if (field != null) break; } } return field; } /** * All fields defined in the document and its parents * This is for internal use * Use {@link #fieldSet()} instead or {@link #fieldSetAll()} if you really want all fields * @return All fields defined in the document and its parents */ @Override public Collection<Field> getFields() { Collection<Field> collection = new LinkedList<>(); for (DocumentType type : inherits) { collection.addAll(type.getFields()); } collection.addAll(headerType.getFields()); collection.addAll(bodyType.getFields()); return ImmutableList.copyOf(collection); } private Set<Field> getAllUniqueFields() { Map<String, Field> map = new LinkedHashMap<>(); for (Field field : getFields()) { // Uniqify on field name map.put(field.getName(), field); } return ImmutableSet.copyOf(map.values()); } /** * <p>Returns an ordered set snapshot of all fields of this documenttype, * <i>except the fields of Document</i>. * Only the overridden version will be returned for overridden fields.</p> * * <p>The fields of a document type has a well-defined order which is * exhibited in this set: * - Fields come in the order defined in the document type definition. * - The fields defined in inherited types come before those in * the document type itself. * - When a field in an inherited type is overridden, the value is overridden, * but not the ordering. * </p> * * @return an unmodifiable snapshot of the fields in this type */ public Set<Field> fieldSet() { return fieldSet(DOCUMENT); } /** * This is identical to {@link #fieldSet()} fieldSet}, but in addition extra hidden synthetic fields are returned. * @return an unmodifiable snapshot of the all fields in this type */ public Set<Field> fieldSetAll() { return fieldSet(ALL); } public Set<Field> fieldSet(String name) { return fieldSets.get(name); } /** * Returns an iterator over all fields in this documenttype * * @return An iterator for iterating the fields in this documenttype. */ public Iterator<Field> fieldIteratorThisTypeOnly() { return new Iterator<>() { Iterator<Field> headerIt = headerType.getFields().iterator(); Iterator<Field> bodyIt = bodyType.getFields().iterator(); public boolean hasNext() { if (headerIt != null) { if (headerIt.hasNext()) return true; headerIt = null; } return bodyIt.hasNext(); } public Field next() { return (headerIt != null ? headerIt.next() : bodyIt.next()); } public void remove() { if (headerIt != null) { headerIt.remove(); } else { bodyIt.remove(); } } }; } public boolean equals(Object o) { if (!(o instanceof DocumentType)) return false; DocumentType other = (DocumentType) o; // Ignore whether one of them have added inheritance to super Document.0 type if (super.equals(o) && headerType.equals(other.headerType) && bodyType.equals(other.bodyType)) { if ((inherits.size() > 1 || other.inherits.size() > 1) || (inherits.size() == 1 && other.inherits.size() == 1)) { return inherits.equals(other.inherits); } return !(((inherits.size() == 1) && !inherits.get(0).getDataTypeName().equals(new DataTypeName("document"))) || ((other.inherits.size() == 1) && !other.inherits.get(0).getDataTypeName().equals(new DataTypeName("document")))); } return false; } public int hashCode() { return super.hashCode() + headerType.hashCode() + bodyType.hashCode() + inherits.hashCode(); } @Override public void onSerialize(Serializer target) { if (target instanceof DocumentWriter) { ((DocumentWriter) target).write(this); } // TODO: what if it's not a DocumentWriter? } @Override public void visitMembers(ObjectVisitor visitor) { super.visitMembers(visitor); visitor.visit("headertype", headerType); visitor.visit("bodytype", bodyType); visitor.visit("inherits", inherits); } }
35.062264
144
0.606791