text
stringlengths
10
2.72M
package com.nag.android.kurikuri; import java.util.HashMap; import java.util.Map; import com.nag.android.kurikri.R; import android.content.Context; import android.media.AudioManager; import android.media.SoundPool; public class AppPlayer { private static final int NUM_OF_SOUND = CONTENTSID.values().length; private boolean mute = false; public enum CONTENTSID{ KURI, CLEAR } private final SoundPool spool; private Map<CONTENTSID, Integer> contents = new HashMap<CONTENTSID, Integer>(); public AppPlayer(Context context){ spool = new SoundPool(NUM_OF_SOUND, AudioManager.STREAM_MUSIC, 0); contents.put(CONTENTSID.KURI, spool.load(context, R.raw.short01a, 1)); contents.put(CONTENTSID.CLEAR, spool.load(context, R.raw.clear1, 1)); } public void mute(boolean mute){ this.mute = mute; } public void play(CONTENTSID id, float left, float right){ if(!mute){ spool.play(contents.get(id), left, right, 1, 0, 1f); } } }
package net.imglib2.trainable_segmention.pixel_feature.filter; import net.imglib2.trainable_segmention.pixel_feature.filter.dog2.DifferenceOfGaussiansFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.gauss.GaussianBlurFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.gradient.GaussianGradientMagnitudeFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.hessian.HessianEigenvaluesFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.laplacian.LaplacianOfGaussianFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.lipschitz.LipschitzFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.stats.SingleSphereShapedFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.gabor.GaborFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.gradient.SobelGradientFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.stats.SphereShapedFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.stats.StatisticsFeature; import net.imglib2.trainable_segmention.pixel_feature.filter.structure.StructureTensorEigenvaluesFeature; import net.imglib2.trainable_segmention.pixel_feature.settings.FeatureSetting; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; /** * @author Matthias Arzt */ public class GroupedFeatures { @Deprecated public static FeatureSetting gabor() { return createFeature(GaborFeature.class, "legacyNormalize", FALSE); } @Deprecated public static FeatureSetting legacyGabor() { return createFeature(GaborFeature.class, "legacyNormalize", TRUE); } public static FeatureSetting gauss() { return createFeature(GaussianBlurFeature.class); } public static FeatureSetting gradient() { return createFeature(GaussianGradientMagnitudeFeature.class); } public static FeatureSetting laplacian() { return createFeature(LaplacianOfGaussianFeature.class); } @Deprecated public static FeatureSetting lipschitz(long border) { return createFeature(LipschitzFeature.class, "border", border); } public static FeatureSetting hessian() { return createFeature(HessianEigenvaluesFeature.class); } public static FeatureSetting differenceOfGaussians() { return createFeature(DifferenceOfGaussiansFeature.class); } public static FeatureSetting structureTensor() { return createFeature(StructureTensorEigenvaluesFeature.class); } public static FeatureSetting statistics() { return statistics(true, true, true, true); } public static FeatureSetting min() { return statistics(true, false, false, false); } public static FeatureSetting max() { return statistics(false, true, false, false); } public static FeatureSetting mean() { return statistics(false, false, true, false); } public static FeatureSetting variance() { return statistics(false, false, false, true); } private static FeatureSetting statistics(boolean min, boolean max, boolean mean, boolean variance) { return createFeature(StatisticsFeature.class, "min", min, "max", max, "mean", mean, "variance", variance); } private static FeatureSetting createFeature(Class<? extends FeatureOp> aClass, Object... args) { return new FeatureSetting(aClass, args); } }
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.limegroup.gnutella.gui; import java.awt.Frame; import java.lang.reflect.InvocationTargetException; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.plaf.basic.BasicHTML; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.limewire.i18n.I18nMarker; import org.limewire.service.ErrorService; import org.limewire.util.I18NConvert; import org.limewire.util.OSUtils; import org.limewire.util.Stopwatch; import org.limewire.util.SystemUtils; import com.frostwire.AzureusStarter; import com.frostwire.util.UserAgentGenerator; import com.limegroup.gnutella.ExternalControl; import com.limegroup.gnutella.LimeCoreGlue; import com.limegroup.gnutella.LimeCoreGlue.InstallFailedException; import com.limegroup.gnutella.LimeWireCore; import com.limegroup.gnutella.gui.bugs.BugManager; import com.limegroup.gnutella.gui.init.SetupManager; import com.limegroup.gnutella.gui.notify.NotifyUserProxy; import com.limegroup.gnutella.gui.util.BackgroundExecutorService; import com.limegroup.gnutella.settings.ApplicationSettings; import com.limegroup.gnutella.settings.StartupSettings; import com.limegroup.gnutella.util.MacOSXUtils; /** Initializes (creates, starts, & displays) the LimeWire Core & UI. */ public final class Initializer { private final Log LOG; /** True if is running from a system startup. */ private volatile boolean isStartup = false; /** The start memory -- only set if debugging. */ private long startMemory; /** A stopwatch for debug logging. */ private final Stopwatch stopwatch; Initializer() { LOG = LogFactory.getLog(Initializer.class); if(LOG.isTraceEnabled()) { startMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.trace("START Initializer, using: " + startMemory + " memory"); } stopwatch = new Stopwatch(LOG); } /** * Initializes all of the necessary application classes. * * If this throws any exceptions, then LimeWire was not able to construct * properly and must be shut down. */ void initialize(String args[], Frame awtSplash) throws Throwable { // ** THE VERY BEGINNING -- DO NOT ADD THINGS BEFORE THIS ** //System.out.println("Initializer.initialize() preinit()"); preinit(); // Various startup tasks... //System.out.println("Initializer.initialize() setup callbacks and listeners"); setupCallbacksAndListeners(); validateStartup(args); // Creates LimeWire itself. //System.out.println("Initializer.initialize() create Limewire"); LimeWireGUI limewireGUI = createLimeWire(); LimeWireCore limeWireCore = limewireGUI.getLimeWireCore(); // Various tasks that can be done after core is glued & started. //System.out.println("Initializer.initialize() glue core"); glueCore(limeWireCore); // Validate any arguments or properties outside of the LW environment. //System.out.println("Initializer.initialize() run external checks"); runExternalChecks(limeWireCore, args); limeWireCore.getExternalControl().startServer(); // Starts some system monitoring for deadlocks. //System.out.println("Initializer.initialize() monitor deadlocks"); DeadlockSupport.startDeadlockMonitoring(); //stopwatch.resetAndLog("Start deadlock monitor"); // Installs properties & resources. //System.out.println("Initializer.initialize() install properties"); installProperties(); installResources(); // Construct the SetupManager, which may or may not be shown. final SetupManager setupManager = new SetupManager(); //stopwatch.resetAndLog("construct SetupManager"); // Move from the AWT splash to the Swing splash & start early core. //System.out.println("Initializer.initialize() switch splashes"); switchSplashes(awtSplash); startEarlyCore(setupManager, limeWireCore); // Initialize early UI components, display the setup manager (if necessary), // and ensure the save directory is valid. //System.out.println("Initializer.initialize() init early UI"); initializeEarlyUI(); startSetupManager(setupManager); validateSaveDirectory(); // Load the UI, system tray & notification handlers, // and hide the splash screen & display the UI. //System.out.println("Initializer.initialize() load UI"); loadUI(); loadTrayAndNotifications(); hideSplashAndShowUI(); // Initialize late tasks, like Icon initialization & install listeners. loadLateTasksForUI(); // Start the core & run any queued control requests, and load DAAP. //System.out.println("Initializer.initialize() start core"); startCore(limeWireCore); runQueuedRequests(limeWireCore); startAzureusCore(); // Run any after-init tasks. postinit(); } /** Initializes the very early things. */ /* * DO NOT CHANGE THIS WITHOUT KNOWING WHAT YOU'RE DOING. * PREINSTALL MUST BE DONE BEFORE ANYTHING ELSE IS REFERENCED. * (Because it sets the preference directory in CommonUtils.) */ private void preinit() { // Make sure the settings directory is set. try { LimeCoreGlue.preinstall(); } catch(InstallFailedException ife) { failPreferencesPermissions(); } } /** Installs all callbacks & listeners. */ private void setupCallbacksAndListeners() { // Set the error handler so we can receive core errors. ErrorService.setErrorCallback(new ErrorHandler()); //stopwatch.resetAndLog("ErrorHandler install"); // Set the messaging handler so we can receive core messages org.limewire.service.MessageService.setCallback(new MessageHandler()); //stopwatch.resetAndLog("MessageHandler install"); // Set the default event error handler so we can receive uncaught // AWT errors. DefaultErrorCatcher.install(); //stopwatch.resetAndLog("DefaultErrorCatcher install"); if (OSUtils.isMacOSX()) { // Raise the number of allowed concurrent open files to 1024. SystemUtils.setOpenFileLimit(1024); stopwatch.resetAndLog("Open file limit raise"); MacEventHandler.instance(); stopwatch.resetAndLog("MacEventHandler instance"); } } /** * Ensures this should continue running, by checking * for expiration failures or startup settings. */ private void validateStartup(String[] args) { // Yield so any other events can be run to determine // startup status, but only if we're going to possibly // be starting... if(StartupSettings.RUN_ON_STARTUP.getValue()) { stopwatch.reset(); Thread.yield(); //stopwatch.resetAndLog("Thread yield"); } if ( OSUtils.isMacOSX() ) { MacOSXUtils.setLoginStatus(StartupSettings.RUN_ON_STARTUP.getValue()); } if (args.length >= 1 && "-startup".equals(args[0])) isStartup = true; if (isStartup) { // if the user doesn't want to start on system startup, exit the // JVM immediately if(!StartupSettings.RUN_ON_STARTUP.getValue()) System.exit(0); } } /** Wires together LimeWire. */ private LimeWireGUI createLimeWire() { LimeWireGUI limeWireGUI = LimeWireModule.instance().getLimeWireGUIModule().getLimeWireGUI(); return limeWireGUI; } /** Wires together remaining non-Guiced pieces. */ private void glueCore(LimeWireCore limeWireCore) { limeWireCore.getLimeCoreGlue().install(); } /** * Initializes any code that is dependent on external controls. * Specifically, GURLHandler & MacEventHandler on OS X, * ensuring that multiple LimeWire's can't run at once, * and processing any arguments that were passed to LimeWire. */ private void runExternalChecks(LimeWireCore limeWireCore, String[] args) { ExternalControl externalControl = limeWireCore.getExternalControl(); if(OSUtils.isMacOSX()) { GURLHandler.getInstance().enable(externalControl); MacEventHandler.instance().enable(externalControl, this); } // Test for preexisting FrostWire and pass it a magnet URL if one // has been passed in. if (args.length > 0 && !args[0].equals("-startup")) { String arg = externalControl.preprocessArgs(args); externalControl.checkForActiveFrostWire(arg); externalControl.enqueueControlRequest(arg); } else if (!StartupSettings.ALLOW_MULTIPLE_INSTANCES.getValue()) { // if we don't want multiple instances, we need to check if // frostwire is already active. externalControl.checkForActiveFrostWire(); } } /** Installs any system properties. */ private void installProperties() { System.setProperty("http.agent", UserAgentGenerator.getUserAgent()); stopwatch.resetAndLog("set system properties"); if (OSUtils.isMacOSX()) { System.setProperty("apple.laf.useScreenMenuBar", "true"); stopwatch.resetAndLog("set OSX properties"); } } /** Sets up ResourceManager. */ private void installResources() { GUIMediator.safeInvokeAndWait(new Runnable() { public void run() { //stopwatch.resetAndLog("wait for event queue"); ResourceManager.instance(); //stopwatch.resetAndLog("ResourceManager instance"); } }); //stopwatch.resetAndLog("come back from evt queue"); } /** Starts any early core-related functionality. */ private void startEarlyCore(SetupManager setupManager, LimeWireCore limeWireCore) { // Add this running program to the Windows Firewall Exceptions list boolean inFirewallException = FirewallUtils.addToFirewall(); //stopwatch.resetAndLog("add firewall exception"); if(!inFirewallException) { limeWireCore.getLifecycleManager().loadBackgroundTasks(); //stopwatch.resetAndLog("load background tasks"); } } /** Switches from the AWT splash to the Swing splash. */ private void switchSplashes(Frame awtSplash) { GUIMediator.safeInvokeAndWait(new Runnable() { public void run() { // Show the splash screen if we're not starting automatically on // system startup if(!isStartup) { SplashWindow.instance().begin(); //stopwatch.resetAndLog("begin splash window"); } } }); if(awtSplash != null) { awtSplash.dispose(); //stopwatch.resetAndLog("dispose AWT splash"); } } /** Initializes any early UI tasks, such as HTML loading & the Bug Manager. */ private void initializeEarlyUI() { // Load up the HTML engine. GUIMediator.setSplashScreenString(I18n.tr("Loading HTML Engine...")); //stopwatch.resetAndLog("update splash for HTML engine"); GUIMediator.safeInvokeAndWait(new Runnable() { public void run() { //stopwatch.resetAndLog("enter evt queue"); JLabel label = new JLabel(); // setting font and color to null to minimize generated css // script // which causes a parser exception under circumstances label.setFont(null); label.setForeground(null); BasicHTML.createHTMLView(label, "<html>.</html>"); //stopwatch.resetAndLog("create HTML view"); } }); //stopwatch.resetAndLog("return from evt queue"); // Initialize the bug manager BugManager.instance(); //stopwatch.resetAndLog("BugManager instance"); } /** Starts the SetupManager, if necessary. */ private void startSetupManager(final SetupManager setupManager) { // Run through the initialization sequence -- this must always be // called before GUIMediator constructs the LibraryTree! GUIMediator.safeInvokeAndWait(new Runnable() { public void run() { //stopwatch.resetAndLog("event evt queue"); // Then create the setup manager if needed. setupManager.createIfNeeded(); //stopwatch.resetAndLog("create setupManager if needed"); } }); //stopwatch.resetAndLog("return from evt queue"); } /** Ensures the save directory is valid. */ private void validateSaveDirectory() { // Make sure the save directory is valid. SaveDirectoryHandler.handleSaveDirectory(); //stopwatch.resetAndLog("check save directory validity"); } /** Loads the UI. */ private void loadUI() { GUIMediator.setSplashScreenString(I18n.tr("Loading User Interface...")); stopwatch.resetAndLog("update splash for UI"); GUIMediator.safeInvokeAndWait(new Runnable() { public void run() { // stopwatch.resetAndLog("enter evt queue"); GUIMediator.instance(); // stopwatch.resetAndLog("GUImediator instance"); } }); GUIMediator.setSplashScreenString(I18n.tr("Loading Core Components...")); //stopwatch.resetAndLog("update splash for core"); } /** Loads the system tray & other notifications. */ private void loadTrayAndNotifications() { // Create the user desktop notifier object. // This must be done before the GUI is made visible, // otherwise the user can close it and not see the // tray icon. GUIMediator.safeInvokeAndWait(new Runnable() { public void run() { //stopwatch.resetAndLog("enter evt queue"); NotifyUserProxy.instance(); //stopwatch.resetAndLog("NotifYUserProxy instance"); if (!ApplicationSettings.DISPLAY_TRAY_ICON.getValue()) NotifyUserProxy.instance().hideTrayIcon(); SettingsWarningManager.checkSettingsLoadSaveFailure(); //stopwatch.resetAndLog("end notify runner"); } }); //stopwatch.resetAndLog("return from evt queue"); } /** Hides the splash screen and sets the UI for allowing viz. */ private void hideSplashAndShowUI() { // Hide the splash screen and recycle its memory. if(!isStartup) { SplashWindow.instance().dispose(); stopwatch.resetAndLog("hide splash"); } GUIMediator.allowVisibility(); stopwatch.resetAndLog("allow viz"); // Make the GUI visible. if(!isStartup) { GUIMediator.setAppVisible(true); stopwatch.resetAndLog("set app visible TRUE"); } else { GUIMediator.startupHidden(); stopwatch.resetAndLog("start hidden"); } } /** Runs any late UI tasks, such as initializing Icons, I18n support. */ private void loadLateTasksForUI() { // Initialize IconManager. //GUIMediator.setSplashScreenString(I18n.tr("Loading Icons...")); GUIMediator.safeInvokeAndWait(new Runnable() { public void run() { GUIMediator.setSplashScreenString(I18n.tr("Loading Icons...")); IconManager.instance(); } }); stopwatch.resetAndLog("IconManager instance"); // Touch the I18N stuff to ensure it loads properly. GUIMediator.setSplashScreenString(I18n.tr("Loading Internationalization Support...")); I18NConvert.instance(); stopwatch.resetAndLog("I18nConvert instance"); } /** Starts the core. */ private void startCore(LimeWireCore limeWireCore) { // Start the backend threads. Note that the GUI is not yet visible, // but it needs to be constructed at this point limeWireCore.getLifecycleManager().start(); stopwatch.resetAndLog("lifecycle manager start"); // Instruct the gui to perform tasks that can only be performed // after the backend has been constructed. GUIMediator.instance().coreInitialized(); GUIMediator.setSplashScreenString(I18nMarker.marktr("Loading Old Downloads...")); limeWireCore.getDownloadManager().loadSavedDownloadsAndScheduleWriting(); stopwatch.resetAndLog("core initialized"); } /** Start Azureus Core. */ private void startAzureusCore() { BackgroundExecutorService.schedule(new Runnable() { public void run() { AzureusStarter.start(); } }); } /** Runs control requests that we queued early in initializing. */ private void runQueuedRequests(LimeWireCore limeWireCore) { // Activate a download for magnet URL locally if one exists limeWireCore.getExternalControl().runQueuedControlRequest(); stopwatch.resetAndLog("run queued control req"); } /** Runs post initialization tasks. */ private void postinit() { // Tell the GUI that loading is all done. GUIMediator.instance().loadFinished(); stopwatch.resetAndLog("load finished"); if(LOG.isTraceEnabled()) { long stopMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.trace("STOP Initializer, using: " + stopMemory + " memory, consumed: " + (stopMemory - startMemory)); } } /** * Sets the startup property to be true. */ void setStartup() { isStartup = true; } /** Fails because preferences can't be set. */ private void failPreferencesPermissions() { fail(I18nMarker .marktr("FrostWire could not create a temporary preferences folder.\n\nThis is generally caused by a lack of permissions. Please make sure that FrostWire (and you) have access to create files/folders on your computer. If the problem persists, please visit www.frostwire.com and click the 'Support' link.\n\nFrostWire will now exit. Thank You.")); } /** Shows a msg & fails. */ private void fail(final String msgKey) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { JOptionPane.showMessageDialog(null, new MultiLineLabel(I18n.tr(msgKey), 400), I18n.tr("Error"), JOptionPane.ERROR_MESSAGE); } }); } catch (InterruptedException ignored) { } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if(cause instanceof RuntimeException) throw (RuntimeException)cause; if(cause instanceof Error) throw (Error)cause; throw new RuntimeException(cause); } System.exit(1); } }
package adapter; import java.util.Enumeration; import java.util.Iterator; public class IterationAdapter<T> implements Enumeration<T> { Iterator<T> myiterator; public IterationAdapter(Iterator<T> myiterator) { this.myiterator=myiterator; } @Override public boolean hasMoreElements() { // TODO Auto-generated method stub return myiterator.hasNext(); } @Override public T nextElement() { // TODO Auto-generated method stub return myiterator.next(); } }
package pojo.DAO; import org.junit.Test; import pojo.valueObject.domain.ProjectVO; import pojo.valueObject.domain.StudentVO; import pojo.valueObject.domain.TeacherVO; import tool.BeanFactory; import static org.junit.Assert.*; /** * Created by geyao on 2017/3/2. */ public class ProjectDAOTest { @Test public void getProjectVO() throws Exception { } @Test public void getTeacherProjectVOList() throws Exception { } @Test public void getTeacherProjectVOListByGrade() throws Exception { } @Test public void getStudentProjectVOList() throws Exception { ProjectDAO projectDAO = BeanFactory.getBean("projectDAO", ProjectDAO.class); StudentDAO studentDAO = BeanFactory.getBean("studentDAO", StudentDAO.class); StudentVO studentVO = studentDAO.getStudentInfoByStudentId(2); System.out.println(projectDAO.getStudentProjectVOList(studentVO)); } // @Test // public void getProjectVO() throws Exception { // // } @Test public void addProjectVO() throws Exception { // ProjectDAO projectDAO = BeanFactory.getBean("projectDAO", ProjectDAO.class); // ProjectVO projectVO = BeanFactory.getBean("projectVO", ProjectVO.class); // TeacherDAO teacherDAO = BeanFactory.getBean("teacherDAO", TeacherDAO.class); // TeacherVO teacherVO= teacherDAO.getTeacherInfo(1); // StudentDAO studentDAO = BeanFactory.getBean("studentDAO", StudentDAO.class); // StudentVO studentVO = studentDAO.getStudentInfoByStudentId(2); // // projectVO.setTeacherVO(teacherVO); // projectVO.setCreatorUserVO(studentVO); // projectVO.setAge("20170302测试"); // // projectDAO.addProjectVO(projectVO); // // System.out.println(projectDAO.getProjectVO(projectVO.getId())); } }
package com.dassa.controller.driver; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.dassa.common.FileCommon; import com.dassa.service.DriverService; import com.dassa.vo.UserVO; @Controller @RequestMapping("/driver") public class DriverMypageController { @Resource private DriverService driverService; //기사설정 페이지(myapge) @RequestMapping(value="/mypage") public String DriverSetting(HttpSession session,Model model) throws Exception { UserVO userVO=(UserVO)session.getAttribute("user"); UserVO user=driverService.selectOne(userVO); model.addAttribute("user", user); //user값 보내기 requestParam과 같은기능 model.addAttribute("subNavi", 1); return "driver/mypage/driverMypage"; } //정보수정 업데이트 @RequestMapping(value="/mypageUpdate") @ResponseBody public String DriverMypageUpdate(UserVO userVO,HttpServletRequest request,MultipartFile fileImg) throws Exception { System.out.println(fileImg); int result=0; result=driverService.driverMypageUpdateText(userVO); if(!fileImg.getOriginalFilename().equals("")){ String[] fileInfo = FileCommon.fileUp(fileImg,request, "driver"); userVO.setProFilename(fileInfo[0]); userVO.setProFilepath(fileInfo[1]); result=driverService.driverMypageUpdate(userVO); } if(result>0) { System.out.println("수정성공"); }else { System.out.println("수정실패"); } return "redirect:/driver/home"; } //이사 최종완료 @RequestMapping("/driverMoveFinalCompletion") public String driverMoveFinalCompletion(int applyIdx) throws Exception { driverService.driverMoveFinalCompletion(applyIdx); return "driver/manager/driverMove"; } }
package com.qunli.network; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import com.bcq.oklib.base.BaseActivity; public class TestFragmentActivity extends BaseActivity { @Override public int setLayoutId() { return R.layout.activity_fragment_lay; } @Override public void init() { TestFragment fragment = new TestFragment(); FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); transaction.add(R.id.ll_root, fragment); transaction.commitAllowingStateLoss(); } }
// ********************************************************** // 1. 제 목: // 2. 프로그램명: SulmunSubjUserBean.java // 3. 개 요: // 4. 환 경: JDK 1.3 // 5. 버 젼: 0.1 // 6. 작 성: Administrator 2003-08-18 // 7. 수 정: // // ********************************************************** package com.ziaan.research; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.ErrorManager; import com.ziaan.library.FormatDate; import com.ziaan.library.ListSet; import com.ziaan.library.Log; import com.ziaan.library.RequestBox; import com.ziaan.library.SQLString; import com.ziaan.library.StringManager; /** * @author Administrator * * To change the template for this generated type comment go to * Window > Preferences > Java > Code Generation > Code and Comments */ public class SulmunSubjUserBean { public SulmunSubjUserBean() { } /** 과목 설문 등록 @param box receive from the form object and session @return int */ public int InsertSulmunUserResult(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; ResultSet rs = null; ListSet ls = null; String sql = ""; String sql1 = ""; String sql2 = ""; int isOk = 2; int isOk1 = 0; String v_grcode = box.getString("p_grcode"); String v_subj = box.getString("p_subj"); String v_gyear = box.getString("p_gyear"); String v_subjseq = box.getString("p_subjseq"); int v_sulpapernum= box.getInt("p_sulpapernum"); //String v_userid = box.getString("p_userid"); String v_userid = box.getSession("userid"); String v_sulnums = box.getString("p_sulnums"); // 문제조합 String v_answers = box.getString("p_answers"); // 정답조합 String v_luserid = box.getSession("userid"); int i_code1 = 0; // 과목만족도 int i_code2 = 0; // 내용이해도 int i_code3 = 0; // 과목난이도 int i_code4 = 0; // 업무활용도 int i_code5 = 0; // 질문대응 int i_code6 = 0; // 장애대응 int i_code7 = 0; // 강사만족도 int i_code8 = 0; // 기타 double i_code1_avg = 0; double i_code2_avg = 0; double i_code3_avg = 0; double i_code4_avg = 0; double i_code5_avg = 0; double i_code6_avg = 0; double i_code7_avg = 0; double i_code8_avg = 0; int i_code1_cnt = 0; int i_code2_cnt = 0; int i_code3_cnt = 0; int i_code4_cnt = 0; int i_code5_cnt = 0; int i_code6_cnt = 0; int i_code7_cnt = 0; int i_code8_cnt = 0; String s_distcode10 = ""; // 소감 try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); // 설문기간 확인 // isOk = getSulmunGigan(box); // 설문 분류별로 척도점수 합계 String[] arr_sulnums = v_sulnums.split("\\,"); String[] arr_answers = v_answers.split("\\,"); for ( int i = 0; i<arr_sulnums.length; i++ ) { // 문제당 분류코드 String ss_distcode = ""; sql = " select distcode from TZ_SUL where subj='ALL' AND GRCODE='ALL' and sulnum = ? "; pstmt1 = connMgr.prepareStatement(sql); pstmt1.setInt(1, Integer.parseInt(arr_sulnums[i])); rs = pstmt1.executeQuery(); if ( rs.next() ) { ss_distcode = rs.getString("distcode"); } if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e ) { } } if ( rs != null ) { try { rs.close(); } catch ( Exception e ) { } } // 10.소감 if ( ss_distcode.equals("10") ) { s_distcode10 = arr_answers[i]; } // 객관식 답 int i_arr_answers = 0; try { i_arr_answers = Integer.parseInt(arr_answers[i]); } catch ( Exception e ) { } if ( i_arr_answers != 0) { // 문제,보기당 보기점수 int ss_selpoint = 0; sql = " select selpoint from TZ_SULSEL where subj='ALL' AND GRCODE='ALL' AND SULNUM=? AND SELNUM=? "; pstmt1 = connMgr.prepareStatement(sql); pstmt1.setInt(1, Integer.parseInt(arr_sulnums[i])); pstmt1.setInt(2, i_arr_answers); rs = pstmt1.executeQuery(); if ( rs.next() ) { ss_selpoint = rs.getInt("selpoint"); } if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e ) { } } if ( rs != null ) { try { rs.close(); } catch ( Exception e ) { } } // 계산 if ( ss_distcode.equals("1") ) { i_code1 +=ss_selpoint; i_code1_cnt++; } if ( ss_distcode.equals("2") ) { i_code2 +=ss_selpoint; i_code2_cnt++; } if ( ss_distcode.equals("3") ) { i_code3 +=ss_selpoint; i_code3_cnt++; } if ( ss_distcode.equals("4") ) { i_code4 +=ss_selpoint; i_code4_cnt++; } if ( ss_distcode.equals("5") ) { i_code5 +=ss_selpoint; i_code5_cnt++; } if ( ss_distcode.equals("6") ) { i_code6 +=ss_selpoint; i_code6_cnt++; } if ( ss_distcode.equals("7") ) { i_code7 +=ss_selpoint; i_code7_cnt++; } if ( ss_distcode.equals("8") ) { i_code8 +=ss_selpoint; i_code8_cnt++; } } } // for문종료 if ( i_code1_cnt != 0)i_code1_avg = i_code1/(double)i_code1_cnt; if ( i_code2_cnt != 0)i_code2_avg = i_code2/(double)i_code2_cnt; if ( i_code3_cnt != 0)i_code3_avg = i_code3/(double)i_code3_cnt; if ( i_code4_cnt != 0)i_code4_avg = i_code4/(double)i_code4_cnt; if ( i_code5_cnt != 0)i_code5_avg = i_code5/(double)i_code5_cnt; if ( i_code6_cnt != 0)i_code6_avg = i_code6/(double)i_code6_cnt; if ( i_code7_cnt != 0)i_code7_avg = i_code7/(double)i_code7_cnt; if ( i_code8_cnt != 0)i_code8_avg = i_code8/(double)i_code8_cnt; if ( isOk == 2) { sql1 = "select userid from TZ_SULEACH"; sql1 += " where subj = ? and grcode = ? and year = ? and subjseq = ? and sulpapernum = ? and userid = ? "; pstmt1 = connMgr.prepareStatement(sql1); pstmt1.setString( 1, v_subj); pstmt1.setString( 2, v_grcode); pstmt1.setString( 3, v_gyear); pstmt1.setString( 4, v_subjseq); pstmt1.setInt( 5, v_sulpapernum); pstmt1.setString( 6, v_userid); try { rs = pstmt1.executeQuery(); if ( !rs.next() ) { // 과거에 등록된 userid 를 확인하고 없을 경우에만 등록 isOk1 = InsertTZ_suleach(connMgr, v_subj , v_grcode, v_gyear, v_subjseq, v_sulpapernum, v_userid, v_sulnums, v_answers, v_luserid, i_code1, i_code2, i_code3, i_code4, i_code5, i_code6, i_code7, i_code8, i_code1_avg, i_code2_avg, i_code3_avg, i_code4_avg, i_code5_avg, i_code6_avg, i_code7_avg, i_code8_avg, s_distcode10); } else { isOk1 = 4; // 이미 설문에 응시하였습니다. } } catch ( Exception e ) { } finally { if ( rs != null ) { try { rs.close(); } catch ( Exception e ) { } }} } } catch ( Exception ex ) { isOk1 = 0; if ( connMgr != null ) { try { connMgr.rollback(); } catch ( Exception e10 ) { } } ErrorManager.getErrorStackTrace(ex); throw new Exception(ex.getMessage() ); } finally { if ( isOk1 > 0 ) { connMgr.commit(); } if ( pstmt1 != null ) { try { pstmt1.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk1; } /** 설문기간 확인 @param box receive from the form object and session @return int */ public int getSulmunGigan(RequestBox box) throws Exception { SulmunSubjPaperBean bean = null; DataBox dbox0 = null; String v_sulstart = ""; String v_sulend = ""; int v_update = 0; try { bean = new SulmunSubjPaperBean(); dbox0 = bean.getPaperData(box); v_sulstart = FormatDate.getFormatDate(dbox0.getString("d_sulstart"),"yyyy.MM.dd"); v_sulend = FormatDate.getFormatDate(dbox0.getString("d_sulend"),"yyyy.MM.dd"); if ( dbox0.getInt("d_sulpapernum") > 0) { long v_fstart = Long.parseLong(dbox0.getString("d_sulstart") ); long v_fend = Long.parseLong(dbox0.getString("d_sulend") ); java.util.Date d_now = new java.util.Date(); String d_year = String.valueOf(d_now.getYear() +1900); String d_month = String.valueOf(d_now.getMonth() +1); String d_day = String.valueOf(d_now.getDate() ); if ( d_month.length() == 1) { d_month = "0" + d_month; } if ( d_day.length() == 1) { d_day = "0" + d_day; } long v_now = Long.parseLong(d_year +d_month +d_day); if ( v_fstart > v_now) { v_update = 1; // 설문 전 } else if ( v_now > v_fend) { v_update = 3; // 설문 완료 } else if ( v_fstart <= v_now && v_now < v_fend) { v_update = 2; // 설문 중 } } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception(ex.getMessage() ); } return v_update; } /** 과목 설문 등록 @param box receive from the form object and session @return int */ public int InsertTZ_suleach(DBConnectionManager connMgr, String p_subj, String p_grcode, String p_gyear, String p_subjseq, int p_sulpapernum, String p_userid, String p_sulnums, String p_answers, String p_luserid, int i_code1, int i_code2, int i_code3, int i_code4, int i_code5,int i_code6,int i_code7, int i_code8, double i_code1_avg, double i_code2_avg, double i_code3_avg, double i_code4_avg, double i_code5_avg, double i_code6_avg, double i_code7_avg, double i_code8_avg, String s_distcode10) throws Exception { PreparedStatement pstmt = null; String sql = ""; int isOk = 0; try { // insert TZ_SULEACH table sql = "insert into TZ_SULEACH "; sql += " (subj, grcode, year, subjseq, sulpapernum, "; sql += " userid, sulnums, answers, luserid, ldate, "; sql += " distcode1, distcode2, distcode3, distcode4, distcode5, distcode6, distcode7, distcode8, "; sql += " distcode1_avg, distcode2_avg, distcode3_avg , distcode4_avg, distcode5_avg, distcode6_avg , distcode7_avg, distcode8_avg, distcode10 "; sql += " )values( "; sql += " ?, ?, ?, ?, ?, "; sql += " ?, ?, ?, ?, ?, "; sql += " ?, ?, ?, ?, ?, ?, ?, ? , "; sql += " ?, ?, ?, ?, ?, ?, ?, ? , ? ) "; pstmt = connMgr.prepareStatement(sql); pstmt.setString( 1, p_subj); pstmt.setString( 2, p_grcode); pstmt.setString( 3, p_gyear); pstmt.setString( 4, p_subjseq); pstmt.setInt ( 5, p_sulpapernum); pstmt.setString( 6, p_userid); pstmt.setString( 7, p_sulnums); pstmt.setString( 8, p_answers); pstmt.setString( 9, p_luserid); pstmt.setString(10, FormatDate.getDate("yyyyMMddHHmmss") ); pstmt.setInt (11, i_code1); pstmt.setInt (12, i_code2); pstmt.setInt (13, i_code3); pstmt.setInt (14, i_code4); pstmt.setInt (15, i_code5); pstmt.setInt (16, i_code6); pstmt.setInt (17, i_code7); pstmt.setInt (18, i_code8); pstmt.setDouble(19, i_code1_avg); pstmt.setDouble(20, i_code2_avg); pstmt.setDouble(21, i_code3_avg); pstmt.setDouble(22, i_code4_avg); pstmt.setDouble(23, i_code5_avg); pstmt.setDouble(24, i_code6_avg); pstmt.setDouble(25, i_code7_avg); pstmt.setDouble(26, i_code8_avg); pstmt.setString(27, s_distcode10); isOk = pstmt.executeUpdate(); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e ) { } } } return isOk; } /** 설문 대상자 리스트 @param box receive from the form object and session @return ArrayList 설문 대상자 */ public DataBox SelectUserPaperResult(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; DataBox dbox = null; String sql = ""; String v_grcode = box.getString("p_grcode"); String v_subj = box.getStringDefault("p_subj", "TARGET"); String v_gyear = box.getString("p_gyear"); String v_subjseq = box.getStringDefault("p_subjseq","0001"); int v_sulpapernum = box.getInt("p_sulpapernum"); String v_userid = box.getString("p_userid"); try { connMgr = new DBConnectionManager(); sql = "select sulnums, answers "; sql += " from tz_suleach "; sql += " where grcode = " + SQLString.Format(v_grcode); sql += " and subj = " + SQLString.Format(v_subj); sql += " and year = " + SQLString.Format(v_gyear); sql += " and subjseq = " + SQLString.Format(v_subjseq); sql += " and sulpapernum = " + SQLString.Format(v_sulpapernum); sql += " and userid = " + SQLString.Format(v_userid); ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception(ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return dbox; } /** 설문 대상자 리스트 @param box receive from the form object and session @return ArrayList 설문 대상자 */ public DataBox selectSulmunUser(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; DataBox dbox = null; String sql = ""; String v_userid = box.getString("p_userid"); try { connMgr = new DBConnectionManager(); /* sql += "select b.comp asgn, get_compnm(b.comp,2,4) asgnnm, "; sql += " b.jikup, get_jikupnm(b.jikup, b.comp) jikupnm, "; sql += " b.cono, b.name "; sql += " from tz_member b "; sql += " where b.userid = " + SQLString.Format(v_userid); */ sql += "select b.comp asgn, '' asgnnm, "; sql += " b.jikup, '' jikupnm, "; sql += " '' cono, b.name "; sql += " from tz_member b "; sql += " where b.userid = " + SQLString.Format(v_userid); ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception(ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return dbox; } /** 교육그룹코드 구하기 @param box receive from the form object and session @return String */ public String getGrcode(DBConnectionManager connMgr, String p_subj, String p_year, String p_subjseq) throws Exception { String v_grcode = ""; ListSet ls = null; String sql = ""; try { sql = "select grcode "; sql += " from tz_subjseq "; sql += " where subj = " + SQLString.Format(p_subj); sql += " and year = " + SQLString.Format(p_year); sql += " and subjseq = " + SQLString.Format(p_subjseq); ls = connMgr.executeQuery(sql); while ( ls.next() ) { v_grcode = ls.getString("grcode"); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } } return v_grcode; } /** 과목 설문 리스트 @param box receive from the form object and session @return ArrayList **/ public ArrayList selectEducationSubjectList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls1 = null; ArrayList list1 = null; DataBox dbox1 = null; String sql1 = ""; String v_subj = ""; // 과목 String v_year = ""; // 년도 String v_subjseq = ""; // 과목기수 String v_user_id = box.getSession("userid"); try { connMgr = new DBConnectionManager(); list1 = new ArrayList(); sql1 ="\r\n select x.*, get_codenm('0004',isonoff) isonoffvalue from ("; sql1 +="\r\n select a.subjnm, a.grcode, a.edustart, a.eduend, a.subj, a.year, a.subjseq, b.userid, b.tstep, c.sulpapernum, c.sulpapernm, c.progress, c.sulnums, c.sultype, '' AS STDT, '' AS ENDT, " + "\r\n (select isonoff from tz_subj where subj=a.subj) isonoff, " + "\r\n (select count(userid) from tz_suleach where subj=a.subj and year=a.year and subjseq=a.subjseq and sulpapernum = a.sulpapernum and userid='" +v_user_id + "') eachcnt " + "\r\n from tz_subjseq a, tz_student b, tz_sulpaper c " + "\r\n where a.subj=b.subj and a.year=b.year and a.subjseq=b.subjseq and a.sulpapernum = c.sulpapernum and b.userid='" +v_user_id + "' " + "\r\n and c.subj='ALL' and c.grcode='ALL' and a.isclosed!='Y'"; sql1 +="\r\n ) x"; sql1 +="\r\n order by x.subj,x.year,x.subjseq "; ls1 = connMgr.executeQuery(sql1); while ( ls1.next() ) { dbox1 = ls1.getDataBox(); list1.add(dbox1); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql1 = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list1; } /** 과목 설문 리스트 @param box receive from the form object and session @return ArrayList **/ public ArrayList selectSulmunList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls1 = null; ArrayList list1 = null; DataBox dbox1 = null; String sql1 = ""; String v_subj = box.getString("p_subj"); // 과목 String v_year = box.getString("p_year"); // 년도 String v_subjseq = box.getString("p_subjseq"); // 과목기수 String v_user_id = box.getSession("userid"); try { connMgr = new DBConnectionManager(); list1 = new ArrayList(); sql1 ="\r\n select * from ("; sql1 +="\r\n select a.subjnm, a.grcode, a.edustart, a.eduend, a.subj, a.year, a.subjseq, b.userid, b.tstep, c.sulpapernum, c.sulpapernm, c.progress, c.sulnums, c.sultype, a.PRESULSDATE STDT, a.PRESULEDATE ENDT," + "\r\n (select isonoff from tz_subj where subj=a.subj) isonoff, " + "\r\n (select count(userid) from tz_suleach where subj=a.subj and year=a.year and subjseq=a.subjseq and sulpapernum = a.presulpapernum and userid='" +v_user_id + "') eachcnt " + "\r\n from tz_subjseq a, tz_student b, tz_sulpaper c " + "\r\n where a.subj=b.subj and a.year=b.year and a.subjseq=b.subjseq and a.presulpapernum = c.sulpapernum and b.userid='" +v_user_id + "' " + "\r\n and c.subj='ALL' and c.grcode='ALL' and a.isclosed!='Y' " + "\r\n and a.subj="+StringManager.makeSQL(v_subj)+" and a.year="+StringManager.makeSQL(v_year)+" and a.subjseq="+StringManager.makeSQL(v_subjseq)+" "; sql1 +="\r\n union "; sql1 +="\r\n select a.subjnm, a.grcode, a.edustart, a.eduend, a.subj, a.year, a.subjseq, b.userid, b.tstep, c.sulpapernum, c.sulpapernm, c.progress, c.sulnums, c.sultype, a.AFTERSULSDATE STDT, a.AFTERSULEDATE ENDT," + "\r\n (select isonoff from tz_subj where subj=a.subj) isonoff, " + "\r\n (select count(userid) from tz_suleach where subj=a.subj and year=a.year and subjseq=a.subjseq and sulpapernum = a.aftersulpapernum and userid='" +v_user_id + "') eachcnt " + "\r\n from tz_subjseq a, tz_student b, tz_sulpaper c " + "\r\n where a.subj=b.subj and a.year=b.year and a.subjseq=b.subjseq and a.aftersulpapernum = c.sulpapernum and b.userid='" +v_user_id + "' " + "\r\n and c.subj='ALL' and c.grcode='ALL' and a.isclosed!='Y'" + "\r\n and a.subj="+StringManager.makeSQL(v_subj)+" and a.year="+StringManager.makeSQL(v_year)+" and a.subjseq="+StringManager.makeSQL(v_subjseq)+" "; sql1 +="\r\n ) x"; sql1 += " order by x.subj,x.year,x.subjseq "; ls1 = connMgr.executeQuery(sql1); while ( ls1.next() ) { dbox1 = ls1.getDataBox(); list1.add(dbox1); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql1 = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list1; } /** 교육그룹코드 구하기 @param box receive from the form object and session @return String */ public int getSulCnt(String p_subj, String p_year, String p_subjseq) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; int sulcnt = 0; try { connMgr = new DBConnectionManager(); sql += " select "; sql += " (case when nvl(sulpapernum,0) > 0 then 1 else 0 end)+ "; sql += " (case when nvl(presulpapernum,0) > 0 then 1 else 0 end)+ "; sql += " (case when nvl(aftersulpapernum,0) > 0 then 1 else 0 end) sulcnt "; sql += " from tz_subjseq "; sql += " where subj = " + SQLString.Format(p_subj); sql += " and year = " + SQLString.Format(p_year); sql += " and subjseq = " + SQLString.Format(p_subjseq); ls = connMgr.executeQuery(sql); while ( ls.next() ) { sulcnt = ls.getInt("sulcnt"); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return sulcnt; } /** 수강중인 과목 리스트 @param box receive from the form object and session @return ArrayList public ArrayList selectEducationSubjectList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls1 = null; ArrayList list1 = null; ArrayList list2 = null; DataBox dbox1 = null; DataBox dbox2 = null; String sql1 = ""; String v_subj = ""; // 과목 String v_year = ""; // 년도 String v_subjseq = ""; // 과목기수 String v_user_id = box.getSession("userid"); try { connMgr = new DBConnectionManager(); list1 = new ArrayList(); // select upperclass,isonoff,course,cyear,courseseq,coursenm,subj,year,subjseq,subjnm,edustart, // eduend,eduurl,classnm,subjtarget sql1 = "select A.scupperclass,A.isonoff,A.course,A.cyear,A.courseseq,A.coursenm,A.subj,A.year,A.subjseq,A.subjseqgr, "; sql1 += "A.subjnm,A.edustart,A.eduend,A.eduurl,A.subjtarget, A.isoutsourcing "; // sql1 += "(select classnm from TZ_CLASS where A.subj=subj and A.year=year and A.subjseq=subjseq) classnm "; sql1 += "from VZ_SCSUBJSEQ A,TZ_STUDENT B "; sql1 += "where A.subj=B.subj and A.year=B.year and A.subjseq=B.subjseq and B.userid=" +SQLString.Format(v_user_id); // sql1 += " and B.isgraduated='N' "; sql1 += " and to_char(sysdate,'YYYYMMDDHH24') between A.edustart and A.eduend "; // sql1 += " and A.isoutsourcing = 'N'"; sql1 += " order by A.course,A.cyear,A.courseseq,A.subj,A.year,A.subjseq,A.edustart,A.eduend "; ls1 = connMgr.executeQuery(sql1); while ( ls1.next() ) { dbox1 = ls1.getDataBox(); box.put("p_subj", dbox1.getString("d_subj") ); box.put("p_year", dbox1.getString("d_year") ); box.put("p_subjseq", dbox1.getString("d_subjseq") ); list2 = this.SelectUserList(connMgr, box); if ( list2.size() > 0) { dbox2 = (DataBox)list2.get(0); } else { dbox2 = new DataBox("resoponsebox"); } dbox2.put("d_subjnm", dbox1.getString("d_subjnm") ); dbox2.put("d_isonoff", dbox1.getString("d_isonoff") ); /* == == == == == 과목설문 응시여부 == == == == == int suldata = this.getUserData(connMgr, box); dbox2.put("d_suldata",String.valueOf(suldata)); /* == == == == == 권장진도율, 자기진도율 시작 == == == == == SubjGongAdminBean sbean = new SubjGongAdminBean(); String promotion = sbean.getPromotion(box); dbox2.put("p_promotion",promotion); String progress = sbean.getProgress(box); dbox2.put("p_progress",progress); list1.add(dbox2); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql1); throw new Exception("sql1 = " + sql1 + "\r\n" + ex.getMessage() ); } finally { if ( ls1 != null ) { try { ls1.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list1; }*/ /** 사용자 해당과목리스트 @param box receive from the form object and session @return ArrayList 해당과목리스트 */ public ArrayList SelectUserList(DBConnectionManager connMgr, RequestBox box) throws Exception { ListSet ls = null; ArrayList list = null; DataBox dbox = null; String sql = ""; try { String s_userid = box.getSession("userid"); String v_subj = box.getString("p_subj"); String v_year = box.getString("p_year"); String v_subjseq = box.getString("p_subjseq"); list = new ArrayList(); sql = "select a.grcode, a.subj, a.subjseq, "; sql += " a.sulpapernum, a.sulpapernm, a.year, "; sql += " a.totcnt, a.sulnums, a.sulmailing, a.sulstart, a.sulend, a.progress "; sql += " from tz_sulpaper a "; sql += " where a.subj = " + SQLString.Format(v_subj); sql += " and a.year = " + SQLString.Format(v_year); sql += " and a.subjseq = " + SQLString.Format(v_subjseq); sql += " and rownum <= 1 "; sql += " order by a.subj, a.sulpapernum"; ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } } return list; } /** 사용자 해당과목 설문 리스트 @param box receive from the form object and session @return ArrayList 해당과목리스트 */ public ArrayList SelectUserSubjSulnum(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; DataBox dbox = null; String sql = ""; int v_sulpapernum = 0; try { String s_userid = box.getSession("userid"); String v_subj = box.getString("p_subj"); String v_year = box.getString("p_year"); String v_subjseq = box.getString("p_subjseq"); connMgr = new DBConnectionManager(); list = new ArrayList(); sql = " SELECT distinct (SELECT CODENM \n"; sql += " FROM TZ_CODE \n"; sql += " WHERE GUBUN = '0097' \n"; sql += " AND CODE = X.SULTYPE) AS SULTYPE \n"; sql += " , X.SULPAPERNM \n"; sql += " , X.SULPAPERNUM, X.TOTCNT, X.SULNUMS \n"; sql += " , DECODE((SELECT COUNT(*) \n"; sql += " FROM TZ_SULEACH Z \n"; sql += " WHERE Z.SUBJ = Y.SUBJ \n"; sql += " AND Z.YEAR = Y.YEAR \n"; sql += " AND Z.SUBJSEQ = Y.SUBJSEQ \n"; sql += " AND Z.SULPAPERNUM = X.SULPAPERNUM \n"; sql += " AND Z.USERID = '" +s_userid + "'), 0, 'N', 'Y') AS ISSUL \n"; // N : 응시함, Y : 응시안함 sql += " , (SELECT TSTEP \n"; sql += " FROM TZ_STUDENT W \n"; sql += " WHERE W.SUBJ = Y.SUBJ \n"; sql += " AND W.YEAR = Y.YEAR \n"; sql += " AND W.SUBJSEQ = Y.SUBJSEQ \n"; sql += " AND W.USERID = '" +s_userid + "') AS NPROGRESS \n"; sql += " , X.PROGRESS \n"; sql += " , DECODE(X.SULTYPE, '1', 'N', 'Y') AS LIMITDT \n"; sql += " , Y.STDT \n"; sql += " , Y.ENDT \n"; sql += " , Y.SUBJ \n"; sql += " , Y.SUBJSEQ \n"; sql += " , Y.YEAR \n"; sql += " , Y.SUBJNM \n"; sql += " , Y.GRCODE \n"; sql += " , (SELECT ISONOFF \n"; sql += " FROM TZ_SUBJ W \n"; sql += " WHERE W.SUBJ = Y.SUBJ ) AS ISONOFF \n"; sql += " FROM TZ_SULPAPER X , ( \n"; sql += " SELECT A.SULPAPERNUM, '' AS STDT, '' AS ENDT, B.SUBJ, B.YEAR, B.SUBJSEQ, B.SUBJNM, B.GRCODE \n"; sql += " FROM TZ_SULPAPER A, TZ_SUBJSEQ B \n"; sql += " WHERE A.SULPAPERNUM = B.SULPAPERNUM \n"; sql += " AND B.SUBJ = " + SQLString.Format(v_subj); sql += " AND B.YEAR = " + SQLString.Format(v_year); sql += " AND B.SUBJSEQ = " + SQLString.Format(v_subjseq); sql += " ) Y \n"; sql += " WHERE X.SULPAPERNUM = Y.SULPAPERNUM \n"; sql += " AND X.SUBJ = 'ALL' \n"; sql += " AND X.GRCODE = 'ALL' \n"; ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); box.put("p_num", dbox.getInt("d_sulpapernum")) ; list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** 사용자 해당과목 설문 리스트 @param box receive from the form object and session @return ArrayList 해당과목리스트 */ public ArrayList SelectUserList(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; DataBox dbox = null; String sql = ""; try { String s_userid = box.getSession("userid"); String v_subj = box.getString("p_subj"); String v_year = box.getString("p_year"); String v_subjseq = box.getString("p_subjseq"); connMgr = new DBConnectionManager(); list = new ArrayList(); // sql = "select a.grcode, a.subj, a.subjseq, "; // sql += " a.sulpapernum, a.sulpapernm, a.year, "; // sql += " a.totcnt, a.sulnums, a.sulmailing, a.sulstart, a.sulend, a.progress "; // sql += " from tz_sulpaper a "; // sql += " where a.subj = " + SQLString.Format(v_subj); // sql += " and a.year = " + SQLString.Format(v_year); // sql += " and a.subjseq = " + SQLString.Format(v_subjseq); // sql += " and rownum <= 1 "; // sql += " order by a.subj, a.sulpapernum desc "; // 2008. 12.2 쿼리변경 // sql = " select a.subjnm, a.grcode, a.edustart, a.eduend, a.subj, a.year, a.subjseq, \n"; // sql += " b.userid, b.tstep, a.sulpapernum,c.sulpapernm, c.progress, c.sulnums, \n"; // sql += " a.presulpapernum, a.presulsdate, a.presuledate, \n"; // sql += " a.aftersulpapernum, a.aftersulsdate, a.aftersuledate, \n"; // sql += " ( \n"; // sql += " select sulpapernm from tz_sulpaper where sulpapernum = a.presulpapernum \n"; // sql += " ) presulpapername, \n"; // sql += " ( \n"; // sql += " select sulpapernm from tz_sulpaper where sulpapernum = a.aftersulpapernum \n"; // sql += " ) aftersulpapername, \n"; // sql += " (select count(userid) from tz_suleach \n"; // sql += " where subj=a.subj and year=a.year and subjseq=a.subjseq \n"; // sql += " and sulpapernum = a.sulpapernum and userid='lee1') eachcnt \n"; // sql += " from TZ_SUBJSEQ a, TZ_STUDENT b, tz_sulpaper c \n"; // sql += " where A.subj=B.subj and A.year=B.year and A.subjseq=B.subjseq and a.sulpapernum = c.sulpapernum \n"; // sql += " and B.userid='" +s_userid + "' and c.subj='ALL' and c.grcode='ALL' \n"; // // sql += " and to_char(sysdate,'YYYYMMDDHH24') between A.edustart and A.eduend "; // sql += " and a.subj=" +SQLString.Format(v_subj) + " and a.year=" +SQLString.Format(v_year) + " and a.subjseq=" +SQLString.Format(v_subjseq) + " "; // sql += " order by A.subj,A.year,A.subjseq,A.edustart,A.eduend \n"; sql = " SELECT distinct (SELECT CODENM \n"; sql += " FROM TZ_CODE \n"; sql += " WHERE GUBUN = '0097' \n"; sql += " AND CODE = X.SULTYPE) AS SULTYPE \n"; sql += " , X.SULPAPERNM \n"; sql += " , X.SULPAPERNUM, X.TOTCNT, X.SULNUMS \n"; sql += " , DECODE((SELECT COUNT(*) \n"; sql += " FROM TZ_SULEACH Z \n"; sql += " WHERE Z.SUBJ = Y.SUBJ \n"; sql += " AND Z.YEAR = Y.YEAR \n"; sql += " AND Z.SUBJSEQ = Y.SUBJSEQ \n"; sql += " AND Z.SULPAPERNUM = X.SULPAPERNUM \n"; sql += " AND Z.USERID = " +StringManager.makeSQL(s_userid) + "), 0, 'N', 'Y') AS ISSUL \n"; // N : 응시함, Y : 응시안함 sql += " , (SELECT TSTEP \n"; sql += " FROM TZ_STUDENT W \n"; sql += " WHERE W.SUBJ = Y.SUBJ \n"; sql += " AND W.YEAR = Y.YEAR \n"; sql += " AND W.SUBJSEQ = Y.SUBJSEQ \n"; sql += " AND W.USERID = " +StringManager.makeSQL(s_userid) + ") AS NPROGRESS \n"; sql += " , X.PROGRESS \n"; sql += " , DECODE(X.SULTYPE, '1', 'N', 'Y') AS LIMITDT \n"; sql += " , Y.STDT \n"; sql += " , Y.ENDT \n"; sql += " , Y.SUBJ \n"; sql += " , Y.SUBJSEQ \n"; sql += " , Y.YEAR \n"; sql += " , Y.SUBJNM \n"; sql += " , Y.GRCODE \n"; sql += " , decode((SELECT COUNT(ANSWER) FROM TZ_EXAMRESULT \n"; sql += " WHERE SUBJ = Y.SUBJ AND YEAR = Y.YEAR AND SUBJSEQ = Y.SUBJSEQ AND USERID = "+StringManager.makeSQL(s_userid)+" AND EXAMTYPE = 'E' "; sql += " ),'1','Y','N') isexam , x.sulgubun \n"; sql += " FROM TZ_SULPAPER X , ( \n"; sql += " SELECT A.SULPAPERNUM, '' AS STDT, '' AS ENDT, B.SUBJ, B.YEAR, B.SUBJSEQ, B.SUBJNM, B.GRCODE \n"; sql += " FROM TZ_SULPAPER A, TZ_SUBJSEQ B \n"; sql += " WHERE A.SULPAPERNUM = B.SULPAPERNUM \n"; sql += " AND B.SUBJ = " + StringManager.makeSQL(v_subj); sql += " AND B.YEAR = " + StringManager.makeSQL(v_year); sql += " AND B.SUBJSEQ = " + StringManager.makeSQL(v_subjseq); sql += " UNION ALL \n"; sql += " SELECT PRESULPAPERNUM, B.PRESULSDATE, B.PRESULEDATE, B.SUBJ, B.YEAR, B.SUBJSEQ, B.SUBJNM, B.GRCODE \n"; sql += " FROM TZ_SULPAPER A, TZ_SUBJSEQ B \n"; sql += " WHERE A.SULPAPERNUM = B.SULPAPERNUM \n"; sql += " AND B.SUBJ = " + StringManager.makeSQL(v_subj); sql += " AND B.YEAR = " + StringManager.makeSQL(v_year); sql += " AND B.SUBJSEQ = " + StringManager.makeSQL(v_subjseq); sql += " UNION ALL \n"; sql += " SELECT AFTERSULPAPERNUM, B.AFTERSULSDATE, B.AFTERSULEDATE, B.SUBJ, B.YEAR, B.SUBJSEQ, B.SUBJNM, B.GRCODE \n"; sql += " FROM TZ_SULPAPER A, TZ_SUBJSEQ B \n"; sql += " WHERE A.SULPAPERNUM = B.SULPAPERNUM \n"; sql += " AND B.SUBJ = " + StringManager.makeSQL(v_subj); sql += " AND B.YEAR = " + StringManager.makeSQL(v_year); sql += " AND B.SUBJSEQ = " + StringManager.makeSQL(v_subjseq); sql += " ) Y \n"; sql += " WHERE X.SULPAPERNUM = Y.SULPAPERNUM \n"; sql += " AND X.SUBJ = 'ALL' \n"; sql += " AND X.GRCODE = 'ALL' \n"; ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** 사용자 해당과목리스트 @param box receive from the form object and session @return ArrayList 해당과목리스트 */ public int getUserData(DBConnectionManager connMgr, RequestBox box) throws Exception { ListSet ls = null; DataBox dbox = null; String sql = ""; int v_research = 0; try { String s_userid = box.getSession("userid"); String v_subj = box.getString("p_subj"); String v_year = box.getString("p_year"); String v_subjseq = box.getString("p_subjseq"); sql = "select count(a.answers) researchcnt "; sql += " from tz_suleach a "; sql += " where a.subj = " + SQLString.Format(v_subj); sql += " and a.year = " + SQLString.Format(v_year); sql += " and a.subjseq = " + SQLString.Format(v_subjseq); sql += " and a.userid = " + SQLString.Format(s_userid); sql += " and a.grcode ! = 'ALL' "; ls = connMgr.executeQuery(sql); if ( ls.next() ) { dbox = ls.getDataBox(); v_research = dbox.getInt("d_researchcnt"); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } } return v_research; } /** * 과정별 설문갯수 * @param box * @return * @throws Exception */ public int getSulData(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; DataBox dbox = null; String sql = ""; int v_suldata = 0; try { String s_userid = box.getSession("userid"); String v_subj = box.getString("p_subj"); String v_year = box.getString("p_year"); String v_subjseq = box.getString("p_subjseq"); connMgr = new DBConnectionManager(); sql = "\n select decode(nvl(a.sulpapernum, 0), 0, 0, 1) " + "\n + decode(nvl(a.presulpapernum, 0), 0, 0, 1) " + "\n + decode(nvl(a.aftersulpapernum, 0), 0, 0, 1) as suldata " + "\n from tz_subjseq a " + "\n where a.subj = " + SQLString.Format(v_subj) + "\n and a.year = " + SQLString.Format(v_year) + "\n and a.subjseq = " + SQLString.Format(v_subjseq); ls = connMgr.executeQuery(sql); if ( ls.next() ) { dbox = ls.getDataBox(); v_suldata = dbox.getInt("d_suldata"); } if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return v_suldata; } /** 과정별 설문기간 @param box receive from the form object and session @return ArrayList 해당과목리스트 */ public ArrayList getSulDate( RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; DataBox dbox = null; String sql = ""; ArrayList list = null; list = new ArrayList(); try { connMgr = new DBConnectionManager(); list = new ArrayList(); String v_subj = box.getString("p_subj"); String v_year = box.getString("p_year"); String v_subjseq = box.getString("p_subjseq"); sql = "select aftersulsdate, aftersuledate "; sql += " from tz_subjseq a "; sql += " where a.subj = " + SQLString.Format(v_subj); sql += " and a.year = " + SQLString.Format(v_year); sql += " and a.subjseq = " + SQLString.Format(v_subjseq); sql += " and a.grcode ! = 'ALL' "; System.out.println("-------------???----------" + sql); ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); list.add(dbox); } System.out.println("-------------list-------" + list); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** 사용자 해당과목리스트 @param box receive from the form object and session @return ArrayList 해당과목리스트 */ public int getUserData(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; DataBox dbox = null; String sql = ""; int v_research = 0; int v_suldata = 0; try { String s_userid = box.getSession("userid"); String v_subj = box.getString("p_subj"); String v_year = box.getString("p_year"); String v_subjseq = box.getString("p_subjseq"); connMgr = new DBConnectionManager(); sql = "\n select decode(nvl(a.sulpapernum, 0), 0, 0, 1) " + "\n + decode(nvl(a.presulpapernum, 0), 0, 0, 1) " + "\n + decode(nvl(a.aftersulpapernum, 0), 0, 0, 1) as suldata " + "\n from tz_subjseq a " + "\n where a.subj = " + SQLString.Format(v_subj) + "\n and a.year = " + SQLString.Format(v_year) + "\n and a.subjseq = " + SQLString.Format(v_subjseq); ls = connMgr.executeQuery(sql); if ( ls.next() ) { dbox = ls.getDataBox(); v_suldata = dbox.getInt("d_suldata"); } if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { ErrorManager.getErrorStackTrace(e, box, sql); throw new Exception("sql = " + sql + "\r\n" + e.getMessage() ); } } sql = "\n select count(a.answers) researchcnt " + "\n from tz_suleach a " + "\n where a.subj = " + SQLString.Format(v_subj) + "\n and a.year = " + SQLString.Format(v_year) + "\n and a.subjseq = " + SQLString.Format(v_subjseq) + "\n and a.userid = " + SQLString.Format(s_userid) + "\n and a.grcode ! = 'ALL' "; ls = connMgr.executeQuery(sql); if ( ls.next() ) { dbox = ls.getDataBox(); v_research = dbox.getInt("d_researchcnt"); } if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return v_research; } }
package Topic20Enum; import java.util.Scanner; public class EnumApp { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.println("Możesz wybrać z poniższych mozliwości"); for (Enum e: Enum.values()){ System.out.println(e.nrkoloru); } String a = sc.nextLine(); System.out.println(sizeFromDescription(a)); } static Enum sizeFromDescription(String desc) { for(Enum s: Enum.values()) { if(s.getNrkoloru().equals(desc)) return s; } return Enum.CZERWONY; } }
package com.pwq.DesignPatterns.SimpleFactory.BuildePattern; /** * @Author:WenqiangPu * @Description * @Date:Created in 14:55 2017/9/19 * @Modified By: */ public class Meal { private String food; private String drink; public String getFood() { return food; } public void setFood(String food) { this.food = food; } public String getDrink() { return drink; } public void setDrink(String drink) { this.drink = drink; } @Override public String toString() { return "Meal{" + "food='" + food + '\'' + ", drink='" + drink + '\'' + '}'; } }
package hanoiTower; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; public class MovesExecutor { private List<String> movesHistory = new LinkedList<>(); public boolean moveDisk(Peg source, Peg destination) { Optional<Disk> cache = source.getTop(); if (!cache.isPresent()) { return false; } try { if (!destination.putOnTop(cache.get())) { throw new RuntimeException(); } } catch (RuntimeException e) { source.putOnTop(cache.get()); return false; } movesHistory.add(String.format("%-16s %s %-15s %-10s", "From " + source.name, " ----> ", destination.name + ": ", "Disk " + cache.get())); return true; } public void showHistory(Consumer<String> consumer) { consumer.accept("MOVES HISTORY: "); consumer.accept("================================================================"); StringBuilder stringBuilder = new StringBuilder(); final AtomicInteger counter = new AtomicInteger(0); movesHistory.stream().forEach(s -> { stringBuilder.append(counter.incrementAndGet() + ". ").append(s).append("\n"); }); consumer.accept(stringBuilder.toString()); } }
import java.awt.*; import java.awt.event.*; import java.applet.*; public class FirstProgram extends Applet implements ActionListener { TextField t1 = new TextField(10); TextField t2 = new TextField(10); TextField t3 = new TextField(10); Label l1 = new Label("First Number:"); Label l2 = new Label("Second Number:"); Label l3 = new Label("Result:"); Button b1 = new Button("Addition"); Button b2 = new Button("Subtraction"); Button b3 = new Button("Multiplication"); @Override public void init() { add(l1); add(t1); add(l2); add(t2); add(l3); add(t3); add(b1); add(b2); add(b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == b1) { int x = Integer.parseInt(t1.getText()); int y = Integer.parseInt(t2.getText()); t3.setText(" " + (x +y)); } if (e.getSource() == b2) { int x = Integer.parseInt(t1.getText()); int y = Integer.parseInt(t2.getText()); t3.setText(" " + (x-y)); } if (e.getSource() == b3) { int x = Integer.parseInt(t1.getText()); int y = Integer.parseInt(t2.getText()); t3.setText(" " + (x*y)); } } }
package com.weathair.service; import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; import com.weathair.dto.indicators.MeteoIndicatorDto; import com.weathair.entities.indicators.MeteoIndicator; import com.weathair.exceptions.MeteoIndicatorException; import com.weathair.services.MeteoIndicatorService; @SpringBootTest @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @AutoConfigureTestDatabase(replace = Replace.NONE) public class MeteoIndicatorServiceTest { @Autowired private MeteoIndicatorService meteoIndicatorService; @Test @Order(1) public void findAllMeteosIndicatorsTest() throws MeteoIndicatorException { List<MeteoIndicator> meteoIndicators = meteoIndicatorService.getAllMeteoIndicators(); assertThat(!meteoIndicators.isEmpty()); } @Test @Order(2) public void findMeteoIndicatorByIdTest() throws MeteoIndicatorException { MeteoIndicator meteoIndicators = meteoIndicatorService.getMeteoIndicatorById(10055); assertThat(meteoIndicators.getDescription()).isEqualTo("clear sky"); } @Test @Order(3) public void findMeteoIndicatorByTownshipnameTest() throws MeteoIndicatorException { List<MeteoIndicator> meteoIndicators = meteoIndicatorService.getMeteoIndicatorsByTownshipName("Montpellier"); assertThat(!meteoIndicators.isEmpty()); } @Test @Order(4) public void createMeteoIndicatorTest() { LocalDateTime now = LocalDateTime.now(); MeteoIndicatorDto meteoIndicatorDto = new MeteoIndicatorDto(); meteoIndicatorDto.setDescription("new meteo indicator"); meteoIndicatorDto.setDateTime(now); meteoIndicatorDto.setTemperature(10000d); meteoIndicatorDto.setHumidity(10000); meteoIndicatorDto.setFeelsLike(10000d); meteoIndicatorDto.setWindDeg(10000); meteoIndicatorDto.setTownshipName("Montpellier"); MeteoIndicator createdMeteoIndicator = meteoIndicatorService.createMeteoIndicator(meteoIndicatorDto); assertThat(createdMeteoIndicator.getDescription()).isEqualTo("new meteo indicator"); assertThat(createdMeteoIndicator.getTemperature()).isEqualTo(10000d); assertThat(createdMeteoIndicator.getHumidity()).isEqualTo(10000); assertThat(createdMeteoIndicator.getFeelsLike()).isEqualTo(10000d); assertThat(createdMeteoIndicator.getWindDeg()).isEqualTo(10000); assertThat(createdMeteoIndicator.getTownship().getName()).isEqualTo("Montpellier"); } @Test @Order(5) public void updateMeteoIndicatorTest() throws MeteoIndicatorException { LocalDateTime now = LocalDateTime.now(); MeteoIndicatorDto meteoIndicatorDto = new MeteoIndicatorDto(); meteoIndicatorDto.setDescription("new meteo indicator updated"); meteoIndicatorDto.setDateTime(now); meteoIndicatorDto.setTemperature(20000d); meteoIndicatorDto.setHumidity(20000); meteoIndicatorDto.setFeelsLike(20000d); meteoIndicatorDto.setWindDeg(20000); meteoIndicatorDto.setTownshipName("Rodez"); int id = 0; List<MeteoIndicator> meteoIndicators = meteoIndicatorService.getAllMeteoIndicators(); for (MeteoIndicator m : meteoIndicators) { if (m.getDescription().equals("new meteo indicator")) { id = m.getId(); meteoIndicatorService.updateMeteoIndicator(id, meteoIndicatorDto); } } MeteoIndicator updatedMeteoIndicator = meteoIndicatorService.getMeteoIndicatorById(id); assertThat(updatedMeteoIndicator.getDescription()).isEqualTo("new meteo indicator updated"); assertThat(updatedMeteoIndicator.getTemperature()).isEqualTo(20000d); assertThat(updatedMeteoIndicator.getHumidity()).isEqualTo(20000); assertThat(updatedMeteoIndicator.getFeelsLike()).isEqualTo(20000d); assertThat(updatedMeteoIndicator.getWindDeg()).isEqualTo(20000); assertThat(updatedMeteoIndicator.getTownship().getName()).isEqualTo("Rodez"); } @Test @Order(6) public void deleteMeteoIndicatorTest() throws MeteoIndicatorException { List<MeteoIndicator> meteoIndicators = meteoIndicatorService.getAllMeteoIndicators(); int initialIndicatorsNb = meteoIndicators.size(); for (MeteoIndicator m : meteoIndicators) { if (m.getDescription().contains("new meteo indicator")) { meteoIndicatorService.deleteMeteoIndicator(m.getId()); } } int finalIndicatorsNb = meteoIndicatorService.getAllMeteoIndicators().size(); assertThat(initialIndicatorsNb).isGreaterThan(finalIndicatorsNb); } @Test @Order(7) public void saveUpdateIndicatorsForOccitanieTest() throws MeteoIndicatorException, JsonProcessingException { int initialIndicatorsNb = meteoIndicatorService.getAllMeteoIndicators().size(); meteoIndicatorService.saveUpdateIndicatorsForOccitanie(); int finalIndicatorsNb = meteoIndicatorService.getAllMeteoIndicators().size(); assertThat(finalIndicatorsNb).isGreaterThan(initialIndicatorsNb); } }
/* * 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 com.mycompany18424021_Baitap; /** * * @author WINPC */ public class Users { protected String _USER; protected String _PASS; protected String _CV; public void setUSER(String _USER) { this._USER = _USER; } public void setPASS(String _PASS) { this._PASS = _PASS; } public void setCV(String _CV) { this._CV = _CV; } public String getPASS() { return _PASS; } public String getCV() { return _CV; } }
package de.csiebmanns.graphqlexample.data; public class Comment implements HasAuthorName { private String authorName; private String content; private long timestamp; public Comment() { } public Comment(CommentData data) { this.authorName = data.getAuthorName(); this.content = data.getContent(); this.timestamp = System.currentTimeMillis() / 1000L; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.transaction.support; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.aop.scope.ScopedObject; import org.springframework.core.InfrastructureProxy; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * Utility methods for triggering specific {@link TransactionSynchronization} * callback methods on all currently registered synchronizations. * * @author Juergen Hoeller * @since 2.0 * @see TransactionSynchronization * @see TransactionSynchronizationManager#getSynchronizations() */ public abstract class TransactionSynchronizationUtils { private static final Log logger = LogFactory.getLog(TransactionSynchronizationUtils.class); private static final boolean aopAvailable = ClassUtils.isPresent( "org.springframework.aop.scope.ScopedObject", TransactionSynchronizationUtils.class.getClassLoader()); /** * Check whether the given resource transaction manager refers to the given * (underlying) resource factory. * @see ResourceTransactionManager#getResourceFactory() * @see InfrastructureProxy#getWrappedObject() */ public static boolean sameResourceFactory(ResourceTransactionManager tm, Object resourceFactory) { return unwrapResourceIfNecessary(tm.getResourceFactory()).equals(unwrapResourceIfNecessary(resourceFactory)); } /** * Unwrap the given resource handle if necessary; otherwise return * the given handle as-is. * @since 5.3.4 * @see InfrastructureProxy#getWrappedObject() */ public static Object unwrapResourceIfNecessary(Object resource) { Assert.notNull(resource, "Resource must not be null"); Object resourceRef = resource; // unwrap infrastructure proxy if (resourceRef instanceof InfrastructureProxy infrastructureProxy) { resourceRef = infrastructureProxy.getWrappedObject(); } if (aopAvailable) { // now unwrap scoped proxy resourceRef = ScopedProxyUnwrapper.unwrapIfNecessary(resourceRef); } return resourceRef; } /** * Trigger {@code flush} callbacks on all currently registered synchronizations. * @throws RuntimeException if thrown by a {@code flush} callback * @see TransactionSynchronization#flush() */ public static void triggerFlush() { for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) { synchronization.flush(); } } /** * Trigger {@code beforeCommit} callbacks on all currently registered synchronizations. * @param readOnly whether the transaction is defined as read-only transaction * @throws RuntimeException if thrown by a {@code beforeCommit} callback * @see TransactionSynchronization#beforeCommit(boolean) */ public static void triggerBeforeCommit(boolean readOnly) { for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) { synchronization.beforeCommit(readOnly); } } /** * Trigger {@code beforeCompletion} callbacks on all currently registered synchronizations. * @see TransactionSynchronization#beforeCompletion() */ public static void triggerBeforeCompletion() { for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) { try { synchronization.beforeCompletion(); } catch (Throwable ex) { logger.error("TransactionSynchronization.beforeCompletion threw exception", ex); } } } /** * Trigger {@code afterCommit} callbacks on all currently registered synchronizations. * @throws RuntimeException if thrown by a {@code afterCommit} callback * @see TransactionSynchronizationManager#getSynchronizations() * @see TransactionSynchronization#afterCommit() */ public static void triggerAfterCommit() { invokeAfterCommit(TransactionSynchronizationManager.getSynchronizations()); } /** * Actually invoke the {@code afterCommit} methods of the * given Spring TransactionSynchronization objects. * @param synchronizations a List of TransactionSynchronization objects * @see TransactionSynchronization#afterCommit() */ public static void invokeAfterCommit(@Nullable List<TransactionSynchronization> synchronizations) { if (synchronizations != null) { for (TransactionSynchronization synchronization : synchronizations) { synchronization.afterCommit(); } } } /** * Trigger {@code afterCompletion} callbacks on all currently registered synchronizations. * @param completionStatus the completion status according to the * constants in the TransactionSynchronization interface * @see TransactionSynchronizationManager#getSynchronizations() * @see TransactionSynchronization#afterCompletion(int) * @see TransactionSynchronization#STATUS_COMMITTED * @see TransactionSynchronization#STATUS_ROLLED_BACK * @see TransactionSynchronization#STATUS_UNKNOWN */ public static void triggerAfterCompletion(int completionStatus) { List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations(); invokeAfterCompletion(synchronizations, completionStatus); } /** * Actually invoke the {@code afterCompletion} methods of the * given Spring TransactionSynchronization objects. * @param synchronizations a List of TransactionSynchronization objects * @param completionStatus the completion status according to the * constants in the TransactionSynchronization interface * @see TransactionSynchronization#afterCompletion(int) * @see TransactionSynchronization#STATUS_COMMITTED * @see TransactionSynchronization#STATUS_ROLLED_BACK * @see TransactionSynchronization#STATUS_UNKNOWN */ public static void invokeAfterCompletion(@Nullable List<TransactionSynchronization> synchronizations, int completionStatus) { if (synchronizations != null) { for (TransactionSynchronization synchronization : synchronizations) { try { synchronization.afterCompletion(completionStatus); } catch (Throwable ex) { logger.error("TransactionSynchronization.afterCompletion threw exception", ex); } } } } /** * Inner class to avoid hard-coded dependency on AOP module. */ private static class ScopedProxyUnwrapper { public static Object unwrapIfNecessary(Object resource) { if (resource instanceof ScopedObject scopedObject) { return scopedObject.getTargetObject(); } else { return resource; } } } }
package alien4cloud.component.repository.exception; /** * Exception thrown when trying to store an existing version of a CSAR * * @author 'Igor Ngouagna' * */ public class CSARVersionAlreadyExistsException extends RepositoryFunctionalException { private static final long serialVersionUID = -7825281720911419035L; public CSARVersionAlreadyExistsException(String message) { super(message); } }
package com.alibaba.druid.bvt.sql.mysql; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.alibaba.druid.DbType; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.util.JdbcConstants; import org.junit.Test; public class SQLUtilsTest extends TestCase { public void test_format() throws Exception { String formattedSql = SQLUtils.format("select * from t where id = ?", JdbcConstants.MYSQL, Arrays.<Object>asList("abc")); Assert.assertEquals("SELECT *" + // "\nFROM t" + // "\nWHERE id = 'abc'", formattedSql); } public void test_format_0() throws Exception { String sql = "select \"%\"'温'\"%\" FROM dual;"; String formattedSql = SQLUtils.formatMySql(sql); Assert.assertEquals("SELECT '%温%'\n" + "FROM dual;", formattedSql); } public void test_format_1() throws Exception { String sql = "select * from t where tname LIKE \"%\"'温'\"%\""; String formattedSql = SQLUtils.formatMySql(sql); Assert.assertEquals("SELECT *\n" + "FROM t\n" + "WHERE tname LIKE '%温%'", formattedSql); } public void test_format_2() throws Exception { String sql = "begin\n"// + " if (a=10) then\n" + " null;\n" + " else\n" + " null;\n" + " end if;\n" + "end;"; Assert.assertEquals("BEGIN" + "\n\tIF a = 10 THEN" + "\n\t\tNULL;" + "\n\tELSE" + "\n\t\tNULL;" + "\n\tEND IF;" + "\nEND;", SQLUtils.formatOracle(sql)); } public void test_format_3() throws Exception { String sql = "select lottery_notice_issue,lottery_notice_date,lottery_notice_result from tb_lottery_notice where lottery_type_id=8 and lottery_notice_issue<=2014066 UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL# and lottery_notice_issue>=2014062 order by lottery_notice_issue desc"; String formattedSql = SQLUtils.formatMySql(sql); String expected = "SELECT lottery_notice_issue, lottery_notice_date, lottery_notice_result\n" + "FROM tb_lottery_notice\n" + "WHERE lottery_type_id = 8\n" + "\tAND lottery_notice_issue <= 2014066\n" + "UNION ALL\n" + "SELECT NULL, NULL, NULL, NULL, NULL\n" + "\t, NULL# and lottery_notice_issue>=2014062 order by lottery_notice_issue desc"; Assert.assertEquals(expected, formattedSql); } public void testAcceptFunctionTest() { List<SQLMethodInvokeExpr> functions = new ArrayList<>(); SQLUtils.acceptFunction( "select count(*) from t", DbType.odps, e -> functions.add(e), e -> true ); assertEquals(1, functions.size()); } public void testAcceptFunctionTest_1() { List<SQLMethodInvokeExpr> functions = new ArrayList<>(); SQLUtils.acceptAggregateFunction( "select count(*) from t", DbType.odps, e -> functions.add(e), e -> true ); assertEquals(1, functions.size()); } public void testAcceptFunctionTest_pg() { List<SQLMethodInvokeExpr> functions = new ArrayList<>(); SQLUtils.acceptFunction( "select count(*) from t", DbType.postgresql, e -> functions.add(e), e -> true ); assertEquals(1, functions.size()); } public void testAcceptFunctionTest_pg_1() { List<SQLMethodInvokeExpr> functions = new ArrayList<>(); SQLUtils.acceptAggregateFunction( "select count(*) from t", DbType.postgresql, e -> functions.add(e), e -> true ); assertEquals(1, functions.size()); } public void testAcceptFunctionTest_oracle() { List<SQLMethodInvokeExpr> functions = new ArrayList<>(); SQLUtils.acceptFunction( "select count(*) from t", DbType.oracle, e -> functions.add(e), e -> true ); assertEquals(1, functions.size()); } public void testAcceptFunctionTest_oracle_1() { List<SQLMethodInvokeExpr> functions = new ArrayList<>(); SQLUtils.acceptAggregateFunction( "select count(*) from t", DbType.oracle, e -> functions.add(e), e -> true ); assertEquals(1, functions.size()); } public void testAcceptFunctionTest_ck() { List<SQLMethodInvokeExpr> functions = new ArrayList<>(); SQLUtils.acceptFunction( "select count(*) from t", DbType.clickhouse, e -> functions.add(e), e -> true ); assertEquals(1, functions.size()); } public void testAcceptFunctionTest_ck_1() { List<SQLMethodInvokeExpr> functions = new ArrayList<>(); SQLUtils.acceptAggregateFunction( "select count(*) from t", DbType.clickhouse, e -> functions.add(e), e -> true ); assertEquals(1, functions.size()); } }
package com.heihei.scoket; public class WebSocketClientOther { //public class WebSocketClientOther extends Service implements WebSocketListener { // // private static final int CONNECT_TO_WEB_SOCKET = 1; // private static final int SEND_MESSAGE = 2; // private static final int CLOSE_WEB_SOCKET = 3; // private static final int DISCONNECT_LOOPER = 4; // // private static final String KEY_MESSAGE = "keyMessage"; // // private Handler mServiceHandler; // private Looper mServiceLooper; // private WebSocket mWebSocket; // private boolean mConnected; // // private final class ServiceHandler extends Handler { // public ServiceHandler(Looper looper) { // super(looper); // } // // @Override // public void handleMessage(Message msg) { // switch (msg.what) { // case CONNECT_TO_WEB_SOCKET: // connectToWebSocket(); // break; // case SEND_MESSAGE: // sendMessageThroughWebSocket(msg.getData().getString(KEY_MESSAGE)); // break; // case CLOSE_WEB_SOCKET: // closeWebSocket(); // break; // case DISCONNECT_LOOPER: // mServiceLooper.quit(); // break; // } // } // } // // private void sendMessageThroughWebSocket(String message) { // if (!mConnected) { // return; // } // try { // mWebSocket.sendMessage(WebSocket.PayloadType.TEXT, new Buffer().write(message.getBytes())); // } catch (IOException e) { // e.printStackTrace(); // } // } // // private void connectToWebSocket() { // OkHttpClient okHttpClient = new OkHttpClient(); // UserMgr.getInstance().loadLoginUser(); // String url = "ws://123.56.0.31:8082/ws/channel?token=" + UserMgr.getInstance().getToken(); // Log.i("jianfei", "url:"+url); // Request request = new Request.Builder().url(url).build(); // mWebSocket = WebSocket.newWebSocket(okHttpClient, request); // try { // Response response = mWebSocket.connect(WebSocketClientOther.this); // if (response.code() == 101) { // mConnected = true; // } // // } catch (IOException e) { // e.printStackTrace(); // } // // Log.i("jianfei", "connectToWebSocket"); // } // // private void closeWebSocket() { // if (!mConnected) { // return; // } // try { // mWebSocket.close(1000, "Goodbye, World!"); // } catch (IOException e) { // e.printStackTrace(); // } // } // // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public void onCreate() { // super.onCreate(); // Log.i("jianfei", "onCreate start"); // HandlerThread thread = new HandlerThread("WebSocket service"); // thread.start(); // mServiceLooper = thread.getLooper(); // mServiceHandler = new ServiceHandler(mServiceLooper); // // mServiceHandler.sendEmptyMessage(CONNECT_TO_WEB_SOCKET); // Log.i("jianfei", "onCreate"); // // } // // @Override // public void onDestroy() { // mServiceHandler.sendEmptyMessage(CLOSE_WEB_SOCKET); // mServiceHandler.sendEmptyMessage(DISCONNECT_LOOPER); // super.onDestroy(); // } // // @Override // public void onMessage(okio.BufferedSource payload, WebSocket.PayloadType type) throws IOException { // Log.i("jianfei", "onMessage"); // if (type == WebSocket.PayloadType.TEXT) { // String str=payload.readUtf8(); // Log.i("jianfei", "str:"+str); // payload.close(); // } // } // // @Override // public void onClose(int code, String reason) { // mConnected = false; // Log.i("jianfei", "onClose"); // } // // @Override // public void onFailure(IOException e) { // Log.i("jianfei", "onFailure"); // mConnected = false; // } }
/* * 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.exolin.sudoku.solver; /** * * @author Thomas */ public interface SudokuListener { public void onStateChanged(Sudoku.PossibleNumersCalculationState state); enum ChangeType { ADDED, REMOVED } public void onNumberKnown(CellBlock block, SudokoCell cell, int number); public void onNumberUnset(CellBlock block, SudokoCell cell); public void onPossibleNumbersChanged(CellBlock block, SudokoCell cell, int number, ChangeType event); SudokuListener NONE = new SudokuListener() { @Override public void onNumberKnown(CellBlock block, SudokoCell cell, int number) {} @Override public void onNumberUnset(CellBlock block, SudokoCell cell) {} @Override public void onPossibleNumbersChanged(CellBlock block, SudokoCell cell, int number, ChangeType event) {} @Override public void onStateChanged(Sudoku.PossibleNumersCalculationState state) {} }; }
/* * 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 programa; /** * * @author laura */ import java.time.LocalDateTime; import javax.swing.JOptionPane; public class aspiradora { //Variables static double bateria; static String teclado; static int posicionAspiradora; static String uPredeterminado = "usuario", //Usuario predeterminado cPredeterminada = "usuario"; //Contraseña predeterminada //Array para guardar los metros cuadrados de cada dependencia static double dependencias[]; //Método main public static void main(String[] args) { inicioSesion(); menu(); } //Método para iniciar sesion en sistema public static void inicioSesion() { // Variables String usuario, contrasenia; // Proceso do { usuario = JOptionPane.showInputDialog(null, "Introduzca el " + "usuario"); contrasenia = JOptionPane.showInputDialog(null, "Introduzca " + "la contraseña"); } while (!usuario.equals(uPredeterminado) || !contrasenia.equals(cPredeterminada)); } //Método que meuestra el menú con las diferenctes opciones public static void menu() { // Variables int seleccion;//Variable que se encarga de guardar la selección del menú //Proceso do { teclado = JOptionPane.showInputDialog(null, "Introduzca la opción " + "deseada:\n" + "1 - Configurar sistema\n" + "2 - Establecer Carga\n" + "3 - Selección de Modo (Aspiración o Aspiración y Fregado\n" + "4 - Estado general\n" + "5 - Llevar a base de Carga\n" + "6 - Salir"); seleccion = Integer.parseInt(teclado); } while (seleccion < 1 || seleccion > 6); seleccionMenu(seleccion); } //Método que activas la seleccion del menú public static void seleccionMenu(int seleccion) { switch (seleccion) { case 1: configuracionSistema(); break; case 2: inicializacionBateria(); break; case 3: seleccionModo(); break; case 4: estadoGeneral(); break; case 5: cargaBateria(); break; default: break; } if (seleccion != 6) { menu(); } } //Método que configura el sistema (dependencias y metros^2 de cada una) public static void configuracionSistema() { // Varaibles // Inicialización de array para dependencias. teclado = JOptionPane.showInputDialog(null, "Introduzca la cantidad " + "de dependencias"); dependencias = new double[Integer.parseInt(teclado)]; // Incializamos las variables relativas a las dependencias, los metros^2 for (int i = 0; i < dependencias.length; i++) { do { teclado = JOptionPane.showInputDialog(null, "Introduzca los " + "metros cuadrados que tiene la dependencia " + i); dependencias[i] = Integer.parseInt(teclado); } while (dependencias[i] < 1 || dependencias[i] > 100); } } //Método para introducir la Batería actual public static void inicializacionBateria() { // PUNTO 2 do { teclado = JOptionPane.showInputDialog(null, "Introduzca la bateria:"); bateria = Double.parseDouble(teclado); } while (bateria > 100 || bateria < 0); } //Método para selección del modo de limpieza (incluye aspiración solo //y asparación junto con fregado) public static void seleccionModo() { //Variables int modo; //Variable que nos guarda el modo seleccionado //Proceso //Nos aseguramos que estén inicializadas las variables necesarias. teclado = JOptionPane.showInputDialog(null, "¿Ha realizado con " + "anterioridad la configuración del sistema y" + " ha establecido la carga?"); if (teclado.equals("Si")) { do { teclado = JOptionPane.showInputDialog(null, "Introduzca el modo" + " que desee\n1 - Aspiración en Modo Completo" + "\n2 - Aspiración en Modo Dependencias" + "\n3 - Aspiración y Fregado en Modo Completo" + "\n4 - Aspiración y Fregado en Modo Dependencias"); modo = Integer.parseInt(teclado); } while (modo < 1 || modo > 4); //Arrays que usaremos para los los siguientes metodos //Array que se encarga de guardar si las dependencias están limpias boolean limpias[] = new boolean[dependencias.length]; /* * Array que se encarga de guardar la batería que consume cada dependencia */ double bateriaDependencia[] = new double[dependencias.length]; //Variables a usar //Se encarga de guardar el consumo de batería por metro^2 final double BATERIA; /* * Estructura que se encarga de inicializar la constante bateria según si es * modo aspiración o aspiración y fregado */ if (modo == 1 || modo == 2) { //Para el modo solo aspiración BATERIA = 1.5; } else { //Para el modo aspiración y fregado BATERIA = 2.25; } //Estructura que nos desplaza al modo seleccionado switch (modo) { //PUNTO 3 case 1: modoCompleto(bateriaDependencia, limpias, BATERIA); break; case 2: modoDependencias(bateriaDependencia, limpias, BATERIA); break; //PUNTO 4 case 3: modoCompleto(bateriaDependencia, limpias, BATERIA); break; case 4: modoDependencias(bateriaDependencia, limpias, BATERIA); break; } } else { /* * En caso de no estar inicializadas las necesarias se pide que vayan a esa * parte del menú */ JOptionPane.showMessageDialog(null, "Vaya primero a 'configuración " + "sistema' y posteriormente a 'Establecer carga'"); } } //Método que se encarga del Modo Completo public static void modoCompleto(double bateriaDependencia[], boolean limpias[], double BATERIA) { //Proceso for (int i = 0; i < bateriaDependencia.length; i++) { /* * Inicializamos el array que nos muestra el consumo de batería por dependencia */ bateriaDependencia[i] = dependencias[i] * BATERIA; //Vamos al metodo que se encarga de la descarga de batería descargarBateria(i, bateriaDependencia, limpias); } String limpio = ""; //Guardamos las dependencias que han sido limpiadas String noLimpio = ""; //Guardamos las que no por falta de batería for (int i = 0; i < limpias.length; i++) { if (limpias[i]) { limpio += "dependecia " + i + " "; } else { noLimpio += "dependecia " + i + " "; } } //Mostramos el resultado del modo Completo JOptionPane.showMessageDialog(null, "Las dependencias limpiadas son: " + limpio); JOptionPane.showMessageDialog(null, "Las dependencias NO limpiadas son: " + noLimpio); } //Método que se encarga del Modo Dependencias public static void modoDependencias(double bateriaDependencia[], boolean limpias[], double BATERIA) { //Variables /* * En la siguiente variable guardamos: 1º si se quiere limpiar una dependencia * 2º la dependencia a limpiar */ int pendienteLimpiar; /* * Inicializamos el array que nos muestra el consumo de batería por dependencia */ for (int i = 0; i < bateriaDependencia.length; i++) { bateriaDependencia[i] = dependencias[i] * BATERIA; } //Proceso do { do { teclado = JOptionPane.showInputDialog(null, "¿Desea limpiar " + "alguna habitación? \nIntroduzca:\n1 - Sí\n2 - No"); pendienteLimpiar = Integer.parseInt(teclado); } while (pendienteLimpiar != 1 && pendienteLimpiar != 2); if (pendienteLimpiar == 1) { do { teclado = JOptionPane.showInputDialog(null, "Introduzca el" + " número de habitación a limpiar"); pendienteLimpiar = Integer.parseInt(teclado); } while (pendienteLimpiar > dependencias.length || pendienteLimpiar < 0); //Vamos al metodo que se encarga de la descarga de batería descargarBateria(pendienteLimpiar, bateriaDependencia, limpias); } } while (pendienteLimpiar != 2); } //Método que se encarga de descargar la bateria tanto en modo completo como //en modo dependencia public static void descargarBateria(int hab, double bateriaDependencia[], boolean limpias[]) { // Proceso if (bateria > bateriaDependencia[hab] && bateria > 3) { bateria -= bateriaDependencia[hab]; limpias[hab] = true; System.out.println("Se ha limpiado la habitación: " + hab); posicionAspiradora = hab; } else { limpias[hab] = false; System.out.println("No tiene suficiente" + "bateria para limpiar la habitacioón " + hab); } } //Método que muestra el estado general de las aspiradora public static void estadoGeneral() { //Variables //Variables para día y hora LocalDateTime localDateTime = LocalDateTime.now(); double metros = 0; //Suma de los metros de la casa for (int i = 0; i < dependencias.length; i++) { metros += dependencias[i]; } //Proceso String estadoGeneral = "La hora y fecha de hoy es: " + localDateTime + "\nEl nivel de batería es: " + bateria + "\nEl lugar donde se " + "encuentra es la habitacion " + posicionAspiradora + "\nEl número de dependencias es: " + dependencias.length + "\nLos metros cuadrados de la casa son: " + metros; JOptionPane.showMessageDialog(null, estadoGeneral); } //Metodo que se encarga de llevar la aspiradora a la base de carga public static void cargaBateria() { //Variables bateria = 100; //Proceso JOptionPane.showMessageDialog(null, "Cargando... Batería cargada."); } }
package com.symphox.framework.utils; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfWriter; import com.symphox.framework.dao.AbstractPdfView; /** * Reference * http://hmkcode.com/spring-mvc-view-json-xml-pdf-or-excel/ * https://github.com/hmkcode/Spring-Framework/blob/master/spring-mvc-json-pdf-xls-excel/src/main/java/com/hmkcode/view/abstractview/AbstractPdfView.java * http://www.technicalkeeda.com/spring/generate-pdf-using-spring-framework * http://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-creating-pdf-documents-with-wkhtmltopdf/ */ public class PDFViewUtil extends AbstractPdfView { protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception { } }
package com.example.qunxin.erp; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.text.TextUtils; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.example.qunxin.erp.activity.PersonalInfoActivity; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by qunxin on 2019/8/9. */ public class UserBaseDatus { //辨别点击+ 按钮时是客户还是供应商 public boolean isKehu=true; public static UserBaseDatus instance=new UserBaseDatus(); public final String url="http://119.23.219.127:8094/"; public String avatar=""; public String userId="1"; public String cretorName="管理员"; private UserBaseDatus(){} public static UserBaseDatus getInstance(){ if(instance==null){ instance=new UserBaseDatus(); } return instance; } //5f179ee93114e6575cffcbddc9193423a1a767e5f0e469fa50e195e05746712c public String getSign(){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); String date = dateFormat.format(new Date()); final String syspwd = Sha.bytes2Hex(Sha.sha256("ppaQunXin" + date)); Log.d("signa", syspwd); return syspwd; } String dealResponseResult(InputStream inputStream) { String resultData = null; //存储处理结果 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; try { while ((len = inputStream.read(data)) != -1) { byteArrayOutputStream.write(data, 0, len); } } catch (IOException e) { e.printStackTrace(); } resultData = new String(byteArrayOutputStream.toByteArray()); return resultData; } //从网络上下载图片 Bitmap mBitmap; public Bitmap isSuccessGet(String strUrl, String contentType) { //通过Get方法请求获取网络图片 try { URL url=new URL(strUrl); HttpURLConnection connection=(HttpURLConnection) url.openConnection(); //设置请求方式 connection.setRequestMethod("GET"); //设置超时时间 connection.setConnectTimeout(30*1000); connection.setRequestProperty("Content-Type",contentType);//设置请求体的类型是文本类型 //发起连接 connection.connect(); //获取状态码 int requestCode=connection.getResponseCode(); if (requestCode==HttpURLConnection.HTTP_OK){ /* * 1.获得文件长度 * 2.通过缓冲输入流 * 3.将输入流转换成字节数组 * 4.将字节数组转换成位图 * */ int fileLength=connection.getContentLength(); InputStream is=new BufferedInputStream(connection.getInputStream()); //获取到字节数组 byte[] arr=streamToArr(is); //将字节数组转换成位图 mBitmap= BitmapFactory.decodeByteArray(arr,0,arr.length); is.close(); /* * 下载完成后将消息发送出去 * 通知主线程,更新UI * */ }else { Log.e("TAG", "run:error "+requestCode); } }catch (MalformedURLException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return mBitmap; } //将输入流转换成字节数组 public byte[] streamToArr(InputStream inputStream){ try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte[] buffer=new byte[1024]; int len; while ((len=inputStream.read(buffer))!=-1){ baos.write(buffer,0,len); } //关闭输出流 baos.close(); //关闭输入流 inputStream.close(); //返回字节数组 return baos.toByteArray(); }catch (IOException e){ e.printStackTrace(); //若失败,则返回空 return null; } } //发送post请求 public Map isSuccessPost (String strUrl, String strData, String contentType) { boolean isSuccess = false; String StrResponseBody = null; JSONObject json=new JSONObject(); Map map=new HashMap(); try { byte[] requestBody = strData.getBytes("UTF-8"); URL url = new URL(strUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(3000); //设置连接超时时间 httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据 httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据 httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据 httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存 httpURLConnection.setRequestProperty("Content-Type",contentType);//设置请求体的类型是文本类型 httpURLConnection.setRequestProperty("Content-Length", String.valueOf(requestBody.length));//设置请求体的长度 OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write(requestBody); int response = httpURLConnection.getResponseCode();//获得服务器的响应码 if (response == HttpURLConnection.HTTP_OK) { InputStream inptStream = httpURLConnection.getInputStream(); //获得响应体的字节数组 StrResponseBody = dealResponseResult(inptStream); json=new JSONObject(StrResponseBody); Log.d("StrResponseBody",StrResponseBody ); if(json.getInt("code")==0){ isSuccess = true; map.put("isSuccess",isSuccess); map.put("json",json); }else { map.put("isSuccess",isSuccess); map.put("json",json); } } } catch (IOException e) { map.put("isSuccess",isSuccess); map.put("json",json); } catch (JSONException e) { map.put("isSuccess",isSuccess); map.put("json",json); e.printStackTrace(); } return map; } //验证手机号 public boolean judPhone(Context context, TextView phoneNumberText) { if (TextUtils.isEmpty(phoneNumberText.getText().toString().trim())) { Toast.makeText(context, "请输入您的电话号码", Toast.LENGTH_SHORT).show(); phoneNumberText.requestFocus(); return false; } else if (phoneNumberText.getText().toString().trim().length() != 11) { Toast.makeText(context, "您的电话号码位数不正确", Toast.LENGTH_SHORT).show(); phoneNumberText.requestFocus(); return false; } else { String phone_number = phoneNumberText.getText().toString().trim(); String num = "[1][358]\\d{9}"; if (phone_number.matches(num)) return true; else { Toast.makeText(context, "请输入正确的手机号码", Toast.LENGTH_SHORT).show(); return false; } } } /** * 判断邮箱是否合法 * @param email * @return */ public boolean isEmail(String email,Context context){ if (null==email || "".equals(email)) return false; //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配 Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配 Matcher m = p.matcher(email); if(m.matches()){ return true; }else { Toast.makeText(context, "请输入正确的邮箱", Toast.LENGTH_SHORT).show(); return false; } } public void getShangpinbianhao(final String type, final Activity activity, final TextView textView){ //http://119.23.219.127:8094/api/numberApp/getNumber?type=5 new Thread(new Runnable() { final String url="http://119.23.219.127:8094/api/numberApp/getNumber"; final String data="type="+type; final String contentType = "application/x-www-form-urlencoded"; @Override public void run() { Map map=UserBaseDatus.getInstance().isSuccessPost(url, data, contentType); if((boolean)(map.get("isSuccess"))){ JSONObject json=(JSONObject) map.get("json"); try { final String string=json.getString("data"); activity.runOnUiThread(new Runnable() { @Override public void run() { textView.setText(string); } }); } catch (JSONException e) { e.printStackTrace(); } } } }).start(); } String dataStr=""; public String getShangpinbianhao(final String type){ //http://119.23.219.127:8094/api/numberApp/getNumber?type=5 new Thread(new Runnable() { final String url="http://119.23.219.127:8094/api/numberApp/getNumber"; final String data="type="+type; final String contentType = "application/x-www-form-urlencoded"; @Override public void run() { Map map=UserBaseDatus.getInstance().isSuccessPost(url, data, contentType); if((boolean)(map.get("isSuccess"))){ JSONObject json=(JSONObject) map.get("json"); try { dataStr=json.getString("data"); } catch (JSONException e) { e.printStackTrace(); } } } }).start(); return dataStr; } /** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * * @param url Service net address * @param params text content * @param files pictures * @return String result of Service response * @throws IOException */ public String post(String url, Map<String, String> params, Map<String, File> files) throws IOException { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX ="--", LINEND = "\r\n"; String MULTIPART_FROM_DATA ="multipart/form-data"; String CHARSET ="UTF-8"; URL uri =new URL(url); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(10* 1000);// 缓存的最长时间 conn.setDoInput(true);// 允许输入 conn.setDoOutput(true);// 允许输出 conn.setUseCaches(false);// 不允许使用缓存 conn.setRequestMethod("POST"); conn.setRequestProperty("connection","keep-alive"); conn.setRequestProperty("Charsert","UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA +";boundary=" + BOUNDARY); // 首先组拼文本类型的参数 StringBuilder sb =new StringBuilder(); for(Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\""+ LINEND); sb.append("Content-Type: text/plain; charset="+ CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit"+ LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream =new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // 发送文件数据 if(files != null) for(Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 =new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getValue().getName() +"\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset="+ CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); InputStream is =new FileInputStream(file.getValue()); byte[] buffer =new byte[1024]; int len = 0; while((len = is.read(buffer)) != -1) { outStream.write(buffer,0, len); } is.close(); outStream.write(LINEND.getBytes()); } // 请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 得到响应码 int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sb2 =new StringBuilder(); if(res == 200) { int ch; while((ch = in.read()) != -1) { sb2.append((char) ch); } } outStream.close(); conn.disconnect(); String name = new String(sb2.toString().getBytes("iso-8859-1"), "UTF-8"); return name; } }
package com.Action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.dao.zzglDao; import com.opensymphony.xwork2.ActionSupport; public class uploadAction extends ActionSupport implements Serializable { /** * */ private static final long serialVersionUID = -6650946208997214277L; private File file1; private String file1FileName; private String file1ContentType; public File getFile1() { return file1; } public void setFile1(File file1) { this.file1 = file1; } public String getFile1FileName() { return file1FileName; } public void setFile1FileName(String file1FileName) { this.file1FileName = file1FileName; } public String getFile1ContentType() { return file1ContentType; } public void setFile1ContentType(String file1ContentType) { this.file1ContentType = file1ContentType; } @Override public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); System.out.println("文件"+request.getParameter("files")); System.out.println("文件:" + file1); System.out.println("文件名:" + file1FileName); System.out.println("文件类型:" + file1ContentType); zzglDao gl =new zzglDao(); gl.addpdf(file1FileName); ServletContext sc = ServletActionContext.getServletContext(); String storePath = sc.getRealPath("jsp/pdf"); OutputStream out = new FileOutputStream(storePath + "\\" + file1FileName); InputStream is = new FileInputStream(file1); byte[] buf = new byte[1024]; int length = 0; while (-1 != (length = is.read(buf))) { out.write(buf, 0, length); } is.close(); out.close(); return SUCCESS; } }
package com.example.sudheep; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; import com.example.sudheep.Sturepository.StudentRepository; import com.example.sudheep.stuentity.Student; @SpringBootTest class DemoJpqlApplicationTests { @Autowired StudentRepository stuRepos; @Test void testFindAll() { List<Student> students = stuRepos.findAllStudents(); students.forEach(student -> System.out.print(student.getId() + " " + student.getFirstname() + " " + student.getLastname() + " \n ")); } @Test void testPartialSelect() { List<Object[]> list = stuRepos.findAllStudentsPartialRecords(); list.forEach(l -> System.out.println(l[0] + " " + l[1])); } @Test void testFindByFirstName() { List<Student> students = stuRepos.findAllStudentsByfirstName("sai"); students.forEach(student -> System.out.print(student.getId() + " " + student.getFirstname() + " " + student.getLastname() + " \n ")); } @Test void testBetweenIds() { List<Student> students = stuRepos.findAllStudentsBetweenScores(2, 5); students.forEach(student -> System.out.print(student.getId() + " " + student.getFirstname() + " " + student.getLastname() + " \n ")); } @Test @Transactional @Rollback(false) void testDeleteByFirstName() { stuRepos.deleteByFirstName("alex"); } @Test @Transactional @Rollback(false) void testInsert() { stuRepos.insertRecord(1,"alex","zelikovsky"); } @Test void testFindAllWithPaging() { Pageable pageable = PageRequest.of(0, 3); List<Student> students = stuRepos.findAllStudents(pageable); students.forEach(student -> System.out.print(student.getId() + " " + student.getFirstname() + " " + student.getLastname() + " \n ")); } @Test void testFindAllWithPagingandSorting() { Pageable pageable = PageRequest.of(1, 3, Sort.by("Id").descending()); List<Student> students = stuRepos.findAllStudents(pageable); students.forEach(student -> System.out.print(student.getId() + " " + student.getFirstname() + " " + student.getLastname() + " \n ")); } }
package com.example.weatherapp.data; import android.accounts.NetworkErrorException; import android.util.Log; import com.example.weatherapp.config.WeatherApiConfig; import com.example.weatherapp.models.Weather; import com.example.weatherapp.models.WeatherModel; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Query; import static com.example.weatherapp.config.WeatherApiConfig.BASE_URL; public class WeatherService { Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); WeatherApi weatherApi = retrofit.create(WeatherApi.class); public void getWeatherByCity(String cityName, WeatherCallBack callBack) { Call<WeatherModel> call = weatherApi.getWeatherByCity(cityName, WeatherApiConfig.API_KEY, "metric"); call.enqueue(new Callback<WeatherModel>() { @Override public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) { if (response.isSuccessful() && response.body() != null) { callBack.onSuccess(response.body()); Log.e("tag", "onResponse: " + response.body()); } } @Override public void onFailure(Call<WeatherModel> call, Throwable t) { callBack.inFailure(new NetworkErrorException()); } }); } public interface WeatherCallBack { void onSuccess(WeatherModel model); void inFailure(Exception e); } public interface WeatherApi { @GET("data/2.5/weather") Call<WeatherModel> getWeatherByCity( @Query("q") String city, @Query("appid") String apiId, @Query("units") String units); } }
package org.squonk.rdkit.db; /** * Created by timbo on 13/12/2015. */ public enum MolSourceType { MOL("mol_from_ctab(%s)", "qmol_from_ctab(%s)"), SMILES("mol_from_smiles(%s)", "qmol_from_smiles(%s)"), SMARTS("mol_from_smarts(%s)", "mol_from_smarts(%s)"); public String molFunction; public String qmolFunction; MolSourceType(String molFunction, String qmolFunction) { this.molFunction = molFunction; this.qmolFunction = qmolFunction; } }
package leetCode.exercise; import java.util.ArrayList; import java.util.List; /** * 6. Z字形变换 * 将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数: P A H N A P L S I I G Y I R 之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR" 实现一个将字符串进行指定行数变换的函数: string convert(string s, int numRows); 示例 1: 输入: s = "PAYPALISHIRING", numRows = 3 输出: "PAHNAPLSIIGYIR" 示例 2: 输入: s = "PAYPALISHIRING", numRows = 4 输出: "PINALSIGYAHRPI" 解释: P I N A L S I G Y A H R P I * @createTime 2018年4月24日 下午10:28:09 * @author MrWang */ public class Num6 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub /*String result = convert("PAYPALISHIRING", 3); System.out.println("PAHNAPLSIIGYIR".equals(result)); String s = convert("PAYPALISHIRING", 4); System.out.println("PINALSIGYAHRPI".equals(s)); String s2 = convert("AB", 1); System.out.println(s2);*/ System.out.println(-123 + ""); System.out.println(reverse(-2147483648)); } public static int reverse(int x) { boolean positive = x >= 0; long abs = Math.abs((long)x); System.out.println(abs); StringBuilder s = new StringBuilder(abs + ""); s.reverse(); System.out.println(s.toString()); long parseLong = Long.parseLong(s.toString()); if(parseLong > Integer.MAX_VALUE || (0 - parseLong) < Integer.MIN_VALUE){ return 0; } return (int) (positive?parseLong:(0-parseLong)); } public static String convert(String s, int numRows) { if(s == null || "".equals(s) || numRows <= 1){ return s; } List<Character>[] lists = new List[numRows]; for(int i = 0; i < lists.length; i++){ lists[i] = new ArrayList<Character>(); } int k = 0; boolean asc = true; int listLength = 0; char[] array = s.toCharArray(); for(int i = 0; i < array.length; i++){ lists[k].add(array[i]); if(k == numRows - 1){ asc = false; } if(k == 0){ asc = true; } if(asc){ k++; } else { k--; } } StringBuilder result = new StringBuilder(); for(int i = 0; i < (s.length() > lists.length? lists.length : s.length()); i++){ List<Character> list = lists[i]; for(int j = 0; j < list.size(); j++){ result.append(list.get(j)); } } return result.toString(); } }
package arraysnstrings; import java.util.ArrayList; import java.util.Arrays; public class Pair { public int a; public int b; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (a != other.a) return false; if (b != other.b) return false; return true; } public static ArrayList<Pair> findPairs(int[] array, int X) { ArrayList<Pair> pairs = new ArrayList<Pair>(); Arrays.sort(array); int start = 0; int end = array.length - 1; System.out.println(Arrays.toString(array)); while (start != end) { int sum = array[start] + array[end]; if (sum == X) { pairs.add(new Pair(array[start], array[end])); } if (X < sum) { end--; } else { start++; } } return pairs; } }
import java.util.*; class reverse_words { static String reverse(String s) { int space=s.indexOf(" "); if(space!=-1) reverse(s.substring(space+1,s.length())); if(space==-1) System.out.print(s.substring(0,s.length())); else System.out.print(s.substring(0,space+1)); return s; } public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter string"); String s=sc.nextLine(); reverse(s+" "); } }
package com.atomix.fragments; import com.atomix.adapter.MainMenuAdapter; import com.atomix.sidrapulse.R; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class SectionFragment extends Fragment { private GridView mGridView; private MainMenuAdapter mMainMenuAdapter; private Activity activity; // public SectionFragment(Activity activity) { // this.activity = activity; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view; // view = inflater.inflate(R.layout.grid_view, container, false); // mGridView = (GridView) view.findViewById(R.id.grid_view_single); // return view; // } // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // if (activity != null) { // mMainMenuAdapter = new MainMenuAdapter(activity, gridItems); // if (mGridView != null) { // mGridView.setAdapter(mMainMenuAdapter); // } // // mGridView.setOnItemClickListener(new OnItemClickListener() { // @Override // public void onItemClick(AdapterView parent, View view, int position, long id) { // onGridItemClick((GridView) parent, view, position, id); // } // }); // } // } // // public void onGridItemClick(GridView g, View v, int position, long id) { // Toast.makeText(activity, "Position Clicked: - " + position + " & " + "Text is: - " + gridItems[position].title, Toast.LENGTH_LONG).show(); // Log.e("TAG", "POSITION CLICKED " + position); // } }
package org.bootcamp.service; import org.bootcamp.model.Person; import java.util.List; public interface PersonService { void addPerson(Person p); void updatePerson(Person p); List<Person> listPerson(); Person getPersonById(int id); void removePerson(int id); }
package com.bag.pin.service; import com.bag.pin.model.Pin; import com.bag.pin.service.handler.CrawlerPinFailureHandler; import com.bag.pin.service.handler.CrawlerPinSuccessHandler; import com.bag.utils.crawler.htmlParser.PinParser; import com.bag.utils.crawler.htmldownloader.HttpClientHtmlDownloader; import org.jsoup.nodes.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PinCrawlerService { public static final String PentoPageBaseUrl = "http://www.pento.cn/pin/"; public static final int DEFAULT_PENTO_RANGE_CHECK_INTERVAL = 100000; @Autowired private HttpClientHtmlDownloader htmlDownloader; @Autowired private PinParser pinParser; @Autowired private CrawlerPinSuccessHandler crawlerPinSuccessHandler; @Autowired private CrawlerPinFailureHandler crawlerPinFailureHandler; public void craw(long minPentoId, long maxPentoId) { for(long i = minPentoId; i<=maxPentoId; i++) { crawl(String.valueOf(i)); } } public void crawl(String pentoId) { String url = getUrl(pentoId); try { Document doc = htmlDownloader.getHtmlDocument(url); Pin pin = pinParser.parseToPin(pentoId, doc); crawlerPinSuccessHandler.handle(pin); } catch (Exception e) { crawlerPinFailureHandler.handle(url, e); } } private String getUrl(String pentoId) { return PentoPageBaseUrl + pentoId; } }
package Classes; import java.io.File; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.ResourceBundle; import Model.MergeTask; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.Button; public class Controller implements Initializable{ public Button confirmMergeButton; public void initialize(URL location, ResourceBundle resources) { } @FXML public void confirmMerge(ActionEvent e) { //MessageBox Path path2 = Paths.get("C:\\HashiCorp\\Vagrant"); Path path = Paths.get("C:\\fedora"); // MergeTask mergeTask = new MergeTask() Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Flow monitor "); alert.setHeaderText("Status"); alert.setContentText("Created new Merge Task !"); alert.showAndWait(); } }
package com.deity.design.decorator; /** * 接口 * Created by Deity on 2017/2/13. */ public interface IMan { /**帅哥总是和身价挂钩的*/ long worth(); /**描述*/ String description(); }
package com.mtp.model; /** * @author jlamby * */ public class VigilanceMessage extends BaseInstruction { private String message; public VigilanceMessage(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "VigilanceMessage [message=" + message + "]"; } }
package com.mridul.customretrofitlibrary.Network; import android.content.Context; import android.util.Log; import com.mridul.customretrofitlibrary.BaseApplication; import com.mridul.customretrofitlibrary.R; import org.json.JSONException; import org.json.JSONObject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by mridul on 05/26/18. */ public class NetworkCall { private final String TAG = NetworkCall.class.getSimpleName(); private Progress mprogress; private NetworkCallBack networkCallBack; private Context context; private Call<String> call; public NetworkCall(NetworkCallBack callBackInterface, Context context) { mprogress = new Progress(context); mprogress.setCancelable(false); networkCallBack = callBackInterface; this.context = context; } public void NetworkAPICall(final String baseUrl, final String apiType, final boolean showprogress) { Log.e(TAG, "================" + apiType); APIInterface service = BaseApplication.getRetrofitInstance(baseUrl).create(APIInterface.class); if (CheckConnection.isConnected(context)) { if (showprogress) mprogress.show(); call = networkCallBack.getAPI(apiType, service); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { if (showprogress) mprogress.dismiss(); if (response.body() != null && response.isSuccessful()) { String jsonString = response.body(); try { if (!jsonString.isEmpty()) { JSONObject jsonObject = new JSONObject(jsonString); networkCallBack.SuccessCallBack(jsonObject, apiType); } else { networkCallBack.ErrorCallBack(context.getString(R.string.jsonparsing_error_message), apiType); } } catch (JSONException e1) { e1.printStackTrace(); } } else { networkCallBack.ErrorCallBack(context.getString(R.string.exception_api_error_message), apiType); } } @Override public void onFailure(Call<String> call, Throwable t) { if (showprogress) mprogress.dismiss(); networkCallBack.ErrorCallBack(context.getResources().getString(R.string.exception_api_error_message), apiType); } }); } else { networkCallBack.ErrorCallBack(context.getString(R.string.internet_error_message), apiType); } } public void cancelRequest() { if (call != null) call.cancel(); } }
package org.aksw.autosparql.tbsl.gui.vaadin.model; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.aksw.autosparql.commons.nlp.wordnet.WordNetUnpacker; import org.aksw.autosparql.tbsl.algorithm.knowledgebase.LocalKnowledgebase; import org.aksw.autosparql.tbsl.algorithm.knowledgebase.RemoteKnowledgebase; import org.aksw.autosparql.tbsl.algorithm.learning.TBSL; import org.aksw.autosparql.tbsl.algorithm.learning.TbslDbpedia; import org.aksw.autosparql.tbsl.algorithm.learning.TbslOxford; import org.aksw.autosparql.tbsl.gui.vaadin.Manager; import org.aksw.autosparql.tbsl.gui.vaadin.util.FallbackIndex; import org.aksw.autosparql.tbsl.gui.vaadin.widget.DBpediaInfoLabel; import org.aksw.autosparql.tbsl.gui.vaadin.widget.OxfordInfoLabel; import org.aksw.sparql2nl.naturallanguagegeneration.SimpleNLGwithPostprocessing; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.vaadin.terminal.Resource; import com.vaadin.terminal.ThemeResource; public class ExtendedTBSL { private final TBSL tbsl; public final SimpleNLGwithPostprocessing nlg; public static final ExtendedTBSL DBPEDIA = createDBpediaTBSL(); public static final ExtendedTBSL OXFORD = createOxfordTBSL(); private final String label; private final String labelPropertyURI; private final String descriptionPropertyURI; private final String imagePropertyURI; private final boolean allowAdditionalProperties; // = false private final Map<String, String> mandatoryProperties; private final Map<String, String> optionalProperties; private final Class infoBoxClass; private final String targetVar; private final List<String> exampleQuestions; private List<String> propertyNamespaces = Collections.emptyList(); private String labelPropertyLanguage; private Set<String> propertyBlackList = Collections.emptySet(); private InfoTemplate infoTemplate = null; private FallbackIndex fallbackIndex = null; private Resource icon = null; /* public ExtendedTBSL(TBSL tbsl, String labelPropertyURI, String descriptionPropertyURI) { this(tbsl, labelPropertyURI, descriptionPropertyURI, null); } public ExtendedTBSL(TBSL tbsl, String labelPropertyURI, String descriptionPropertyURI, String imagePropertyURI) { this.tbsl = tbsl; this.labelPropertyURI = labelPropertyURI; this.descriptionPropertyURI = descriptionPropertyURI; this.imagePropertyURI = imagePropertyURI; } public ExtendedTBSL(TBSL tbsl, String labelPropertyURI, String descriptionPropertyURI, String imagePropertyURI, Map<String, String> mandatoryProperties, Map<String, String> optionalProperties) { this.tbsl = tbsl; this.labelPropertyURI = labelPropertyURI; this.descriptionPropertyURI = descriptionPropertyURI; this.imagePropertyURI = imagePropertyURI; this.mandatoryProperties = mandatoryProperties; this.optionalProperties = optionalProperties; } public ExtendedTBSL(TBSL tbsl, String labelPropertyURI, String descriptionPropertyURI, String imagePropertyURI, InfoTemplate infoTemplate, Map<String, String> mandatoryProperties, Map<String, String> optionalProperties) { this.tbsl = tbsl; this.labelPropertyURI = labelPropertyURI; this.descriptionPropertyURI = descriptionPropertyURI; this.imagePropertyURI = imagePropertyURI; this.infoTemplate = infoTemplate; this.label = tbsl.getLabel(); this.mandatoryProperties = mandatoryProperties; this.optionalProperties = optionalProperties; } public ExtendedTBSL(TBSL tbsl, String labelPropertyURI, String descriptionPropertyURI, String imagePropertyURI, Map<String, String> mandatoryProperties, Map<String, String> optionalProperties, Class infoBoxClass, String targetVar, boolean allowAdditionalProperties) { this.tbsl = tbsl; this.labelPropertyURI = labelPropertyURI; this.descriptionPropertyURI = descriptionPropertyURI; this.imagePropertyURI = imagePropertyURI; this.label = tbsl.getLabel(); this.mandatoryProperties = mandatoryProperties; this.optionalProperties = optionalProperties; this.infoBoxClass = infoBoxClass; this.targetVar = targetVar; this.allowAdditionalProperties = allowAdditionalProperties; } */ public ExtendedTBSL(TBSL tbsl, String labelPropertyURI, String descriptionPropertyURI,String imagePropertyURI, Map<String, String> mandatoryProperties, Map<String, String> optionalProperties, Class infoBoxClass, String targetVar, boolean allowAdditionalProperties, List<String> exampleQuestions,SimpleNLGwithPostprocessing nlg, Resource icon) { this.tbsl = tbsl; this.labelPropertyURI = labelPropertyURI; this.descriptionPropertyURI = descriptionPropertyURI; this.imagePropertyURI = imagePropertyURI; this.label = tbsl.getLabel(); this.mandatoryProperties = mandatoryProperties; this.optionalProperties = optionalProperties; this.infoBoxClass = infoBoxClass; this.targetVar = targetVar; this.allowAdditionalProperties = allowAdditionalProperties; this.exampleQuestions = exampleQuestions; this.nlg=nlg; this.icon=icon; } public void setPropertyNamespaces(List<String> propertyNamespaces) { this.propertyNamespaces = propertyNamespaces; } public List<String> getPropertyNamespaces() { return propertyNamespaces; }; public TBSL getTBSL() { return tbsl; } public String getLabelPropertyURI() { return labelPropertyURI; } public String getDescriptionPropertyURI() { return descriptionPropertyURI; } public String getImagePropertyURI() { return imagePropertyURI; } public InfoTemplate getInfoTemplate() { return infoTemplate; } public Map<String, String> getMandatoryProperties() { return mandatoryProperties; } public Map<String, String> getOptionalProperties() { return optionalProperties; } public Class getInfoBoxClass() { return infoBoxClass; } public String getLabel() { return label; } public String getTargetVar() { return targetVar; } public boolean isAllowAdditionalProperties() { return allowAdditionalProperties; } public void setLabelPropertyLanguage(String labelPropertyLanguage) { this.labelPropertyLanguage = labelPropertyLanguage; } public String getLabelPropertyLanguage() { return labelPropertyLanguage; } public List<String> getExampleQuestions() { return exampleQuestions; } public void setPropertyBlackList(Set<String> propertyBlackList) { this.propertyBlackList = propertyBlackList; } public Set<String> getPropertyBlackList() { return propertyBlackList; } public void setFallbackIndex(FallbackIndex fallbackIndex) { this.fallbackIndex = fallbackIndex; } public FallbackIndex getFallbackIndex() { return fallbackIndex; } public void setIcon(Resource icon) { this.icon = icon; } public Resource getIcon() { return icon; } @Override public String toString() { return label; } static private List<String> loadQuestions(InputStream fileInputStream){ List<String> questions = new ArrayList<String>(); try { BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream)); String question; while((question = br.readLine()) != null){ questions.add(question); } br.close(); } catch (IOException e) { e.printStackTrace(); } return questions; } private static Set<String> loadPropertyBlackList(String filename){ Set<String> uris = new HashSet<String>(); try { BufferedReader br = new BufferedReader(new InputStreamReader(ExtendedTBSL.class.getClassLoader().getResourceAsStream(filename))); String line; while((line = br.readLine()) != null){ uris.add(line); } br.close(); } catch (IOException e) { e.printStackTrace(); } return uris; } private static ExtendedTBSL createDBpediaTBSL() { String infoTemplateHtml = "<div><h3><b>label</b></h3></div>" + "<div style='float: right; height: 100px; width: 200px'>" + "<div style='height: 100%;'><img style='height: 100%;' src=\"imageURL\"/></div>" + "</div>" + "<div>description</div>"; Map<String, String> propertiesMap = new HashMap<String, String>(); propertiesMap.put("label", "http://www.w3.org/2000/01/rdf-schema#label"); propertiesMap.put("imageURL", "http://www.w3.org/2000/01/rdf-schema#comment"); propertiesMap.put("description", "http://xmlns.com/foaf/0.1/depiction"); InfoTemplate infoTemplate = new InfoTemplate(infoTemplateHtml, null); List<String> exampleQuestions = loadQuestions(ExtendedTBSL.class.getClassLoader().getResourceAsStream("dbpedia_example_questions.txt")); SimpleNLGwithPostprocessing nlg = new SimpleNLGwithPostprocessing(((RemoteKnowledgebase)TbslDbpedia.INSTANCE.getKnowledgebase()).getEndpoint(),Manager.getInstance().getCacheDir(),WordNetUnpacker.getUnpackedWordNetDir().getAbsolutePath()); ExtendedTBSL eTBSL = new ExtendedTBSL( TbslDbpedia.INSTANCE, "http://www.w3.org/2000/01/rdf-schema#label", "http://www.w3.org/2000/01/rdf-schema#comment", "http://xmlns.com/foaf/0.1/depiction", null, null, DBpediaInfoLabel.class, "x0", true, exampleQuestions,nlg,new ThemeResource("images/dbpedia_live_logo.png")); eTBSL.setLabelPropertyLanguage("en"); eTBSL.setPropertyNamespaces(Arrays.asList(new String[]{"http://dbpedia.org/ontology/", RDF.getURI(), RDFS.getURI()})); Set<String> propertyBlackList = loadPropertyBlackList("dbpedia_property_blacklist.txt"); eTBSL.setPropertyBlackList(propertyBlackList); // FallbackIndex fallback = new SolrIndex(SOLR_SERVER_URI_EN+"dbpedia_resources"); // ekb.setFallbackIndex(fallback); return eTBSL; } private static ExtendedTBSL createOxfordTBSL(){ String infoTemplateHtml = "<div><h3><b>label</b></h3></div>" + "<div style='float: right; height: 100px; width: 200px'>" + "<div style='height: 100%;'><img style='height: 100%;' src=\"imageURL\"/></div>" + "</div>" + "<div>description</div>"; Map<String, String> propertiesMap = new HashMap<String, String>(); propertiesMap.put("label", "http://purl.org/goodrelations/v1#name"); propertiesMap.put("imageURL", "http://xmlns.com/foaf/0.1/depiction"); propertiesMap.put("description", "http://purl.org/goodrelations/v1#description"); InfoTemplate infoTemplate = new InfoTemplate(infoTemplateHtml, null); Map<String, String> optionalProperties = new HashMap<String, String>(); optionalProperties.put("bedrooms", "http://diadem.cs.ox.ac.uk/ontologies/real-estate#bedrooms"); optionalProperties.put("bathrooms", "http://diadem.cs.ox.ac.uk/ontologies/real-estate#bathrooms"); optionalProperties.put("receptions", "http://diadem.cs.ox.ac.uk/ontologies/real-estate#receptions"); optionalProperties.put("street", "http://www.w3.org/2006/vcard/ns#street-address"); optionalProperties.put("locality", "http://www.w3.org/2006/vcard/ns#locality"); List<String> exampleQuestions = loadQuestions(ExtendedTBSL.class.getClassLoader().getResourceAsStream("oxford_example_questions.txt")); String wordnetDir = WordNetUnpacker.getUnpackedWordNetDir().getAbsolutePath(); /*@Nonnull */Model model = ((LocalKnowledgebase)TbslOxford.INSTANCE.getKnowledgebase()).getModel(); SimpleNLGwithPostprocessing nlg = new SimpleNLGwithPostprocessing(model,wordnetDir); Resource icon = new ThemeResource("images/oxford_logo.gif"); ExtendedTBSL ekb = new ExtendedTBSL( TbslOxford.INSTANCE, "http://purl.org/goodrelations/v1#name", "http://purl.org/goodrelations/v1#description", "http://xmlns.com/foaf/0.1/depiction", null, optionalProperties, OxfordInfoLabel.class, "x0", false, exampleQuestions,nlg,icon); return ekb; } }
package com.gy.service.impl; import com.gy.entity.Car; import com.gy.mapper.CarMapper; import com.gy.service.CarService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @Author: liumin * @Description: * @Date: Created in 2018/3/29 17:13 */ @Service public class CarServiceImpl implements CarService { @Autowired private CarMapper carMapper; @Override public List<Car> findCarByCarNo(String carNo) { return carMapper.findCarByCarNo(carNo); } }
package me.jcomo.slimtwitter.utils; import java.util.Map; import java.util.Scanner; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; /** * A class used to scan strings for words with certain character prefixes. When a word with a * registered character prefix is found, the appropriate handler is called. * * One use case for this class is to format Twitter text. The scanner is configured to search for * hashtags and mentions and instructed to add spans accordingly to the text. */ public class PrefixScanner { private static final Pattern WHITESPACE = Pattern.compile("\\s+"); private final Map<Character, OnPrefixDetectedListener> prefixListeners = new ConcurrentHashMap<>(); public interface OnPrefixDetectedListener { void onPrefixDetected(int position, String text); } public void addPrefix(char prefix, OnPrefixDetectedListener listener) { prefixListeners.put(prefix, listener); } public void scan(String text) { Scanner s = new Scanner(text); s.useDelimiter(WHITESPACE); while (s.hasNext()) { String token = s.next(); if (0 == token.length()) { continue; } char prefix = token.charAt(0); OnPrefixDetectedListener listener = prefixListeners.get(prefix); if (listener != null) { int position = s.match().start(); listener.onPrefixDetected(position, token); } } } }
package com.example.sqlshop; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.example.sqlshop.db.ProductDBAdapter; import com.example.sqlshop.utils.StringUrlUtil; public class AddProductActivity extends AppCompatActivity { private EditText add_proContent, add_proPrice, add_proName; private ImageView add_proBmppath; private ProductDBAdapter productDBAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_product); add_proContent = findViewById(R.id.add_proContent); add_proPrice = findViewById(R.id.add_proPrice); add_proName = findViewById(R.id.add_proName); add_proBmppath = findViewById(R.id.add_proBmppath); productDBAdapter = new ProductDBAdapter(this); add_proBmppath.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent, 1001); } }); } public void addProduct(View view) { String name = add_proName.getText().toString(); String price = add_proPrice.getText().toString(); String content = add_proContent.getText().toString(); String bmpPath = StringUrlUtil.getRealFilePath(this, uri); Log.e("testDemo", bmpPath); if (!TextUtils.isEmpty(name) & !TextUtils.isEmpty(bmpPath)) { try { if (!productDBAdapter.CheckIsDataAlreadyInDBorNot(name)) { productDBAdapter.add(name, price, bmpPath, content); Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show(); finish(); } else { Toast.makeText(this, "商品已存在", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show(); } } } private Uri uri; @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1001) { // 从相册返回的数据 if (data != null) { // 得到图片的全路径 uri = data.getData(); add_proBmppath.setImageURI(uri); } } } }
package raft.server.storage; /** * Author: ylgrgyq * Date: 18/6/10 */ public enum RecordType { // Zero is reserved for preallocated files kZeroType((byte)0), kFullType((byte)1), // For fragments kFirstType((byte)2), kMiddleType((byte)3), kLastType((byte)4), // EOF kEOF((byte)5), // For unfinished record kUnfinished((byte)6), // For corrupted record kCorruptedRecord((byte)7); private final byte code; RecordType(byte code) { this.code = code; } public byte getCode() { return code; } public static RecordType getRecordTypeByCode(byte code) { for (RecordType type: RecordType.values()) { if (type.getCode() == code) { return type; } } throw new IllegalArgumentException(String.format("type not found by code: %s", code)); } }
package com.gmail.filoghost.holograms.api; import org.bukkit.Location; import org.bukkit.World; @Deprecated public abstract interface Hologram { @Deprecated public abstract boolean update(); @Deprecated public abstract void hide(); @Deprecated public abstract void addLine(String paramString); @Deprecated public abstract void removeLine(int paramInt); @Deprecated public abstract void setLine(int paramInt, String paramString); @Deprecated public abstract void insertLine(int paramInt, String paramString); @Deprecated public abstract String[] getLines(); @Deprecated public abstract int getLinesLength(); @Deprecated public abstract void clearLines(); @Deprecated public abstract Location getLocation(); @Deprecated public abstract double getX(); @Deprecated public abstract double getY(); @Deprecated public abstract double getZ(); @Deprecated public abstract World getWorld(); @Deprecated public abstract void setLocation(Location paramLocation); @Deprecated public abstract void teleport(Location paramLocation); @Deprecated public abstract void setTouchHandler(TouchHandler paramTouchHandler); @Deprecated public abstract TouchHandler getTouchHandler(); @Deprecated public abstract boolean hasTouchHandler(); @Deprecated public abstract long getCreationTimestamp(); @Deprecated public abstract void delete(); @Deprecated public abstract boolean isDeleted(); }
package lab.nnverify.platform.verifyplatform.services; import lab.nnverify.platform.verifyplatform.mapper.VerificationMapper; import lab.nnverify.platform.verifyplatform.models.Verification; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class VerificationService { @Autowired VerificationMapper verificationMapper; public List<Verification> findVerificationHistoryByUserId(Integer userId) { return verificationMapper.fetchVerificationByUserId(userId); } public Verification fetchVerificationById(String verifyId) { return verificationMapper.fetchVerificationById(verifyId); } public boolean saveVerificationParams(Verification params) { int modified = verificationMapper.insertVerificationRecord(params); return modified != 0; } public boolean finishVerificationUpdateStatus(String verifyId, String status) { int modified = verificationMapper.updateVerificationRecordStatus(verifyId, status); return modified != 0; } }
package com.imooc.ioc.com.imooc.ioc.beanlifecycle; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * @Author: Asher Huang * @Date: 2019-10-16 * @Description: com.imooc.ioc.com.imooc.ioc.beanlifecycle * @Version:1.0 */ public class BeanLifecylce implements BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean { private String name; public BeanLifecylce() { System.out.println("第一步:BeanLifecylce被构造方法执行了"); } public void setName(String name) { System.out.println("第二步:设置bean属性"); this.name = name; } @Override public void setBeanName(String s) { System.out.println("第三步:设置beanname"+name); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("第四步:了解工厂信息"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("第六步:属性设置后"); } public void init() { System.out.println("第七步:BeanLifecycle被初始化了"); } public void run() { System.out.println("第九步:执行bean自身的方法,即:处理业务逻辑方法"); } @Override public void destroy() throws Exception { System.out.println("第十步:因为实现了DisposableBean,所以要执行destory()方法"); } public void teardown() { System.out.println("第十一步:执行用户自定义的销毁方法。BeanLifecycle被销毁了"); } }
package com.portware.FIXCertification; public class Test { public static void main(String a[]) { new Property(); System.out.println(Property.getGlobalProp("RunType")); } }
package com.project.alex.ServiceDiscipline; import lombok.Data; import org.springframework.stereotype.Component; import javax.persistence.*; @Data @Entity public class HoursZCE { @Id @GeneratedValue(strategy= GenerationType.AUTO, generator = "hoursZ") private int id; private int hoursCourse; private int hoursExam; private int hoursZachet; }
package DataStructures.arrays; import java.util.ArrayList; /** * Created by senthil on 20/8/16. */ public class PascalsTriangle { /*public List<Integer> getRow(int rowIndex) { ArrayList<Integer> result = new ArrayList<Integer>(); if (rowIndex < 0) return result; result.add(1); for (int i = 1; i <= rowIndex; i++) { for (int j = result.size() - 2; j >= 0; j--) { result.set(j + 1, result.get(j) + result.get(j + 1)); } result.add(1); } return result; }*/ public ArrayList<ArrayList<Integer>> buildPascal(int n) { ArrayList<ArrayList<Integer>> pList = new ArrayList<>(); if(n == 0) return pList; ArrayList<Integer> p = new ArrayList<>(); p.add(1); pList.add(p); for(int i = 1; i <= n; i++) { ArrayList<Integer> c = new ArrayList<>(); c.add(1); for(int j = 0; j < i - 1; j++) { c.add(p.get(j) + p.get(j+1)); } c.add(1); pList.add(c); p = c; } return pList; } public ArrayList<Integer> getRow(int a) { ArrayList<Integer> p = new ArrayList<>(); if (a == 0) { p.add(1); return p; } p.add(1); for (int i = 1; i <= a; i++) { ArrayList<Integer> c = new ArrayList<>(); c.add(1); for (int j = 0; j < i - 1; j++) { c.add(p.get(j) + p.get(j + 1)); } c.add(1); p = c; if (a == i-1) return c; } return p; } public static void main(String a[]) { PascalsTriangle pt = new PascalsTriangle(); //pt.buildPascal(4); pt.getRow(4); } }
package com.melodygram.fragment; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.melodygram.R; import com.melodygram.database.CategoryDataSource; import com.melodygram.model.ChatSticker; import com.melodygram.model.ChatStickerCategory; import com.melodygram.model.Sticker; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; /** * Created by LALIT on 14-06-2016. */ public class StickersFragment extends android.support.v4.app.Fragment implements ViewPager.OnPageChangeListener { private int mEmojiTabLastSelectedIndex = -1; private View[] mStickersTabs; private ArrayList<ChatSticker> stickerListOne = new ArrayList<>(); private ArrayList<ChatSticker> stickerListTwo = new ArrayList<>(); private ArrayList<ChatSticker> stickerListThree = new ArrayList<>(); private ArrayList<ChatSticker> stickerListFour = new ArrayList<>(); private ArrayList<ChatSticker> stickerListFive = new ArrayList<>(); private OnStickerButtonClickedListener onStickerButtonClickedListener; private ViewPager stickerPager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.stickers_layout, container, false); stickerPager = (ViewPager) view.findViewById(R.id.sticker_pager); stickerPager.addOnPageChangeListener(this); mStickersTabs = new View[6]; mStickersTabs[0] = view.findViewById(R.id.sticker_0); mStickersTabs[1] = view.findViewById(R.id.sticker_1); mStickersTabs[2] = view.findViewById(R.id.sticker_2); mStickersTabs[3] = view.findViewById(R.id.sticker_3); mStickersTabs[4] = view.findViewById(R.id.sticker_4); mStickersTabs[5] = view.findViewById(R.id.emojis_button); for (int i = 0; i < mStickersTabs.length; i++) { final int position = i; mStickersTabs[i].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (v.getId() != R.id.emojis_button) stickerPager.setCurrentItem(position); else { // load stickers fragment if (onStickerButtonClickedListener != null) { onStickerButtonClickedListener.onEmojiConButtonClicked(); } } } }); } onPageSelected(0); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (getActivity() instanceof OnStickerButtonClickedListener) { onStickerButtonClickedListener = (OnStickerButtonClickedListener) getActivity(); } else if (getParentFragment() instanceof OnStickerButtonClickedListener) { onStickerButtonClickedListener = (OnStickerButtonClickedListener) getParentFragment(); } else { throw new IllegalArgumentException(activity + " must implement interface " + OnStickerButtonClickedListener.class.getSimpleName()); } } @Override public void onDetach() { onStickerButtonClickedListener = null; super.onDetach(); } @Override public void onPageScrolled(int i, float v, int i2) { } @Override public void onPageSelected(int i) { if (mEmojiTabLastSelectedIndex == i) { return; } switch (i) { case 0: case 1: case 2: case 3: case 4: if (mEmojiTabLastSelectedIndex >= 0 && mEmojiTabLastSelectedIndex < mStickersTabs.length) { mStickersTabs[mEmojiTabLastSelectedIndex].setSelected(false); } mStickersTabs[i].setSelected(true); mEmojiTabLastSelectedIndex = i; break; } } @Override public void onPageScrollStateChanged(int i) { } private static class StickersPagerAdapter extends FragmentStatePagerAdapter { private List<StickersGridFragment> fragments; public StickersPagerAdapter(FragmentManager fm, List<StickersGridFragment> fragments) { super(fm); this.fragments = fragments; } @Override public android.support.v4.app.Fragment getItem(int i) { return fragments.get(i); } @Override public int getCount() { return fragments.size(); } } /** * A class, that can be used as a TouchListener on any view (e.g. a Button). * It cyclically runs a clickListener, emulating keyboard-like behaviour. First * click is fired immediately, next before initialInterval, and subsequent before * normalInterval. * <p/> * <p>Interval is scheduled before the onClick completes, so it has to run fast. * If it runs slow, it does not generate skipped onClicks. */ public static class RepeatListener implements View.OnTouchListener { private Handler handler = new Handler(); private int initialInterval; private final int normalInterval; private final View.OnClickListener clickListener; private Runnable handlerRunnable = new Runnable() { @Override public void run() { if (downView == null) { return; } handler.removeCallbacksAndMessages(downView); handler.postAtTime(this, downView, SystemClock.uptimeMillis() + normalInterval); clickListener.onClick(downView); } }; private View downView; /** * @param initialInterval The interval before first click event * @param normalInterval The interval before second and subsequent click * events * @param clickListener The OnClickListener, that will be called * periodically */ public RepeatListener(int initialInterval, int normalInterval, View.OnClickListener clickListener) { if (clickListener == null) throw new IllegalArgumentException("null runnable"); if (initialInterval < 0 || normalInterval < 0) throw new IllegalArgumentException("negative interval"); this.initialInterval = initialInterval; this.normalInterval = normalInterval; this.clickListener = clickListener; } public boolean onTouch(View view, MotionEvent motionEvent) { switch (motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: downView = view; handler.removeCallbacks(handlerRunnable); handler.postAtTime(handlerRunnable, downView, SystemClock.uptimeMillis() + initialInterval); clickListener.onClick(view); return true; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_OUTSIDE: handler.removeCallbacksAndMessages(downView); downView = null; return true; } return false; } } public interface OnStickerButtonClickedListener { void onEmojiConButtonClicked(); } public void getAllStickers() { CategoryDataSource categoryDataSource = new CategoryDataSource(getActivity()); categoryDataSource.open(); LinkedHashMap<String, ChatStickerCategory> list = categoryDataSource.getAllStickersCategory(); categoryDataSource.close(); int s = 0; for (String key : list.keySet()) { switch (s) { case 0: stickerListOne.addAll(list.get(String.valueOf(key)).getStickerList()); break; case 1: stickerListTwo.addAll(list.get(String.valueOf(key)).getStickerList()); break; case 2: stickerListThree.addAll(list.get(String.valueOf(key)).getStickerList()); break; case 3: stickerListFour.addAll(list.get(String.valueOf(key)).getStickerList()); break; case 4: stickerListFive.addAll(list.get(String.valueOf(key)).getStickerList()); break; case 5: break; } s++; } final StickersPagerAdapter stickersAdapter = new StickersPagerAdapter(getFragmentManager(), Arrays.asList( StickersGridFragment.newInstance(stickerListOne), StickersGridFragment.newInstance(stickerListTwo), StickersGridFragment.newInstance(stickerListThree), StickersGridFragment.newInstance(stickerListFour) , StickersGridFragment.newInstance(stickerListFive))); stickerPager.setAdapter(stickersAdapter); } }
/* * 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 bbdd; /** * * @author JD */ public class pruebaEntradas { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here /* Fecha f= new Fecha(2,10,2016); Sesion s = new Sesion("nombre pelicula","nombre sala",f,"21:30"); FactoriaEntradas factor = new FactoriaEntradas(); Entrada e; //Entrada normal e = factor.nuevaEntrada(0, "0", s, 10, 5, false, 6); System.out.println(e.toString()); e = factor.nuevaEntrada(1, "1", s, 5, 14, false, 6); System.out.println(e.toString()); */ int participantes = 9; double winner=-1; for (int i = 0; i < 20; i++) { winner = Math.floor(Math.random()*participantes); System.out.println("winner: "+winner); } } }
package data; import engine.DataProcessor; import lombok.Data; import lombok.Getter; import lombok.Setter; import pojo.Board; import pojo.Player; import java.util.*; @Getter @Setter public class StateData { private int hash; private Board board; private boolean isWhiteTurn; private boolean isEnd; private String winner; private double stateValue; private Set<Integer> parentHash; private Set<Integer> childrenHash; private Player whitePlayer; private Player blackPlayer; public StateData(){ this.board = new Board(); this.isWhiteTurn = true; this.isEnd = false; this.winner = null; this.stateValue = 0; this.parentHash = new HashSet<>(); this.childrenHash = new HashSet<>(); this.whitePlayer = new Player(true); this.blackPlayer = new Player(false); this.hash = this.hashCode(); } public StateData(Board board, boolean isWhiteTurn, boolean isEnd){ this.board = board; this.isWhiteTurn = isWhiteTurn; this.isEnd = isEnd; this.winner = null; this.stateValue = 0; this.parentHash = new HashSet<>(); this.childrenHash = new HashSet<>(); this.whitePlayer = new Player(true); this.blackPlayer = new Player(false); this.hash = this.hashCode(); } public StateData(StateData copy){ this.hash = copy.hash; this.board = new Board(copy.board); this.isWhiteTurn = copy.isWhiteTurn; this.isEnd = copy.isEnd; this.stateValue = copy.stateValue; this.parentHash = new HashSet<>(); this.childrenHash = new HashSet<>(); this.winner = null; this.whitePlayer = new Player(copy.whitePlayer); this.blackPlayer = new Player(copy.blackPlayer); this.hash = copy.hash; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof StateData)) return false; StateData stateData = (StateData) o; if (isWhiteTurn != stateData.isWhiteTurn) return false; if (isEnd != stateData.isEnd) return false; if (Double.compare(stateData.stateValue, stateValue) != 0) return false; if (!Objects.equals(board, stateData.board)) return false; if (!Objects.equals(winner, stateData.winner)) return false; if (!Objects.equals(parentHash, stateData.parentHash)) return false; if (!Objects.equals(childrenHash, stateData.childrenHash)) return false; if (!Objects.equals(whitePlayer, stateData.whitePlayer)) return false; return Objects.equals(blackPlayer, stateData.blackPlayer); } @Override public int hashCode() { int result; long temp; result = board != null ? board.hashCode() : 0; result = 31 * result + (isWhiteTurn ? 1 : 0); result = 31 * result + (isEnd ? 1 : 0); result = 31 * result + (winner != null ? winner.hashCode() : 0); // temp = Double.doubleToLongBits(stateValue); // result = 31 * result + (int) (temp ^ (temp >>> 32)); // result = 31 * result + (parentHash != null ? parentHash.hashCode() : 0); // result = 31 * result + (childrenHash != null ? childrenHash.hashCode() : 0); // result = 31 * result + (whitePlayer != null ? whitePlayer.hashCode() : 0); // result = 31 * result + (blackPlayer != null ? blackPlayer.hashCode() : 0); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.hash); sb.append(";"); sb.append(DataProcessor.boardToNotation(this.board)); sb.append(";"); sb.append(this.isWhiteTurn); sb.append(";"); sb.append(this.isEnd); sb.append(";"); sb.append(this.winner); sb.append(";"); sb.append(this.stateValue); sb.append(";"); sb.append(this.childrenHash); sb.append(";"); sb.append(this.parentHash); sb.append("\n"); return sb.toString(); } public void print(){ this.getBoard().print(); System.out.println(this.isWhiteTurn); System.out.println(this.whitePlayer); System.out.println(this.blackPlayer); System.out.println(this.hash); System.out.println(this.toString()); } }
package com.ramonmr95.app.entities; import java.io.Serializable; import java.util.Date; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import org.modelmapper.ModelMapper; import com.ramonmr95.app.dtos.BrandDto; @Entity @Table(name = "brands") public class Brand implements Serializable { private static final long serialVersionUID = 3788028350480857010L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private UUID id; @NotNull(message = "The name is required") @Column(nullable = false, unique = true) private String name; @Temporal(TemporalType.TIMESTAMP) @CreationTimestamp private Date created_at; @Temporal(TemporalType.TIMESTAMP) @UpdateTimestamp private Date updated_at; public Brand() { } public Brand(String name) { this.name = name; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreated_at() { return created_at; } public void setCreated_at(Date created_at) { this.created_at = created_at; } public Date getUpdated_at() { return updated_at; } public void setUpdated_at(Date updated_at) { this.updated_at = updated_at; } public BrandDto getDto() { ModelMapper modelMapper = new ModelMapper(); return modelMapper.map(this, BrandDto.class); } }
package com.example.fiorella.gastoapp.Controllers; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.fiorella.gastoapp.Database.AdminSQLiteOpenHelper; import com.example.fiorella.gastoapp.R; public class ActivityGeneralLimit extends AppCompatActivity { private EditText txt_limit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_general_limit); txt_limit = (EditText)findViewById(R.id.txt_limit); } /** * Metodo para guardar el limite general de gastos * @param view */ public void saveGeneralLimit(View view){ AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "gastoApp", null, 1); SQLiteDatabase dataBase = admin.getWritableDatabase(); String string_limit = txt_limit.getText().toString(); if(!string_limit.equals("")){ int int_limit = Integer.parseInt(string_limit); ContentValues limitModification = new ContentValues(); limitModification.put("general_limit", int_limit); dataBase.update("general_configuration", limitModification,"general_limit=" + int_limit, null); Toast.makeText(this, "El limite de gastos ha sido cambiado", Toast.LENGTH_SHORT).show(); dataBase.close(); startActivity(new Intent(ActivityGeneralLimit.this, ActivityConfiguration.class)); }else{ Toast.makeText(this, "Debes llenar el campo", Toast.LENGTH_SHORT).show(); } dataBase.close(); } @Override public void onBackPressed(){ startActivity(new Intent(ActivityGeneralLimit.this, ActivityConfiguration.class)); } }
package com.moped.snake.view; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.LinearLayout; import com.moped.snake.model.Food; import com.moped.snake.model.OnFinishGameListener; import com.moped.snake.model.Snake; import com.moped.snake.model.World; import com.moped.snake.resources.FieldLoader; import com.moped.snake.resources.FieldLoaderFactory; public class SnakeView extends LinearLayout implements OnFinishGameListener { private static final int GAME_SPEED = 300; private Update updateRunnable; private final Paint paint; private final Paint resultPaint; private int score = 0; private World world; private boolean endGame = false; public SnakeView(Context context, AttributeSet attrs) { super(context, attrs); paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.BLACK); resultPaint = new Paint(Paint.ANTI_ALIAS_FLAG); resultPaint.setColor(Color.RED); resultPaint.setTextSize(80); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if(endGame) { dispatchWinningDraw(canvas); } else { world.setDimensions(getWidth(), getHeight()); world.draw(canvas); } } private int incRows = 15; private int incColumns = 30; private void dispatchWinningDraw(Canvas canvas) { float width = getWidth(); float height = getHeight(); int rows = 15; int columns = 30; float cWidht = width/rows; float cHeight = height/columns; paint.setColor(Color.BLACK); int x = 0; int y = 0; for(int i = 0; i < columns-incColumns; i++) { for(int j = 0; j < rows-incRows; j++) { if(i%2 == 0) { if(j%2 == 0) canvas.drawRect(x, y, x+cWidht, y+cHeight, paint); } else if(j%2 != 0) canvas.drawRect(x, y, x+cWidht, y+cHeight, paint); x += cWidht; } x = 0; y += cHeight; } if(incColumns != 0) { incColumns-=2; incRows--; postInvalidateDelayed(30); } else { canvas.drawText("Game Over", width/10, height/2, resultPaint); new PosterDialog(getContext(), score).show(); } } @Override protected void onFinishInflate() { super.onFinishInflate(); initializeWorld(); } private void initializeWorld() { FieldLoader fieldLoader = FieldLoaderFactory.newFieldLoader(getContext(), FieldLoaderFactory.LOCAL_FIELD_LOADER); world = new World(fieldLoader.load()); world.addGameObject(new Food()); world.addGameObject(new Food()); world.addGameObject(new Snake()); world.setPosition(null); world.setOnFinishGameListener(this); updateRunnable = new Update(); postDelayed(updateRunnable, GAME_SPEED); } private class Update implements Runnable { public void run() { if(!endGame) { world.updatePositions(); invalidate(); updateRunnable = new Update(); postDelayed(updateRunnable, GAME_SPEED); } } } public void onFinishGame(int score) { endGame = true; this.score = score; } @Override public boolean onTouchEvent(MotionEvent event) { if(endGame) ((Activity)getContext()).finish(); else if(event.getAction() == MotionEvent.ACTION_DOWN) world.onTouch(event.getX(), event.getY()); return super.onTouchEvent(event); } }
package com.example.praty.githubrepo.viewmodel; import android.arch.lifecycle.MutableLiveData; import android.arch.lifecycle.ViewModel; import com.example.praty.githubrepo.model.Repositories; import com.example.praty.githubrepo.repository.RepoRepository; import java.util.List; //viewmodel class for MainActivity public class MainActivityViewModel extends ViewModel { private MutableLiveData<List<Repositories>> mRepositories; private RepoRepository mRepo; public void queryRepo(String query, String sort, String order, int page){ mRepo=RepoRepository.getInstance(); mRepositories=mRepo.getRepositories(query,sort,order,page); } public MutableLiveData<List<Repositories>> getRepositories() { return mRepositories; } }
package com.xiezh.findlost.activity; import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.xiezh.findlost.adapter.TalkAdapter; import com.xiezh.findlost.domain.Item; import com.xiezh.findlost.domain.Message; import com.xiezh.findlost.domain.UserInfo; import com.xiezh.findlost.service.MessageService; import com.xiezh.findlost.service.MyService; import com.xiezh.findlost.utils.DataManager; import com.xiezh.fragmentdemo2.R; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class TalkActivity extends BaseActivity implements View.OnClickListener { private static final int addMessage = 0x161; MessageService.MessageBinder myBinder; private Item item; private File userCache; private List<Message> data; private TextView back; private TextView username; private Button send; private EditText message; private UserInfo userinfo; private ListView listView; private TalkAdapter adapter; private Message needSend; private String talkWithName; private String talkWithUserId; private ServiceConnection connForUserinfo = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { MyService.MyBinder myBinder = (MyService.MyBinder) service; myBinder.getUserInfo(item.getCreateByID()); } @Override public void onServiceDisconnected(ComponentName name) { } }; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { myBinder = (MessageService.MessageBinder) service; if (needSend != null) { myBinder.sendMessage(needSend); } } @Override public void onServiceDisconnected(ComponentName name) { } }; private Handler handler = new Handler() { @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case addMessage: add(DataManager.newMessage); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_talk); DataManager.talkHandler = handler; Intent intent = getIntent(); data = new ArrayList<>(); item = (Item) intent.getSerializableExtra("item"); if (item != null) { Log.i("TalkActivity", "传递过来的" + item.toString()); talkWithName = item.getUserName(); talkWithUserId = item.getCreateByID(); Intent intentservice = new Intent(this, MyService.class); bindService(intentservice, connForUserinfo, Service.BIND_AUTO_CREATE); } else { UserInfo userinfo = (UserInfo) intent.getSerializableExtra("userinfo"); talkWithName = userinfo.getUserName(); talkWithUserId = userinfo.getUserID(); } blindView(); init(); adapter = new TalkAdapter(this, data); listView.setAdapter(adapter); DataManager.currentTalkActivity = talkWithUserId; listView.setSelection(adapter.getCount() - 1); } private void blindView() { back = (TextView) findViewById(R.id.talk_back); back.setOnClickListener(this); username = (TextView) findViewById(R.id.username); username.setText(talkWithName); send = (Button) findViewById(R.id.message_send); send.setOnClickListener(this); message = (EditText) findViewById(R.id.message); listView = (ListView) findViewById(R.id.message_list); } public void init() { File cacheDir = getCacheDir(); userCache = new File(cacheDir, talkWithUserId + ".cache"); if (!userCache.exists()) { try { userCache.createNewFile(); } catch (IOException e) { Toast.makeText(this, "创建缓存失败,将不会记录消息", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } FileInputStream in = null; BufferedReader bf = null; try { //读取记录文件 in = new FileInputStream(userCache); bf = new BufferedReader(new InputStreamReader(in)); String str; if (bf != null) { while ((str = bf.readLine()) != null && !str.equals("")) { //封装message JSONObject jsonObject = JSON.parseObject(str); String toId = jsonObject.getString("toId"); String fromId = jsonObject.getString("fromId"); JSONArray jsonArray = jsonObject.getJSONArray("messageList"); String toUser = jsonObject.getString("toUser"); UserInfo userinfo = JSON.parseObject(toUser, UserInfo.class); String date = jsonObject.getString("date"); Boolean type = jsonObject.getBoolean("type"); List<String> list = new ArrayList<String>(); for (int i = 0; i < jsonArray.size(); i++) { list.add((String) jsonArray.get(i)); } Message message = new Message(toId, fromId); message.setDate(date); message.setMessageList(list); message.setToUser(userinfo); message.setType(type); data.add(message); } bf.close(); in.close(); } } catch (Exception e) { e.printStackTrace(); } } public void writeMessage(Message message) { //写入输入输出 FileOutputStream out = null; BufferedWriter bfo = null; try { out = new FileOutputStream(userCache, true); bfo = new BufferedWriter(new OutputStreamWriter(out)); bfo.write(JSON.toJSONString(message)); bfo.newLine(); bfo.flush(); bfo.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.talk_back: finish(); break; case R.id.message_send: String txt = message.getText().toString(); message.setText(""); if (txt != null & !txt.equals("")) { //组装message /** * private String toId; private String fromId; private List<String> messageList; private UserInfo toUser; private String date; public Message(String toId,String fromId){ this.toId = toId; this.fromId = fromId; messageList = new ArrayList<String>(); } */ //Toast.makeText(this,"得到message",Toast.LENGTH_SHORT).show(); userinfo = DataManager.userInfo; //Toast.makeText(this,userinfo.getUserName(),Toast.LENGTH_SHORT).show(); if (userinfo != null) { Message message = new Message(talkWithUserId, userinfo.getUserID()); //Toast.makeText(this, userinfo.getUserID() + " to " +talkWithUserId,Toast.LENGTH_SHORT).show(); message.getMessageList().add(txt); //Toast.makeText(this,"userinfo不是空的",Toast.LENGTH_SHORT).show(); message.setToUser(userinfo); Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm"); String format = simpleDateFormat.format(date); message.setDate(format); message.setType(true); message.setItemId(-1); if (adapter != null) { //Toast.makeText(this,"adapter不是空的",Toast.LENGTH_SHORT).show(); adapter.add(message); writeMessage(message); needSend = message; if (myBinder == null) { Intent intent = new Intent(this, MessageService.class); bindService(intent, connection, Service.BIND_AUTO_CREATE); } else { myBinder.sendMessage(message); } } } } break; } } public void add(Message message) { adapter.add(message); int count = adapter.getCount(); listView.setSelection(count - 1); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }
/* $Id$ */ package djudge.swing; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import djudge.judge.AbstractDescription; import djudge.judge.checker.CheckerDescription; import djudge.judge.checker.CheckerTypeEnum; public class JValidatorPanel extends JPanel implements ActionListener, DocumentListener { private static final long serialVersionUID = 1L; AbstractDescription desc; JTextField txtParam; JTextField txtFile; JComboBox cbTypes; JButton jbChooseFile; JButton jbSave; private void setupComponent() { setupGUI(); setBorder(BorderFactory.createTitledBorder("Validator")); setPreferredSize(new Dimension(250, 140)); } public JValidatorPanel() { setupComponent(); setVisible(true); } protected void setupGUI() { final Dimension sz = new Dimension(150, 20); setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.WEST; c.gridx = 1; c.gridy = 0; c.gridwidth = 3; c.gridheight = 1; c.weighty = 1; c.insets = new Insets(2, 5, 2, 5); cbTypes = new JComboBox(CheckerTypeEnum.values()); cbTypes.setPreferredSize(sz); cbTypes.addActionListener(this); add(cbTypes, c); c.gridy = 1; txtParam = new JTextField(); txtParam.setPreferredSize(sz); txtParam.setEnabled(false); txtParam.addActionListener(this); txtParam.getDocument().addDocumentListener(this); add(txtParam, c); c.gridy = 2; txtFile = new JTextField(); txtFile.setPreferredSize(sz); txtFile.setEnabled(false); txtFile.addActionListener(this); txtFile.getDocument().addDocumentListener(this); add(txtFile, c); c.gridy = 3; jbSave = new JButton("Save"); jbSave.addActionListener(this); add(jbSave, c); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight = 1; c.anchor = GridBagConstraints.EAST; add(new JLabel("Type"), c); c.gridy = 1; c.anchor = GridBagConstraints.EAST; add(new JLabel("Param"), c); c.gridy = 2; c.anchor = GridBagConstraints.EAST; add(new JLabel("File"), c); } public void setData(AbstractDescription desc) { this.desc = desc; CheckerDescription limits = desc.getWorkValidator(); cbTypes.setSelectedItem(limits.type); txtFile.setText(limits.getExeName()); txtParam.setText(limits.param); } public void updateType() { String strType = cbTypes.getSelectedItem().toString(); CheckerTypeEnum type = CheckerTypeEnum.parse(strType); txtFile.setEnabled(false); txtParam.setEnabled(false); if (type.isParametrized()) { txtParam.setEnabled(true); } if (type.isExternal()) { txtFile.setEnabled(true); } } private void saveData() { String strType = cbTypes.getSelectedItem().toString(); CheckerTypeEnum type = CheckerTypeEnum.parse(strType); CheckerDescription vd = new CheckerDescription(desc.getContestID(), desc.getProblemID(), type, txtParam.getText(), txtFile.getText()); if (!vd.equals(desc.getWorkValidator())) { desc.setValidator(vd); } } private void updateParams() { } @Override public void actionPerformed(ActionEvent arg0) { if (arg0.getSource().equals(cbTypes)) { updateType(); } else if (arg0.getSource().equals(jbSave)) { saveData(); } } @Override public void changedUpdate(DocumentEvent arg0) { updateParams(); } @Override public void insertUpdate(DocumentEvent arg0) { updateParams(); } @Override public void removeUpdate(DocumentEvent arg0) { updateParams(); } }
package Test; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * Created by nschell on 3/12/14. */ public class TestLogin { }
import java.util.*; public class Main{ public static int Solution(int[] arr,int n,int m){ int result=0; int start =0; int end = Arrays.stream(arr).max().getAsInt(); while (start<=end){ int sum=0; int mid = (start+end)/2; for(int num: arr){ if (num>mid) sum+=num-mid; } if(sum<m) end=mid-1; else{ result= mid; start=mid+1; } } return result; } public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n =sc.nextInt(); int m = sc.nextInt(); int [] arr =new int[n]; for(int i =0;i<n;i++) arr[i] = sc.nextInt(); System.out.println(Solution(arr,n,m)); } }
package com.tpg.brks.ms.expenses.persistence.integration; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class Pair<T, U> { private T first; private U second; }
package com.cognixia.jump.djk.firstjavaproject.inputs; import com.cognixia.jump.djk.firstjavaproject.data.RecordWithId; import com.cognixia.jump.djk.firstjavaproject.functionalInterfaces.DataRecordInHandler; import com.cognixia.jump.djk.firstjavaproject.functionalInterfaces.Executor; import java.util.Collection; import java.util.Optional; import com.cognixia.jump.djk.firstjavaproject.InputScanner; class IdInput { private String prompt; private Executor canceler = null; private DataRecordInHandler inputHandler; private final static String RETRY_PROMPT = "Unable to process input. Please enter a valid id (or \"0\" or \"b\")."; private Collection<RecordWithId> entities; IdInput(String prompt, DataRecordInHandler inputHandler, Executor canceler) { this.prompt = prompt; this.inputHandler = inputHandler; this.canceler = canceler; } void run(Collection<RecordWithId> entities) { this.entities = entities; run("\n" + prompt); } private void run(String fullPrompt) { printFullPrompt(fullPrompt); try { int input = InputScanner.getIntInput(false); if (input < 0) tryAgain(); else if (input == 0 && canceler != null) { canceler.execute(); } else { Optional<RecordWithId> entity = findByIdInCollection(entities, input); if (entity.isPresent()) inputHandler.handleInput(entity.get()); else tryAgain(); } } catch(Exception e) { boolean isB = InputScanner.getInput().trim().toLowerCase().equals("b"); if (isB && (canceler != null)) canceler.execute(); else tryAgain(); } } private void tryAgain() { run(RETRY_PROMPT); } private Optional<RecordWithId> findByIdInCollection(Collection<RecordWithId> entities, int id) { // source: https://stackoverflow.com/questions/17526608/how-to-find-an-object-in-an-arraylist-by-property#answer-48839294 return entities.stream().filter(entity -> entity.hasId(id)).findFirst(); } private void printFullPrompt(String fullPrompt) { if (canceler != null) { fullPrompt += "\n(Or enter \"0\" or \"b\" to go back.):"; } System.out.println(fullPrompt); System.out.print(InputScanner.getLinePreface()); } }
package com.ads.utils; public class NetworkConfParser { }
package org.andrill.conop.core.solver; import org.andrill.conop.core.Dataset; import org.andrill.conop.core.Solution; /** * Defines a simple interface for solver components to publish results from the * solver run. * * @author Josh Reed (jareed@andrill.org) */ public interface SolverContext { /** * Gets the best solution found. * * @return the best solution or null. */ Solution getBest(); /** * Sets the best solution. * * @param best * the best solution. * @return the best solution. */ Solution setBest(Solution best); /** * Gets the dataset. * * @return the dataset. */ Dataset getDataset(); /** * Sets the dataset. * * @param dataset * the dataset. * @return the dataset. */ Dataset setDataset(Dataset dataset); /** * Get next potential solution. * * @return the next solution or null. */ Solution getNext(); /** * Set the next solution to try. * * @param next * the next solution. * @return the next solution. */ Solution setNext(Solution next); /** * Get a result by type. * * @param type * the interface or class of the type. * @return the object or null. */ <O> O get(Class<? super O> type); /** * Put a result by type. * * @param type * the interface or class of the type. * @param obj * the object. * @return the object. */ <O> O put(Class<? super O> type, O obj); }
/* * 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. */ /** * * @author dream */ public class Hunter extends MovablePiece implements CalcEatingMoves,CalcStraightMoves,CalcDiagonalMoves //inheritance between Hunter and parent GamePiece { //class datat members for Hunter public int energyLevel; //shows the current energy level of a hunter final int MAXENERGY = 6; //maximum energy constant of hunter char hName; //indicates the character the player chooses for a hunter private int[]position; int timesNotEaten; //shows the numbers of rounds since the hunter last ate //methods public Hunter() //constructor { type= "hunter"; //intializing hunter to type symbol= 'H'; //intializing symbol to H energyLevel= 4; // energy level of hunter set to 4 GamePiece Hunter= new GamePiece(); } public void setEnergyLevel(int S) { energyLevel = S; } public void sethName (char J) { hName = J; } public int getEnergyLevel() { return energyLevel; } public int getMAXENERGY() { return MAXENERGY; } public char gethName() { return hName; } public int[] calcNewPos(int direction) { int [] position = new int [2]; if (direction == 1) //integer variable to move and eat in direction up { calcMoveUp(); calcEatUp(); } else if (direction == 2) //integer variable to move and eat in direction right { calcMoveRight(); calcEatRight(); } if (direction == 3) //integer variable to move and eat in direction down { calcMoveDown(); calcEatDown(); } else if (direction == 4) //integer variable to move and eat in drection left { calcMoveLeft(); calcEatLeft(); } else if (direction == 5) //integer variable for up-left { calcMoveUpLeft(); } else if (direction == 6) //integer variable for up-right { calcMoveUpRight(); } else if(direction == 7) //integer variable for down-right { calcMoveDownRight(); } else if (direction == 8) //integer variable for down-left { calcMoveDownLeft(); } return position; } public void moveToNewPos(int newRow,int newCol) //updates data members on current postions to aid in moving the hunter setRowPos(newRow); setColPos(newCol); } @Override public void calcMoveLeft() { position[0]=rowPos; position[1]=colPos-1; } @Override public void calcEatLeft() { position[0]=rowPos; position[1]=colPos-1; } @Override public void calcMoveRight() { position[0]=rowPos; position[1]=colPos+1; } @Override public void calcEatRight() { position[0]=rowPos; position[1]=colPos+1; } @Override public void calcMoveUp() { position[0]=rowPos-1; position[1]=colPos; } @Override public void calcEatUp() { int colPos=getColPos(); int rowPos=getRowPos(); rowPos--; position[0]=rowPos-1; position[1]=colPos; } @Override public void calcMoveDown() { position[0]=rowPos+1; position[1]=colPos; } @Override public void calcEatDown() { position[0]=rowPos+1; position[1]=colPos; } @Override public void calcMoveUpLeft() { position[0]=rowPos-1; position[1]=colPos-1; } @Override public void calcMoveUpRight() { position[0]=rowPos-1; position[1]=colPos+1; } @Override public void calcMoveDownLeft() { position[0]=rowPos+1; position[1]=colPos-1; } @Override public void calcMoveDownRight() { position[0]=rowPos+1; position[1]=colPos+1; } }//Hunter
package vnfoss2010.smartshop.serverside.database.entity; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; import vnfoss2010.smartshop.webbased.share.WMedia; @PersistenceCapable public class Media { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private String name; @Persistent private String link; @Persistent private String mime_type; @Persistent private String description; public Media() { } // public Media(String name, String link, String mimeType, String // description, // Product product) { // this.name = name; // this.link = link; // mime_type = mimeType; // this.description = description; // } public Media(String name, String link, String mimeType, String description) { this.name = name; this.link = link; mime_type = mimeType; this.description = description; } public Media(String name, String link) { this.name = name; this.link = link; this.description = name; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the link */ public String getLink() { return link; } /** * @param link * the link to set */ public void setLink(String link) { this.link = link; } /** * @return the mime_type */ public String getMime_type() { return mime_type; } /** * @param mimeType * the mime_type to set */ public void setMime_type(String mimeType) { mime_type = mimeType; } /** * @return the description */ public String getDescription() { return description; } /** * @param description * the description to set */ public void setDescription(String description) { this.description = description; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Media other = (Media) obj; if (getId() == null) { if (other.getId() != null) return false; } else if (!getId().equals(other.getId())) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Media [id=" + getId() + ", link=" + link + ", mime_type=" + mime_type + ", name=" + name + "]"; } // /** // * @param product // * the product to set // */ // public void setProduct(Product product) { // this.product = product; // } // // /** // * @return the product // */ // public Product getProduct() { // return product; // } /** * @return the id */ public Long getId() { return id; } public WMedia cloneObject() { WMedia wm = new WMedia(); wm.name = this.name; wm.link = this.link; wm.mime_type = this.mime_type; wm.description = this.description; return wm; } }
package com.paypal.bfs.test.employeeserv.util; import java.time.format.DateTimeFormatter; /** * The Class Constants. */ public class Constants { public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); }
public class LinkedList<T> { private LinkedListNode<T> head; private LinkedListNode<T> tail; /** * Returns the head value of the list. Returns null if the head is null. * @return */ public T getHeadValue() { if(head == null) return null; return head.getData(); } public void removeHead() { if(head == null) return; LinkedListNode<T> top = head; head = head.getNext(); top.setNext(null); } /** * Adds the passed value to the tail of the list. Does nothing if the value is null. * @param value */ public void addToTail(T value) { if(value == null) return; LinkedListNode<T> node = new LinkedListNode<T>(value); if(head == null) { head = node; tail = node; } else { tail.setNext(node); tail = node; } } /** * Adds the passed value to the head of the list. Does nothing if the value is null. * @param value */ public void addToHead(T value) { if(value == null) return; LinkedListNode<T> node = new LinkedListNode<T>(value); if(head == null) { head = node; tail = node; } else { node.setNext(head); head = node; } } /** * Returns a comma delimited string containing all values in the list. */ public String toString() { if(head == null) return null; StringBuilder sb = new StringBuilder(); LinkedListNode<T> node = head; while(node != null) { sb.append(node.getData() + ", "); node = node.getNext(); } String result = sb.toString(); result = result.substring(0, result.length() - 2); return result; } }
package fr.skytasul.quests.utils.compatibility; import java.lang.reflect.Field; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.gmail.filoghost.holographicdisplays.api.Hologram; import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; import com.gmail.filoghost.holographicdisplays.api.VisibilityManager; import fr.skytasul.quests.BeautyQuests; import fr.skytasul.quests.api.AbstractHolograms; public class BQHolographicDisplays2 extends AbstractHolograms<Hologram> { private final boolean protocolLib = Bukkit.getPluginManager().isPluginEnabled("ProtocolLib"); private Field visibilitiesField; @Override public boolean supportPerPlayerVisibility() { return protocolLib; } @Override public boolean supportItems() { return true; } @Override public HD2Hologram createHologram(Location lc, boolean visible) { Hologram holo = HologramsAPI.createHologram(BeautyQuests.getInstance(), lc); if (protocolLib) holo.getVisibilityManager().setVisibleByDefault(visible); return new HD2Hologram(holo); } public class HD2Hologram extends BQHologram { protected HD2Hologram(Hologram hologram) { super(hologram); } @Override public void setPlayersVisible(List<Player> players) { try { List<String> all = players.stream().map(Player::getName).collect(Collectors.toList()); VisibilityManager visibility = hologram.getVisibilityManager(); if (visibilitiesField == null) { visibilitiesField = visibility.getClass().getDeclaredField("playersVisibilityMap"); visibilitiesField.setAccessible(true); } Map<String, Boolean> map = (Map<String, Boolean>) visibilitiesField.get(visibility); if (map == null) { map = new ConcurrentHashMap<>(); visibilitiesField.set(visibility, map); } for (Iterator<Entry<String, Boolean>> iterator = map.entrySet().iterator(); iterator.hasNext();) { Entry<String, Boolean> en = iterator.next(); if (!en.getValue()) continue; if (!all.contains(en.getKey())) { Player player = Bukkit.getPlayer(en.getKey()); if (player != null) { visibility.hideTo(player); }else { iterator.remove(); } } all.remove(en.getKey()); } for (String p : all) { if (p == null) continue; visibility.showTo(Bukkit.getPlayer(p)); } }catch (ReflectiveOperationException ex) { ex.printStackTrace(); } } @Override public void setPlayerVisibility(Player p, boolean visible) { if (visible) { hologram.getVisibilityManager().showTo(p); }else hologram.getVisibilityManager().hideTo(p); } @Override public void appendItem(ItemStack item) { hologram.appendItemLine(item); } @Override public void appendTextLine(String text) { hologram.appendTextLine(text); } @Override public void teleport(Location lc) { hologram.teleport(lc); } @Override public void delete() { hologram.delete(); } } }
/*4. Implement a JAVA program to find the square of the number. */ class SquareNumber{ public static void main(String args[]) { int num = 25; num *= num; System.out.println("Square of given number is " + num); } }
package com.rafael.personalitytest.ui.splash; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.rafael.personalitytest.App; import com.rafael.personalitytest.R; import com.rafael.personalitytest.ui.login.LoginActivity; import com.rafael.personalitytest.ui.question.QuestionActivity; import com.rafael.personalitytest.ui.register.RegisterActivity; import javax.inject.Inject; public class SplashActivity extends AppCompatActivity { @Inject SplashViewModel viewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); ((App) getApplication()).getComponent().inject(this); viewModel.getLoginStatus().observe(this, isAuth -> { if (isAuth) { Intent intent = new Intent(this, QuestionActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } else { Intent intent = new Intent(this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } }); } @Override protected void onResume() { super.onResume(); viewModel.validateToken(); } }
package dados; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import beans.Funcionario; import exceptions.FuncionarioException; public class RepositorioFuncionarios implements IRepositorioFuncionarios, Serializable { private static final long serialVersionUID = 1025911660485970999L; private List<Funcionario> funcionarios; public static RepositorioFuncionarios instance; private RepositorioFuncionarios() { funcionarios = new ArrayList<Funcionario>(); } @Override public List<Funcionario> listar(){ return this.funcionarios; } public static RepositorioFuncionarios getInstance() { if (instance == null) { instance = RepositorioFuncionarios.lerArquivo(); } return instance; } private static RepositorioFuncionarios lerArquivo() { RepositorioFuncionarios instanciaLocal = null; File f = new File ("bancoDados" + File.separatorChar + "pessoas" +File.separatorChar+ "arqFuncionarios.dat"); FileInputStream fis = null; ObjectInputStream ois = null; try{ fis = new FileInputStream(f); ois = new ObjectInputStream(fis); Object o = ois.readObject(); instanciaLocal = (RepositorioFuncionarios) o; } catch(Exception e){ instanciaLocal = new RepositorioFuncionarios(); } finally{ if(ois!=null){ try{ ois.close(); } catch(IOException e){ System.out.println("Nao foi possivel fechar o arquivo!"); e.printStackTrace(); } } } return instanciaLocal; } @Override public void salvarArquivo() { if(instance == null){ return; } File f = new File("bancoDados" + File.separatorChar + "pessoas" +File.separatorChar+ "arqFuncionarios.dat"); FileOutputStream fos = null; ObjectOutputStream oos = null; try{ if(!f.exists()) { f.createNewFile(); } fos = new FileOutputStream(f); oos = new ObjectOutputStream(fos); oos.writeObject(instance); }catch(Exception e){ e.printStackTrace(); }finally{ if(oos!=null){ try{ oos.close(); }catch(IOException e){ System.out.println("Nao foi possivel fechar o arquivo."); e.printStackTrace(); } } } } @Override public void cadastrar(Funcionario funcionario) throws FuncionarioException { boolean temEmail = false; boolean temCpf = false; boolean temNome = false; if(funcionarios.isEmpty()){ funcionarios.add(funcionario); }else{ for(Funcionario f: funcionarios) { if(f.getCpf().equals(funcionario.getCpf())) { temEmail = true; temCpf = true; temNome = true; } } if(!temEmail && !temCpf && !temNome) { funcionarios.add(funcionario); } else { FuncionarioException cadastrarfuncionario = new FuncionarioException("Funcionario nao encontrado!"); throw cadastrarfuncionario; } } } private int retornarIndice(String cpf) { int indice =-1; for(int i =0; i< funcionarios.size(); i++) { if(funcionarios.get(i).getCpf().equals(cpf)) { indice = i; } } return indice; } }
package com.atlassian.theplugin.idea.action.issues.oneissue; import com.atlassian.theplugin.idea.IdeaHelper; import com.intellij.openapi.actionSystem.AnActionEvent; /** * User: jgorycki * Date: Dec 29, 2008 * Time: 12:59:35 PM */ public class RefreshCommentsAction extends AbstractEditorIssueAction { public void actionPerformed(AnActionEvent e) { IdeaHelper.getIssueDetailsToolWindow(e).refreshComments(e.getPlace()); } }
package com.limefriends.molde.menu_mypage; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.limefriends.molde.R; import butterknife.BindView; import butterknife.ButterKnife; public class MyPageSettingsActivity extends AppCompatActivity implements View.OnClickListener{ @BindView(R.id.mypage_made_by) Button mypage_made_by; @BindView(R.id.mypage_made_by_answer) TextView mypage_made_by_answer; @BindView(R.id.mypage_provisions) Button mypage_provisions; @BindView(R.id.mypage_provisions_answer) TextView mypage_provisions_answer; @BindView(R.id.mypage_license) Button mypage_license; @BindView(R.id.mypage_license_answer) TextView mypage_license_answer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mypage_activity_settings); ButterKnife.bind(this); Intent intent = getIntent(); String title = intent.getStringExtra("title"); getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.default_toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); TextView toolbar_title = getSupportActionBar().getCustomView().findViewById(R.id.toolbar_title); toolbar_title.setText(title); findViewById(R.id.mypage_made_by).setOnClickListener(this); findViewById(R.id.mypage_provisions).setOnClickListener(this); findViewById(R.id.mypage_license).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.mypage_made_by: mypage_made_by_answer.setVisibility(View.VISIBLE); mypage_provisions_answer.setVisibility(View.GONE); mypage_license_answer.setVisibility(View.GONE); break; case R.id.mypage_provisions: mypage_made_by_answer.setVisibility(View.GONE); mypage_provisions_answer.setVisibility(View.VISIBLE); mypage_license_answer.setVisibility(View.GONE); break; case R.id.mypage_license: mypage_made_by_answer.setVisibility(View.GONE); mypage_provisions_answer.setVisibility(View.GONE); mypage_license_answer.setVisibility(View.VISIBLE); break; } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); return true; } return false; } }
package com.proba.proba12.repositories; import com.proba.proba12.models.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface UserRepository extends JpaRepository<User,Long> { }
package io.mosip.tf.t5.cryptograph.idrepo.dto; import java.util.List; import io.mosip.tf.t5.cryptograph.dto.Documents; import lombok.Data; /** * The Class ResponseDTO. * * @author M1048358 Alok */ @Data public class ResponseDTO { /** The entity. */ private String entity; /** The identity. */ private Object identity; private List<Documents> documents; /** The status. */ private String status; }
package com.github.spocot.mythra; import java.awt.Color; public class BlockGrass extends Block{ public BlockGrass(int x, int y) { super(false, Color.green, x, y); } }
package com.mc.library.constants; /** * Created by dinghui on 2016/10/14. */ public class UMengConstants { }
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.log4j.Logger; public class SMSThread { public static List<Map<String,String>> delaySMS = new ArrayList<Map<String,String>>(); public static Properties s2tconf; public static Logger logger;// public static ProcessS2T.PS2T s2t; //20150723 public static Date SMSThreadExcuteTime = new Date(); //20150804 public static Date SMSThreadWacherTime = new Date(); static Boolean Exit = false; public static Thread watcher; public static Thread program; static{ initial(); } public static void initial(){ System.out.println("Initial SMSThread"); s2tconf = TWNLDprovision.s2tconf; logger = TWNLDprovision.logger; s2t = TWNLDprovision.s2t; if(program==null) program = new Thread(new SMSThread_Program()); if(!program.isAlive()) program.start(); if(watcher==null) watcher = new Thread(new ThreadWatcher()); if(!watcher.isAlive()) watcher.start(); }; static class ThreadWatcher implements Runnable { public void run() { // implements Runnable run() int count =0; int countT =0; while(true){ try { Thread.sleep(60*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } SMSThreadWacherTime = new Date(); if(SMSThreadExcuteTime.getTime()-SMSThreadWacherTime.getTime()>=10*60*1000&&count<10){ Send_AlertMail("Send SMS Thread not Execute 10 minute!"); count ++; } System.out.println("Execute ThreadWatcher!"); } } } static class SMSThread_Program implements Runnable { public void run() { // implements Runnable run() SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); int count =0; while(!Exit){ try { Thread.sleep(60*1000); SMSThreadExcuteTime = new Date(); if(SMSThreadExcuteTime.getTime()-SMSThreadWacherTime.getTime()>=10*60*1000&&count<10){ Send_AlertMail("Send watcher Thread not Execute 10 minute!"); count ++; } //直接使用list.remove()會產生error,必須使用iterator,當iterator執行時會同步兩個參數的數值 synchronized(delaySMS){ Iterator<Map<String, String>> it = delaySMS.iterator(); while(it.hasNext()){ Map<String,String> m = it.next(); String msg=m.get("VARREALMSG"); msg = new String(msg.getBytes("BIG5"), "ISO-8859-1"); String phone=m.get("TWNLDMSISDN"); String sendtime=m.get("sendtime"); String logid = m.get("SMSLOGID"); if(SMSThreadExcuteTime.after(sdf.parse(sendtime))){ if("OTA Message".equalsIgnoreCase(msg)){ send_OTASMS(msg,phone,logid); }else{ send_SMS(msg,phone,logid); } it.remove(); } } } }catch (InterruptedException e){ ErrorHandle("InterruptedException",e); } catch (ParseException e) { ErrorHandle("ParseException",e); } catch (UnsupportedEncodingException e) { ErrorHandle("UnsupportedEncodingException",e); } catch (Exception e) { ErrorHandle("Exception",e); } } } } public static void send_OTASMS(String msg,String phone,String logid){ if("true".equals(s2tconf.getProperty("TestMod"))){ phone=s2tconf.getProperty("TestPhoneNumber"); } String res; try { res = setOTASMSPostParam(msg, phone); logger.debug("OTA send "+logid+" sms result : " + res); if(res.indexOf("Message Submitted")==-1){ throw new Exception("Sendding SMS Error!<br>" + "cTWNLDMSISDN="+phone+"<br>" + "VARREALMSG="+msg); } } catch (IOException e) { ErrorHandle("IOException",e); } catch (Exception e) { ErrorHandle("Exception",e); } } private static String setOTASMSPostParam(String msg,String phone) throws IOException{ String PhoneNumber=phone,Text=msg,charset="big5",InfoCharCounter=null,PID=null,DCS=null; String param = "PhoneNumber=+{{PhoneNumber}}&" + "UNUSED=on&" + "UDH=&" + "Data=B30200F1&" + "PID=7F&" + "DCS=F6&" + "Submit=Submit&" + "Binary=1"; if(PhoneNumber==null)PhoneNumber=""; if(Text==null)Text=""; //if(charset==null)charset=""; if(InfoCharCounter==null)InfoCharCounter=""; if(PID==null)PID=""; if(DCS==null)DCS=""; param=param.replace("{{PhoneNumber}}",PhoneNumber ); param=param.replace("{{Text}}",Text.replaceAll("/+", "%2b") ); param=param.replace("{{charset}}",charset ); param=param.replace("{{InfoCharCounter}}",InfoCharCounter ); param=param.replace("{{PID}}",PID ); param=param.replace("{{DCS}}",DCS ); return HttpPost("http://10.42.200.100:8800/Send Binary Message Other.htm",param,""); } public static void send_SMS(String msg,String phone,String logid){ if("true".equals(s2tconf.getProperty("TestMod"))){ phone=s2tconf.getProperty("TestPhoneNumber"); } String res; try { res = setSMSPostParam(msg, phone); logger.debug("delay send "+logid+" sms result : " + res); if(res.indexOf("Message Submitted")==-1){ throw new Exception("Sendding SMS Error!<br>" + "cTWNLDMSISDN="+phone+"<br>" + "VARREALMSG="+msg); } } catch (IOException e) { ErrorHandle("IOException",e); } catch (Exception e) { ErrorHandle("Exception",e); } } public void ErrorHandle(Exception e){ StringWriter s = new StringWriter(); e.printStackTrace(new PrintWriter(s)); logger.error(e); Send_AlertMail(s.toString()); } public static void ErrorHandle(String cont,Exception e){ StringWriter s = new StringWriter(); e.printStackTrace(new PrintWriter(s)); logger.error(cont,e); Send_AlertMail(cont+"<br>"+s); } public static void Send_AlertMail(String content){ try{ String Smailserver=s2tconf.getProperty("mailserver"); String SFrom=s2tconf.getProperty("From"); String Sto=s2tconf.getProperty("RDGroup"); String SSubject,SmessageText; SSubject=new Date().toString()+" TWNLD_SMSThread alert !"; SmessageText = content; s2t.SendAlertMail(Smailserver, SFrom, Sto, SSubject, SmessageText); logger.info("Send Mail Content:"+SmessageText);} catch(Exception ex){ logger.error("JAVA Error:"+ex.toString(),ex); } /*String Sto=s2tconf.getProperty("RDGroup"); String SSubject,SmessageText; SSubject="TWNLD_ERROR"; SmessageText = content; try{ String [] cmd=new String[3]; cmd[0]="/bin/bash"; cmd[1]="-c"; cmd[2]= "/bin/echo \""+SmessageText+"\" | /bin/mailx -s \""+SSubject+"\" -r TWNLD_ALERT "+Sto; Process p = Runtime.getRuntime().exec (cmd); p.waitFor(); logger.info("send mail cmd:"+cmd[2]); }catch (Exception e){ logger.error("send mail fail:"+SmessageText+"。",e); }*/ } private static String setSMSPostParam(String msg,String phone) throws IOException{ //StringBuffer sb=new StringBuffer (); String PhoneNumber=phone,Text=msg,charset="big5",InfoCharCounter=null,PID=null,DCS=null; String param = "PhoneNumber=+{{PhoneNumber}}&" + "Text={{Text}}&" + "charset={{charset}}&" + "InfoCharCounter={{InfoCharCounter}}&" + "PID={{PID}}&" + "DCS={{DCS}}&" + "Submit=Submit"; if(PhoneNumber==null)PhoneNumber=""; if(Text==null)Text=""; //if(charset==null)charset=""; if(InfoCharCounter==null)InfoCharCounter=""; if(PID==null)PID=""; if(DCS==null)DCS=""; param=param.replace("{{PhoneNumber}}",PhoneNumber ); param=param.replace("{{Text}}",Text.replace("+", "%2b")); param=param.replace("{{charset}}",charset ); param=param.replace("{{InfoCharCounter}}",InfoCharCounter ); param=param.replace("{{PID}}",PID ); param=param.replace("{{DCS}}",DCS ); return HttpPost("http://10.42.200.100:8800/Send%20Text%20Message.htm", param,""); } public static String HttpPost(String url,String param,String charset) throws IOException{ URL obj = new URL(url); if(charset!=null && !"".equals(charset)) param=URLEncoder.encode(param, charset); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header /*con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");*/ // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(param); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL("+new Date()+") : " + url); System.out.println("Post parameters : " + new String(param.getBytes("ISO8859-1"))); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result return(response.toString()); } }
/* * Origin of the benchmark: * repo: https://github.com/diffblue/cbmc.git * branch: develop * directory: regression/cbmc-java/multinewarray * The benchmark was taken from the repo: 24 January 2018 */ class Main { public static void main(String[] args) { int[][][] some_a = new int[4][3][2]; assert some_a.length==4; assert some_a[0].length==3; assert some_a[0][0].length==2; int x=3; int y=5; int[][] int_array = new int[x][y]; for(int i=0; i<x; ++i) for(int j=0; j<y; ++j) int_array[i][j]=i+j; assert int_array[2][4] == 6; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.transaction.support; import java.lang.reflect.Field; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.transaction.IllegalTransactionStateException; import org.springframework.transaction.MockCallbackPreferringTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TestTransactionExecutionListener; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.TransactionSystemException; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatRuntimeException; import static org.springframework.transaction.TransactionDefinition.ISOLATION_REPEATABLE_READ; import static org.springframework.transaction.TransactionDefinition.ISOLATION_SERIALIZABLE; import static org.springframework.transaction.TransactionDefinition.PROPAGATION_MANDATORY; import static org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRED; import static org.springframework.transaction.TransactionDefinition.PROPAGATION_SUPPORTS; import static org.springframework.transaction.support.AbstractPlatformTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION; import static org.springframework.transaction.support.DefaultTransactionDefinition.PREFIX_ISOLATION; import static org.springframework.transaction.support.DefaultTransactionDefinition.PREFIX_PROPAGATION; /** * @author Juergen Hoeller * @author Sam Brannen * @since 29.04.2003 */ class TransactionSupportTests { @AfterEach void postConditions() { assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty(); assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); } @Test void noExistingTransaction() { PlatformTransactionManager tm = new TestTransactionManager(false, true); DefaultTransactionStatus status1 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(PROPAGATION_SUPPORTS)); assertThat(status1.hasTransaction()).as("Must not have transaction").isFalse(); DefaultTransactionStatus status2 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(PROPAGATION_REQUIRED)); assertThat(status2.hasTransaction()).as("Must have transaction").isTrue(); assertThat(status2.isNewTransaction()).as("Must be new transaction").isTrue(); assertThatExceptionOfType(IllegalTransactionStateException.class) .isThrownBy(() -> tm.getTransaction(new DefaultTransactionDefinition(PROPAGATION_MANDATORY))); } @Test void existingTransaction() { PlatformTransactionManager tm = new TestTransactionManager(true, true); DefaultTransactionStatus status1 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(PROPAGATION_SUPPORTS)); assertThat(status1.getTransaction()).as("Must have transaction").isNotNull(); assertThat(status1.isNewTransaction()).as("Must not be new transaction").isFalse(); DefaultTransactionStatus status2 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(PROPAGATION_REQUIRED)); assertThat(status2.getTransaction()).as("Must have transaction").isNotNull(); assertThat(status2.isNewTransaction()).as("Must not be new transaction").isFalse(); DefaultTransactionStatus status3 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(PROPAGATION_MANDATORY)); assertThat(status3.getTransaction()).as("Must have transaction").isNotNull(); assertThat(status3.isNewTransaction()).as("Must not be new transaction").isFalse(); } @Test void commitWithoutExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(false, true); TestTransactionExecutionListener tl = new TestTransactionExecutionListener(); tm.addListener(tl); TransactionStatus status = tm.getTransaction(null); tm.commit(status); assertThat(tm.begin).as("triggered begin").isTrue(); assertThat(tm.commit).as("triggered commit").isTrue(); assertThat(tm.rollback).as("no rollback").isFalse(); assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); assertThat(tl.beforeBeginCalled).isTrue(); assertThat(tl.afterBeginCalled).isTrue(); assertThat(tl.beforeCommitCalled).isTrue(); assertThat(tl.afterCommitCalled).isTrue(); assertThat(tl.beforeRollbackCalled).isFalse(); assertThat(tl.afterRollbackCalled).isFalse(); } @Test void rollbackWithoutExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(false, true); TestTransactionExecutionListener tl = new TestTransactionExecutionListener(); tm.addListener(tl); TransactionStatus status = tm.getTransaction(null); tm.rollback(status); assertThat(tm.begin).as("triggered begin").isTrue(); assertThat(tm.commit).as("no commit").isFalse(); assertThat(tm.rollback).as("triggered rollback").isTrue(); assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); assertThat(tl.beforeBeginCalled).isTrue(); assertThat(tl.afterBeginCalled).isTrue(); assertThat(tl.beforeCommitCalled).isFalse(); assertThat(tl.afterCommitCalled).isFalse(); assertThat(tl.beforeRollbackCalled).isTrue(); assertThat(tl.afterRollbackCalled).isTrue(); } @Test void rollbackOnlyWithoutExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(false, true); TestTransactionExecutionListener tl = new TestTransactionExecutionListener(); tm.addListener(tl); TransactionStatus status = tm.getTransaction(null); status.setRollbackOnly(); tm.commit(status); assertThat(tm.begin).as("triggered begin").isTrue(); assertThat(tm.commit).as("no commit").isFalse(); assertThat(tm.rollback).as("triggered rollback").isTrue(); assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); assertThat(tl.beforeBeginCalled).isTrue(); assertThat(tl.afterBeginCalled).isTrue(); assertThat(tl.beforeCommitCalled).isFalse(); assertThat(tl.afterCommitCalled).isFalse(); assertThat(tl.beforeRollbackCalled).isTrue(); assertThat(tl.afterRollbackCalled).isTrue(); } @Test void commitWithExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(true, true); TestTransactionExecutionListener tl = new TestTransactionExecutionListener(); tm.addListener(tl); TransactionStatus status = tm.getTransaction(null); tm.commit(status); assertThat(tm.begin).as("no begin").isFalse(); assertThat(tm.commit).as("no commit").isFalse(); assertThat(tm.rollback).as("no rollback").isFalse(); assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); assertThat(tl.beforeBeginCalled).isFalse(); assertThat(tl.afterBeginCalled).isFalse(); assertThat(tl.beforeCommitCalled).isFalse(); assertThat(tl.afterCommitCalled).isFalse(); assertThat(tl.beforeRollbackCalled).isFalse(); assertThat(tl.afterRollbackCalled).isFalse(); } @Test void rollbackWithExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(true, true); TestTransactionExecutionListener tl = new TestTransactionExecutionListener(); tm.addListener(tl); TransactionStatus status = tm.getTransaction(null); tm.rollback(status); assertThat(tm.begin).as("no begin").isFalse(); assertThat(tm.commit).as("no commit").isFalse(); assertThat(tm.rollback).as("no rollback").isFalse(); assertThat(tm.rollbackOnly).as("triggered rollbackOnly").isTrue(); assertThat(tl.beforeBeginCalled).isFalse(); assertThat(tl.afterBeginCalled).isFalse(); assertThat(tl.beforeCommitCalled).isFalse(); assertThat(tl.afterCommitCalled).isFalse(); assertThat(tl.beforeRollbackCalled).isFalse(); assertThat(tl.afterRollbackCalled).isFalse(); } @Test void rollbackOnlyWithExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(true, true); TestTransactionExecutionListener tl = new TestTransactionExecutionListener(); tm.addListener(tl); TransactionStatus status = tm.getTransaction(null); status.setRollbackOnly(); tm.commit(status); assertThat(tm.begin).as("no begin").isFalse(); assertThat(tm.commit).as("no commit").isFalse(); assertThat(tm.rollback).as("no rollback").isFalse(); assertThat(tm.rollbackOnly).as("triggered rollbackOnly").isTrue(); assertThat(tl.beforeBeginCalled).isFalse(); assertThat(tl.afterBeginCalled).isFalse(); assertThat(tl.beforeCommitCalled).isFalse(); assertThat(tl.afterCommitCalled).isFalse(); assertThat(tl.beforeRollbackCalled).isFalse(); assertThat(tl.afterRollbackCalled).isFalse(); } @Test void transactionTemplate() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(tm); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { } }); assertThat(tm.begin).as("triggered begin").isTrue(); assertThat(tm.commit).as("triggered commit").isTrue(); assertThat(tm.rollback).as("no rollback").isFalse(); assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @Test void transactionTemplateWithCallbackPreference() { MockCallbackPreferringTransactionManager ptm = new MockCallbackPreferringTransactionManager(); TransactionTemplate template = new TransactionTemplate(ptm); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { } }); assertThat(ptm.getDefinition()).isSameAs(template); assertThat(ptm.getStatus().isRollbackOnly()).isFalse(); } @Test void transactionTemplateWithException() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(tm); RuntimeException ex = new RuntimeException("Some application exception"); assertThatRuntimeException() .isThrownBy(() -> template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { throw ex; } })) .isSameAs(ex); assertThat(tm.begin).as("triggered begin").isTrue(); assertThat(tm.commit).as("no commit").isFalse(); assertThat(tm.rollback).as("triggered rollback").isTrue(); assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @SuppressWarnings("serial") @Test void transactionTemplateWithRollbackException() { final TransactionSystemException tex = new TransactionSystemException("system exception"); TestTransactionManager tm = new TestTransactionManager(false, true) { @Override protected void doRollback(DefaultTransactionStatus status) { super.doRollback(status); throw tex; } }; TransactionTemplate template = new TransactionTemplate(tm); RuntimeException ex = new RuntimeException("Some application exception"); assertThatRuntimeException() .isThrownBy(() -> template.executeWithoutResult(status -> { throw ex; })) .isSameAs(tex); assertThat(tm.begin).as("triggered begin").isTrue(); assertThat(tm.commit).as("no commit").isFalse(); assertThat(tm.rollback).as("triggered rollback").isTrue(); assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @Test void transactionTemplateWithError() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(tm); assertThatExceptionOfType(Error.class) .isThrownBy(() -> template.executeWithoutResult(status -> { throw new Error("Some application error"); })); assertThat(tm.begin).as("triggered begin").isTrue(); assertThat(tm.commit).as("no commit").isFalse(); assertThat(tm.rollback).as("triggered rollback").isTrue(); assertThat(tm.rollbackOnly).as("no rollbackOnly").isFalse(); } @Test void transactionTemplateEquality() { TestTransactionManager tm1 = new TestTransactionManager(false, true); TestTransactionManager tm2 = new TestTransactionManager(false, true); TransactionTemplate template1 = new TransactionTemplate(tm1); TransactionTemplate template2 = new TransactionTemplate(tm2); TransactionTemplate template3 = new TransactionTemplate(tm2); assertThat(template2).isNotEqualTo(template1); assertThat(template3).isNotEqualTo(template1); assertThat(template3).isEqualTo(template2); } @Nested class AbstractPlatformTransactionManagerConfigurationTests { private final AbstractPlatformTransactionManager tm = new TestTransactionManager(false, true); @Test void setTransactionSynchronizationNameToUnsupportedValues() { assertThatIllegalArgumentException().isThrownBy(() -> tm.setTransactionSynchronizationName(null)); assertThatIllegalArgumentException().isThrownBy(() -> tm.setTransactionSynchronizationName(" ")); assertThatIllegalArgumentException().isThrownBy(() -> tm.setTransactionSynchronizationName("bogus")); } /** * Verify that the internal 'constants' map is properly configured for all * SYNCHRONIZATION_ constants defined in {@link AbstractPlatformTransactionManager}. */ @Test void setTransactionSynchronizationNameToAllSupportedValues() { Set<Integer> uniqueValues = new HashSet<>(); streamSynchronizationConstants() .forEach(name -> { tm.setTransactionSynchronizationName(name); int transactionSynchronization = tm.getTransactionSynchronization(); int expected = AbstractPlatformTransactionManager.constants.get(name); assertThat(transactionSynchronization).isEqualTo(expected); uniqueValues.add(transactionSynchronization); }); assertThat(uniqueValues).containsExactlyInAnyOrderElementsOf(AbstractPlatformTransactionManager.constants.values()); } @Test void setTransactionSynchronization() { tm.setTransactionSynchronization(SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); assertThat(tm.getTransactionSynchronization()).isEqualTo(SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); } private static Stream<String> streamSynchronizationConstants() { return Arrays.stream(AbstractPlatformTransactionManager.class.getFields()) .filter(ReflectionUtils::isPublicStaticFinal) .map(Field::getName) .filter(name -> name.startsWith("SYNCHRONIZATION_")); } } @Nested class TransactionTemplateConfigurationTests { private final TransactionTemplate template = new TransactionTemplate(); @Test void setTransactionManager() { TestTransactionManager tm = new TestTransactionManager(false, true); template.setTransactionManager(tm); assertThat(template.getTransactionManager()).as("correct transaction manager set").isSameAs(tm); } @Test void setPropagationBehaviorNameToUnsupportedValues() { assertThatIllegalArgumentException().isThrownBy(() -> template.setPropagationBehaviorName(null)); assertThatIllegalArgumentException().isThrownBy(() -> template.setPropagationBehaviorName(" ")); assertThatIllegalArgumentException().isThrownBy(() -> template.setPropagationBehaviorName("bogus")); assertThatIllegalArgumentException().isThrownBy(() -> template.setPropagationBehaviorName("ISOLATION_SERIALIZABLE")); } /** * Verify that the internal 'propagationConstants' map is properly configured * for all PROPAGATION_ constants defined in {@link TransactionDefinition}. */ @Test void setPropagationBehaviorNameToAllSupportedValues() { Set<Integer> uniqueValues = new HashSet<>(); streamPropagationConstants() .forEach(name -> { template.setPropagationBehaviorName(name); int propagationBehavior = template.getPropagationBehavior(); int expected = DefaultTransactionDefinition.propagationConstants.get(name); assertThat(propagationBehavior).isEqualTo(expected); uniqueValues.add(propagationBehavior); }); assertThat(uniqueValues).containsExactlyInAnyOrderElementsOf(DefaultTransactionDefinition.propagationConstants.values()); } @Test void setPropagationBehavior() { assertThatIllegalArgumentException().isThrownBy(() -> template.setPropagationBehavior(999)); assertThatIllegalArgumentException().isThrownBy(() -> template.setPropagationBehavior(ISOLATION_SERIALIZABLE)); template.setPropagationBehavior(PROPAGATION_MANDATORY); assertThat(template.getPropagationBehavior()).isEqualTo(PROPAGATION_MANDATORY); } @Test void setIsolationLevelNameToUnsupportedValues() { assertThatIllegalArgumentException().isThrownBy(() -> template.setIsolationLevelName(null)); assertThatIllegalArgumentException().isThrownBy(() -> template.setIsolationLevelName(" ")); assertThatIllegalArgumentException().isThrownBy(() -> template.setIsolationLevelName("bogus")); assertThatIllegalArgumentException().isThrownBy(() -> template.setIsolationLevelName("PROPAGATION_MANDATORY")); } /** * Verify that the internal 'isolationConstants' map is properly configured * for all ISOLATION_ constants defined in {@link TransactionDefinition}. */ @Test void setIsolationLevelNameToAllSupportedValues() { Set<Integer> uniqueValues = new HashSet<>(); streamIsolationConstants() .forEach(name -> { template.setIsolationLevelName(name); int isolationLevel = template.getIsolationLevel(); int expected = DefaultTransactionDefinition.isolationConstants.get(name); assertThat(isolationLevel).isEqualTo(expected); uniqueValues.add(isolationLevel); }); assertThat(uniqueValues).containsExactlyInAnyOrderElementsOf(DefaultTransactionDefinition.isolationConstants.values()); } @Test void setIsolationLevel() { assertThatIllegalArgumentException().isThrownBy(() -> template.setIsolationLevel(999)); template.setIsolationLevel(ISOLATION_REPEATABLE_READ); assertThat(template.getIsolationLevel()).isEqualTo(ISOLATION_REPEATABLE_READ); } @Test void getDefinitionDescription() { assertThat(template.getDefinitionDescription()).asString() .isEqualTo("PROPAGATION_REQUIRED,ISOLATION_DEFAULT"); template.setPropagationBehavior(PROPAGATION_MANDATORY); template.setIsolationLevel(ISOLATION_REPEATABLE_READ); template.setReadOnly(true); template.setTimeout(42); assertThat(template.getDefinitionDescription()).asString() .isEqualTo("PROPAGATION_MANDATORY,ISOLATION_REPEATABLE_READ,timeout_42,readOnly"); } private static Stream<String> streamPropagationConstants() { return streamTransactionDefinitionConstants() .filter(name -> name.startsWith(PREFIX_PROPAGATION)); } private static Stream<String> streamIsolationConstants() { return streamTransactionDefinitionConstants() .filter(name -> name.startsWith(PREFIX_ISOLATION)); } private static Stream<String> streamTransactionDefinitionConstants() { return Arrays.stream(TransactionDefinition.class.getFields()) .filter(ReflectionUtils::isPublicStaticFinal) .map(Field::getName); } } }
package OnlineRetailer; import java.io.*; import java.util.ArrayList; /** - Main file that runs the system. @Justin Ho Shue **/ public class Main { public static void main(String[] args) throws IOException{ BufferedReader key = new BufferedReader(new InputStreamReader(System.in)); Games minecraft = new Games("Minecraft", 35); Games overwatch = new Games("overwatch", 20); Games theForest = new Games("theForest", 15); Food pizza = new Food("pizza", 15); Food iceCream = new Food("iceCream", 4); Food bacon = new Food("bacon", 4.47); Electronics ps5 = new Electronics("ps5", 399); Electronics laptop = new Electronics("laptop", 899); Electronics tv = new Electronics("tv", 1398); ArrayList<Games> purchasedGames = new ArrayList<Games>(); ArrayList<Food> purchasedFood = new ArrayList<Food>(); ArrayList<Electronics> purchasedElectronics = new ArrayList<Electronics>(); String Category = ""; String Games = "1"; String Electronics = "2"; String Food = "3"; double subTotal = 0; double total; double tax; System.out.println("Welcome to the OnlineRetailer"); while(!Category.equalsIgnoreCase("Done")){ System.out.println("how may we help you?"); System.out.println("1. Games"); System.out.println("2. Electronics"); System.out.println("3. Food"); System.out.println("Enter 1,2, or 3 to choose a category, type Done when your ready to checkout"); Category = key.readLine(); if(Category.equals("1")) { System.out.println("1. Minecraft - $35"); System.out.println("2. Overwatch - $20"); System.out.println("3. TheForest - $15"); System.out.println("Enter 1, 2, or 3 to choose an item"); Category = key.readLine(); if(Category.equals("1")) { purchasedGames.add(minecraft); } else if (Category.equals("2")) { purchasedGames.add(overwatch); } else if (Category.equals("3")) { purchasedGames.add(theForest); } } else if (Category.equals("2")) { System.out.println("1. ps5 - $399"); System.out.println("2. laptop - $899"); System.out.println("3. tv - $1398"); System.out.println("Enter 1, 2, or 3 to choose an item"); Category = key.readLine(); if(Category.equals("1")) { purchasedElectronics.add(ps5); } else if (Category.equals("2")) { purchasedElectronics.add(laptop); } else if (Category.equals("3")) { purchasedElectronics.add(tv); } } else if (Category.equals("3")) { System.out.println("1. pizza - $15"); System.out.println("2. iceCream - $4"); System.out.println("3. bacon - $4.47"); System.out.println("Enter 1, 2, or 3 to choose an item"); Category = key.readLine(); if(Category.equals("1")) { purchasedFood.add(pizza); } else if (Category.equals("2")) { purchasedFood.add(iceCream); } else if (Category.equals("3")) { purchasedFood.add(bacon); } } } for (int i = 0; i < purchasedGames.size(); i++){ System.out.print(purchasedGames.get(i).getGameName()+" $"); System.out.println(purchasedGames.get(i).getPrice()); subTotal += purchasedGames.get(i).getPrice(); } for (int i = 0; i < purchasedFood.size(); i++){ System.out.print(purchasedFood.get(i).getFoodName()+" $"); System.out.println(purchasedFood.get(i).getPrice()); subTotal += purchasedFood.get(i).getPrice(); } for (int i = 0; i < purchasedElectronics.size(); i++){ System.out.print(purchasedElectronics.get(i).getElectronicName()+" $"); System.out.println(purchasedElectronics.get(i).getPrice()); subTotal += purchasedElectronics.get(i).getPrice(); } //calculates the tax and the total tax = subTotal*0.13; total = subTotal + tax; //prints the subtotal,tax,total System.out.println("Subtotal: "+subTotal); System.out.println("Tax: "+tax); System.out.println("Total: "+total); } }
package com.trump.auction.reactor.bid; import com.trump.auction.reactor.api.model.BidRequest; import com.trump.auction.reactor.api.model.BidResponse; /** * 出价处理 * * @author Owen * @since 2018/1/16 */ public interface BidHandler { BidResponse handleRequest(BidRequest bidRequest); boolean support(BidRequest bidRequest); }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.console.components.fstree; import java.awt.Component; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import java.util.EventObject; import javax.swing.AbstractCellEditor; import javax.swing.JCheckBox; import javax.swing.JTree; import javax.swing.tree.TreeCellEditor; class FileSystemTreeNodeEditor extends AbstractCellEditor implements TreeCellEditor { private FileSystemTreeNodeRenderer renderer = new FileSystemTreeNodeRenderer(); public FileSystemTreeNodeEditor() {} @Override public Object getCellEditorValue() { JCheckBox cb = renderer.getLeafRenderer(); return new FileSystemTreeNode(new File(cb.getText()), null); } @Override public boolean isCellEditable(EventObject event) { return true; } @Override public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row) { JCheckBox editor = (JCheckBox) renderer.getTreeCellRendererComponent( tree, value, true, expanded, leaf, row, true); // editor always selected / focused ItemListener itemListener = new ItemListener() { @Override public void itemStateChanged(ItemEvent itemEvent) { if (stopCellEditing()) fireEditingStopped(); } }; editor.addItemListener(itemListener); FileSystemTreeNode node = (FileSystemTreeNode) value; node.setSelected(!node.isSelected()); ((FileSystemTreeModel) tree.getModel()).setSelectedRecurse(node, node.isSelected()); tree.repaint(); return editor; } }
package com.capstone.videoeffect; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.PorterDuff; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.capstone.videoeffect.utils.Tools; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.tabs.TabLayout; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.UserProfileChangeRequest; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.StorageTask; import com.google.firebase.storage.UploadTask; import com.mikhaellopez.circularimageview.CircularImageView; import java.io.IOException; import java.util.Objects; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager.widget.ViewPager; import static android.content.ContentValues.TAG; public class MyProfileActivity extends AppCompatActivity { ImageView ivback; public static final int TAKE_PIC_REQUEST_CODE = 0; public static final int CHOOSE_PIC_REQUEST_CODE = 1; private static final int MY_CAMERA_PERMISSION_CODE = 100; ViewPager view_pager; SectionsPagerAdapter viewPagerAdapter; TabLayout tab_layout; TextView tvname, tvemail; LinearLayout mChangeProfilePic; CircularImageView mPreviewImageView; FirebaseUser user; public String imageId; FirebaseAuth firebaseAuth; StorageReference strRef; StorageTask taskStorage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_profile); ivback = findViewById(R.id.ivback); ivback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MyProfileActivity.this, HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); view_pager = (ViewPager) findViewById(R.id.view_pager); tab_layout = (TabLayout) findViewById(R.id.tab_layout); tvname = findViewById(R.id.tvname); tvemail = findViewById(R.id.tvemail); mChangeProfilePic = findViewById(R.id.mChangeProfilePic); mPreviewImageView = findViewById(R.id.mPreviewImageView); firebaseAuth = FirebaseAuth.getInstance(); FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { tvname.setText(user.getDisplayName()); tvemail.setText(user.getEmail()); if (user.getPhotoUrl() != null){ Glide.with(this) .load(user.getPhotoUrl()) .into(mPreviewImageView); } } //Change profile imagep //set onlClick to TextView mChangeProfilePic.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onClick(View v) { if (Objects.requireNonNull(checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) { requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE); } else{ //show dialog AlertDialog.Builder builder = new AlertDialog.Builder(MyProfileActivity.this); builder.setTitle("Upload or Take a photo"); builder.setPositiveButton("Upload", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //upload image Intent choosePictureIntent = new Intent(Intent.ACTION_GET_CONTENT); choosePictureIntent.setType("image/*"); startActivityForResult(choosePictureIntent, CHOOSE_PIC_REQUEST_CODE); } }); builder.setNegativeButton("Take Photo", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //take photo Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(takePicture, TAKE_PIC_REQUEST_CODE); } }); AlertDialog dialog = builder.create(); dialog.show(); } } });//End change profile image onClick Listener setupViewPager(view_pager); tab_layout.setupWithViewPager(view_pager); tab_layout.getTabAt(0).setIcon(R.drawable.ic_camera); tab_layout.getTabAt(1).setIcon(R.drawable.ic_video); // set icon color pre-selected tab_layout.getTabAt(0).getIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN); tab_layout.getTabAt(1).getIcon().setColorFilter(getResources().getColor(R.color.grey_20), PorterDuff.Mode.SRC_IN); tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { tab.getIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN); } @Override public void onTabUnselected(TabLayout.Tab tab) { tab.getIcon().setColorFilter(getResources().getColor(R.color.grey_20), PorterDuff.Mode.SRC_IN); } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } private void setupViewPager(ViewPager viewPager) { viewPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); viewPagerAdapter.addFragment(FragmentTabsPhotos.newInstance(), "My Photos"); // index 0 viewPagerAdapter.addFragment(FragmentTabsVideos.newInstance(), "My Videos"); // index 1 viewPager.setAdapter(viewPagerAdapter); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode != RESULT_CANCELED) { switch (requestCode) { case TAKE_PIC_REQUEST_CODE: if (resultCode == Activity.RESULT_OK && data != null) { Bitmap photo = (Bitmap) data.getExtras().get("data"); mPreviewImageView.setImageBitmap(photo); UploadImageToFirebase(photo); } break; case CHOOSE_PIC_REQUEST_CODE: if (resultCode == RESULT_OK && data != null) { Uri imageUri = data.getData(); try { Bitmap photo = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri); mPreviewImageView.setImageBitmap(photo); UploadImageToFirebase(photo); } catch (IOException e) { e.printStackTrace(); } } break; } } } private void UploadImageToFirebase(Bitmap photo) { Uri image_uri = Tools.getImageUri(this,photo); user = FirebaseAuth.getInstance().getCurrentUser(); strRef = FirebaseStorage.getInstance().getReference("ProfileImages"); imageId = System.currentTimeMillis() + "." + findExtension(image_uri); StorageReference refStorage = strRef.child(imageId); taskStorage = refStorage.putFile(image_uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { final Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl(); while (!urlTask.isSuccessful()); final Uri taskResult = urlTask.getResult(); final String downloadUrl = taskResult.toString(); UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder() .setPhotoUri(Uri.parse(downloadUrl)) .build(); user.updateProfile(profileUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User profile updated."); } } }); } }); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == MY_CAMERA_PERMISSION_CODE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show(); Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, TAKE_PIC_REQUEST_CODE); } else { Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show(); } } } private String findExtension(Uri imgUri) { ContentResolver contentResolver = getContentResolver(); MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(imgUri)); } }
package com.bistel.mq.impl; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import org.atmosphere.cpr.Broadcaster; import org.atmosphere.cpr.BroadcasterFactory; import com.bistel.configuration.ConfigConstants; import com.bistel.configuration.ConfigurationManager; import com.bistel.mq.ExchangeInfo; import com.bistel.mq.MessageInfo; import com.bistel.mq.Messaging; import com.bistel.mq.MessagingException; import com.bistel.mq.QueueInfo; import com.bistel.web.realanalytics.RealtimeDataLookup; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; public class MessagingImpl implements Messaging { private long timeout; private String hostName; ConnectionFactory factory; private boolean listen; private String consumerTag; private QueueingConsumer consumer; private Channel channel; private ConfigurationManager cm; public MessagingImpl() { try { initialize(); factory = new ConnectionFactory(); factory.setHost(hostName); } catch(Exception ex) { ex.printStackTrace(); } } private void initialize() { /** * TODO: read the properties using Configuration Manager */ cm = ConfigurationManager.getInstance(ConfigConstants.DEFAULT_RESOURCE_NAME); hostName = cm.getConfiguration("rabbitmq.host"); timeout = 10000; } private void cleanup(Connection conn, Channel channel) { try { if(channel!=null && channel.isOpen()) channel.close(); if(conn!=null && conn.isOpen()) conn.close(); } catch(Exception ex) { ex.printStackTrace(); } } public void publishMessage(ExchangeInfo exchange, MessageInfo message) throws MessagingException { Connection conn = null; Channel channel = null; try { conn = factory.newConnection(); channel = conn.createChannel(); channel.exchangeDeclare(exchange.getName(), exchange.getType(), exchange.isDurable(), exchange.isAutoDelete(), false, exchange.getArgs()); channel.basicPublish(exchange.getName(), message.getRoutingKey(), null, message.getMessage()); } catch(Exception ex) { ex.printStackTrace(); throw new MessagingException(ex); } finally { cleanup(conn, channel); } } public void consumeMessage(QueueInfo queue, ExchangeInfo exchange, Map<String,String> params) throws MessagingException { Connection conn = null; try { listen = true; conn = factory.newConnection(); channel = conn.createChannel(); channel.queueDeclare(queue.getName(), queue.isDurable(), queue.isExclusive(), queue.isAutoDelete(), queue.getArgs()); channel.exchangeDeclare(exchange.getName(), exchange.getType()); for(String key:exchange.getBindingKeys()) { channel.queueBind(queue.getName(), exchange.getName(), key); } consumer = new QueueingConsumer(channel); channel.basicConsume(queue.getName(), true, consumer); String topicId = params.get("topicId"); Broadcaster b = BroadcasterFactory.getDefault().lookup(topicId,true); consumerTag = consumer.getConsumerTag(); while(listen) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String body = new String(delivery.getBody()); String routingKey = delivery.getEnvelope().getRoutingKey(); System.out.println(body+" "+routingKey); String data = RealtimeDataLookup.dataMap.get(topicId); System.out.println("data: "+data); Map<String, String> map =new HashMap<String, String>(); StringTokenizer st = new StringTokenizer(body, "|"); while(st.hasMoreTokens()) { String token = st.nextToken(); String[] a = token.split(","); map.put(a[0], token); } System.out.println("map: "+map); String paramValues = ""; st = new StringTokenizer(data, "|"); while(st.hasMoreTokens()) { String token = st.nextToken(); String paramName = token.substring(token.lastIndexOf(":")+1); if(map.containsKey(paramName)) { if(paramValues!=null && paramValues.trim().length()>0) paramValues+="*"; paramValues+=map.get(paramName); } } System.out.println("paramValues: "+paramValues); b.broadcast(paramValues); } System.out.println("I have exit from this!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } catch(Exception ex) { ex.printStackTrace(); throw new MessagingException(ex); } finally { //cleanup(conn, channel); } } public void removeQueue(String queueName) { Connection conn = null; //Channel channel = null; try { listen = false; /*conn = factory.newConnection(); channel = conn.createChannel();*/ //channel.basicCancel(consumerTag); channel.queueDelete(queueName); } catch(Exception ex) { ex.printStackTrace(); //throw new MessagingException(ex); } finally { cleanup(conn, channel); } } @Override public void bindQueue(QueueInfo queue, ExchangeInfo exchange, Map<String, String> params) throws MessagingException { try { for(String key:exchange.getBindingKeys()) { channel.queueBind(queue.getName(), exchange.getName(), key); } } catch(Exception ex) { ex.printStackTrace(); throw new MessagingException("error while binding queues", ex); } } public void unbindQueue(QueueInfo queue, ExchangeInfo exchange, Map<String,String> params) throws MessagingException { try { for(String key:exchange.getBindingKeys()) { channel.queueUnbind(queue.getName(), exchange.getName(), key); } } catch(Exception ex) { ex.printStackTrace(); throw new MessagingException("error while unbinding queues", ex); } } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.jpa.vendor; import com.oracle.svm.core.annotate.Alias; import com.oracle.svm.core.annotate.RecomputeFieldValue; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import org.hibernate.bytecode.spi.BytecodeProvider; import static com.oracle.svm.core.annotate.RecomputeFieldValue.Kind; /** * Hibernate substitution designed to prevent ByteBuddy reachability on native, and to enforce the * usage of {@code org.hibernate.bytecode.internal.none.BytecodeProviderImpl} with Hibernate 6.3+. * TODO Collaborate with Hibernate team on a substitution-less alternative that does not require a custom list of StandardServiceInitiator * * @author Sebastien Deleuze * @since 6.1 */ @TargetClass(className = "org.hibernate.bytecode.internal.BytecodeProviderInitiator") final class Target_BytecodeProviderInitiator { @Alias public static String BYTECODE_PROVIDER_NAME_NONE; @Alias @RecomputeFieldValue(kind = Kind.FromAlias) public static String BYTECODE_PROVIDER_NAME_DEFAULT = BYTECODE_PROVIDER_NAME_NONE; @Substitute public static BytecodeProvider buildBytecodeProvider(String providerName) { return new org.hibernate.bytecode.internal.none.BytecodeProviderImpl(); } }
package RecursionTest; /* * 递归方法的使用(了解) * 1.递归方法:一个方法体内调用它自身。 * 2. 方法递归包含了一种隐式的循环,它会重复执行某段代码,但这种重复执行无须循环控制。 * 递归一定要向已知方向递归,否则这种递归就变成了无穷递归,类似于死循环。 * */ public class RecursionTest { public static void main(String[] args) { RecursionTest test=new RecursionTest(); int sum1=test.getsum(100); System.out.println(sum1); int sum2=test.getsum1(10); System.out.println(sum2); int sum3=test.f(10); System.out.println(sum3); } // 例1:计算1-n之间所有自然数的和 public int getsum(int n) { if(n==1) return n; else { return n+getsum(n-1); } } // 例2:计算1-n之间所有自然数的乘积:n! public int getsum1(int n) { if(n==1) return n; else { return n*getsum(n-1); } } //例3:已知有一个数列:f(0) = 1,f(1) = 4,f(n+2)=2*f(n+1) + f(n), //其中n是大于0的整数,求f(10)的值。 public int f(int n) { if(n==0) return 1; else if(n==1) return 4; else return 2*f(n-1)+f(n-2); } }
package com.junzhao.base.base; import com.junzhao.base.http.MLConstants; import com.junzhao.rongyun.service.RongContext; import com.junzhao.shanfen.model.PHUserData; import com.junzhao.shanfen.model.SmallComPanyData; /** * Created by Administrator on 2016/5/19. */ public class APPCache { //token public static void setToken(String token) { APP.aCache.put(MLConstants.TOKEN, token); } public static String getToken() { String token; Object obj = APP.aCache.getAsString(MLConstants.TOKEN); if (obj==null||obj==""){ RongContext.quit(false); return ""; }else { token= (String) obj; } return token; } public static void setUseData(PHUserData userdata) { APP.aCache.put(MLConstants.USERDATA, userdata); } public static Object getUseData() { PHUserData userdata; Object obj = APP.aCache.getAsObject(MLConstants.USERDATA); if (obj==null){ return null; }else { userdata= (PHUserData) obj; } return userdata; } public static void setUserInfo(UserRong userdata) { APP.aCache.put(MLConstants.USERINFO, userdata); } public static Object getUserInfo() { UserRong userdata; Object obj = APP.aCache.getAsObject(MLConstants.USERINFO); if (obj==null){ return null; }else { userdata= (UserRong) obj; } return userdata; } public static void setUse(String username) { APP.aCache.put(MLConstants.USERNAME, username); } public static String getUse() { String username; Object obj = APP.aCache.getAsString(MLConstants.USERNAME); if (obj==null){ return ""; }else { username= (String) obj; } return username; } public static void setRongUseId(String username) { APP.aCache.put(MLConstants.RONGUSEID, username); } public static String getRongUseId() { String username; Object obj = APP.aCache.getAsString(MLConstants.RONGUSEID); if (obj==null){ return ""; }else { username= (String) obj; } return username; } public static void setOpenid(String openid) { APP.aCache.put(MLConstants.OPENID, openid); } public static String getOpenid() { String openid; Object obj = APP.aCache.getAsString(MLConstants.OPENID); if (obj==null){ return ""; }else { openid= (String) obj; } return openid; } public static void setWeiPhoto(String openid) { APP.aCache.put(MLConstants.WEIXINTOUXIANG, openid); } public static String getWeiPhoto() { String openid; Object obj = APP.aCache.getAsString(MLConstants.WEIXINTOUXIANG); if (obj==null){ return ""; }else { openid= (String) obj; } return openid; } public static void setYouKe(boolean youke) { APP.aCache.put(MLConstants.YOUKE, youke); } public static boolean getYouKe() { boolean youke; Object obj = APP.aCache.getAsObject(MLConstants.YOUKE); if (obj==null){ return false; }else { youke= (Boolean) obj; } return youke; } public static void setTalktoRongUseId(String id) { APP.aCache.put(MLConstants.TALKTORONGUSEID, id); } public static String getTalktoRongUseId() { String id; Object obj = APP.aCache.getAsString(MLConstants.TALKTORONGUSEID); if (obj==null){ return ""; }else { id= (String) obj; } return id; } public static void setPwd(String pwd) { APP.aCache.put(MLConstants.PASSWORD, pwd); } public static String getPwd() { String pwd; Object obj = APP.aCache.getAsString(MLConstants.PASSWORD); if (obj==null){ return ""; }else { pwd= (String) obj; } return pwd; } ///IP地址 public static void setIPAddress(String pwd) { APP.aCache.put(MLConstants.IPAddress, pwd); } public static String getIPAddress() { String pwd; Object obj = APP.aCache.getAsString(MLConstants.IPAddress); if (obj==null){ return ""; }else { pwd= (String) obj; } return pwd; } public static void setBussitionBackgroup(String backColor) { APP.aCache.put(MLConstants.BUSSITIONBACKGROUP, backColor); } public static String getBussitionBackgroup() { String pwd; Object obj = APP.aCache.getAsString(MLConstants.BUSSITIONBACKGROUP); if (obj==null){ return ""; }else { pwd= (String) obj; } return pwd; } public static void setBussitionShow(String show) { APP.aCache.put(MLConstants.BUSSITIONSHOW, show); } public static String getBussitionShow() { String pwd; Object obj = APP.aCache.getAsString(MLConstants.BUSSITIONSHOW); if (obj==null){ return ""; }else { pwd= (String) obj; } return pwd; } public static void setSmallComPanyData(SmallComPanyData userdata) { APP.aCache.put(MLConstants.SmallComPanyData, userdata); } public static Object getSmallComPanyData() { SmallComPanyData userdata; Object obj = APP.aCache.getAsObject(MLConstants.SmallComPanyData); if (obj==null){ return null; }else { userdata= (SmallComPanyData) obj; } return userdata; } public static void setCpmStr(String userdata) { APP.aCache.put(MLConstants.SmallComPanyData, userdata); } public static Object getCpmStr() { String userdata; Object obj = APP.aCache.getAsString(MLConstants.SmallComPanyData); if (obj==null){ return null; }else { userdata= (String) obj; } return userdata; } }
package com.telekomatrix.hadoop.solution.mr; import java.net.URI; import org.apache.hadoop.fs.FileSystem; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix="hadoop") public class HadoopConf { private String input; private String output; private String url; public String getInput() { return input; } public void setInput(String input) { this.input = input; } public String getOutput() { return output; } public void setOutput(String output) { this.output = output; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public org.apache.hadoop.conf.Configuration getLocalHadoopConf() throws Exception { // ====== Init HDFS File System Object org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration(); // Set FileSystem URI conf.set("fs.defaultFS", url); // Because of Maven conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); // Set HADOOP user System.setProperty("HADOOP_USER_NAME", "hdfs"); System.setProperty("hadoop.home.dir", "/"); //Get the filesystem - HDFS FileSystem fs = FileSystem.get(URI.create(url), conf); return conf; } }
package com.restcode.restcode.resource; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class SaveProductResource { @NotNull @NotBlank @Size(max=100) private String name; private String description; @NotNull private Double price; public String getName() { return name; } public SaveProductResource setName(String name) { this.name = name; return this;} public String getDescription() { return description; } public SaveProductResource setDescription(String description) { this.description = description; return this; } public Double getPrice() { return price; } public SaveProductResource setPrice(Double price) { this.price = price; return this; } }
package controller2.ScannerFiles; import java.util.*; import java.io.*; public class PersonTest { public static void main( String[] args ) { Formatter output = null; try{ output = new Formatter( "E:/imtiaz/client.txt" ); }catch( FileNotFoundException e ) { e.printStackTrace(); } Scanner input = new Scanner( System.in ); Person p = new Person(); System.out.println("Enter any name and press \'n\' to terminate."); String temp = "y"; try{ while( !temp.equals("n") ) { p.setName( input.nextLine() ); temp = p.getName(); if( !temp.equals("n") ) output.format("%s\n", p.getName()); } }catch(FormatterClosedException e ) { e.printStackTrace(); return; }catch( NoSuchElementException e ) { e.printStackTrace(); return; }finally{ output.flush(); output.close(); input.close(); } } }
package com.gome.manager.domain; import java.io.Serializable; /** * * 评论实体类. * * <pre> * 修改日期 修改人 修改原因 * 2015年11月6日 caowei 新建 * </pre> */ public class ReadingSupport implements Serializable { /** * */ private static final long serialVersionUID = -3576016565013678112L; //ID private Long id; private Long yid; //名称 private String perId; //发表日期 private String createTime; private String typeV; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public Long getYid() { return yid; } public void setYid(Long yid) { this.yid = yid; } public String getPerId() { return perId; } public void setPerId(String perId) { this.perId = perId; } public String getTypeV() { return typeV; } public void setTypeV(String typeV) { this.typeV = typeV; } }
/** * Annotations denoting the roles of types or methods in the overall architecture * (at a conceptual, rather than implementation, level). * * <p>Intended for use by tools and aspects (making an ideal target for pointcuts). */ @NonNullApi @NonNullFields package org.springframework.stereotype; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package ca.l5.expandingdev.jsgf; import java.util.*; public class Sequence implements Expansion, Collection { private List<Expansion> exp; public Sequence(Expansion... e) { exp = Arrays.asList(e); } public Sequence() { exp = new ArrayList<>(); } @Override public boolean hasChildren() { return exp.size() != 0; } @Override public boolean hasUnparsedChildren() { for (Expansion e : exp) { if (e instanceof Grammar.UnparsedSection) { return true; } } return false; } public boolean addExpansion(Expansion e) { return exp.add(e); } public boolean removeExpansion(Expansion e) { return exp.remove(e); } @Override public String getString() { String s = ""; for (Expansion e : exp) { s = s.concat(e.getString() + " "); } s = s.trim(); return s; } // Checks to see if the sequence container is necessary or not public Expansion simplestForm() { if (exp.size() == 1) { // Has only one Expansion, so return that simpler expansion return exp.get(0); } else { // Cannot be simplified return this; } } @Override public int size() { return exp.size(); } @Override public boolean isEmpty() { return exp.size() == 0; } @Override public boolean contains(Object o) { if (o instanceof Expansion) { return exp.contains((Expansion) o); } return false; } @Override public Iterator<Expansion> iterator() { return exp.iterator(); } @Override public Object[] toArray() { Object[] o = new Object[exp.size()]; exp.toArray(o); return o; } @Override public boolean add(Object o) { if (o instanceof Expansion) { return this.addExpansion((Expansion) o); } else { return false; } } @Override public boolean remove(Object o) { if (o instanceof Expansion) { return this.removeExpansion((Expansion) o); } else { return false; } } @Override public boolean addAll(Collection c) { for (Object o : c) { this.add(o); } return true; } @Override public void clear() { exp.clear(); } @Override public boolean retainAll(Collection c) { return false; } @Override public boolean removeAll(Collection c) { for (Object o : c) { this.remove(o); } return true; } @Override public boolean containsAll(Collection c) { for (Object o : c) { if (!this.contains(o)) { return false; } } return true; } @Override public Object[] toArray(Object[] a) { return new Object[0]; } }
package com.meehoo.biz.core.basic.ro.bos; import lombok.Data; import java.util.List; /** * 中间表设置 * @author zc * @date 2019-09-03 */ @Data public class BatchUpdateRO { private String mainId; private List<String> subIds; }
package com.ibm.apt.sba_back.domain; import javax.persistence.*; import java.sql.Date; @Entity @Table(name = "users", schema = "sba", catalog = "sba") public class Users { private Integer userId; private String userName; private String password; private int roleId; private int active; private String email; private Date createDate; private Date workTimingStart; private Date workTimingEnd; private String linkedinUrl; private String mentorProfile; private Integer expYear; @Id @Column(name = "USER_ID", nullable = false) public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @Basic @Column(name = "USER_NAME", nullable = false, length = 20) public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Basic @Column(name = "PASSWORD", nullable = false, length = 45) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Basic @Column(name = "ROLE_ID", nullable = false) public int getRoleId() { return roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } @Basic @Column(name = "ACTIVE", nullable = false) public int getActive() { return active; } public void setActive(int active) { this.active = active; } @Basic @Column(name = "EMAIL", nullable = false, length = 45) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Basic @Column(name = "CREATE_DATE", nullable = false) public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } @Basic @Column(name = "WORK_TIMING_START", nullable = true) public Date getWorkTimingStart() { return workTimingStart; } public void setWorkTimingStart(Date workTimingStart) { this.workTimingStart = workTimingStart; } @Basic @Column(name = "WORK_TIMING_END", nullable = true) public Date getWorkTimingEnd() { return workTimingEnd; } public void setWorkTimingEnd(Date workTimingEnd) { this.workTimingEnd = workTimingEnd; } @Basic @Column(name = "LINKEDIN_URL", nullable = true, length = 45) public String getLinkedinUrl() { return linkedinUrl; } public void setLinkedinUrl(String linkedinUrl) { this.linkedinUrl = linkedinUrl; } @Basic @Column(name = "MENTOR_PROFILE", nullable = true, length = 45) public String getMentorProfile() { return mentorProfile; } public void setMentorProfile(String mentorProfile) { this.mentorProfile = mentorProfile; } @Basic @Column(name = "EXP_YEAR", nullable = true) public Integer getExpYear() { return expYear; } public void setExpYear(Integer expYear) { this.expYear = expYear; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Users users = (Users) o; if (userId != users.userId) return false; if (roleId != users.roleId) return false; if (active != users.active) return false; if (userName != null ? !userName.equals(users.userName) : users.userName != null) return false; if (password != null ? !password.equals(users.password) : users.password != null) return false; if (email != null ? !email.equals(users.email) : users.email != null) return false; if (createDate != null ? !createDate.equals(users.createDate) : users.createDate != null) return false; if (workTimingStart != null ? !workTimingStart.equals(users.workTimingStart) : users.workTimingStart != null) return false; if (workTimingEnd != null ? !workTimingEnd.equals(users.workTimingEnd) : users.workTimingEnd != null) return false; if (linkedinUrl != null ? !linkedinUrl.equals(users.linkedinUrl) : users.linkedinUrl != null) return false; if (mentorProfile != null ? !mentorProfile.equals(users.mentorProfile) : users.mentorProfile != null) return false; if (expYear != null ? !expYear.equals(users.expYear) : users.expYear != null) return false; return true; } @Override public int hashCode() { Integer result = userId; result = 31 * result + (userName != null ? userName.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + roleId; result = 31 * result + active; result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (createDate != null ? createDate.hashCode() : 0); result = 31 * result + (workTimingStart != null ? workTimingStart.hashCode() : 0); result = 31 * result + (workTimingEnd != null ? workTimingEnd.hashCode() : 0); result = 31 * result + (linkedinUrl != null ? linkedinUrl.hashCode() : 0); result = 31 * result + (mentorProfile != null ? mentorProfile.hashCode() : 0); result = 31 * result + (expYear != null ? expYear.hashCode() : 0); return result; } }
package com.chaojicode; public interface Shell { void color(); }
class Solution { HashMap<Integer,List<Integer>> map = new HashMap<>(); HashSet<Integer> set = new HashSet<>(); List<Integer> ans = new ArrayList<>(); boolean impossible = false; public int[] findOrder(int numCourses, int[][] prerequisites) { for(int i=0;i<numCourses;i++){ map.put(i,new ArrayList<Integer>()); } for(int[] p: prerequisites){ map.get(p[0]).add(p[1]); } for(int i = 0; i<numCourses;i++){ if(impossible){ return new int[0]; } dfs(i,new ArrayList<Integer>()); } return ans.stream().mapToInt(i -> i).toArray(); } void dfs(int id, List<Integer> vis){ List<Integer> visi = new ArrayList<>(vis); if(impossible) return; List<Integer> l = map.get(id); if(l.size()==0){ if(ans.contains(id)){ return; } } visi.add(id); for(Integer s: map.get(id)){ if(visi.contains(s)){ impossible = true; return; } dfs(s,visi); } map.put(id,new ArrayList<>()); ans.add(id); } }
package com.xld.common.validator; import com.baidu.unbiz.fluentvalidator.Validator; import java.lang.reflect.Constructor; import java.util.HashMap; /** * 简易 校验器工厂 */ public class SimpleValidatorFactory { /** * 简易匹配规则 */ private static HashMap<Class, Class> validatorMap; static { validatorMap = new HashMap<>(); validatorMap.put(String.class, StringLengthValidator.class); validatorMap.put(Double.class, DoubleLengthValidator.class); validatorMap.put(Integer.class, IntegerValidator.class); } /** * 获取指定的校验器 * @param clazz 需要校验的字段的类 * @param fieldName 需要校验的字段名称 * @return 指定的校验器 null 无匹配的校验器 */ public static Validator getInstanceByType(Class clazz, String fieldName) { try { Constructor constructor = validatorMap.get(clazz).getConstructor(String.class); return (Validator) constructor.newInstance(fieldName); } catch (Exception e) { e.printStackTrace(); } return null; } }
package PageObjectRepository; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class POM_HomePage { WebDriver brows; @FindBy (id = "srchword" ) WebElement Textbox_search; @FindBy (className ="newsrchbtn" ) WebElement Button_search; @FindBy (id ="find" ) WebElement text_validmsg; @FindBy(css = "p[class = 'sorrymsg']") WebElement text_invalidmsg; @FindBy(xpath = ".//div[@id='myDataDiv']/div/div[1]/div[1]/a/img") WebElement img_floodandfire; public POM_HomePage(WebDriver driver) { brows=driver; PageFactory.initElements(brows, this); } public void Enter_searchword(String Search_Item) { Textbox_search.sendKeys(Search_Item); } public void click_Searchbutton() { Button_search.click(); } public String get_validmsg(){ return text_validmsg.getText(); } public String get_invalidmsg() { return text_invalidmsg.getText(); } public void click_img() { img_floodandfire.click(); } public void execute_comm_methods(String Search_Item) { Enter_searchword( Search_Item); click_Searchbutton(); } }