text
stringlengths
10
2.72M
package wai.weakdemo; import android.app.KeyguardManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.util.Log; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationListener; import com.lzy.okgo.OkGo; import com.lzy.okgo.callback.AbsCallback; import okhttp3.Call; import okhttp3.Response; /** * Created by Administrator on 2016/7/2. */ public class NoticeService extends Service { private Handler myHandler = new Handler(); private String httpResult = "0"; private PowerManager pm; private PowerManager.WakeLock wakeLock; public AMapLocationClientOption mLocationOption = new AMapLocationClientOption(); //声明AMapLocationClient类对象 //声明定位回调监听器 public AMapLocationListener mLocationListener = new AMapLocationListener() { @Override public void onLocationChanged(AMapLocation aMapLocation) { System.out.println("```````````" + aMapLocation.getLatitude() + ":" + aMapLocation.getLongitude()); mLocationClient.stopLocation(); OkGo.post("http://kuaipao.myejq.com/App/Android/Deliver/AddLatLng.aspx") .params("did", "274") .params("lat", aMapLocation.getLatitude()) .params("lng", aMapLocation.getLongitude()) .params("Glat", aMapLocation.getLatitude()) .params("Glng", aMapLocation.getLongitude()) .execute(new AbsCallback<String>() { @Override public String convertSuccess(Response response) throws Exception { return null; } @Override public void onSuccess(String s, Call call, Response response) { System.out.println("```````````3" + s); } }); } }; //初始化定位 AMapLocationClient mLocationClient; /** * @param intent * @return */ @Override public IBinder onBind(Intent intent) { return null; } private Runnable myTasks = new Runnable() { @Override public void run() { //间隔多久 Message msg = myHandler.obtainMessage(); msg.obj = 0; myHandler.sendMessage(msg); System.out.println("```````````2"); mLocationClient.startLocation(); myHandler.postDelayed(myTasks, 15000); } }; @Override public void onCreate() { super.onCreate(); mLocationClient = new AMapLocationClient(this); mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); mLocationClient.setLocationOption(mLocationOption); mLocationOption.setOnceLocation(true); mLocationOption.setOnceLocationLatest(false); mLocationOption.setNeedAddress(false); mLocationOption.setLocationCacheEnable(false); //设置定位回调监听 mLocationClient.setLocationListener(mLocationListener); //mLocationClient.startLocation(); new Thread(myTasks).start(); myHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; } @Override public void onStart(Intent intent, int startId) { pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CPUKeepRunning"); wakeLock.acquire(); super.onStart(intent, startId); //保持cpu一直运行,不管屏幕是否黑屏 } }
package hiber; public class Customer { private int pid; private String pname; public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } private String email; public Customer(String pname, String email) { super(); this.pname = pname; this.email = email; } }
package com.cimcssc.chaojilanling.entity.job; import java.util.ArrayList; /** * Created by cimcitech on 2017/5/11. */ public class WorkTypeVo { private boolean result; private ArrayList<ResultUIs> resultUIs; public boolean isResult() { return result; } public void setResult(boolean result) { this.result = result; } public ArrayList<ResultUIs> getResultUIs() { return resultUIs; } public void setResultUIs(ArrayList<ResultUIs> resultUIs) { this.resultUIs = resultUIs; } public class ResultUIs { private String id; private String name; private String url; private String count; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getCount() { return count; } public void setCount(String count) { this.count = count; } } }
package com.stem.controller; import java.io.PrintWriter; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.alibaba.fastjson.JSONObject; import com.stem.core.commons.AjaxConroller; import com.stem.core.constant.CookieConstant; import com.stem.core.constant.ErrorConstant; import com.stem.entity.User; import com.stem.service.UserService; import com.stem.util.CookieUtil; import com.stem.util.Md5Encrypt; import com.stem.vo.UserLoginVO; @Controller @RequestMapping("") public class LoginController extends AjaxConroller{ private final Logger logger = LoggerFactory.getLogger(getClass()); @Value("#{propertiesReader[cookie_username_key]}") private String cookieUserNameKey; private UserService userService; @RequestMapping("/index") public String index() { return "fore/home"; } @RequestMapping("/login") public void doLogin(@ModelAttribute UserLoginVO user, Model model, PrintWriter pw) { if(null==user){ user = new UserLoginVO(); } User entity = this.userService.selectByUserName(user.getUserName()); JSONObject resultObject = new JSONObject(); if(null==entity){ resultObject.put("errcode", ErrorConstant.USER_PWD_ERROR); resultObject.put("errmsg", getMessage("user.noexist")); writeJson(resultObject.toJSONString()); return; } String encryptedPwd = Md5Encrypt.getMD5ofStr(user.getPassword()); if(!encryptedPwd.equalsIgnoreCase(entity.getPassword())){ resultObject.put("errcode", ErrorConstant.USER_PWD_ERROR); resultObject.put("errmsg", getMessage("user.login.up.error")); writeJson(resultObject.toJSONString()); return; } //登录成功 CookieUtil.addCookie(response, CookieConstant.COOKIE_USERNAME_KEY, user.getUserName()); logger.debug("用户【"+user.getUserName()+"】登录成功..."); resultObject.put("errcode", ErrorConstant.OPERATION_SUCCESS); resultObject.put("errmsg", getMessage("user.login.success")); writeJson(resultObject.toJSONString()); } @RequestMapping("/welcome") public String content(Model model) { return "redirect:pro/index.htm"; } public UserService getUserService() { return userService; } @Resource public void setUserService(UserService userService) { this.userService = userService; } }
package com.cognitive.newswizard.service.repository; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import com.cognitive.newswizard.service.entity.RawFeedEntryEntity; public interface RawFeedEntryRepository extends MongoRepository<RawFeedEntryEntity, String> { RawFeedEntryEntity findByFeedEntryId(final String feedEntryId); @Query(value="{}", fields="{_id : 1}") List<RawFeedEntryEntity> findAllIds(); @Query(value="{_id : ?0}", fields="{publishedDateTime : 1}") RawFeedEntryEntity findPublishedDateTimeById(String id); }
package proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DynamicProxy<T> implements InvocationHandler { // 要代理的真实对象 private T t; private ProxyCallback proxyCallback; public T bind(T t, ProxyCallback proxyCallback) { this.t = t; this.proxyCallback = proxyCallback; return (T) Proxy.newProxyInstance(t.getClass().getClassLoader(), t.getClass().getInterfaces(), this); } /** * proxy : 要代理的真实对象 * method : 要调用真实对象的方法 * args : method 的参数 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (proxyCallback != null) { proxyCallback.beforeProxy(); } Object result = method.invoke(t, args); if (proxyCallback != null) { proxyCallback.afterProxy(); } return result; } interface ProxyCallback { void beforeProxy(); void afterProxy(); } }
package com.google; import java.io.FileInputStream; import java.util.List; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Rediff { WebDriver driver = null ; public void readproperty() throws Exception { FileInputStream fis = new FileInputStream("Resources\\config.properties"); Properties prop = new Properties(); prop.load(fis); String browser = prop.getProperty("browser"); String URL = prop.getProperty("URL"); fis.close(); setup(browser,URL); } public void setup(String browser, String URL) throws InterruptedException { switch(browser){ case "firefox": System.setProperty("webdriver.gecko.driver", "Resources\\geckodriver.exe"); driver = new FirefoxDriver(); break; case "chrome": System.setProperty("webdriver.chrome.driver", "Resources\\chromedriver.exe"); driver = new ChromeDriver(); break; case "Edge": System.setProperty("webdriver.edge.driver", "Resources\\msedgedriver.exe"); driver = new EdgeDriver(); break; } driver.get(URL); rediffmailLinkTest(); } public void rediffmailLinkTest() throws InterruptedException { driver.findElement(By.linkText("Rediffmail")).click(); String navURL = driver.getCurrentUrl(); if (navURL.equals("https://mail.rediff.com/cgi-bin/login.cgi")) System.out.println("Pass"); else System.out.println("Fail"); // loginTest(); orderOfCursor(); } /* public void loginTest() throws InterruptedException { driver.findElement(By.id("login1")).sendKeys("trainer23"); driver.findElement(By.id("password")).sendKeys("trainer23"); driver.findElement(By.id("remember")).sendKeys(Keys.SPACE); Thread.sleep(3000); driver.findElement(By.name("proceed")).click(); if (driver.findElement(By.id("login1")).getAttribute("value").isEmpty()) System.out.println("Pass"); else System.out.println("Fail"); if (driver.findElement(By.id("remember")).isSelected()) System.out.println("Pass"); else System.out.println("Fail"); } */ public void orderOfCursor() { if (driver.findElement(By.id("login1")).getAttribute("tabindex").equals("1")) System.out.println("Login 1st focus"); if (driver.findElement(By.id("password")).getAttribute("tabindex").equals("2")) System.out.println("Password 2nd focus"); if (driver.findElement(By.id("remember")).getAttribute("tabindex").equals("3")) System.out.println("Remember 3nd focus"); if (driver.findElement(By.name("proceed")).getAttribute("tabindex").equals("4")) System.out.println(" Signin 4th focus"); createNewAccountTest(); } public void createNewAccountTest() { driver.findElement(By.linkText("Create a new account")).click(); driver.findElement(By.xpath("//*[@id=\"tblcrtac\"]/tbody/tr[24]/td[3]/input[2]")).click(); List<WebElement> gender = driver.findElements(By.xpath("//*[@id=\'tblcrtac\']/tbody/tr[24]/td[3]")); System.out.println(gender); for (WebElement g : gender) { if (g.isSelected()) System.out.println("You have selected : " + g.getAttribute("m")); } } // public void teardown() // { // // driver.quit(); // } public static void main(String[] args) throws Exception { Rediff red = new Rediff(); red.readproperty(); } }
/** * @file: com.innovail.trouble.graphics - FontStillModel.java * @date: May 24, 2012 * @author: bweber */ package com.innovail.trouble.graphics; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.g3d.loaders.g3d.G3dLoader; import com.badlogic.gdx.graphics.g3d.loaders.g3d.chunks.G3dExporter; import com.badlogic.gdx.graphics.g3d.model.SubMesh; import com.badlogic.gdx.graphics.g3d.model.still.StillModel; import com.badlogic.gdx.graphics.g3d.model.still.StillSubMesh; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; /** * */ public class FontStillModel { private static final String TAG = "FontStillModel"; private final StillModel _fontModel; private Map <Character, String> _fontMap; private float _fontSpacing = 0.04f; private Character _referenceCharacter; @SuppressWarnings ("unchecked") public static FontStillModel importModel (final FileHandle handleSM, final FileHandle handleFSM) { final StillModel tempModel = G3dLoader.loadStillModel (handleSM); FontStillModel fsm = null; try { final InputStream is = handleFSM.read (); final ObjectInput oi = new ObjectInputStream (is); final Map <Character, String> fm = (HashMap <Character, String>) oi.readObject (); final float fs = oi.readFloat (); final char rc = oi.readChar (); oi.close (); fsm = new FontStillModel (tempModel, fm, rc); fsm.setFontSpacing (fs); } catch (final Exception ex) { Gdx.app.log (TAG, ex.getMessage ()); } return fsm; } public FontStillModel (final StillModel model) { _fontModel = model; createFontMap (); } public FontStillModel (final StillModel model, final Map <Character, String> fontMap, final Character referenceCharacter) { _fontModel = model; _fontMap = fontMap; _referenceCharacter = referenceCharacter; } private void createFontMap () { if ((_fontMap == null) || _fontMap.isEmpty ()) { _fontMap = new HashMap <Character, String> (); } final SubMesh [] subMeshes = _fontModel.getSubMeshes (); for (int i = 0; i < subMeshes.length; i++) { final String line = subMeshes[i].name; String [] tokens = line.split ("\\."); if (tokens[1].isEmpty ()) { tokens[1] = "._"; } tokens = tokens[1].split ("_"); if (tokens[0].isEmpty ()) { tokens[0] = "_"; } _fontMap.put (tokens[0].charAt (0), line); if (i == 0) { _referenceCharacter = tokens[0].charAt (0); } } } public StillModel createStillModel (final String text) { if ((_fontMap != null) && !_fontMap.isEmpty ()) { final int textSize = text.length (); final Vector2 boxWidth = new Vector2 (Vector2.Zero); final List <SubMesh> characterMeshes = new ArrayList <SubMesh> (); final BoundingBox referenceBB = new BoundingBox (); final List <Float> xVectors = new ArrayList <Float> (); _fontModel.getSubMesh (_fontMap.get (_referenceCharacter)).getBoundingBox (referenceBB); /* * We need to add a spacer here to compensate for the loop's first * character */ for (int i = 0; i < textSize; i++) { /* Skip spaces */ if (text.charAt (i) == ' ') { boxWidth.x += referenceBB.getDimensions ().x; continue; } final String name = _fontMap.get (Character.valueOf (text.charAt (i))); final String newName = new String (UUID.randomUUID ().toString ()); final SubMesh tempSubMesh = _fontModel.getSubMesh (name); if (tempSubMesh == null) { return null; } final SubMesh character = new StillSubMesh (newName, tempSubMesh.getMesh ().copy (true), tempSubMesh.primitiveType, tempSubMesh.material); final BoundingBox currentBB = new BoundingBox (); character.getBoundingBox (currentBB); final Vector3 bbDimensions = currentBB.getDimensions (); xVectors.add (boxWidth.x); boxWidth.x += _fontSpacing + bbDimensions.x; if (boxWidth.y < bbDimensions.y) { boxWidth.y = bbDimensions.y; } characterMeshes.add (character); } boxWidth.x -= _fontSpacing; final float newPos = -boxWidth.x / 2; for (int i = 0; i < characterMeshes.size (); i++) { final Mesh currentMesh = characterMeshes.get (i).getMesh (); final int vertArraySize = currentMesh.getNumVertices () * 6; final float [] tempVerts = new float [vertArraySize]; currentMesh.getVertices (tempVerts); for (int j = 0; j < vertArraySize;) { tempVerts[j] += newPos + xVectors.get (i); /* skip Y and Z coordinates and the normals */ j += 6; } currentMesh.setVertices (tempVerts); } final SubMesh [] textMeshArray = new SubMesh [characterMeshes.size ()]; characterMeshes.toArray (textMeshArray); final StillModel textMesh = new StillModel (textMeshArray); return textMesh; } return null; } public void exportModel (final FileHandle handleSM, final FileHandle handleFSM) { G3dExporter.export (_fontModel, handleSM); try { final OutputStream os = handleFSM.write (false); final ObjectOutput oo = new ObjectOutputStream (os); oo.writeObject (_fontMap); oo.writeFloat (_fontSpacing); oo.writeChar (_referenceCharacter); oo.flush (); os.close (); } catch (final Exception ex) { Gdx.app.log (TAG, ex.getMessage ()); } } public Map <Character, String> getFontMap () { return _fontMap; } public float getFontSpacing () { return _fontSpacing; } public Character getReferenceCharacter () { return _referenceCharacter; } public StillModel getStillModel () { return _fontModel; } public void setFontSpacing (final float spacing) { _fontSpacing = spacing; } }
package com.espendwise.ocean.common.webaccess; import java.io.Serializable; import java.util.List; public class BasicResponseValue<T> implements Serializable { public static interface STATUS { public static final int OK = 1; public static final int EXCEPTION = 2; public static final int ERROR = 3; public static final int ACCESS_DENIED = 4; public static final int ACCESS_TOKEN_EXPIRED = 5; } private List<ResponseError> errors; private int status; private T object; public BasicResponseValue(T object, int status, List<ResponseError> errors) { this.object = object; this.status = status; this.errors = errors; } public BasicResponseValue() { } public List<ResponseError> getErrors() { return errors; } public void setErrors(List<ResponseError> errors) { this.errors = errors; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public T getObject() { return object; } public void setObject(T object) { this.object = object; } @Override public String toString() { return "BasicResponseValue{" + "errors=" + errors + ", status=" + status + ", object=" + object + '}'; } }
package com.techlabs.accounttest; import java.util.ArrayList; import com.techlabs.account.Account; public class AccountListTest { public static void main(String[] args) { ArrayList<Account>accounts=new ArrayList<Account>(); Account a = new Account("101", "Sonam", 5000); accounts.add(a);; a.deposit(0); printInfo(a); a.withdraw(4500); System.out.println(" "); } public static void printInfo(Account a) { } }
package {packagename}; import java.util.Date; import lombok.Data; /** * @Author wx * @Description: * @Modified By: */ @Data public class {model} { {field} }
package com.geekbrains.septembermarket.utils; import com.geekbrains.septembermarket.entities.Product; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @Component @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) public class Cart { private HashMap<String, CartItem> cartItems; private int allCost; public HashMap<String, CartItem> getProducts() { return cartItems; } @PostConstruct public void init() { cartItems = new HashMap<>(); allCost = 0; } public void addProduct(Product product) { if(cartItems.containsKey(product.getTitle())){ CartItem item = cartItems.get(product.getTitle()); item.setAmount(item.getAmount() + 1); } else { CartItem item = new CartItem(product.getId(), product.getTitle(),product.getPrice(), 1); cartItems.put(product.getTitle(), item); } allCost+=product.getPrice(); } public void deleteProduct(Product product){ CartItem cartItem = cartItems.get(product.getTitle()); cartItem.setAmount(cartItem.getAmount() - 1); if(cartItem.getAmount() == 0){ cartItems.remove(product.getTitle()); } allCost-=product.getPrice(); } public int getAllCost() { return allCost; } }
package net.minecraft.world; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; public interface IWorldEventListener { void notifyBlockUpdate(World paramWorld, BlockPos paramBlockPos, IBlockState paramIBlockState1, IBlockState paramIBlockState2, int paramInt); void notifyLightSet(BlockPos paramBlockPos); void markBlockRangeForRenderUpdate(int paramInt1, int paramInt2, int paramInt3, int paramInt4, int paramInt5, int paramInt6); void playSoundToAllNearExcept(EntityPlayer paramEntityPlayer, SoundEvent paramSoundEvent, SoundCategory paramSoundCategory, double paramDouble1, double paramDouble2, double paramDouble3, float paramFloat1, float paramFloat2); void playRecord(SoundEvent paramSoundEvent, BlockPos paramBlockPos); void spawnParticle(int paramInt, boolean paramBoolean, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, int... paramVarArgs); void func_190570_a(int paramInt, boolean paramBoolean1, boolean paramBoolean2, double paramDouble1, double paramDouble2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6, int... paramVarArgs); void onEntityAdded(Entity paramEntity); void onEntityRemoved(Entity paramEntity); void broadcastSound(int paramInt1, BlockPos paramBlockPos, int paramInt2); void playEvent(EntityPlayer paramEntityPlayer, int paramInt1, BlockPos paramBlockPos, int paramInt2); void sendBlockBreakProgress(int paramInt1, BlockPos paramBlockPos, int paramInt2); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\world\IWorldEventListener.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package wmsClient; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.net.URL; import javax.swing.UIManager; import com.l2fprod.gui.plaf.skin.SkinLookAndFeel; import com.l2fprod.gui.plaf.skin.Skin; public class WMSClient { @SuppressWarnings("empty-statement") public static void main(String[] args) { try { try { Skin skin = null; try { // URL packtheme = WMSClient.class.getResource( "themepack_modern.zip" ); // InputStream packtheme = WMSClient.class.getResourceAsStream( "themepack_modern.zip" ); // skin = SkinLookAndFeel.loadThemePack(packtheme); URL packtheme = WMSClient.class.getResource( "skinlf-themepack.xml" ); skin = SkinLookAndFeel.loadThemePackDefinition( packtheme ); System.out.println( "Theme: "+ packtheme); } catch(Exception e) { System.out.println("No theme provided, defaulting to application Look And Feel"); } if (skin != null) { SkinLookAndFeel.setSkin(skin); UIManager.setLookAndFeel("com.l2fprod.gui.plaf.skin.SkinLookAndFeel"); UIManager.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { //Object oldLF = event.getOldValue(); Object newLF = event.getNewValue(); if ((newLF instanceof SkinLookAndFeel) == false) { try { UIManager.setLookAndFeel("com.l2fprod.gui.plaf.skin.SkinLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } } } }); } } catch(Exception e) { System.out.println("No themes available."+e); } //LME WmsClientStartup startup = new WmsClientStartup(); new WmsClientStartup(); } catch ( Exception e ) { System.out.println("An error occurred:"); e.printStackTrace(); } } }
package com.ibiscus.myster.model.survey.item; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity(name = "NumberItem") @DiscriminatorValue("NUMBER") public class NumberItem extends AbstractSurveyItem { NumberItem() { super(); } public NumberItem(long id, long categoryId, int position, String title, String description) { super(id, categoryId, position, title, description); } }
package com.project.linkedindatabase.jsonToPojo; import com.project.linkedindatabase.domain.post.LikeComment; import com.project.linkedindatabase.domain.post.LikePost; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class LikeJson { private Long profileId; private Long id; private Long post_comment_id; private boolean isForPost ; private boolean isForComment; public static LikeJson convertToJsonPost(LikePost likePost) { LikeJson likeJson = new LikeJson(); likeJson.setForComment(false); likeJson.setForPost(true); likeJson.setId(likePost.getId()); likeJson.setPost_comment_id(likePost.getPostId()); likeJson.setProfileId(likePost.getProfileId()); return likeJson; } public static LikeJson convertToJsonComment(LikeComment likeComment) { LikeJson likeJson = new LikeJson(); likeJson.setForComment(true); likeJson.setForPost(false); likeJson.setId(likeComment.getId()); likeJson.setPost_comment_id(likeComment.getCommentId()); likeJson.setProfileId(likeComment.getProfileId()); return likeJson; } }
import java.util.*; import static javax.swing.JOptionPane.*; public class Birthdate { public int month, day, year; public static void main(String[]args) { new Birthdate();//call app constructor } public Birthdate()// app constructor { GregorianCalendar birthdate, today; birthdate = obtainBirthdate(); showMessageDialog(null, birthdate.toString()); } public GregorianCalendar obtainBirthdate() { String dateString; dateString = readValidBirthdate(); scanMonthDayYear(dateString); return new GregorianCalendar(year, month, day); } public String readValidBirthdate() { String prompt; prompt = "Enter your birthdate (e.g. 12/02/1990)"; return showInputDialog(prompt); } public void scanMonthDayYear(String s) { Scanner scan = new Scanner(s); scan.useDelimiter("/"); month = scan.nextInt(); day = scan.nextInt(); year = scan.nextInt(); } public void display() { showMessageDialog( " your birthdate is "); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cockpit.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import org.assertj.core.api.Assertions; import org.junit.Test; public final class TypeToolsTest { @Test(expected = NullPointerException.class) public void testCreateCollectionWhenClazzIsNull() { TypeTools.createCollection(null, Collections.emptyList()); } @Test(expected = NullPointerException.class) public void testCreateCollectionWhenItemsCollectionIsNull() { TypeTools.createCollection(ArrayList.class, null); } @Test public void testCreateCollectionWhenClazzIsLinkedHashSet() { // given final Collection<String> items = Collections.unmodifiableList(Arrays.asList("a", "b", "c")); // when final Collection<String> collection = TypeTools.createCollection(LinkedHashSet.class, items); // then Assertions.assertThat(collection).isInstanceOf(LinkedHashSet.class); Assertions.assertThat(collection).hasSameSizeAs(items); Assertions.assertThat(collection).containsAll(items); } @Test public void testCreateCollectionWhenClazzIsSet() { // given final Collection<String> items = Collections.unmodifiableList(Arrays.asList("1", "2", "3")); // when final Collection<String> collection = TypeTools.createCollection(Set.class, items); // then Assertions.assertThat(collection).isInstanceOf(HashSet.class); Assertions.assertThat(collection).hasSameSizeAs(items); Assertions.assertThat(collection).containsAll(items); } @Test public void testCreateCollectionWhenClazzIsEmptyList() { // given final Collection<String> items = Collections.unmodifiableList(Arrays.asList("a", "b", "c")); // when final Collection<String> collection = TypeTools.createCollection(Collections.emptyList().getClass(), items); // then Assertions.assertThat(collection).isInstanceOf(ArrayList.class); Assertions.assertThat(collection).hasSameSizeAs(items); Assertions.assertThat(collection).containsAll(items); } }
package com.halilayyildiz.game.model; public interface IPlayerMove { }
package com.bit.myfood.model.enumclass; import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor public enum PaymentType { BANK_TRANSFER(0, "", ""), CARD(1, "", ""), CHECK_CARD(2, "", ""), CASH(3, "", "") ; private Integer id; private String title; private String description; }
package com.tencent.mm.boot.svg.a.a; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import android.os.Looper; import com.tencent.mm.svg.WeChatSVGRenderC2Java; import com.tencent.mm.svg.c; public final class anp extends c { private final int height = 60; private final int width = 60; protected final int b(int i, Object... objArr) { switch (i) { case 0: return 60; case 1: return 60; case 2: Canvas canvas = (Canvas) objArr[0]; Looper looper = (Looper) objArr[1]; c.f(looper); c.e(looper); Paint i2 = c.i(looper); i2.setFlags(385); i2.setStyle(Style.FILL); Paint i3 = c.i(looper); i3.setFlags(385); i3.setStyle(Style.STROKE); i2.setColor(-16777216); i3.setStrokeWidth(1.0f); i3.setStrokeCap(Cap.BUTT); i3.setStrokeJoin(Join.MITER); i3.setStrokeMiter(4.0f); i3.setPathEffect(null); i3 = c.a(i3, looper); i3.setStrokeWidth(1.0f); canvas.save(); Paint a = c.a(i3, looper); a.setColor(-1); a.setStrokeWidth(3.0f); Path j = c.j(looper); j.moveTo(1.5f, 4.5f); j.cubicTo(1.5f, 2.8431456f, 2.8431456f, 1.5f, 4.5f, 1.5f); j.lineTo(54.0f, 1.5f); j.cubicTo(55.656853f, 1.5f, 57.0f, 2.8431456f, 57.0f, 4.5f); j.lineTo(57.0f, 54.0f); j.cubicTo(57.0f, 55.656853f, 55.656853f, 57.0f, 54.0f, 57.0f); j.lineTo(4.5f, 57.0f); j.cubicTo(2.8431456f, 57.0f, 1.5f, 55.656853f, 1.5f, 54.0f); j.lineTo(1.5f, 4.5f); j.close(); canvas.drawPath(j, a); canvas.restore(); canvas.save(); i2 = c.a(i2, looper); i2.setColor(-1); j = c.j(looper); j.moveTo(31.5f, 18.0f); j.lineTo(31.5f, 46.5f); j.cubicTo(31.5f, 47.328426f, 30.828426f, 48.0f, 30.0f, 48.0f); j.lineTo(27.0f, 48.0f); j.cubicTo(26.171574f, 48.0f, 25.5f, 47.328426f, 25.5f, 46.5f); j.lineTo(25.5f, 18.0f); j.lineTo(13.5f, 18.0f); j.cubicTo(12.671573f, 18.0f, 12.0f, 17.328426f, 12.0f, 16.5f); j.lineTo(12.0f, 13.5f); j.cubicTo(12.0f, 12.671573f, 12.671573f, 12.0f, 13.5f, 12.0f); j.lineTo(45.0f, 12.0f); j.cubicTo(45.828426f, 12.0f, 46.5f, 12.671573f, 46.5f, 13.5f); j.lineTo(46.5f, 16.5f); j.cubicTo(46.5f, 17.328426f, 45.828426f, 18.0f, 45.0f, 18.0f); j.lineTo(31.5f, 18.0f); j.close(); WeChatSVGRenderC2Java.setFillType(j, 2); canvas.drawPath(j, i2); canvas.restore(); c.h(looper); break; } return 0; } }
package LMS; import java.util.NoSuchElementException; import java.util.Scanner; import javax.swing.plaf.synth.SynthSpinnerUI; public class Stack { protected NodeReader top; protected int size; /* Các phương thức khởi dựng */ public Stack() { top = null; size = 0; } /* Function to check if stack is empty */ public boolean isEmpty() { return top == null; } /* Function to get the size of the stack */ public int getSize() { return size; } /* Function to check the top element of the stack */ public NodeReader peek() { if (isEmpty()) { return top = null; } return top; } // Function to push an element to the stack public NodeReader push(Reader r) { NodeReader node = new NodeReader(r, null); if (top == null) { top = node; } else { node.setNext(top); top = node; } size++; return node; } // Function to pop an element from the stack public NodeReader pop() { if (isEmpty()) { System.out.println("Empty..."); return null; } else { NodeReader node = top; top = node.getNext(); size--; return node; } } public NodeReader searchNode(String rcode) { NodeReader node = top; int i; while (node != null) { if (rcode.equals(node.getReader().getRcode())) { return node; } node = node.getNext(); } return null; } public Reader searchReader(Stack s) { System.out.println("Vui lòng nhập rcode để tìm reader..."); Scanner sc = new Scanner(System.in); String target = sc.nextLine(); if (target != null && !target.isEmpty()) { NodeReader n = s.searchNode(target); if (n != null) { System.out.printf("%-10s%s%-20s%s%-10s%s\n", "Rcode", "|", "Name", "|", "Byear", "|"); n.printNode(n.getReader()); return n.getReader(); } else { System.out.println("Data not found..."); return null; } } else { System.out.println("Ko duoc rong"); return searchReader(s); } } public void printStack() { System.out.println("\nStack: "); if (size == 0) { System.out.println("Empty\n"); } NodeReader nodeR = top; System.out.printf("%-10s%s%-20s%s%-10s%s\n", "Rcode", "|", "Name", "|", "Byear", "|"); while (nodeR != null) { nodeR.printNode(nodeR.getReader()); nodeR = nodeR.getNext(); } System.out.println("..."); } }
package com.brainmentors.testengine.controllers; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.brainmentors.testengine.models.test.Test; import com.brainmentors.testengine.models.test.TestResponse; import com.brainmentors.testengine.models.test.TestService; @RestController public class TestController { @Autowired private TestService service; @RequestMapping(path = "/addtest",method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody TestResponse createTest(@RequestBody Test test) { test.setCreationDateTime(new Date()); return service.addTest(test); } }
package com.stuff; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Skriv in 10 heltal: "); int[] numbers = new int[10]; for (int i = 0; i < 10; i++) { // put the input into array numbers[i] = input.nextInt(); } int max = Arrays.stream(numbers).max().getAsInt(); int min = Arrays.stream(numbers).min().getAsInt(); // calculate average float sum = Arrays.stream(numbers).sum(); float average = sum / 10; // results System.out.println("--------------------------"); // for aesthetic reasons System.out.println(Arrays.toString(numbers)); System.out.println("Högst: " + max); System.out.println("Lägst: " + min); System.out.println("Medelvärde: " + average); } }
package cn.ouyangnengda.dubbo.JavaSPI; /** * @Description: * @Author: 欧阳能达 * @Created: 2019年09月08日 12:56:00 **/ public class PrimeImpl implements Robot { @Override public void sayHello() { System.out.println("This is Prime."); } }
package com.qiang.graduation.main.entity.dto; import com.qiang.graduation.main.entity.Good; import lombok.AllArgsConstructor; import lombok.Data; import java.util.List; /** * Created with IntelliJ IDEA By * User: cjyong * Date: 2018/4/8 * Time: 20:50 * Description: */ @Data @AllArgsConstructor public class IndexGoods { List<Good> hot; List<Good> discount; List<Good> latest; }
package com.skilldistillery.cardgames.blackjack; import java.util.List; import com.skilldistillery.cardgames.common.Card; import com.skilldistillery.cardgames.common.Deck; import com.skilldistillery.cardgames.common.Person; public class Dealer extends Person { public Dealer() { this("Dealer"); } public Dealer(String name) { super(name, new BlackJackHand()); } public void takeTurn(Deck deck) { System.out.println("\n" + getName() + "'s turn!\n"); sleep(); System.out.println("\n" + getName() + "'s other card was a " + getHand().getCards().get(1).toString()); printStatus(); while (getHand().getHandValue() < 17 || hasSoft17()) { sleep(); if (hasSoft17()) { System.out.println("\n" + getName() + " has soft 17 and is taking a card...\n"); } else { System.out.println("\n" + getName() + " is taking a card...\n"); } sleep(); getHand().addCard(deck.dealCard()); printStatus(); } if (getHand().getHandValue() <= 21) { System.out.println("\n" + getName() + " is standing.\n"); } sleep(); } void sleep() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } // Internal - during dealer's turn private void printStatus() { List<Card> cards = getHand().getCards(); System.out.print("\t" + getName() + " has " + getHand().getHandValue() + ": "); for (Card card : cards) { System.out.print("\n\t\t" + card.toString()); } } public String getUpCard() { return getHand().getCards().get(0).toString(); } public boolean hasBlackjack() { if (getHand().getCards().size() == 2 && getHand().getHandValue() == 21) { return true; } return false; } public boolean hasSoft17() { BlackJackHand hand = (BlackJackHand) getHand(); boolean hasAce = false; if (hand.getHandValue() != 17) { return false; } for (Card card : hand.getCards()) { if (card.getValue() == 11) { hasAce = true; } } if (hasAce) { int nonAcesVal = 0; int acesCount = 0; for (Card card : hand.getCards()) { int val = card.getValue(); if (val != 11) { nonAcesVal += val; } else { acesCount += 1; } } return 17 - 11 - nonAcesVal + acesCount - 1 == 0; } return false; } }
package edu.matc.controller; import org.apache.log4j.Logger; import org.hibernate.Session; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Servlet for the index * web page. * * @author nfenev */ @WebServlet( urlPatterns = {"/homePage"} ) public class ScheduController extends HttpServlet { private final Logger logger = Logger.getLogger(this.getClass()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher dispatcher = req.getRequestDispatcher("index.jsp"); dispatcher.forward(req, resp); } }
package ist.meic.ie.eventmediation; import ist.meic.ie.events.EventItem; import ist.meic.ie.events.exceptions.InvalidEventTypeException; import ist.meic.ie.utils.Constants; import ist.meic.ie.utils.DatabaseConfig; import ist.meic.ie.utils.KafkaConfig; import org.apache.commons.cli.*; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.json.simple.parser.ParseException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Mediator { public static void main(String[] args) throws SQLException { CommandLine cmd = parseArgs(args); List<String> topics = new ArrayList<String>(Arrays.asList(cmd.getOptionValue("topics").split(":"))); System.out.println(topics); KafkaConsumer<String, String> consumer = KafkaConfig.createKafkaConsumer(cmd.getOptionValue("kafkaip"), "group-id-test", topics); DatabaseConfig config = new DatabaseConfig(Constants.MEDIATION_DB, "SafeHomeIoTEvents", Constants.MEDIATION_DB_USER, Constants.MEDIATION_DB_PASSWORD); while (true) { ConsumerRecords<String, String> records = consumer.poll(100); for (ConsumerRecord<String, String> record : records) { try { EventItem eventItem = new EventItem(record.value()); eventItem.getEvent().insertToDb(config); System.out.println(eventItem.getEvent()); } catch (InvalidEventTypeException | ParseException e) { e.printStackTrace(); } } } } private static CommandLine parseArgs(String[] args) { Options options = new Options(); Option input1 = new Option("kafkaip", "kafkaip", true, "ip:port of the kafka server"); input1.setRequired(true); options.addOption(input1); Option input2 = new Option("awsip", "awsip", true, "endpoint of AWS RDS"); input2.setRequired(false); options.addOption(input2); Option input3 = new Option("dbname", "dbname", true, "name of the AWS RD databse"); input3.setRequired(false); options.addOption(input3); Option input4 = new Option("username", "masterusername", true, "master username to access the database"); input4.setRequired(false); options.addOption(input4); Option input5 = new Option("password", "password", true, "password to access the database"); input5.setRequired(false); options.addOption(input5); Option input6 = new Option("topics", "topics", true, "Kafka topics to subscribe to"); input5.setRequired(false); options.addOption(input6); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("utility-name", options); System.exit(1); } return cmd; } }
package com.tencent.mm.plugin.card.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.plugin.report.service.h; class CardNewMsgUI$6 implements OnMenuItemClickListener { final /* synthetic */ CardNewMsgUI hFN; CardNewMsgUI$6(CardNewMsgUI cardNewMsgUI) { this.hFN = cardNewMsgUI; } public final boolean onMenuItemClick(MenuItem menuItem) { h.mEJ.h(11582, new Object[]{"CardMsgClearMenu", Integer.valueOf(2), Integer.valueOf(0), "", "", ""}); CardNewMsgUI.h(this.hFN); return true; } }
package main.java.breakingPointTool.calculations; import java.sql.SQLException; import java.util.ArrayList; import main.java.breakingPointTool.artifact.ClassMetrics; import main.java.breakingPointTool.artifact.PackageMetrics; import main.java.breakingPointTool.database.DatabaseGetData; import main.java.breakingPointTool.database.DatabaseSaveData; public class Results { private static final double MINUTES_IN_HOUR = 60.0; private static final double HOURLY_LINES_OF_CODE = 25.0; private static final double HOURLY_WAGE = 45.81; private double interest; private double principal; private double breakingPoint; private double fitnessValueDit; private double fitnessValueNocc; private double fitnessValueMpc; private double fitnessValueRfc; private double fitnessValueLcom; private double fitnessValueDac; private double fitnessValueNom; private double fitnessValueWmpc; private double fitnessValueSize1; private double fitnessValueSize2; public Results() { this.interest = 0; this.principal = 0; this.breakingPoint = 0; } public void calculateInterest(ClassMetrics investigatedClass, OptimalArtifact optimalClass, int version) throws SQLException { double k = investigatedClass.getAverageLocChange(); this.fitnessValueDit = calculateFitnessValueMin(optimalClass.getDit(), investigatedClass.getDit()); this.fitnessValueNocc = calculateFitnessValueMin(optimalClass.getNocc(), investigatedClass.getNocc()); this.fitnessValueMpc = calculateFitnessValueMin(optimalClass.getMpc(), investigatedClass.getMpc()); this.fitnessValueRfc = calculateFitnessValueMin(optimalClass.getRfc(), investigatedClass.getRfc()); this.fitnessValueLcom = calculateFitnessValueMin(optimalClass.getLcom(), investigatedClass.getLcom()); this.fitnessValueDac = calculateFitnessValueMin(optimalClass.getDac(), investigatedClass.getDac()); this.fitnessValueNom = calculateFitnessValueMin(optimalClass.getNom(), investigatedClass.getNom()); this.fitnessValueWmpc = calculateFitnessValueMin(optimalClass.getWmpc(), investigatedClass.getWmpc()); this.fitnessValueSize1 = calculateFitnessValueMin(optimalClass.getSize1(), investigatedClass.getSize1()); this.fitnessValueSize2 = calculateFitnessValueMin(optimalClass.getSize2(), investigatedClass.getSize2()); this.interest = this.fitnessValueDit + this.fitnessValueNocc + this.fitnessValueMpc + this.fitnessValueRfc + this.fitnessValueLcom + this.fitnessValueDac + this.fitnessValueNom + this.fitnessValueWmpc + this.fitnessValueSize1 + this.fitnessValueSize2; //System.out.println("gchsgd: " + this.interest); System.out.println("k: " + k); /*System.out.println("Interest test: " + this.fitnessValueDit + " " + this.fitnessValueNocc +" "+ this.fitnessValueMpc +" "+ this.fitnessValueRfc + " "+this.fitnessValueLcom + " "+ this.fitnessValueDac +" "+ this.fitnessValueNom +" "+ this.fitnessValueWmpc +" "+ this.fitnessValueSize1 +" "+ this.fitnessValueSize2);*/ this.interest = this.interest / 10; this.interest = 1 - this.interest ; System.out.println("Interest is: " + interest); this.interest = this.interest * k; this.interest = (this.interest / HOURLY_LINES_OF_CODE) * HOURLY_WAGE; System.out.println("Interest is in money: " + interest); System.out.println("Version: " + version); calculatePrincipal(investigatedClass); calculateBreakingPoint(); if (Double.isInfinite(this.breakingPoint)) { // It means infinity this.breakingPoint = -1; } else if (Double.isNaN(breakingPoint)) { // It means it is not defined this.breakingPoint = -2; } double rate = calculateInterestProbability(investigatedClass.getClassName(), version); System.out.println("Interest probability: " + rate); DatabaseSaveData saveDataInDatabase = new DatabaseSaveData(); saveDataInDatabase.saveBreakingPointInDatabase(investigatedClass.getClassName(), version, this.breakingPoint, this.principal, this.interest, k, rate); saveDataInDatabase.updatePrincipal(investigatedClass.getClassName(), version, this.principal); } public void calculateInterestPackage(PackageMetrics investigatedPackage, OptimalArtifact optimalClass, int version) throws SQLException { double k = investigatedPackage.getAverageLocChange(); this.fitnessValueDit = calculateFitnessValueMax(optimalClass.getDit(), investigatedPackage.getDit()); this.fitnessValueNocc = calculateFitnessValueMax(optimalClass.getNocc(), investigatedPackage.getNocc()); this.fitnessValueMpc = calculateFitnessValueMin(optimalClass.getMpc(), investigatedPackage.getMpc()); this.fitnessValueRfc = calculateFitnessValueMin(optimalClass.getRfc(), investigatedPackage.getRfc()); this.fitnessValueLcom = calculateFitnessValueMin(optimalClass.getLcom(), investigatedPackage.getLcom()); this.fitnessValueDac = calculateFitnessValueMin(optimalClass.getDac(), investigatedPackage.getDac()); this.fitnessValueNom = calculateFitnessValueMin(optimalClass.getNom(), investigatedPackage.getNom()); this.fitnessValueWmpc = calculateFitnessValueMin(optimalClass.getWmpc(), investigatedPackage.getWmpc()); this.fitnessValueSize1 = calculateFitnessValueMin(optimalClass.getSize1(), investigatedPackage.getSize1()); this.fitnessValueSize2 = calculateFitnessValueMin(optimalClass.getSize2(), investigatedPackage.getSize2()); this.interest = this.fitnessValueDit + this.fitnessValueNocc + this.fitnessValueMpc + this.fitnessValueRfc + this.fitnessValueLcom + this.fitnessValueDac + this.fitnessValueNom + this.fitnessValueWmpc + this.fitnessValueSize1 + this.fitnessValueSize2; System.out.println("k: " + k); //System.out.println("Interest test: " + this.fitnessValueDit + " " + this.fitnessValueNocc +" "+ this.fitnessValueMpc +" "+ this.fitnessValueRfc + " "+this.fitnessValueLcom + " "+ // this.fitnessValueDac +" "+ this.fitnessValueWmpc +" "+ this.fitnessValueCc +" "+ this.fitnessValueSize1 +" "+ this.fitnessValueSize2); this.interest = this.interest / 10; this.interest = 1 - this.interest ; System.out.println("Interest is: " + interest); this.interest = this.interest * k; this.interest = (this.interest / HOURLY_LINES_OF_CODE) * HOURLY_WAGE; System.out.println("Interest is in money: " + interest); calculatePrincipalPackage(investigatedPackage); calculateBreakingPoint(); if (Double.isInfinite(this.breakingPoint)) { // It means infinity this.breakingPoint = -1; } else if (Double.isNaN(breakingPoint)) { // It means it is not defined this.breakingPoint = -2; } double rate = calculateInterestProbability(investigatedPackage.getPackageName(), version); System.out.println("Interest probability: " + rate); DatabaseSaveData saveDataInDatabase = new DatabaseSaveData(); saveDataInDatabase.saveBreakingPointInDatabase(investigatedPackage.getPackageName(), version, this.breakingPoint, this.principal, this.interest, k, rate); saveDataInDatabase.updatePrincipal(investigatedPackage.getPackageName(), version, this.principal); } public double calculateInterestProbability(String artifact, int version) { ArrayList<Double> locs = new ArrayList<Double>(); double flag = 0.0; // Get k values from database DatabaseGetData dbCall = new DatabaseGetData(); locs.addAll(dbCall.getLoCForArtifact(artifact, version)); // bug when version are less than full if (locs.size() == 0 || locs.size() == 1) return 0.0; if (locs.size() == 2) { double diff = locs.get(1) - locs.get(0); if (diff != 0) return 1.0; else return 0.0; } for (int i = 0; i < locs.size()-1; i++ ) { double diff = locs.get(i + 1) - locs.get(i); if (diff != 0) { flag++; } } return flag / (locs.size()-1); } public void calculateInterestOnePackage(PackageMetrics investigatedPackage, String projectName, int version) throws SQLException { ArrayList<Double> interests = new ArrayList<Double>(); DatabaseGetData dbCall = new DatabaseGetData(); interests.addAll(dbCall.getInterestForArtifactC(projectName, version)); for (int i = 0; i < interests.size()-1; i++ ) { this.interest = this.interest + interests.get(i); } double k = investigatedPackage.getAverageLocChange(); System.out.println("----- Only one package -----"); System.out.println("Package Name: " + investigatedPackage.getPackageName()); System.out.println("Interest is: " + interest); System.out.println("K: " + k); calculatePrincipalPackage(investigatedPackage); calculateBreakingPoint(); if (Double.isInfinite(this.breakingPoint)) { // It means infinity this.breakingPoint = -1; } else if (Double.isNaN(breakingPoint)) { // It means it is not defined this.breakingPoint = -2; } double rate = calculateInterestProbability(investigatedPackage.getPackageName(), version); DatabaseSaveData saveDataInDatabase = new DatabaseSaveData(); System.out.println("Before saved in database: " + investigatedPackage.getPackageName() + " " + version + " " + this.breakingPoint + " " + this.principal + " " + this.interest + " " + k + " " + rate); saveDataInDatabase.saveBreakingPointInDatabase(investigatedPackage.getPackageName(), version, this.breakingPoint, this.principal, this.interest, k, rate); saveDataInDatabase.updatePrincipal(investigatedPackage.getPackageName(), version, this.principal); } public void calculatePrincipalPackage(PackageMetrics testedClass) { this.principal = (testedClass.getTD() / MINUTES_IN_HOUR ) * HOURLY_WAGE; System.out.println("Principal is: " + principal); } public void calculatePrincipal(ClassMetrics testedClass) { this.principal = (testedClass.getTD() / MINUTES_IN_HOUR ) * HOURLY_WAGE; System.out.println("Principal is: " + principal); } public void calculateBreakingPoint() { //TODO maybe i should change NaN to a number, lets say -1 this.breakingPoint = this.principal / this.interest; System.out.println("Breaking point is: " + breakingPoint + "\n"); } public double calculateFitnessValueMin (double optimal, double actual) { if (optimal == 00) return 0; else return optimal / actual; } public double calculateFitnessValueMax (double optimal, double actual) { if (optimal == 00) return 0; else return actual / optimal; } public double getPrincipal() { return this.principal; } public double getInterest() { return this.interest; } public double getBreakingPoint() { return this.breakingPoint; } }
package com.tencent.mm.plugin.wallet_ecard.ui; import com.tencent.mm.plugin.wallet_core.ui.m.a; import com.tencent.mm.protocal.c.btq; import com.tencent.mm.wallet_core.ui.e; class WalletECardLogoutUI$5 implements a { final /* synthetic */ btq pCB; final /* synthetic */ WalletECardLogoutUI pCz; WalletECardLogoutUI$5(WalletECardLogoutUI walletECardLogoutUI, btq btq) { this.pCz = walletECardLogoutUI; this.pCB = btq; } public final void aCb() { e.l(this.pCz.mController.tml, this.pCB.rvK, false); } }
package com.company; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPatch; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.List; public class Main { public static void main(String[] args) { News news = new News(); // get newses from google news page news.getNews(); // open local news page with data collected from google news news.openNewsPage(); } } class News { public void getNews() { // locate the chrome driver file System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver"); WebDriver page = new ChromeDriver(); //open google news page page.get("https://news.google.com/?hl=en-ET&gl=ET&ceid=ET:en"); // get newses on the page List<WebElement> news = page.findElements(By.className("NiLAwe")); // store each news in the database for (WebElement element: news){ String title = element.findElement(new By.ByTagName("span")).getText(); String content = element.findElement(new By.ByTagName("p")).getText(); String link = element.findElement(new By.ByClassName("VDXfz")).getAttribute("href"); String img = ""; // check if the news has image if (element.findElements(By.tagName("img")).size()>0){ img = element.findElement(By.tagName("img")).getAttribute("src"); } System.out.println(title + " \n " + content + "\n image \n"+ img); DefaultHttpClient httpClient = new DefaultHttpClient(); try { // trying to store the data collected from google news into the database HttpPatch request = new HttpPatch("http://localhost:3000/api/news"); StringEntity params = new StringEntity("{" + "\"content\":\"" + content + "\",\"title\":\"" + title + "\",\"img\":\"" + img + "\",\"link\"" + ":\"" + link + "\"} "); request.addHeader("content-type", "application/json"); request.addHeader("Accept","application/json"); request.setEntity(params); HttpResponse response = httpClient.execute(request); System.out.println(response); }catch (Exception ex) { System.out.println(ex.getMessage()); } finally { httpClient.getConnectionManager().shutdown(); } } } public void openNewsPage() { // locate the chrome driver file System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver"); WebDriver page = new ChromeDriver(); //open local news page page.get("http://localhost:4200/"); } }
package com.highradius.invoicesmanagement.dao; import com.highradius.invoicesmanagement.model.Invoice; import java.math.BigDecimal; import java.sql.*; import java.util.ArrayList; import java.util.List; public class InvoiceDAO { private String jdbcURL = "jdbc:mysql://localhost:3306/neha?useSSL=false"; private String jdbcUsername = "root"; private String jdbcPassword = "0609"; private static final String INSERT_INVOICE_SQL = "INSERT INTO mytable" + " (Customer_Name,Customer_,Invoice_,Invoice_Amount,Due_Date,Predicted_Payment_Date,Notes) VALUES " + " (?, ?, ?, ?, ?, ?, ?);"; private static final String SELECT_INVOICE_BY_ID = "select S_No,Customer_Name,Customer_,Invoice_,Invoice_Amount,Due_Date,Predicted_Payment_Date,Notes from mytable where S_No =?"; private static final String SELECT_ALL_INVOICES = "select * from mytable order by Due_Date desc"; private static final String DELETE_INVOICE_SQL = "delete from mytable where S_No = ?;"; private static final String UPDATE_INVOICE_SQL = "update mytable set Invoice_Amount = ?,Notes= ? where S_No = ?;"; public InvoiceDAO() { } private Connection getConnection() { Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return connection; } public void insertInvoice(Invoice invoice) throws SQLException { System.out.println(INSERT_INVOICE_SQL); //Customer_Name,Customer_ID,Invoice_ID,Invoice_Amount,Due_Date,Predicted_Payment_Date,Notes // try-with-resource statement will auto close the connection. try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(INSERT_INVOICE_SQL)) { preparedStatement.setString(1, invoice.getCustomerName()); preparedStatement.setString(2, invoice.getCustomerID()); preparedStatement.setString(3, invoice.getInvoiceID()); preparedStatement.setString(4, invoice.getAmount().toPlainString()); preparedStatement.setDate(5, new java.sql.Date(invoice.getDueDate().getTime())); preparedStatement.setDate(6, new java.sql.Date(invoice.getPredictedPaymentDate().getTime())); preparedStatement.setString(7, invoice.getNotes()); System.out.println(preparedStatement); preparedStatement.executeUpdate(); } catch (SQLException e) { printSQLException(e); } } public Invoice selectInvoice(int id) { Invoice invoice = null; // Step 1: Establishing a Connection try (Connection connection = getConnection(); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection.prepareStatement(SELECT_INVOICE_BY_ID);) { preparedStatement.setInt(1, id); System.out.println(preparedStatement); // Step 3: Execute the query or update query ResultSet rs = preparedStatement.executeQuery(); // Step 4: Process the ResultSet object. while (rs.next()) { invoice = createInvoice(rs); } } catch (SQLException e) { printSQLException(e); } return invoice; } private Invoice createInvoice(ResultSet rs) throws SQLException { //Customer_Name,Customer_ID,Invoice_ID,Invoice_Amount,Due_Date,Predicted_Payment_Date,Notes Invoice invoice = new Invoice(); invoice.setId(rs.getInt("S_No")); invoice.setCustomerName(rs.getString("Customer_Name")); invoice.setCustomerID(rs.getString("Customer_")); invoice.setInvoiceID(rs.getString("Invoice_")); invoice.setAmount(new BigDecimal(rs.getString("Invoice_Amount"))); invoice.setDueDate(new java.util.Date(rs.getDate("Due_Date").getTime())); invoice.setPredictedPaymentDate(new java.util.Date(rs.getDate("Predicted_Payment_Date").getTime())); invoice.setNotes(rs.getString("Notes")); return invoice; } public List<Invoice> selectAllInvoices() { // using try-with-resources to avoid closing resources (boiler plate code) List<Invoice> invoices = new ArrayList<>(); // Step 1: Establishing a Connection try (Connection connection = getConnection(); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_INVOICES);) { System.out.println(preparedStatement); // Step 3: Execute the query or update query ResultSet rs = preparedStatement.executeQuery(); // Step 4: Process the ResultSet object. while (rs.next()) { invoices.add(createInvoice(rs)); } } catch (SQLException e) { printSQLException(e); } return invoices; } public boolean deleteInvoice(int id) throws SQLException { boolean rowDeleted; try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(DELETE_INVOICE_SQL);) { statement.setInt(1, id); rowDeleted = statement.executeUpdate() > 0; } return rowDeleted; } public boolean updateInvoice(Invoice invoice) throws SQLException { boolean rowUpdated; try (Connection connection = getConnection(); //Invoice_Amount = ?,Notes= ? PreparedStatement statement = connection.prepareStatement(UPDATE_INVOICE_SQL);) { statement.setString(1, invoice.getAmount().toPlainString()); statement.setString(2, invoice.getNotes()); statement.setInt(3, invoice.getId()); rowUpdated = statement.executeUpdate() > 0; } return rowUpdated; } private void printSQLException(SQLException ex) { for (Throwable e : ex) { if (e instanceof SQLException) { e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException) e).getSQLState()); System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); System.err.println("Message: " + e.getMessage()); Throwable t = ex.getCause(); while (t != null) { System.out.println("Cause: " + t); t = t.getCause(); } } } } }
package com.kgitbank.spring.domain.article.dto; import java.util.List; import lombok.Data; @Data public class ArticlePageDto { private int seqId; private int articleIndex; private final int articleCount = 6; private List<ArticleDto> articles; private boolean hasMore; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package an1.persistence; import an1.exceptions.NonexistentEntityException; import an1.exceptions.PreexistingEntityException; import an1.exceptions.RollbackFailureException; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; //import javax.transaction.UserTransaction; /** * * @author bbernard */ public class CodesEcrituresJpaController { private EntityTransaction utx = null; public EntityManager getEntityManager() { EntityManagerFactory emf = Persistence .createEntityManagerFactory("anbJPA"); EntityManager em = emf.createEntityManager(); return em; } public void create(Codesecriture codeEcriture) throws PreexistingEntityException, RollbackFailureException, Exception { EntityManager em = null; try { em = getEntityManager(); utx = em.getTransaction(); utx.begin(); em.persist(codeEcriture); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } if (findCodeEcritures(codeEcriture.getCode()) != null) { throw new PreexistingEntityException("codeEcriture " + codeEcriture + " already exists.", ex); } throw ex; } finally { if (em != null) { em.close(); } } } public void edit(Codesecriture codeEcriture) throws NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { em = getEntityManager(); utx = em.getTransaction(); utx.begin(); codeEcriture = em.merge(codeEcriture); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { String code = codeEcriture.getCode(); if (findCodeEcritures(code) == null) { throw new NonexistentEntityException("The membres with id " + code + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } } public void destroy(String code) throws NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { em = getEntityManager(); utx = em.getTransaction(); utx.begin(); Codesecriture codeEcriture; try { codeEcriture = em.getReference(Codesecriture.class, code); codeEcriture.getCode(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The codeecriture with id " + code + " no longer exists.", enfe); } em.remove(codeEcriture); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } throw ex; } finally { if (em != null) { em.close(); } } } public List<Codesecriture> findEcrituresEntities() { return findCodeEcrituresEntities(true, -1, -1); } public List<Codesecriture> findEcrituresEntities(int maxResults, int firstResult) { return findCodeEcrituresEntities(false, maxResults, firstResult); } @SuppressWarnings("unchecked") private List<Codesecriture> findCodeEcrituresEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { Query q = em.createQuery("select object(o) from Codesecriture as o"); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public Codesecriture findCodeEcritures(String code) { EntityManager em = getEntityManager(); try { return em.find(Codesecriture.class, code); } finally { em.close(); } } public int getCodeEcrituresCount() { EntityManager em = getEntityManager(); try { return ((Long) em .createQuery("select count(o) from Codesecriture as o") .getSingleResult()).intValue(); } finally { em.close(); } } }
/** * Klasse for å starte programmet vårt */ public class Main { /** * Javaapplikasjonens startpunkt (denne metoden blir kjørt når java-applikasjonen kjøres) */ public static void main(String[] args) { // Oppretter og instansierer et objekt (student1) av klassen Student Student student1 = new Student("Andreas", "Hansen"); // Oppretter et objekt (student2) og setter den til å referere på samme objekt som student1 Student student2 = student1; // Setter en ny verdi til instansvariabelen etternavn for student1 student1.setEtternavn("Johansen"); // Skriver ut informasjon om student1 System.out.println("Student1: " + student1.getFornavn() + " " + student1.getEtternavn()); // Skriver ut infromasjon om student2 (vil den være det samme, eller forskjellig?) System.out.println("Student2: " + student2.getFornavn() + " " + student2.getEtternavn()); } }
package com.chuxin.family.calendar; import com.chuxin.family.R; import com.chuxin.family.app.CxRootActivity; import com.chuxin.family.models.CalendarDataObj; import com.chuxin.family.net.CalendarApi; import com.chuxin.family.net.ConnectionManager.JSONCaller; import com.chuxin.family.utils.DateUtil; import com.chuxin.family.utils.DialogUtil; import com.chuxin.family.utils.DialogUtil.OnSureClickListener; import com.chuxin.family.utils.CxLoadingUtil; import com.chuxin.family.utils.CxLog; import com.chuxin.family.utils.TextUtil; import com.chuxin.family.utils.ToastUtil; import com.chuxin.family.widgets.DatePicker; import com.chuxin.family.widgets.DatePicker.OnLunarImgClickListener; import com.chuxin.family.widgets.OnDateChangeListener; import com.chuxin.family.widgets.QuickMessage; import com.chuxin.family.widgets.TimePicker; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.PopupWindow; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * * @author shichao.wang * */ public class CxCalendarEditActivity extends CxRootActivity { public enum EditMode { ADD_MODE, UPDATE_MODE } private final String TAG = "RkCalendarEditActivity"; protected static final int COMMON_MEMORIAL = 0; private PopupWindow mLunarDatePickerDialog = null; private PopupWindow mDatePickerDialog = null; private CalendarController mController = null; private EditMode mode; // 判断是新添模式还是编辑模式 private int type = 0; // 判断是事项还是纪念日 这两项判断需要先执行已进行不同的UI展示 0 事项 1 纪念日 private int memorialType = 2; // 判断是一般纪念日还是生日 2 一般纪念日 1 生日 private TextView titleText; private TextView mReminderDateText; private ImageView mReminderSettingImg; private LinearLayout mReminderShowLayout; private TextView mReminderTargetText; private TextView mReminderTimeText; private TextView mReminderCycleText; private TextView mReminderAdvanceText; private LinearLayout mReminderDateLayout; private LinearLayout mMemorialTypeLayout; private LinearLayout mReminderTimeLayout; private LinearLayout mReminderCycleLayout; private LinearLayout mTabItemLayout; private TextView mTabItemText; private LinearLayout mTabMemorialLayout; private TextView mTabMemorialText; private EditText mContentEdit; private TextView mMemorialTypeText; private int itemReminderFlag = 0; // 0,不提醒;1,提醒。 private String itemDate; // yyyy-MM-dd private String itemTempDate; // yyyy-MM-dd private int itemTarget = 2; // 显示对象,0:自己 1:对方 2:双方 private String itemTime = "10:00"; // HH-mm; private int itemCycle = 0; // 循环周期类型,0:不循环,1:按天,2:按周,3:按月,4:按年 private int itemTempCycle = 0; // 循环周期类型,0:不循环,1:按天,2:按周,3:按月,4:按年 private int itemAdvance = 0; // 提前提醒类型,0:不提前,1:15分钟,2:1小时,3:1天,4:3天 ,5:5天 private long itemFullTime = 0; private int memorialReminderFlag = 1; private String memorialDate; private int memorialTarget = 2; private String memorialTime = "10:00"; // 默认十点 private int memorialCycle = 4; // 默认按年 private int memorialAdvance = 0; private long memorialFullTime = 0; private int memorialLunar = 0; // 0,公历;1 农历。 private String mCalendarId = ""; // private long fullTime=0; private Button mDeleteBtn; private String[] targets = { "只给自己看", "给对方看", "给双方看" }; private String[] cycles = { "提醒一次", "每天一次", "每周一次", "每月一次", "每年一次" }; private String[] advances = { "不提前提醒", "提前15分钟", "提前1小时", "提前1天", "提前3天", "提前5天" }; private String[] memorialTypes = { "生日", "一般纪念日" }; private String[] dateWeeks = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" }; private TextView mCommonText; private Dialog dialog; private PopupWindow mTimePickerDialog; private PopupWindow mDatePickerDialogWithMonthFixed; private PopupWindow mDatePickerDialogWithAnnuallyFixed; private Button mSaveButton; @Override protected void onCreate(Bundle arg0) { super.onCreate(arg0); setContentView(R.layout.cx_fa_activity_calendar_edit); // itemFullTime = memorialFullTime = System.currentTimeMillis(); Locale locale = Locale.getDefault(); Calendar today = Calendar.getInstance(locale); itemFullTime = today.getTimeInMillis(); Calendar cal = Calendar.getInstance(locale); cal.set(Calendar.HOUR_OF_DAY, 10); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); memorialFullTime = cal.getTimeInMillis(); SimpleDateFormat nowFormat = new SimpleDateFormat("yyyy-MM-dd,HH:mm"); String[] times = nowFormat.format(itemFullTime).split(","); itemDate = memorialDate = times[0]; itemTime = times[1]; Intent intent = getIntent(); int modeExtra = intent.getIntExtra(CxCalendarParam.CALENDAR_EDIT_MODE, 0); int typeExtra = intent.getIntExtra(CxCalendarParam.CALENDAR_EDIT_TYPE, 0); dateExtra = intent.getStringExtra(CxCalendarParam.CALENDAR_EDIT_DATE); if (modeExtra == CxCalendarParam.CALENDAR_EDIT_ADD) { mode = EditMode.ADD_MODE; } else { mode = EditMode.UPDATE_MODE; } if (typeExtra == CxCalendarParam.CALENDAR_TYPE_ITEM) { type = 0; } else { type = 1; } if (modeExtra == CxCalendarParam.CALENDAR_EDIT_UPDATE && typeExtra == CxCalendarParam.CALENDAR_TYPE_MEMORIAL) { int intExtra = intent.getIntExtra(CxCalendarParam.CALENDAR_MEMORIAL_TYPE, 0); if (intExtra == CxCalendarParam.CALENDAR_MEMORIAL_BIRTHDAY) { memorialType = 1; } else { memorialType = 2; } } initTitle(); init(); setEditState(); // 设置UI的各个参数展示 // fillData(); } private void setEditState() { // if(null == mController.getId() || // TextUtils.isEmpty(mController.getId())){ // mode = EditMode.ADD_MODE; // } else { // mode = EditMode.UPDATE_MODE; // } if (mode == EditMode.ADD_MODE) { add(); } else { update(); } } // 添加模式 private void add() { mDeleteBtn.setVisibility(View.GONE); if(!TextUtils.isEmpty(dateExtra)){ Calendar instance = Calendar.getInstance(); instance.set(Calendar.YEAR, Integer.parseInt(dateExtra.substring(0, 4))); instance.set(Calendar.MONTH, Integer.parseInt(dateExtra.substring(4, 6))-1); instance.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateExtra.substring(6, 8))); itemFullTime=instance.getTimeInMillis(); instance.set(Calendar.HOUR_OF_DAY, 10); instance.set(Calendar.MINUTE, 0); instance.set(Calendar.SECOND, 0); memorialFullTime = instance.getTimeInMillis(); SimpleDateFormat nowFormat = new SimpleDateFormat("yyyy-MM-dd,HH:mm"); String[] times = nowFormat.format(itemFullTime).split(","); itemDate = memorialDate = times[0]; itemTime = times[1]; } if (type == 0) { addItem(); } else { addMemorial(); } } // 添加事项 private void addItem() { titleText.setText(R.string.cx_fa_calendar_edit_title_text1);// 标题 itemTab();// UI状态切换 setItemReminderShow(); // 提醒UI显示 setRemainderData(); // 提醒数据显示 CxLog.i("RkCalendarEidtAcitivity_men", "itemReminderFlag:"+itemReminderFlag+",itemDate:"+itemDate +",itemTime:"+itemTime+",itemCycle:"+itemCycle+",itemAdvance:"+itemAdvance +",mCalendarId:"+"null"); } // 添加纪念日 private void addMemorial() { titleText.setText(R.string.cx_fa_calendar_edit_title_text2); memorialTab(); setMemorialReminderShow(); setRemainderData(); CxLog.i("RkCalendarEidtAcitivity_men", "memorialReminderFlag:"+memorialReminderFlag+",memorialDate:"+memorialDate +",memorialTarget:"+memorialTarget+",memorialAdvance:"+memorialAdvance+",memorialLunar:"+memorialLunar +",mCalendarId:"+"null"+",memorialType:"+memorialType); } // 修改模式 private void update() { type = mController.getType(); mDeleteBtn.setVisibility(View.VISIBLE); // mController.reset(); if(!TextUtils.isEmpty(mController.getContent())){ mContentEdit.setText(mController.getContent()); mContentEdit.setSelection(mController.getContent().length()); } if (type == 0) { updateItem(); } else { updateMemorial(); } } private void updateItem() { titleText.setText(R.string.cx_fa_calendar_edit_title_text3); itemTab(); // 根据intent传过来的参数进行赋值。 itemReminderFlag = mController.getIsRemind(); itemFullTime = (long)mController.getTime() * 1000; // RkLog.i("RkCalendarEditActivity_men", // ">>>>>>>>>" + nowFormat.format(new Date((long)(itemFullTime*1000)))); SimpleDateFormat nowFormat = new SimpleDateFormat("yyyy-MM-dd,HH:mm"); String[] times = nowFormat.format(itemFullTime).split(","); itemDate = times[0]; itemTime = times[1]; itemTarget=mController.getTarget(); itemCycle = mController.getPeriod(); itemAdvance = mController.getAdvance(); mCalendarId = mController.getId(); setItemReminderShow(); setRemainderData(); CxLog.i("RkCalendarEidtAcitivity_men", "itemReminderFlag:"+itemReminderFlag+",itemDate:"+itemDate +",itemTime:"+itemTime+",itemCycle:"+itemCycle+",itemAdvance:"+itemAdvance +",mCalendarId:"+mCalendarId); } private void updateMemorial() { titleText.setText(R.string.cx_fa_calendar_edit_title_text4); memorialTab(); // 根据intent传过来的参数进行赋值。 memorialReminderFlag = mController.getIsRemind(); memorialFullTime = (long)(mController.getTime() * 1000); SimpleDateFormat nowFormat = new SimpleDateFormat("yyyy-MM-dd,HH:mm"); String[] times = nowFormat.format(memorialFullTime).split(","); memorialDate = times[0]; memorialTarget = mController.getTarget(); memorialAdvance = mController.getAdvance(); memorialLunar=mController.getIsLunar(); mCalendarId = mController.getId(); setMemorialReminderShow(); setRemainderData(); CxLog.i("RkCalendarEidtAcitivity_men", "memorialReminderFlag:"+memorialReminderFlag+",memorialDate:"+memorialDate +",memorialTarget:"+memorialTarget+",memorialAdvance:"+memorialAdvance+",memorialLunar:"+memorialLunar +",mCalendarId:"+mCalendarId+",memorialType:"+memorialType); } private void setItemReminderShow() { // if (mode == EditMode.UPDATE_MODE) { // mContentEdit.setHint(mController.getContent()); // } if (itemReminderFlag == 1) { mReminderSettingImg.setImageResource(R.drawable.calendar_set_on); mReminderTimeLayout.setVisibility(View.VISIBLE); mReminderShowLayout.setVisibility(View.VISIBLE); } else { mReminderSettingImg.setImageResource(R.drawable.calendar_set_off); mReminderTimeLayout.setVisibility(View.GONE); mReminderShowLayout.setVisibility(View.GONE); } } private void setRemainderData() { if (type == 0) { mReminderDateText.setText(itemDate); mReminderTargetText.setText(targets[itemTarget]); mReminderTimeText.setText(itemTime); mReminderCycleText.setText(cycles[itemCycle]); mReminderAdvanceText.setText(advances[itemAdvance]); } else { mMemorialTypeText.setText(memorialTypes[memorialType - 1]); mReminderDateText.setText(memorialDate); mReminderTargetText.setText(targets[memorialTarget]); mReminderAdvanceText.setText(advances[memorialAdvance]); } } private void setMemorialReminderShow() { // if (mode == EditMode.UPDATE_MODE) { // mContentEdit.setHint(mController.getContent()); // } if (memorialReminderFlag == 1) { mReminderSettingImg.setImageResource(R.drawable.calendar_set_on); mReminderShowLayout.setVisibility(View.VISIBLE); } else { mReminderSettingImg.setImageResource(R.drawable.calendar_set_off); mReminderShowLayout.setVisibility(View.GONE); } } private void setReminderDateType() { if (type == 0) { mReminderDateLayout.setVisibility(View.VISIBLE); Calendar c = Calendar.getInstance(); c.setTimeInMillis(itemFullTime); Calendar c1 = Calendar.getInstance(); c1.set(Calendar.HOUR, c.get(Calendar.HOUR)); c1.set(Calendar.MINUTE, c.get(Calendar.MINUTE)); c1.set(Calendar.SECOND, c.get(Calendar.SECOND)); CxLog.i("RkCalendarEditActivity_men", ">>>>>>>>>" + c.get(Calendar.YEAR) + ":" + c.get(Calendar.MONTH) + ":" + c.get(Calendar.DAY_OF_MONTH) + ":" + c.get(Calendar.DAY_OF_WEEK)); SimpleDateFormat nowFormat = null; if (itemCycle == 0) { nowFormat = new SimpleDateFormat("yyyy-MM-dd"); itemDate = nowFormat.format(new Date(itemFullTime)); } else if (itemCycle == 1) { itemFullTime=c1.getTimeInMillis(); mReminderDateLayout.setVisibility(View.GONE); } else if (itemCycle == 2) { itemFullTime=c1.getTimeInMillis(); itemDate = DateUtil.getCatipalNumber(c1.get(Calendar.DAY_OF_WEEK)); } else if (itemCycle == 3) { c1.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH)); itemFullTime=c1.getTimeInMillis(); itemDate = String.format(getResources().getString(R.string.cx_fa_nls_reminder_everymonth_format), c1.get(Calendar.DAY_OF_MONTH)); } else { c1.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH)); c1.set(Calendar.MONTH, c.get(Calendar.MONTH)); itemFullTime=c1.getTimeInMillis(); nowFormat = new SimpleDateFormat("MM-dd"); itemDate = nowFormat.format(new Date(itemFullTime)); } mReminderDateText.setText(itemDate); } else { mReminderDateText.setText(memorialDate); } } // 获取布局文件参数 private void init() { mController = CalendarController.getInstance(); mTabItemLayout = (LinearLayout)findViewById(R.id.cx_fa_calendar_edit_tab_item_layout); mTabItemText = (TextView)findViewById(R.id.cx_fa_calendar_edit_tab_item_tv); mTabMemorialLayout = (LinearLayout)findViewById(R.id.cx_fa_calendar_edit_tab_memorial_layout); mTabMemorialText = (TextView)findViewById(R.id.cx_fa_calendar_edit_tab_memorial_tv); mContentEdit = (EditText)findViewById(R.id.cx_fa_calendar_edit_content_et); mCommonText = (TextView)findViewById(R.id.cx_fa_calendar_edit_content_recommend_tv); mMemorialTypeLayout = (LinearLayout)findViewById(R.id.cx_fa_calendar_edit_memorial_day_selecter_layout); mMemorialTypeText = (TextView)findViewById(R.id.cx_fa_calendar_edit_memorial_day_selecter_tv); mReminderDateLayout = (LinearLayout)findViewById(R.id.cx_fa_calendar_edit_reminder_date_layout); mReminderDateText = (TextView)findViewById(R.id.cx_fa_calendar_edit_reminder_date_tv); LinearLayout mReminderTargetLayout = (LinearLayout)findViewById(R.id.cx_fa_calendar_edit_reminder_target_layout); mReminderTargetText = (TextView)findViewById(R.id.cx_fa_calendar_edit_reminder_target_tv); mReminderTimeLayout = (LinearLayout)findViewById(R.id.cx_fa_calendar_edit_reminder_time_layout); mReminderTimeText = (TextView)findViewById(R.id.cx_fa_calendar_edit_reminder_time_tv); mReminderCycleLayout = (LinearLayout)findViewById(R.id.cx_fa_calendar_edit_reminder_cycle_layout); mReminderCycleText = (TextView)findViewById(R.id.cx_fa_calendar_edit_reminder_cycle_tv); LinearLayout mReminderAdvanceLayout = (LinearLayout)findViewById(R.id.cx_fa_calendar_edit_reminder_advance_layout); mReminderAdvanceText = (TextView)findViewById(R.id.cx_fa_calendar_edit_reminder_advance_tv); mReminderShowLayout = (LinearLayout)findViewById(R.id.cx_fa_calendar_edit_reminder_is_show_layout); LinearLayout mReminderSettingLayout = (LinearLayout)findViewById(R.id.cx_fa_calendar_edit_reminder_setting_layout); mReminderSettingImg = (ImageView)findViewById(R.id.cx_fa_calendar_edit_reminder_setting_iv); mDeleteBtn = (Button)findViewById(R.id.cx_fa_calendar_edit_delete_btn); mTabItemLayout.setOnClickListener(contentListener); mTabMemorialLayout.setOnClickListener(contentListener); mCommonText.setOnClickListener(contentListener); mMemorialTypeLayout.setOnClickListener(contentListener); mReminderDateLayout.setOnClickListener(reminderListener); mReminderTargetLayout.setOnClickListener(reminderListener); mReminderTimeLayout.setOnClickListener(reminderListener); mReminderCycleLayout.setOnClickListener(reminderListener); mReminderAdvanceLayout.setOnClickListener(reminderListener); mReminderSettingLayout.setOnClickListener(reminderListener); mDeleteBtn.setOnClickListener(reminderListener); mContentEdit.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { // RkLog.v(TAG, "come afterTextChanged"); // if(s.length()>0){ // mSaveButton.setClickable(true); // mSaveButton.setTextColor(getResources().getColor(R.color.cx_fa_co_navi_button_text)); // mSaveButton.setText(getString(R.string.cx_fa_calendar_edit_title_save_text)); // }else{ // mSaveButton.setClickable(false); // mSaveButton.setTextColor(getResources().getColor(R.color.cx_fa_co_grey)); // mSaveButton.setText(getString(R.string.cx_fa_calendar_edit_title_save_text)); // } } }); } // 初始化标题栏 private void initTitle() { Button backBtn = (Button)findViewById(R.id.cx_fa_activity_title_back); mSaveButton = (Button)findViewById(R.id.cx_fa_activity_title_more); titleText = (TextView)findViewById(R.id.cx_fa_activity_title_info); backBtn.setText(getString(R.string.cx_fa_navi_back)); mSaveButton.setTextColor(getResources().getColor(R.color.cx_fa_co_navi_button_text)); mSaveButton.setText(getString(R.string.cx_fa_calendar_edit_title_save_text)); mSaveButton.setVisibility(View.VISIBLE); backBtn.setOnClickListener(titleListener); mSaveButton.setOnClickListener(titleListener); } private OnClickListener titleListener = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.cx_fa_activity_title_back: back(); break; case R.id.cx_fa_activity_title_more: mSaveButton.setClickable(false); saveCalendar(); break; default: break; } } }; private OnClickListener contentListener = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.cx_fa_calendar_edit_tab_item_layout:// 事项标签切换 if (type == 0) { return; } type = 0; changeTab(); break; case R.id.cx_fa_calendar_edit_tab_memorial_layout:// 纪念日标签切换 if (type == 1) { return; } type = 1; changeTab(); break; case R.id.cx_fa_calendar_edit_content_recommend_tv: // 常用纪念日 Intent commonIntent = new Intent(CxCalendarEditActivity.this, CxCalendarCommonMemorialDay.class); startActivityForResult(commonIntent, COMMON_MEMORIAL); overridePendingTransition(R.anim.tran_next_in, R.anim.tran_next_out); break; case R.id.cx_fa_calendar_edit_memorial_day_selecter_layout: //纪念日/生日切换 showTargetOrCycleOrAdvanceDialog(4); break; default: break; } } }; // 表情点击切换 private void changeTab() { if (type == 0) { if (mode == EditMode.ADD_MODE) { titleText.setText(R.string.cx_fa_calendar_edit_title_text1); } else { titleText.setText(R.string.cx_fa_calendar_edit_title_text3); } itemTab(); setItemReminderShow(); setRemainderData(); } else { if (mode == EditMode.ADD_MODE) { titleText.setText(R.string.cx_fa_calendar_edit_title_text2); } else { titleText.setText(R.string.cx_fa_calendar_edit_title_text4); } memorialTab(); setMemorialReminderShow(); setRemainderData(); } } private OnClickListener reminderListener = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.cx_fa_calendar_edit_reminder_date_layout: // 日期 // showDatePickerDialog(); if (type == 0) { if (itemCycle == 3) { showDatePickerDialogWithMonthFixed(); } else if (itemCycle == 2) { showReminderEditDateForWeeklyList(); } else if (itemCycle == 4) { showDatePickerDialogWithAnnuallyFixed(); } else { showDatePickerDialog(); } } else { if (memorialType == 1) { showDateLunarPickerDialog(true); } else { showDatePickerDialog2(); } } break; case R.id.cx_fa_calendar_edit_reminder_target_layout: // 提醒对象 showTargetOrCycleOrAdvanceDialog(1); break; case R.id.cx_fa_calendar_edit_reminder_time_layout: // 时间 showTimePickerDialog(); break; case R.id.cx_fa_calendar_edit_reminder_cycle_layout: // 周期 showTargetOrCycleOrAdvanceDialog(2); break; case R.id.cx_fa_calendar_edit_reminder_advance_layout: // 是否提前 showTargetOrCycleOrAdvanceDialog(3); break; case R.id.cx_fa_calendar_edit_reminder_setting_layout:// 是否提醒 if (type == 0) { setItemReminderClick(); } else { setMemorialReminderClick(); } break; case R.id.cx_fa_calendar_edit_delete_btn: dropItem(); break; default: break; } } }; // 显示dialog private void showTargetOrCycleOrAdvanceDialog(int which) { View view = View.inflate(this, R.layout.cx_fa_widget_calendar_edit_common_dialog, null); LinearLayout targetLayout = (LinearLayout)view.findViewById(R.id.cx_fa_calendar_edit_target); LinearLayout cycleLayout = (LinearLayout)view.findViewById(R.id.cx_fa_calendar_edit_cycle); LinearLayout advanceLayout = (LinearLayout)view.findViewById(R.id.cx_fa_calendar_edit_advance); LinearLayout memorialTypeLayout = (LinearLayout)view.findViewById(R.id.cx_fa_calendar_edit_memorial_type); LinearLayout dateLayout = (LinearLayout)view.findViewById(R.id.cx_fa_calendar_edit_date); Button cancelBtn = (Button)view.findViewById(R.id.cx_fa_calendar_edit_common_dialog_cancel); switch (which) { case 1: targetLayout.setVisibility(View.VISIBLE); cycleLayout.setVisibility(View.GONE); advanceLayout.setVisibility(View.GONE); memorialTypeLayout.setVisibility(View.GONE); dateLayout.setVisibility(View.GONE); break; case 2: targetLayout.setVisibility(View.GONE); cycleLayout.setVisibility(View.VISIBLE); advanceLayout.setVisibility(View.GONE); memorialTypeLayout.setVisibility(View.GONE); dateLayout.setVisibility(View.GONE); break; case 3: targetLayout.setVisibility(View.GONE); cycleLayout.setVisibility(View.GONE); advanceLayout.setVisibility(View.VISIBLE); memorialTypeLayout.setVisibility(View.GONE); dateLayout.setVisibility(View.GONE); break; case 4: targetLayout.setVisibility(View.GONE); cycleLayout.setVisibility(View.GONE); advanceLayout.setVisibility(View.GONE); memorialTypeLayout.setVisibility(View.VISIBLE); dateLayout.setVisibility(View.GONE); break; case 5: targetLayout.setVisibility(View.GONE); cycleLayout.setVisibility(View.GONE); advanceLayout.setVisibility(View.GONE); memorialTypeLayout.setVisibility(View.GONE); dateLayout.setVisibility(View.VISIBLE); break; default: break; } TextView targetMe = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_target_me); TextView targetOppo = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_target_oppo); TextView targetBoth = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_target_both); View targetOppoView = view.findViewById(R.id.cx_fa_calendar_edit_target_oppo_view); TextView cycleOnce = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_cycle_once); TextView cycleDay = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_cycle_day); TextView cycleWeek = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_cycle_week); TextView cycleMonth = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_cycle_month); TextView cycleYear = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_cycle_year); TextView advanceNone = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_advance_none); TextView advance15m = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_advance_15m); TextView advance1h = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_advance_1h); TextView advance1d = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_advance_1d); TextView advance3d = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_advance_3d); TextView advance5d = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_advance_5d); TextView memorialTypeBir = (TextView)view .findViewById(R.id.cx_fa_calendar_edit_memorial_type_birthday); TextView memorialTypeNormal = (TextView)view .findViewById(R.id.cx_fa_calendar_edit_memorial_type_normal); TextView date1 = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_date_1); TextView date2 = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_date_2); TextView date3 = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_date_3); TextView date4 = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_date_4); TextView date5 = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_date_5); TextView date6 = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_date_6); TextView date7 = (TextView)view.findViewById(R.id.cx_fa_calendar_edit_date_7); if (type == 0) { targetOppo.setVisibility(View.VISIBLE); targetOppoView.setVisibility(View.VISIBLE); } else { targetOppo.setVisibility(View.GONE); targetOppoView.setVisibility(View.GONE); } targetMe.setOnClickListener(dialogListener); targetOppo.setOnClickListener(dialogListener); targetBoth.setOnClickListener(dialogListener); cycleOnce.setOnClickListener(dialogListener); cycleDay.setOnClickListener(dialogListener); cycleWeek.setOnClickListener(dialogListener); cycleMonth.setOnClickListener(dialogListener); cycleYear.setOnClickListener(dialogListener); advanceNone.setOnClickListener(dialogListener); advance15m.setOnClickListener(dialogListener); advance1h.setOnClickListener(dialogListener); advance1d.setOnClickListener(dialogListener); advance3d.setOnClickListener(dialogListener); advance5d.setOnClickListener(dialogListener); memorialTypeBir.setOnClickListener(dialogListener); memorialTypeNormal.setOnClickListener(dialogListener); date1.setOnClickListener(dialogListener); date2.setOnClickListener(dialogListener); date3.setOnClickListener(dialogListener); date4.setOnClickListener(dialogListener); date5.setOnClickListener(dialogListener); date6.setOnClickListener(dialogListener); date7.setOnClickListener(dialogListener); cancelBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog = new Dialog(this, R.style.simple_dialog); dialog.setContentView(view); dialog.show(); } OnClickListener dialogListener = new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); switch (v.getId()) { case R.id.cx_fa_calendar_edit_target_me: mReminderTargetText.setText(R.string.cx_fa_calendar_edit_dialog_target_me); if (type == 0) { itemTarget = 0; } else { memorialTarget = 0; } break; case R.id.cx_fa_calendar_edit_target_oppo: mReminderTargetText.setText(R.string.cx_fa_calendar_edit_dialog_target_oppo); itemTarget = 1; break; case R.id.cx_fa_calendar_edit_target_both: mReminderTargetText.setText(R.string.cx_fa_calendar_edit_dialog_target_both); if (type == 0) { itemTarget = 2; } else { memorialTarget = 2; } break; case R.id.cx_fa_calendar_edit_cycle_once: mReminderCycleText.setText(R.string.cx_fa_calendar_edit_dialog_cycle_noce); itemCycle = 0; setReminderDateType(); break; case R.id.cx_fa_calendar_edit_cycle_day: mReminderCycleText.setText(R.string.cx_fa_calendar_edit_dialog_cycle_day); itemCycle = 1; setReminderDateType(); break; case R.id.cx_fa_calendar_edit_cycle_week: mReminderCycleText.setText(R.string.cx_fa_calendar_edit_dialog_cycle_week); itemCycle = 2; setReminderDateType(); break; case R.id.cx_fa_calendar_edit_cycle_month: mReminderCycleText.setText(R.string.cx_fa_calendar_edit_dialog_cycle_month); itemCycle = 3; setReminderDateType(); break; case R.id.cx_fa_calendar_edit_cycle_year: mReminderCycleText.setText(R.string.cx_fa_calendar_edit_dialog_cycle_year); itemCycle = 4; setReminderDateType(); break; case R.id.cx_fa_calendar_edit_advance_none: mReminderAdvanceText.setText(R.string.cx_fa_calendar_edit_dialog_advance_none); if (type == 0) { itemAdvance = 0; } else { memorialAdvance = 0; } break; case R.id.cx_fa_calendar_edit_advance_15m: mReminderAdvanceText.setText(R.string.cx_fa_calendar_edit_dialog_advance_15m); if (type == 0) { itemAdvance = 1; } else { memorialAdvance = 1; } break; case R.id.cx_fa_calendar_edit_advance_1h: mReminderAdvanceText.setText(R.string.cx_fa_calendar_edit_dialog_advance_1h); if (type == 0) { itemAdvance = 2; } else { memorialAdvance = 2; } break; case R.id.cx_fa_calendar_edit_advance_1d: mReminderAdvanceText.setText(R.string.cx_fa_calendar_edit_dialog_advance_1d); if (type == 0) { itemAdvance = 3; } else { memorialAdvance = 3; } break; case R.id.cx_fa_calendar_edit_advance_3d: mReminderAdvanceText.setText(R.string.cx_fa_calendar_edit_dialog_advance_3d); if (type == 0) { itemAdvance = 4; } else { memorialAdvance = 4; } break; case R.id.cx_fa_calendar_edit_advance_5d: mReminderAdvanceText.setText(R.string.cx_fa_calendar_edit_dialog_advance_5d); if (type == 0) { itemAdvance = 5; } else { memorialAdvance = 5; } break; case R.id.cx_fa_calendar_edit_memorial_type_birthday: mMemorialTypeText.setText(R.string.cx_fa_calendar_edit_dialog_memorial_type_bir); memorialType = 1; break; case R.id.cx_fa_calendar_edit_memorial_type_normal: mMemorialTypeText.setText(R.string.cx_fa_calendar_edit_dialog_memorial_type_normal); memorialType = 2; break; case R.id.cx_fa_calendar_edit_date_1: onDateWeekClick(2); break; case R.id.cx_fa_calendar_edit_date_2: onDateWeekClick(3); break; case R.id.cx_fa_calendar_edit_date_3: onDateWeekClick(4); break; case R.id.cx_fa_calendar_edit_date_4: onDateWeekClick(5); break; case R.id.cx_fa_calendar_edit_date_5: onDateWeekClick(6); break; case R.id.cx_fa_calendar_edit_date_6: onDateWeekClick(7); break; case R.id.cx_fa_calendar_edit_date_7: onDateWeekClick(1); break; default: break; } } }; private String dateExtra; private PopupWindow mDatePickerMemorialDialog; private void onDateWeekClick(int i) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(itemFullTime)); calendar.set(Calendar.DAY_OF_WEEK, i); itemFullTime = calendar.getTimeInMillis(); setReminderDateType(); } // 提醒点击设置 private void setItemReminderClick() { if (itemReminderFlag == 0) { itemCycle=itemTempCycle; setReminderDateType(); mReminderSettingImg.setImageResource(R.drawable.calendar_set_on); mReminderShowLayout.setVisibility(View.VISIBLE); mReminderTimeLayout.setVisibility(View.VISIBLE); itemReminderFlag = 1; } else { itemTempCycle=itemCycle; itemCycle=0; setReminderDateType(); mReminderSettingImg.setImageResource(R.drawable.calendar_set_off); mReminderShowLayout.setVisibility(View.GONE); mReminderTimeLayout.setVisibility(View.GONE); itemReminderFlag = 0; } } // 提醒点击设置 private void setMemorialReminderClick() { if (memorialReminderFlag == 0) { mReminderSettingImg.setImageResource(R.drawable.calendar_set_on); mReminderShowLayout.setVisibility(View.VISIBLE); memorialReminderFlag = 1; } else { mReminderSettingImg.setImageResource(R.drawable.calendar_set_off); mReminderShowLayout.setVisibility(View.GONE); memorialReminderFlag = 0; } } // 标签切换 private void itemTab() { mCommonText.setVisibility(View.GONE); mMemorialTypeLayout.setVisibility(View.GONE); mContentEdit.setHint(R.string.cx_fa_calendar_edit_edit_item_hint); mReminderCycleLayout.setVisibility(View.VISIBLE); // mReminderTimeLayout.setVisibility(View.VISIBLE); /* if (itemCycle == 1) { mReminderTimeLayout.setVisibility(View.GONE); mReminderDateLayout.setVisibility(View.GONE); } else { mReminderTimeLayout.setVisibility(View.VISIBLE); mReminderDateLayout.setVisibility(View.VISIBLE); }*/ mTabItemLayout.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_white); mTabItemText.setText(TextUtil.getNewSpanStr( getString(R.string.cx_fa_calendar_edit_tab_item), 18, Color.rgb(235, 161, 121))); mTabMemorialLayout .setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_gray); mTabMemorialText.setText(TextUtil.getNewSpanStr( getString(R.string.cx_fa_calendar_edit_tab_memorial_day), 16, Color.argb(144, 0, 0, 0))); } // 标签切换 private void memorialTab() { mCommonText.setVisibility(View.VISIBLE); mMemorialTypeLayout.setVisibility(View.VISIBLE); mContentEdit.setHint(R.string.cx_fa_calendar_edit_edit_memorial_day_hint); mReminderDateLayout.setVisibility(View.VISIBLE); mReminderCycleLayout.setVisibility(View.GONE); mReminderTimeLayout.setVisibility(View.GONE); mTabMemorialLayout.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_white); mTabMemorialText.setText(TextUtil.getNewSpanStr( getString(R.string.cx_fa_calendar_edit_tab_memorial_day), 18, Color.rgb(235, 161, 121))); mTabItemLayout.setBackgroundResource(R.drawable.cx_fa_accounting_homepage_detail_bg_gray); mTabItemText.setText(TextUtil.getNewSpanStr( getString(R.string.cx_fa_calendar_edit_tab_item), 16, Color.argb(144, 0, 0, 0))); } // 获取常用纪念日 public void onActivityResult(int requestCode, int resultCode, Intent data) { if (Activity.RESULT_OK != resultCode) { return; } if (requestCode == COMMON_MEMORIAL) { String extra = data.getStringExtra(CxCalendarParam.CALENDAR_COMMON_MEMORIAL); if (!TextUtils.isEmpty(extra)) { mContentEdit.setText(extra); mContentEdit.setSelection(extra.length()); if(extra.contains("生日")){ mMemorialTypeText.setText(R.string.cx_fa_calendar_edit_dialog_memorial_type_bir); memorialType = 1; }else{ mMemorialTypeText.setText(R.string.cx_fa_calendar_edit_dialog_memorial_type_normal); memorialType = 2; } } } } protected void back() { if(mLunarDatePickerDialog!=null && mLunarDatePickerDialog.isShowing()){ mLunarDatePickerDialog.dismiss(); mLunarDatePickerDialog=null; return ; } if(mDatePickerDialogWithMonthFixed!=null && mDatePickerDialogWithMonthFixed.isShowing()){ mDatePickerDialogWithMonthFixed.dismiss(); mDatePickerDialogWithMonthFixed=null; return ; } if(mDatePickerDialogWithAnnuallyFixed!=null && mDatePickerDialogWithAnnuallyFixed.isShowing()){ mDatePickerDialogWithAnnuallyFixed.dismiss(); mDatePickerDialogWithAnnuallyFixed=null; return ; } if(mDatePickerDialog!=null && mDatePickerDialog.isShowing()){ mDatePickerDialog.dismiss(); mDatePickerDialog=null; return ; } if(mTimePickerDialog!=null && mTimePickerDialog.isShowing()){ mTimePickerDialog.dismiss(); mTimePickerDialog=null; return ; } if(mDatePickerMemorialDialog!=null && mDatePickerMemorialDialog.isShowing()){ mDatePickerMemorialDialog.dismiss(); mDatePickerMemorialDialog=null; return ; } if(dialog!=null && dialog.isShowing()){ dialog.dismiss(); dialog=null; return ; } if(!TextUtils.isEmpty(mContentEdit.getText().toString().trim())){ showSureExitDialog(); return ; } finish(); overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out); } private void showSureExitDialog() { DialogUtil instance = DialogUtil.getInstance(); instance.setOnSureClickListener(new OnSureClickListener() { @Override public void surePress() { finish(); overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out); } }); instance.getSimpleDialog(CxCalendarEditActivity.this, null, "确定退出吗?", null, null).show(); } protected void back2() { if(mLunarDatePickerDialog!=null && mLunarDatePickerDialog.isShowing()){ mLunarDatePickerDialog.dismiss(); mLunarDatePickerDialog=null; } if(mDatePickerDialogWithMonthFixed!=null && mDatePickerDialogWithMonthFixed.isShowing()){ mDatePickerDialogWithMonthFixed.dismiss(); mDatePickerDialogWithMonthFixed=null; } if(mDatePickerDialogWithAnnuallyFixed!=null && mDatePickerDialogWithAnnuallyFixed.isShowing()){ mDatePickerDialogWithAnnuallyFixed.dismiss(); mDatePickerDialogWithAnnuallyFixed=null; } if(mDatePickerDialog!=null && mDatePickerDialog.isShowing()){ mDatePickerDialog.dismiss(); mDatePickerDialog=null; } if(mTimePickerDialog!=null && mTimePickerDialog.isShowing()){ mTimePickerDialog.dismiss(); mTimePickerDialog=null; } if(mDatePickerMemorialDialog!=null && mDatePickerMemorialDialog.isShowing()){ mDatePickerMemorialDialog.dismiss(); mDatePickerMemorialDialog=null; } if(dialog!=null && dialog.isShowing()){ dialog.dismiss(); dialog=null; } finish(); overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out); } @Override public boolean onKeyDown(int keyCode, android.view.KeyEvent event) { if (keyCode == android.view.KeyEvent.KEYCODE_BACK) { back(); return false; } return super.onKeyDown(keyCode, event); }; /** * show time dialog at the bottom */ private void showTimePickerDialog() { TimePicker timePicker = new TimePicker(this); if (mTimePickerDialog == null) { // long time = mController.getTime(); mTimePickerDialog = new PopupWindow(timePicker, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mTimePickerDialog.setWidth(LayoutParams.MATCH_PARENT); mTimePickerDialog.setHeight(LayoutParams.WRAP_CONTENT); mTimePickerDialog.setBackgroundDrawable(getResources().getDrawable( R.color.cx_fa_co_datepicker_dialog_background)); mTimePickerDialog.setTouchable(true); mTimePickerDialog.setOutsideTouchable(true); timePicker.setOnTimeChangeListener(new OnDateChangeListener() { @Override public void onTimeChange(TimePicker view, int hourOfDay, int minute) { // long time = mController.getTime(); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(itemFullTime)); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minute); SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); itemFullTime = calendar.getTimeInMillis(); String format = timeFormat.format(new Date(itemFullTime)); if (type == 0) { itemTime = format; mReminderTimeText.setText(itemTime); } else { memorialTime = format; mReminderTimeText.setText(memorialTime); } } @Override public void onDateChange(DatePicker view, int year, int monthOfYear, int dayOfMonth) { ; } }); } else { if (mTimePickerDialog.isShowing()) { mTimePickerDialog.dismiss(); return; } } Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(itemFullTime)); timePicker.setHourOfDay(calendar.get(Calendar.HOUR_OF_DAY)); timePicker.setMinute(calendar.get(Calendar.MINUTE)); mTimePickerDialog.showAtLocation(timePicker, Gravity.BOTTOM, 0, 0); } /** * 每月提醒只显示的每月有多少天的dialog */ private void showDatePickerDialogWithMonthFixed() { final DatePicker datePicker = new DatePicker(CxCalendarEditActivity.this); if (mDatePickerDialogWithMonthFixed == null) { datePicker.setVisibleFields(DatePicker.VISIBLE_DAY); datePicker.setOnDateChangeListener(new OnDateChangeListener() { @Override public void onDateChange(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(itemFullTime)); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); itemFullTime = calendar.getTimeInMillis(); setReminderDateType(); } @Override public void onTimeChange(TimePicker view, int hourOfDay, int minute) { ; } }); mDatePickerDialogWithMonthFixed = new PopupWindow(datePicker, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mDatePickerDialogWithMonthFixed.setWidth(LayoutParams.MATCH_PARENT); mDatePickerDialogWithMonthFixed.setHeight(LayoutParams.WRAP_CONTENT); mDatePickerDialogWithMonthFixed.setBackgroundDrawable(getResources().getDrawable( R.color.cx_fa_co_datepicker_dialog_background)); mDatePickerDialogWithMonthFixed.setTouchable(true); mDatePickerDialogWithMonthFixed.setOutsideTouchable(true); } else { if (mDatePickerDialogWithMonthFixed.isShowing()) { mDatePickerDialogWithMonthFixed.dismiss(); return; } } Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(itemFullTime)); datePicker.setDate(calendar.get(Calendar.YEAR), 1, calendar.get(Calendar.DAY_OF_MONTH));// use // the // 1st// // month mDatePickerDialogWithMonthFixed.showAtLocation(datePicker, Gravity.BOTTOM, 0, 0); } /** * 每年提醒只显示的月和天的dialog */ private void showDatePickerDialogWithAnnuallyFixed() { final DatePicker datePicker = new DatePicker(CxCalendarEditActivity.this); if (mDatePickerDialogWithAnnuallyFixed == null) { datePicker.setVisibleFields(DatePicker.VISIBLE_DAY | DatePicker.VISIBLE_MONTH); datePicker.setOnDateChangeListener(new OnDateChangeListener() { @Override public void onDateChange(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(itemFullTime)); calendar.set(Calendar.MONTH, monthOfYear - 1); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); // mController.setTime(calendar.getTime().getTime()); // updateDateFields(); itemFullTime = calendar.getTimeInMillis(); setReminderDateType(); } @Override public void onTimeChange(TimePicker view, int hourOfDay, int minute) { ; } }); mDatePickerDialogWithAnnuallyFixed = new PopupWindow(datePicker, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mDatePickerDialogWithAnnuallyFixed.setWidth(LayoutParams.MATCH_PARENT); mDatePickerDialogWithAnnuallyFixed.setHeight(LayoutParams.WRAP_CONTENT); mDatePickerDialogWithAnnuallyFixed.setBackgroundDrawable(getResources().getDrawable( R.color.cx_fa_co_datepicker_dialog_background)); mDatePickerDialogWithAnnuallyFixed.setTouchable(true); mDatePickerDialogWithAnnuallyFixed.setOutsideTouchable(true); } else { if (mDatePickerDialogWithAnnuallyFixed.isShowing()) { mDatePickerDialogWithAnnuallyFixed.dismiss(); return; } } Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(itemFullTime)); datePicker.setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)); mDatePickerDialogWithAnnuallyFixed.showAtLocation(datePicker, Gravity.BOTTOM, 0, 0); } /** * 显示每周提醒列表 */ private void showReminderEditDateForWeeklyList() { showTargetOrCycleOrAdvanceDialog(5); } private void showDateLunarPickerDialog(boolean isShowSetLunar) { final DatePicker datePicker = new DatePicker(CxCalendarEditActivity.this); if (isShowSetLunar) { datePicker.setChangeToLunar(); } else { datePicker.hideLunarLayout(); } if (mLunarDatePickerDialog == null) { mLunarDatePickerDialog = new PopupWindow(datePicker, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mLunarDatePickerDialog.setWidth(LayoutParams.MATCH_PARENT); mLunarDatePickerDialog.setHeight(LayoutParams.WRAP_CONTENT); mLunarDatePickerDialog.setBackgroundDrawable(getResources().getDrawable( R.color.cx_fa_co_datepicker_dialog_background)); mLunarDatePickerDialog.setTouchable(true); mLunarDatePickerDialog.setOutsideTouchable(true); datePicker.setOnDateChangeListener(new OnDateChangeListener() { @Override public void onDateChange(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // long time = mController.getTime(); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(memorialFullTime)); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONDAY, monthOfYear - 1); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); memorialFullTime = calendar.getTimeInMillis(); datePicker.setLunar(calendar); datePicker.setLunar(calendar); SimpleDateFormat nowFormat = new SimpleDateFormat("yyyy-MM-dd"); memorialDate = nowFormat.format(memorialFullTime); mReminderDateText.setText(memorialDate); } @Override public void onTimeChange(TimePicker view, int hourOfDay, int minute) { } }); datePicker.setOnLunarImgClickListener(new OnLunarImgClickListener() { @Override public void onOnLunarImgClick(boolean isSelected) { if (isSelected) { memorialLunar = 1; } else { memorialLunar = 0; } } }); } else { if (null != mDatePickerDialog && mDatePickerDialog.isShowing()) { mDatePickerDialog.dismiss(); return; } } Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(memorialFullTime)); if(memorialLunar==0){ datePicker.hideLunar(); }else{ datePicker.showLunar(calendar); } datePicker.setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1,calendar.get(Calendar.DAY_OF_MONTH)); mLunarDatePickerDialog.showAtLocation(datePicker, Gravity.BOTTOM, 0, 0); } /** * show date dialog at the bottom */ private void showDatePickerDialog() { DatePicker datePicker = new DatePicker(CxCalendarEditActivity.this); if (mDatePickerDialog == null) { mDatePickerDialog = new PopupWindow(datePicker, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mDatePickerDialog.setWidth(LayoutParams.MATCH_PARENT); mDatePickerDialog.setHeight(LayoutParams.WRAP_CONTENT); mDatePickerDialog.setBackgroundDrawable(getResources().getDrawable(R.color.cx_fa_co_datepicker_dialog_background)); mDatePickerDialog.setTouchable(true); mDatePickerDialog.setOutsideTouchable(true); datePicker.setOnDateChangeListener(new OnDateChangeListener() { @Override public void onDateChange(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // long time = mController.getTime(); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(itemFullTime)); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONDAY, monthOfYear - 1); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); itemFullTime = calendar.getTimeInMillis(); setReminderDateType(); } @Override public void onTimeChange(TimePicker view, int hourOfDay, int minute) { } }); } else { if (mDatePickerDialog.isShowing()) { mDatePickerDialog.dismiss(); return; } } Calendar c = Calendar.getInstance(); c.setTimeInMillis(itemFullTime); datePicker.setDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH)); mDatePickerDialog.showAtLocation(datePicker, Gravity.BOTTOM, 0, 0); } private void showDatePickerDialog2() { DatePicker datePicker = new DatePicker(CxCalendarEditActivity.this); if (mDatePickerMemorialDialog == null) { mDatePickerMemorialDialog = new PopupWindow(datePicker, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mDatePickerMemorialDialog.setWidth(LayoutParams.MATCH_PARENT); mDatePickerMemorialDialog.setHeight(LayoutParams.WRAP_CONTENT); mDatePickerMemorialDialog.setBackgroundDrawable(getResources().getDrawable(R.color.cx_fa_co_datepicker_dialog_background)); mDatePickerMemorialDialog.setTouchable(true); mDatePickerMemorialDialog.setOutsideTouchable(true); datePicker.setOnDateChangeListener(new OnDateChangeListener() { @Override public void onDateChange(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // long time = mController.getTime(); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(memorialFullTime)); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONDAY, monthOfYear - 1); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); memorialFullTime = calendar.getTimeInMillis(); SimpleDateFormat nowFormat = new SimpleDateFormat("yyyy-MM-dd"); memorialDate = nowFormat.format(memorialFullTime); mReminderDateText.setText(memorialDate); } @Override public void onTimeChange(TimePicker view, int hourOfDay, int minute) { } }); } else { if (mDatePickerMemorialDialog.isShowing()) { mDatePickerMemorialDialog.dismiss(); return; } } Calendar c = Calendar.getInstance(); c.setTimeInMillis(memorialFullTime); datePicker.setDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH)); mDatePickerMemorialDialog.showAtLocation(datePicker, Gravity.BOTTOM, 0, 0); } /** * 保存日历或者纪念日 */ private void saveCalendar() { if (type == 0) { // 事项 CxLog.i("RkCalendarEditActivity_men", "mCalendarId:"+mCalendarId+",type:"+type+",itemTarget:"+itemTarget+ ",memorialType:"+memorialType+",memorialLunar:"+memorialLunar+",itemReminderFlag:"+itemReminderFlag +",itemCycle:"+itemCycle+",itemAdvance:"+itemAdvance); mController.setData(mCalendarId, type, itemTarget, mContentEdit.getText().toString(), memorialType, memorialLunar, itemReminderFlag, itemFullTime, itemCycle, itemAdvance); } else { // 纪念日 CxLog.i("RkCalendarEditActivity_men", "mCalendarId:"+mCalendarId+",type:"+type+",memorialTarget:"+memorialTarget+ ",memorialType:"+memorialType+",memorialLunar:"+memorialLunar+",memorialReminderFlag:"+memorialReminderFlag +",memorialCycle:"+memorialCycle+",memorialAdvance:"+memorialAdvance); mController.setData(mCalendarId, type, memorialTarget, mContentEdit.getText() .toString(), memorialType, memorialLunar, memorialReminderFlag, memorialFullTime, memorialCycle, memorialAdvance); } if(TextUtils.isEmpty(mContentEdit.getText())){ //QuickMessage.info(this, R.string.cx_fa_calendar_content_can_not_empty); ToastUtil.getSimpleToast(CxCalendarEditActivity.this, -3, getString(R.string.cx_fa_calendar_content_can_not_empty), 1).show(); mSaveButton.setClickable(true); return; } // RkLoadingUtil.getInstance().showLoading(RkCalendarEditActivity.this, true); // check if the user-set time valid; try { if (mController.getPeriod() == CalendarController.sReminderPeriodOnce && (mController.getIsRemind()==1)) { Calendar now = Calendar.getInstance(); Calendar remindTime = Calendar.getInstance(); remindTime.setTimeInMillis(mController.getRealTime()); if (remindTime.before(now)) { mSaveButton.setClickable(true); QuickMessage.error(this, R.string.cx_fa_nls_reminder_invalid_date_for_creation); // RkLoadingUtil.getInstance().dismissLoading(); return; } } if (mController.getId().length() > 0) { mController.cancelAlarmReminder(CxCalendarEditActivity.this, mController.getFlag()); } CxLog.d(TAG,"save privious time="+ CalendarDisplayUtility.getDateStr(mController.getRealTime())); DialogUtil.getInstance().getLoadingDialogShow(CxCalendarEditActivity.this, -1); mController.submitCalendarChanges(this, new JSONCaller() { @Override public int call(Object result) { DialogUtil.getInstance().setLoadingDialogDismiss(null, -1, 1000); new Handler(getMainLooper()){ public void handleMessage(Message msg) { mSaveButton.setClickable(true); }; }.sendEmptyMessage(0); if(result==null){ showResponseToast(getString(R.string.cx_fa_net_response_code_null), 0); return -1; } CxLog.i("RkCalendarEditActivity_men", result.toString()); try { JSONObject reminderObj = (JSONObject)result; if(!reminderObj.isNull("rc")){ int rc = reminderObj.getInt("rc"); if(rc==408){ showResponseToast(getString(R.string.cx_fa_net_response_code_null), 0); return -2; } if(rc!=0){ showResponseToast(getString(R.string.cx_fa_net_response_code_fail), 0); return -3; } } CalendarDataObj reminder = new CalendarDataObj(reminderObj,CxCalendarEditActivity.this); CxLog.d(TAG, "after request api time=" + CalendarDisplayUtility.getDateStr((long)reminder.getBaseTimestamp() * 1000)); CxLog.v(TAG, "local remindId: " + reminder.mId); CxLog.v(TAG, "local remind get flag: " + reminder.getFlag()); int basetime = reminder.getBaseTimestamp(); CxLog.d(TAG,"after adjust time="+ CalendarDisplayUtility.getDateStr((long)reminder.getBaseTimestamp() * 1000)); Calendar c = Calendar.getInstance(); c.setTimeInMillis((long)basetime * 1000); android.os.Message calendarMessage = CxCalendarFragment.getInstance().calendarHandler.obtainMessage(CxCalendarFragment.getInstance().REFRESH_CALENDAR_DATA,c); calendarMessage.sendToTarget(); back2(); } catch (Exception e) { CxLog.e(TAG, "Error: failed to get object from create reminder result"); e.printStackTrace(); } return 0; } }); } catch (Exception e) { e.printStackTrace(); // RkLoadingUtil.getInstance().dismissLoading(); } } private void dropItem(){ // RkLoadingUtil.getInstance().showLoading(RkCalendarEditActivity.this, true); DialogUtil.getInstance().getLoadingDialogShow(this, -1); CalendarApi.getInstance().doDeleteReminder(mController.getData().getId(), new JSONCaller() { @Override public int call(Object result) { DialogUtil.getInstance().setLoadingDialogDismiss(null, -1, 2000); if(result!=null){ try { JSONObject obj=(JSONObject)result; if(!obj.isNull("rc")){ int rc = obj.getInt("rc"); if(rc==408){ showResponseToast(getString(R.string.cx_fa_net_response_code_null), 0); return -2; } if(rc!=0){ showResponseToast(getString(R.string.cx_fa_net_response_code_fail), 0); return -3; } }else{ showResponseToast(getString(R.string.cx_fa_net_response_code_fail), 0); return -3; } } catch (JSONException e) { e.printStackTrace(); } } if(mController.getData().getIsRemind()){ CalendarController.getInstance().cancelAlarmReminder(CxCalendarEditActivity.this, mController.getData().getFlag()); } Message calendarMessage = CxCalendarFragment.calendarHandler .obtainMessage(CxCalendarFragment.getInstance().REFRESH_CALENDAR_DATA); calendarMessage.sendToTarget(); back2(); // RkLoadingUtil.getInstance().dismissLoading(); return 0; } }); } /** * * @param info * @param number 0 失败;1 成功;2 不要图。 */ private void showResponseToast(String info,int number) { Message msg = new Message(); msg.obj = info; msg.arg1=number; new Handler(CxCalendarEditActivity.this.getMainLooper()) { public void handleMessage(Message msg) { if ((null == msg) || (null == msg.obj)) { return; } int id=-1; if(msg.arg1==0){ id= R.drawable.chatbg_update_error; }else if(msg.arg1==1){ id=R.drawable.chatbg_update_success; } ToastUtil.getSimpleToast(CxCalendarEditActivity.this, id, msg.obj.toString(), 1).show(); }; }.sendMessage(msg); } }
package algo_ad.day2; import java.util.Arrays; public class P143_QuickSort { private static int[] src = {3,2,4,6,9,1,8,7,5}; public static void main(String[] args) { sort(src,0,src.length-1); System.out.println(Arrays.toString(src)); } public static void sort(int[] arr, int begin, int end) { if(begin < end) { // 정렬할 대상이 있다면 대상을 쪼개자! // s는 각 그룹의 경계값, 이미 정렬 완료된 위치 int s = partition(arr, begin, end); sort(arr,begin,s-1); sort(arr,s+1,end); } } private static int partition(int[] arr, int begin, int end) { int left = begin; int right = end; int p =left; while(left<right) { while(arr[left] <=arr[p]) { if(left>=end) { break; // 안전장치 } left++; } while(arr[right]>=arr[p]) { if(right<=begin) { break; // 안전장치 } right--; } if(left<right) { swap(arr,left,right); } } // while{피벗}{작은 녀석들}{큰 녀석들} // 피벗을 작은녀석들과 큰녀석들 사이에 끼워두자 swap(arr,p,right); return right; } private static void swap(int[] arr , int a , int b) { int tmp = arr[a]; arr[a] = arr[b]; arr[b] = tmp; } }
/* * 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 win10 */ public class SmallMargherita extends javax.swing.JFrame implements Pizza, Cheese{ /** * Creates new form SmallMargherita */ public SmallMargherita() { initComponents(); } @Override public float checkCrust() { if (Thin.isSelected()) { return 20; } else { return 25; } } @Override public float hasVegetable() { return -1; } public float hasCheese(Cheese c) { float cheeseValue = 0; if (CheeseSelector.getSelectedIndex() == 0) { cheeseValue = c.Mozzarella(); } else if (CheeseSelector.getSelectedIndex() == 1) { cheeseValue = c.Cheddar(); } else if (CheeseSelector.getSelectedIndex() == 2) { cheeseValue = c.DoubleLayerMozzarella(); } else if (CheeseSelector.getSelectedIndex() == 3) { cheeseValue = c.DoubleLayerCheddar(); } else { cheeseValue = c.Mozzarella(); } return cheeseValue; } @Override public float hasTopping() { if (Jalapino.isSelected()) { return 10; } else { return 12; } } @Override public String cookongTime() { return "20 minutes"; } @Override public float totalCost() { float total; Cheese c = new Cheese() { @Override public float Mozzarella() { return 20; } @Override public float Cheddar() { return 25; } @Override public float DoubleLayerMozzarella() { return 25; } @Override public float DoubleLayerCheddar() { return 30; } }; total = checkCrust() + hasCheese(c) + hasTopping() + 20; return total; } // Cheese Interface methods @Override public float Mozzarella() { return 20; } @Override public float Cheddar() { return 25; } @Override public float DoubleLayerMozzarella() { return 25; } @Override public float DoubleLayerCheddar() { return 30; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel2 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); Amount = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); ToppingsAmt = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); Thin = new javax.swing.JRadioButton(); jLabel3 = new javax.swing.JLabel(); Thick = new javax.swing.JRadioButton(); BlackOlives = new javax.swing.JCheckBox(); Jalapino = new javax.swing.JCheckBox(); jLabel4 = new javax.swing.JLabel(); CheeseSelector = new javax.swing.JComboBox<>(); MargheritaBackground = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel2.setFont(new java.awt.Font("SansSerif", 1, 24)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 176, 87)); jLabel2.setText("Margherita"); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 60, 130, -1)); jLabel5.setFont(new java.awt.Font("SansSerif", 1, 16)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Amount"); getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 320, -1, -1)); Amount.setEditable(false); Amount.setBackground(new java.awt.Color(240, 240, 240)); Amount.setFont(new java.awt.Font("SansSerif", 0, 14)); // NOI18N Amount.setForeground(new java.awt.Color(255, 255, 255)); Amount.setEnabled(false); Amount.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AmountActionPerformed(evt); } }); getContentPane().add(Amount, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 320, 60, 20)); jLabel6.setFont(new java.awt.Font("SansSerif", 1, 16)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Toppings"); getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 290, -1, -1)); ToppingsAmt.setEditable(false); ToppingsAmt.setBackground(new java.awt.Color(240, 240, 240)); ToppingsAmt.setFont(new java.awt.Font("SansSerif", 0, 14)); // NOI18N ToppingsAmt.setForeground(new java.awt.Color(255, 255, 255)); ToppingsAmt.setEnabled(false); ToppingsAmt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ToppingsAmtActionPerformed(evt); } }); getContentPane().add(ToppingsAmt, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 290, 60, 20)); jButton1.setText("Calculate"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 360, -1, -1)); jPanel1.setBackground(new java.awt.Color(0, 0, 0, 150)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("SansSerif", 1, 14)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Cheese"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 130, -1, -1)); buttonGroup1.add(Thin); Thin.setFont(new java.awt.Font("SansSerif", 1, 12)); // NOI18N Thin.setForeground(new java.awt.Color(255, 255, 255)); Thin.setText("Thin"); Thin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ThinActionPerformed(evt); } }); jPanel1.add(Thin, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, -1, -1)); jLabel3.setFont(new java.awt.Font("SansSerif", 1, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("CRUST"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 10, -1, -1)); buttonGroup1.add(Thick); Thick.setFont(new java.awt.Font("SansSerif", 1, 12)); // NOI18N Thick.setForeground(new java.awt.Color(255, 255, 255)); Thick.setText("Thick"); Thick.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ThickActionPerformed(evt); } }); jPanel1.add(Thick, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 40, -1, -1)); BlackOlives.setForeground(new java.awt.Color(255, 255, 255)); BlackOlives.setText("Black Olives"); BlackOlives.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BlackOlivesActionPerformed(evt); } }); jPanel1.add(BlackOlives, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 100, -1, -1)); Jalapino.setForeground(new java.awt.Color(255, 255, 255)); Jalapino.setText("Jalapino"); Jalapino.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JalapinoActionPerformed(evt); } }); jPanel1.add(Jalapino, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 100, -1, -1)); jLabel4.setFont(new java.awt.Font("SansSerif", 1, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("TOPPINGS"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 70, -1, -1)); CheeseSelector.setForeground(new java.awt.Color(255, 255, 255)); CheeseSelector.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Mozzarella", "Cheddar", "DoubleLayeredMozzarella", "DoubleLayeredCheddar" })); CheeseSelector.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CheeseSelectorActionPerformed(evt); } }); jPanel1.add(CheeseSelector, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 160, 150, -1)); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 90, 170, 200)); MargheritaBackground.setIcon(new javax.swing.ImageIcon("C:\\Users\\win10\\Downloads\\depositphotos_292635914-stock-photo-pizza-cutting-board-at-wooden.jpg")); // NOI18N getContentPane().add(MargheritaBackground, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 600, 400)); pack(); }// </editor-fold>//GEN-END:initComponents private void ThinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ThinActionPerformed // TODO add your handling code here: }//GEN-LAST:event_ThinActionPerformed private void ThickActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ThickActionPerformed // TODO add your handling code here: }//GEN-LAST:event_ThickActionPerformed private void BlackOlivesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BlackOlivesActionPerformed // TODO add your handling code here: }//GEN-LAST:event_BlackOlivesActionPerformed private void JalapinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JalapinoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_JalapinoActionPerformed private void CheeseSelectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CheeseSelectorActionPerformed // TODO add your handling code here: }//GEN-LAST:event_CheeseSelectorActionPerformed private void AmountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AmountActionPerformed // TODO add your handling code here: }//GEN-LAST:event_AmountActionPerformed private void ToppingsAmtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ToppingsAmtActionPerformed // TODO add your handling code here: }//GEN-LAST:event_ToppingsAmtActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // Calculate Cost: ToppingsAmt.setText("" + hasTopping()); Amount.setText("" + totalCost()); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(SmallMargherita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SmallMargherita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SmallMargherita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SmallMargherita.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SmallMargherita().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField Amount; private javax.swing.JCheckBox BlackOlives; private javax.swing.JComboBox<String> CheeseSelector; private javax.swing.JCheckBox Jalapino; private javax.swing.JLabel MargheritaBackground; private javax.swing.JRadioButton Thick; private javax.swing.JRadioButton Thin; private javax.swing.JTextField ToppingsAmt; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
package com.bookapp.exception; public class DataAccessException { public DataAccessException(String message) { super(); } }
package cn.zl.sm.upload.dao; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class MusicDaoFactory { private static Properties props; static { InputStream in=MusicDaoFactory.class.getClassLoader().getResourceAsStream("dao.properties"); props=new Properties(); try { props.load(in); } catch (IOException e) { throw new RuntimeException(e); } } public static MusicDao getMusicDao() { try { Class clazz=Class.forName(props.getProperty("cn.zl.sm.upload.dao.MusicDao")); return (MusicDao) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } }
package stringboot.springbootcourse.service; import org.springframework.data.jpa.repository.JpaRepository; import stringboot.springbootcourse.persistence.model.BaseEntity; import java.io.Serializable; import java.util.Collection; public interface BaseService<T extends BaseEntity, K extends Serializable, R extends JpaRepository<T, K>> { R getRepository(); T save(T entity); T delete(K id); Collection<T> getAll(); T getOne(K id); }
package com.ssm.wechatpro.util; import javax.servlet.http.HttpServletRequest; import com.wechat.service.WendaJiqirenService; public class MessageSendUtil { /** * 获取验证码 */ public static String getWord() throws Exception{ String word = (int)((Math.random()*9+1)*100000)+""; return word; } /** * 不是回复关键字的回复----------图灵机器人 * * @param fromUserName * @param toUserName * @return */ public static String Reback(String fromUserName, String toUserName, String content, HttpServletRequest request) throws Exception { // 回复文本消息 String result = null; result = WendaJiqirenService.getRequest1(content); if (result == null) { return MessageUtil.textMessageToXml(WeChatPublicUtil.getTextMessage(fromUserName, toUserName, Constants.RESP_MESSAGE_TYPE_TEXT, "该机器人不支持该文字" + content + "的回复")); } else { return MessageUtil.textMessageToXml(WeChatPublicUtil.getTextMessage(fromUserName, toUserName, Constants.RESP_MESSAGE_TYPE_TEXT,"麦克思机器人小麦:" + result)); } } }
package mobi.wrt.oreader.app.clients.feedly.datasource; import by.istin.android.xcore.source.DataSourceRequest; import by.istin.android.xcore.source.impl.http.HttpAndroidDataSource; public class PostDataSourceRequest extends DataSourceRequest { private static final String BODY = "body"; public PostDataSourceRequest(String requestDataUri, String data) { super(HttpAndroidDataSource.DefaultHttpRequestBuilder.getUrl(requestDataUri, HttpAndroidDataSource.DefaultHttpRequestBuilder.Type.POST)); putParam(BODY, data); } public static String getBody(DataSourceRequest dataSourceRequest) { return dataSourceRequest.getParam(BODY); } }
package com.mysql.cj.jdbc; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; public class Driver extends NonRegisteringDriver implements Driver { static { try { DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Can't register driver!"); } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\jdbc\Driver.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package 集合; /** * @Author: Mr.M * @Date: 2019-04-10 10:35 * @Description: **/ import java.util.*; public class ArrayToCollection { public static void main(String args[]) { int n = 5; // 5 个元素 // String[] name = new String[n]; // int[] name = new int[n]; Integer[] name = new Integer[n]; for (int i = 0; i < n; i++) { name[i] = i; } // List<String> list = Arrays.asList(name); List<Integer> list = Arrays.asList(name); System.out.println(); // for (String li : list) { for (Integer li : list) { // String str = li; Integer str = li; System.out.print(str + " "); } } void s(){ int[] a ={1,2,3}; // new ArrayList<Integer>(a); } }
package pwr.chrzescijanek.filip.gifa.core.function.hsv.variance; import org.opencv.core.Mat; import pwr.chrzescijanek.filip.gifa.core.function.EvaluationFunction; import static org.opencv.imgproc.Imgproc.COLOR_BGR2HSV_FULL; import static pwr.chrzescijanek.filip.gifa.core.util.FunctionUtils.calculateVariances; import static pwr.chrzescijanek.filip.gifa.core.util.ImageUtils.convertType; /** * Provides method to calculate value variance. */ public final class VarianceValue implements EvaluationFunction { /** * Default constructor. */ public VarianceValue() {} @Override public double[] evaluate(final Mat[] images) { convertType(images, COLOR_BGR2HSV_FULL); return calculateVariances(images, 2); } }
package com.java.smart_garage.controllers.rest; import com.java.smart_garage.ModelMaper.ModelConversionHelper; import com.java.smart_garage.configuration.AuthenticationHelper; import com.java.smart_garage.contracts.serviceContracts.ModelService; import com.java.smart_garage.exceptions.DuplicateEntityException; import com.java.smart_garage.exceptions.EntityNotFoundException; import com.java.smart_garage.models.ModelCar; import com.java.smart_garage.models.User; import com.java.smart_garage.models.dto.ModelCarDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping("smartgarage/model") public class ModelController { private final ModelService service; private final ModelConversionHelper modelConversionHelper; private final AuthenticationHelper authenticationHelper; @Autowired public ModelController(ModelService service, ModelConversionHelper modelConversionHelper, AuthenticationHelper authenticationHelper) { this.service = service; this.modelConversionHelper = modelConversionHelper; this.authenticationHelper = authenticationHelper; } @GetMapping public List<ModelCar> getAllModels(){ return service.getAllModels(); } @GetMapping("/{id}") public ModelCar getModelById(@PathVariable int id) { try { return service.getModelById(id); } catch (EntityNotFoundException e) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage()); } } @PostMapping public ModelCar create(@RequestHeader HttpHeaders headers, @Valid @RequestBody ModelCarDto modelCarDto) { try { User user = authenticationHelper.tryGetUser(headers); ModelCar modelCar = modelConversionHelper.modelFromDto(modelCarDto); service.create(modelCar, user); return modelCar; } catch (DuplicateEntityException e) { throw new ResponseStatusException(HttpStatus.CONFLICT, e.getMessage()); } } @DeleteMapping("/{id}") public void delete(@RequestHeader HttpHeaders headers, @PathVariable int id) { try { User user = authenticationHelper.tryGetUser(headers); service.delete(id, user); } catch (EntityNotFoundException e) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage()); } } }
package baadraan.u.batman.ui; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.RelativeLayout; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import java.util.ArrayList; import baadraan.u.batman.R; import baadraan.u.batman.SnackMessage; import baadraan.u.batman.adapter.RecyclerMovieAdapter; import baadraan.u.batman.db.DatabaseHelper; import baadraan.u.batman.service.ListMovie; import baadraan.u.batman.service.MoviePresenter; import baadraan.u.batman.service.MovieView; import io.github.inflationx.viewpump.ViewPumpContextWrapper; public class MainActivity extends AppCompatActivity implements MovieView.movieList { RecyclerView recycler; MoviePresenter presenter; RecyclerMovieAdapter adapter; Boolean internet; RelativeLayout rlNointernet; SwipeRefreshLayout swipe; @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init(){ recycler = (RecyclerView)findViewById(R.id.recycler_main); rlNointernet = (RelativeLayout) findViewById(R.id.rl_nointernet); swipe = (SwipeRefreshLayout)findViewById(R.id.swipe); swipe.setRefreshing(true); recycler.setLayoutManager(new GridLayoutManager(getApplicationContext() , 3 , RecyclerView.VERTICAL , false)); recycler.setHasFixedSize(true); adapter = new RecyclerMovieAdapter(new ArrayList<ListMovie>(0)); recycler.setAdapter(adapter); load(); swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { load(); } }); adapter.setOnClick(new RecyclerMovieAdapter.OnClick() { @Override public void onClick(String imdbId) { Intent intent = new Intent(MainActivity.this , DetailActivity.class); intent.putExtra("imdbId" , imdbId); startActivity(intent); } }); } @Override public void success(ArrayList<ListMovie> movies) { swipe.setRefreshing(false); adapter.update(movies); DatabaseHelper dbh = new DatabaseHelper(getApplicationContext()); dbh.insertToTable(movies); } @Override public void error(String error) { new SnackMessage(this , error , rlNointernet).showMessage(); } private void load(){ internet = isInternetConnection(); if (internet){ hideView(rlNointernet); presenter = new MoviePresenter(this); presenter.getMovies(); }else{ swipe.setRefreshing(false); showView(rlNointernet); DatabaseHelper dbh = new DatabaseHelper(getApplicationContext()); ArrayList<ListMovie>movies = dbh.getMovieList(); adapter.update(movies); } } public boolean isInternetConnection() { ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); return isConnected; } private void hideView(View view){ Animation animOut = AnimationUtils.loadAnimation(this , R.anim.top_to_bottom); view.setAnimation(animOut); view.setVisibility(View.GONE); } private void showView(View view){ Animation animIn = AnimationUtils.loadAnimation(this , R.anim.bottom_to_top); view.setAnimation(animIn); view.setVisibility(View.VISIBLE); } }
package net.asurovenko.netexam.ui.student_screen; import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TabHost; import android.widget.TextView; import net.asurovenko.netexam.R; import net.asurovenko.netexam.events.OpenLoginFragmentEvent; import net.asurovenko.netexam.events.OpenMainActivityEvent; import net.asurovenko.netexam.events.StartExamEvent; import net.asurovenko.netexam.network.models.AvailableExams; import net.asurovenko.netexam.network.models.CompletedExams; import net.asurovenko.netexam.network.models.User; import net.asurovenko.netexam.ui.MainActivity; import net.asurovenko.netexam.ui.base.BaseFragment; import net.asurovenko.netexam.utils.ServerUtils; import butterknife.Bind; import butterknife.OnClick; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class MainStudentFragment extends BaseFragment { @Bind(R.id.available_exam_recycler_view) RecyclerView availableExamRecyclerView; @Bind(R.id.completed_exam_recycler_view) RecyclerView completedExamRecyclerView; @Bind(R.id.available_exam_text_empty_list) TextView availableExamTextEmptyList; @Bind(R.id.completed_exam_text_empty_list) TextView completedExamTextEmptyList; @Bind(R.id.progress_load_available_exam) ProgressBar progressBarLoadAvailableExam; @Bind(R.id.progress_load_completed_exam) ProgressBar progressBarLoadCompleteExam; @Bind(R.id.student_tab_host) TabHost tabHost; @Bind(R.id.fio) TextView fio; @Bind(R.id.group_and_semester) TextView groupAndSemester; private User student = null; private Snackbar snackBarStartExam; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main_student, container, false); } @Override public void onStart() { super.onStart(); setupStudent(((MainActivity) getActivity()).getUser()); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); tabHostSetup(); } @OnClick(R.id.exit_btn) public void exitBtnClick() { if (snackBarStartExam != null) { snackBarStartExam.dismiss(); } showProgressBar(getString(R.string.wait_with_dots), ProgressDialog.STYLE_SPINNER); getNetExamApi().logout(student.getToken()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(responseBody -> logout(), error -> logout()); } private void logout() { getPreferences().deleteAll(getPreferences().getSharedPreferences()); hideProgressBar(); getBus().post(new OpenLoginFragmentEvent()); } private void loadAvailableExams() { getNetExamApi().getAvailableExams(student.getToken()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::completeLoadAvailableExams, this::errorLoadAvailableExams); } private void completeLoadAvailableExams(AvailableExams exams) { RecyclerView.LayoutManager availableExamLayoutManager = new LinearLayoutManager(getActivity()); availableExamRecyclerView.setLayoutManager(availableExamLayoutManager); availableExamRecyclerView.setHasFixedSize(false); if (exams.getExams().size() > 0) { RecyclerView.Adapter availableExamAdapter = new AvailableExamAdapter(this, exams.getExams()); availableExamRecyclerView.setAdapter(availableExamAdapter); availableExamRecyclerView.setVisibility(View.VISIBLE); } else { availableExamTextEmptyList.setVisibility(View.VISIBLE); } progressBarLoadAvailableExam.setVisibility(View.GONE); } public void showSnackBarStartExam(AvailableExams.Exam exam) { snackBarStartExam = Snackbar .make(getView(), exam.getName() + getString(R.string.start_without_return), Snackbar.LENGTH_INDEFINITE) .setAction(getString(R.string.start), view -> getBus().post(new StartExamEvent(exam))); View view = snackBarStartExam.getView(); view.setPadding(0, 0, 0, 0); Button button = (Button) view.findViewById(android.support.design.R.id.snackbar_action); button.setTextSize(20); button.setPadding(5, 5, 25, 5); snackBarStartExam.show(); } private void errorLoadAvailableExams(Throwable error) { showSnackBar(ServerUtils.getMsgId(error)); availableExamTextEmptyList.setText(getString(R.string.an_error_occurred)); availableExamTextEmptyList.setVisibility(View.VISIBLE); progressBarLoadAvailableExam.setVisibility(View.GONE); } private void tabHostSetup() { tabHost.setup(); TabHost.TabSpec availableTab = tabHost.newTabSpec("available"); availableTab.setContent(R.id.available_tab); availableTab.setIndicator(getString(R.string.available_exams)); tabHost.addTab(availableTab); TabHost.TabSpec completedTab = tabHost.newTabSpec("completed"); completedTab.setContent(R.id.completed_tab); completedTab.setIndicator(getString(R.string.complete_exams)); tabHost.addTab(completedTab); tabHost.setCurrentTab(getActivity().getIntent().getIntExtra(OpenMainActivityEvent.CURRENT_TAB, 0)); tabHost.setOnTabChangedListener(tabId -> { if (snackBarStartExam != null && snackBarStartExam.isShown()) { snackBarStartExam.dismiss(); } }); } private void setInfoStudent() { StringBuilder sb = new StringBuilder(student.getUserInfo().getLastName()) .append(" ") .append(student.getUserInfo().getFirstName()); if (student.getUserInfo().getPatronymic() != null) { sb.append(" ").append(student.getUserInfo().getPatronymic()); } fio.setText(sb.toString()); sb = new StringBuilder(student.getUserInfo().getGroup()) .append(", ") .append(student.getUserInfo().getSemester()) .append(" семестр"); groupAndSemester.setText(sb.toString()); } private void setupStudent(User student) { this.student = student; setInfoStudent(); loadAvailableExams(); loadCompletedExams(); } private void loadCompletedExams() { getNetExamApi().getCompletedExams(student.getToken()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::completeLoadCompletedExams, this::errorLoadCompleteExams); } private void completeLoadCompletedExams(CompletedExams exams) { RecyclerView.LayoutManager completedExamLayoutManager = new LinearLayoutManager(getActivity()); completedExamRecyclerView.setLayoutManager(completedExamLayoutManager); completedExamRecyclerView.setHasFixedSize(false); if (exams.getExams().size() != 0) { RecyclerView.Adapter completedExamAdapter = new CompletedExamAdapter(exams.getExams()); completedExamRecyclerView.setAdapter(completedExamAdapter); completedExamRecyclerView.setVisibility(View.VISIBLE); } else { completedExamTextEmptyList.setVisibility(View.VISIBLE); } progressBarLoadCompleteExam.setVisibility(View.GONE); } private void errorLoadCompleteExams(Throwable error) { showSnackBar(ServerUtils.getMsgId(error)); completedExamTextEmptyList.setText(getString(R.string.an_error_occurred)); completedExamTextEmptyList.setVisibility(View.VISIBLE); progressBarLoadCompleteExam.setVisibility(View.GONE); } }
package com.example.codetribe1.constructionappsuite.util; import android.content.Context; import android.graphics.Typeface; import android.widget.TextView; import com.example.codetribe1.constructionappsuite.R; public class Statics { // REMOTE URL - bohamaker back end - production public static final String WEBSOCKET_URL = "ws://bohamaker.com:51490/mwp/"; public static final String URL = "http://bohamaker.com:51490/mwp/"; public static final String CRASH_REPORTS_URL = URL + "crash?"; public static final String IMAGE_URL = "http://bohamaker.com:51490/"; //google cloud http://mggolf-303.appspot.com/golf?JSON={requestType:38,golfGroupID:21} //public static final String URL = "http://mggolf-303.appspot.com/"; //10.20.36.8 // public static final String WEBSOCKET_URL = "ws://10.20.36.8:8080/mwp/"; // public static final String URL = "http://10.20.36.8:8080/mwp/"; // public static final String IMAGE_URL = "http://10.20.36.8:8080/"; // public static final String WEBSOCKET_URL = "ws://192.168.56.1:8080/mwp/"; // public static final String URL = "http://192.168.56.1:8080/mwp/"; // public static final String IMAGE_URL = "http://192.168.56.1:8080/"; // public static final String PDF_URL = "http://192.168.56.1:8080/monitor_documents/"; public static final String PDF_URL = "http://bohamaker.com:51490/monitor_documents/"; public static final String INVITE_DESTINATION = "https://play.google.com/store/apps/details?id="; public static final String INVITE_EXEC = INVITE_DESTINATION + "com.boha.monitor.exec"; public static final String INVITE_OPERATIONS_MGR = INVITE_DESTINATION + "com.boha.monitor.operations"; public static final String INVITE_PROJECT_MGR = INVITE_DESTINATION + "com.boha.monitor.pmanager"; public static final String INVITE_SITE_MGR = INVITE_DESTINATION + "com.boha.monitor.site"; public static final String UPLOAD_URL_REQUEST = "uploadUrl?"; public static final String UPLOAD_BLOB = "uploadBlob?"; public static final String PROJECT_ENDPOINT = "wsproject", COMPANY_ENDPOINT = "wscompany"; public static final String SESSION_ID = "sessionID"; public static final int CRASH_STRING = R.string.crash_toast; public static void setDroidFontBold(Context ctx, TextView txt) { Typeface font = Typeface.createFromAsset(ctx.getAssets(), "DroidSerif-Bold"); txt.setTypeface(font); } public static void setRobotoFontBoldCondensed(Context ctx, TextView txt) { Typeface font = Typeface.createFromAsset(ctx.getAssets(), "fonts/Roboto-BoldCondensed.ttf"); txt.setTypeface(font); } public static void setRobotoFontRegular(Context ctx, TextView txt) { Typeface font = Typeface.createFromAsset(ctx.getAssets(), "fonts/Roboto-Regular.ttf"); txt.setTypeface(font); } public static void setRobotoFontLight(Context ctx, TextView txt) { Typeface font = Typeface.createFromAsset(ctx.getAssets(), "fonts/Roboto-Light.ttf"); txt.setTypeface(font); } public static void setRobotoFontBold(Context ctx, TextView txt) { Typeface font = Typeface.createFromAsset(ctx.getAssets(), "fonts/Roboto-Bold.ttf"); txt.setTypeface(font); } public static void setRobotoItalic(Context ctx, TextView txt) { Typeface font = Typeface.createFromAsset(ctx.getAssets(), "fonts/Roboto-Italic.ttf"); txt.setTypeface(font); } public static void setRobotoRegular(Context ctx, TextView txt) { Typeface font = Typeface.createFromAsset(ctx.getAssets(), "fonts/Roboto-Regular.ttf"); txt.setTypeface(font); } }
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int sp = n - 1; int ha = 1; for(int i = 0; i < n; i++) { for(int j = 0; j < sp; j++) { System.out.print(" "); // print spaces } for(int k = 0; k < ha; k++) { System.out.print("#"); // print #s } System.out.println(); // print new line sp--; ha++; } } }
package com.heartmarket.model.service; import java.util.HashMap; import java.util.Map; import java.util.Objects; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.heartmarket.model.dao.MannerRepository; import com.heartmarket.model.dao.ReviewRepository; import com.heartmarket.model.dao.TradeRepository; import com.heartmarket.model.dao.UserRepository; import com.heartmarket.model.dto.Manner; import com.heartmarket.model.dto.Review; import com.heartmarket.model.dto.response.ReviewResponse; import com.heartmarket.util.ResultMap; @Service public class MannerServiceImpl implements MannerService{ @Autowired MannerRepository mr; @Autowired ReviewRepository rr; @Autowired TradeRepository tr; @Autowired UserRepository ur; // 매너에서 필요한 기능 // 매너 평가 // 공식 대입으로 평가 점수 저장 // 평가는 3 택 1 // user 를 기반으로 저장 public Manner evalueManner(int value, int userNo){ Manner tMnr = mr.findBymUserUserNo(userNo); double pGauge = tMnr.getPlusGauge(); double nGauge = tMnr.getNormalGauge(); double mGauge = tMnr.getMinusGauge(); double hg = tMnr.getHeartGauge(); // 긍정 if(value == 3) { pGauge = pGauge >= 0 ? pGauge + 1 : 0; // if( pGauge >= 0 )tMnr.setPlusGauge(pGauge+1); // else tMnr.setPlusGauge(0); } // 보통 else if(value == 0) { // tMnr.setNormalGauge(nGauge+1); nGauge+=1; } // 부정 else { mGauge = mGauge >= 0 ? mGauge+1 : 0; // if(mGauge >= 0) tMnr.setMinusGauge(mGauge+1); // else tMnr.setMinusGauge(0); } double calc = hg + (pGauge + nGauge + mGauge); tMnr.setPlusGauge(pGauge); tMnr.setNormalGauge(nGauge); tMnr.setMinusGauge(mGauge); tMnr.setHeartGauge(calc); // mr.save(tMnr); // return new ResultMap<Manner>("SUCCESS", "평가완료", tMnr); return tMnr; } // 매너 평가를 위해서는 거래 완료가 필요하다. // 거래 완료 여부를 확인하고 @Override public ResultMap<ReviewResponse> evalueUser(int tradeNo, int userNo, int val){ try { // 매너 평가 완료 // if(Objects.isNull(tr.findByTradeNo(tradeNo))) { // // } // 리뷰 등록 완료 Review rev = rr.findByrTradeTradeNo(tradeNo); if(rev == null){ Review rvw = new Review(tr.findByTradeNo(tradeNo)); Manner rMnr = evalueManner(val, userNo); mr.save(rMnr); rr.save(rvw); return new ResultMap<ReviewResponse>("SUCCESS", "평가 완료", new ReviewResponse( rvw,rMnr)); }else { return new ResultMap<ReviewResponse>("FAIL", "이미 평가가 완료된 게시글입니다.", null); } }catch(Exception e) { e.printStackTrace(); throw e; } } @Override public ResultMap<Map<String, Integer>> findManner(String email){ try { Manner manner = mr.findBymUserUserNo(ur.findByEmail(email).getUserNo()); if(manner != null) { Map<String, Integer> rm = new HashMap<String, Integer>(); rm.put("heartgauge",(int) manner.getHeartGauge()); return new ResultMap<Map<String, Integer>>("SUCCESS", "매너 불러오기", rm); }else { return new ResultMap<Map<String, Integer>>("FAIL", "찾을 수 없는 유저입니다.", null); } }catch(Exception e) { e.printStackTrace(); throw e; } } }
package abstractfactory.design.pattern.example; public class HighSeverityError extends Error { @Override void setErrorType(String errType) { errorType = errType; } }
package gxc.dao.impl; import java.util.List; import org.hibernate.SQLQuery; import org.hibernate.Session; import gxc.dao.ReplyDao; import gxc.dao.TopicDao; import gxc.dao.UserDao; import gxc.domain.Reply; import gxc.domain.Topic; import gxc.domain.User; import gxc.utils.HibernateUtil; public class ReplyDaoImpl implements ReplyDao { /** * UserDao、TopicDao */ UserDao userDao = new UserDaoImpl(); TopicDao topicDao = new TopicDaoImpl(); /** * 添加回复 */ @Override public void addReply(Integer uid, Integer tid, Reply reply) { Session session = HibernateUtil.getCurrentSession(); User user = userDao.findUserById(uid); Topic topic = topicDao.findTopicById(tid); reply.setUser(user); reply.setTopic(topic); session.save(reply); } /** * 根据帖子的ID,查询所有的回复(顺序) * 暂时不可用 */ @SuppressWarnings("unchecked") @Override public List<Reply> findReplyByTid(Integer tid, String order) { /*Session session = HibernateUtil.getCurrentSession(); Query query = session.createQuery("from Reply r where r.topic.tid = :tid"); query.setInteger("tid", tid); List<Reply> list = (List<Reply>)query.list(); return list;*/ Session session = HibernateUtil.getCurrentSession(); SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM reply WHERE tid = :tid ORDER BY replyDate desc"); sqlQuery.setInteger("tid", tid); List<Reply> list = sqlQuery.list(); return list; } }
package com.example; import java.io.Serializable; import java.util.Date; public class Function implements Serializable { private static final long serialVersionUID = 1L; private int id; private String name; private String descr; private Date ctime; private String active; public Function(int id, String name, String descr, Date ctime, String active) { this.id = id; this.name = name; this.descr = descr; this.ctime = ctime; this.active = active; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescr() { return descr; } public void setDescr(String descr) { this.descr = descr; } public Date getCtime() { return ctime; } public void setCtime(Date ctime) { this.ctime = ctime; } public String getActive() { return active; } public void setActive(String active) { this.active = active; } public String getActiveMsg() { if ("N".equals(this.active)) return "OFF"; return "ON"; } }
package jp.co.tau.web7.admin.supplier.dto; import java.time.LocalDateTime; import lombok.Getter; import lombok.Setter; /** * <p>ファイル名 : UserInfoDTO.java</p> * <p>説明 : UserInfoDTO</p> * @author * @since : */ @Getter @Setter public class UserInfoDTO extends MasterBaseDTO { private String userId; private String userPwd; private String pwdInputCnt; private LocalDateTime pwdInputCntUpdTime; private String pwdIssueFlag; private LocalDateTime pwdUpdDate; private String userEmlAddr; private String aucTypeCd; private String updateUser; private String updateClass; private String createUser; private String createClass; private String deleteFlg; private LocalDateTime lastLoginTime; private LocalDateTime deleteTime; private LocalDateTime logInNgSetDate; private LocalDateTime createTime; private LocalDateTime updateTime; private Integer orgCd; private Integer roleCd; private String userNm; private String roleNm; /** 未ログイン時 */ private boolean notLoginFlg = false; }
package com.tencent.mm.plugin.shake.ui; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import com.tencent.mm.ui.tools.k; class ShakeTvHistoryListUI$4 implements OnItemLongClickListener { final /* synthetic */ k hle; final /* synthetic */ ShakeTvHistoryListUI nbu; ShakeTvHistoryListUI$4(ShakeTvHistoryListUI shakeTvHistoryListUI, k kVar) { this.nbu = shakeTvHistoryListUI; this.hle = kVar; } public final boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long j) { if (i >= ShakeTvHistoryListUI.b(this.nbu).getHeaderViewsCount()) { this.hle.a(view, i, j, this.nbu.mController.tml, ShakeTvHistoryListUI.c(this.nbu)); } return true; } }
package com.github.mikewtao.webf.test.util; import com.github.mikewtao.webf.annotation.Controller; import com.github.mikewtao.webf.annotation.Handler; import com.github.mikewtao.webf.annotation.RequestMethod; @Controller public class ControllerTest { @Handler(value="/test",method=RequestMethod.GET) public void Test(){ } }
package game;// //Created by DaMasterHam on 30-03-2017. // public class Game { private Player p1; private Player p2; private Board board; private IGameEvents gameEvents; private boolean won; private int playerTurn; public Game(Player p1, Player p2, IGameEvents gameEvents) { this.p1 = p1; this.p2 = p2; board = new Board(); this.gameEvents = gameEvents; won = false; playerTurn = p1.getId(); } private int otherPlayer() { if (p1.getId() == playerTurn) return p2.getId(); else if (p2.getId() == playerTurn) return p1.getId(); return -1; } public void placePiece(Player player, int col) { if (won) return; if (player.getId() != playerTurn) { gameEvents.wrongPlayer(player); return; } //gameEvents.placePieceInColumn(); if (board.placePiece(player.generatePiece(), col)) { gameEvents.placementSuccess(player, board.getLastAddedCol(), board.getLastAddedRow()); playerTurn = otherPlayer(); } else gameEvents.placementFailure(player); if (board.checkWin()) gameEvents.winner(player); } public int getColSize() { return board.getColSize(); } public int getRowSize() { return board.getRowSize(); } // public void startGame() // { // gameEvents.gameStart(); // while (!won) // { // round(p1); // round(p2); // } // gameEvents.gameOver(); // } /*public static void main(String[] args) { Board board = new Board(); Player p1 = new Player("Player1", Color.cyan); Player p2 = new Player("Player2", Color.ORANGE); pseudoRound(board, p1, 1); pseudoRound(board, p1, 1); pseudoRound(board, p1, 1); pseudoRound(board, p1, 1); } private static void pseudoRound(Board board, Player player, int col) { board.placePiece(player.generatePiece(), col); board.print(); System.out.println(board.checkWin()); }*/ }
package interviewbit.stackandqueue; import java.util.LinkedList; public class ReverseString { public String reverseString(String a) { LinkedList<Character> l = new LinkedList<Character>(); int i=0; StringBuffer s = new StringBuffer(); while(i<a.length()){ l.add(a.charAt(i)); i++; } while(l.size()!=0){ s.append(l.pollLast()); } return s.toString(); } }
package com.e6soft.bpm.dao; import com.e6soft.bpm.model.NodeTemplate; import com.e6soft.core.mybatis.EntityDao; public interface NodeTemplateDao extends EntityDao<NodeTemplate,String> { public String getTemplateIdByFormIdAndNodeId(String businessFormId,String nodeId); public String getFormIdByTemplateIdAndNodeId(String templateId,String nodeId); public void deleteByBusinessFormId(String businessFormId); }
package com.conorh.codetest.api.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Data @Builder @AllArgsConstructor @NoArgsConstructor @Entity public class Address { @Id private Long id; @Column(nullable = false) private String street; @Column(nullable = false) private String city; @Column(nullable = false) private String state; @Column(nullable = false) private String postalCode; @ManyToOne @JoinColumn(name = "person_id", nullable = false) private Person person; }
/** * */ package site.com.google.anywaywrite.component.menu; import site.com.google.anywaywrite.component.gui.BgAreaLabel; /** * @author kitajima * */ public interface BgCreateActionMenu { public BgMenuItem createActionMenu(BgAreaLabel area); }
package controllers; import entities.Medicine; import repositories.interfaces.IMedicineRepository; import javax.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; @Path("medicines") public class MedicineController { @Inject private IMedicineRepository repo; @GET @Produces(MediaType.APPLICATION_JSON) public Response getAllMedicine() { List<Medicine> medicines; try { medicines = repo.getAllMedicine(); } catch (ServerErrorException ex) { return Response .status(500).entity(ex.getMessage()).build(); } return Response .status(Response.Status.OK) .entity(medicines) .build(); } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createMedicine(Medicine medicine) { boolean created; try { created = repo.createMedicine(medicine); } catch (ServerErrorException ex) { return Response.serverError().entity(ex.getMessage()).build(); } if (!created) { return Response .status(Response.Status.BAD_REQUEST) .entity("Medicine cannot be created!") .build(); } return Response .status(Response.Status.CREATED) .entity("Medicine created successfully!") .build(); } @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public Response getByID(@PathParam("id") int id) { Medicine medicine; try { medicine = repo.getByID(id); } catch (ServerErrorException ex) { return Response .status(500).entity(ex.getMessage()).build(); } if (medicine == null) { return Response .status(Response.Status.NOT_FOUND) .entity("Medicine does not exist!") .build(); } return Response .status(Response.Status.OK) .entity(medicine) .build(); } @GET @Path("/get/{name}") @Produces(MediaType.APPLICATION_JSON) public Response getByName(@PathParam("name") String name) { Medicine medicine; try { medicine = repo.getByName(name); } catch (ServerErrorException ex) { return Response .status(500).entity(ex.getMessage()).build(); } if (medicine == null) { return Response .status(Response.Status.NOT_FOUND) .entity("Medicine does not exist!") .build(); } return Response .status(Response.Status.OK) .entity(medicine) .build(); } @GET @Path("/get/company/{manufacturer}") @Produces(MediaType.APPLICATION_JSON) public Response getByManufacturer(@PathParam("manufacturer") String manufacturer) { List<Medicine> medicine; try { medicine = repo.getByManufacturer(manufacturer); } catch (ServerErrorException ex) { return Response .status(500).entity(ex.getMessage()).build(); } if (medicine == null) { return Response .status(Response.Status.NOT_FOUND) .entity("Medicine does not exist!") .build(); } return Response .status(Response.Status.OK) .entity(medicine) .build(); } @GET @Path("/expired") @Produces(MediaType.APPLICATION_JSON) public Response getExpired() { List<Medicine> medicines; try { medicines = repo.getExpired(); } catch (ServerErrorException ex) { return Response .status(500).entity(ex.getMessage()).build(); } return Response .status(Response.Status.OK) .entity(medicines) .build(); } @GET @Path("/checkorder/{id}") @Produces(MediaType.APPLICATION_JSON) public Response checkOrder(@PathParam("id") int id) { boolean checker; try { checker = repo.checkOrder(id); } catch (ServerErrorException ex) { return Response .status(500).entity(ex.getMessage()).build(); } return Response .status(Response.Status.OK) .entity(checker) .build(); } @GET @Path("/removeByID/{id}") @Produces(MediaType.APPLICATION_JSON) public Response removeByID(@PathParam("id") int id) { boolean deleted; try { deleted = repo.removeByID(id); } catch (ServerErrorException ex) { return Response .status(500).entity(ex.getMessage()).build(); } if (deleted == false) { return Response .status(Response.Status.NOT_FOUND) .entity("Medicine does not exist!") .build(); } return Response .status(Response.Status.OK) .entity(deleted ? "Medicine was removed!" : "Medicine creation was failed! Such Medicine already exists!") .build(); } }
package com.leetcode.oj; // 111 https://leetcode.com/problems/minimum-depth-of-binary-tree/ public class MinimumDepthOfBinaryTree_111 { // Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public int minDepth(TreeNode root) { if(root==null){ return 0; } int leftMin = minDepth(root.left); int rightMin = minDepth(root.right); if(leftMin==0){ return rightMin+1; }else{ if(rightMin==0){ return leftMin+1; } return 1+Math.min(leftMin, rightMin); } } public static void main(String[] args) { // TODO Auto-generated method stub } }
package com.tt.miniapphost; import java.util.HashMap; import java.util.Map; public class ModeManager { Map<String, NativeModule> modules = new HashMap<String, NativeModule>(); private ModeManager() {} public static ModeManager getInst() { return Holder.holder; } public NativeModule get(String paramString) { return this.modules.get(paramString); } public Map<String, NativeModule> getModules() { return this.modules; } public void register(String paramString, NativeModule paramNativeModule) { this.modules.put(paramString, paramNativeModule); } static class Holder { static ModeManager holder = new ModeManager(); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapphost\ModeManager.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.example.tcc.services; import java.util.List; import java.util.Optional; import org.hibernate.ObjectNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.tcc.entities.Project; import com.example.tcc.repositories.ProjectRepository; @Service public class ProjectService { @Autowired private ProjectRepository repository; public List<Project> findAll(){ return repository.findAll(); } public Project insert(Project obj) { return repository.save(obj); } public Project findName(String name) { Optional<Project> obj = repository.findByName(name); return obj.orElseThrow(() -> new ObjectNotFoundException("Objeto não encontrado!", name)); } }
package ws.chess.server; import lombok.AllArgsConstructor; import ws.chess.core.Board; import ws.chess.server.player.Player; import static ws.chess.core.pieces.Piece.Color.BLACK; import static ws.chess.core.pieces.Piece.Color.WHITE; @AllArgsConstructor public class SimpleChessServer { private Board board; private Player white; private Player black; public void run() { while (board.getAvailableMoves().size() != 0) { System.out.println(board.toString()); System.out.println(); board = board.applyMove(board.getNext().equals(WHITE) ? white.getMove(board) : black.getMove(board)); } System.out.println(board.toString()); System.out.println(String.format("%s wins!!!", board.getNext().equals(WHITE) ? BLACK : WHITE)); } }
2017.05.18. 12. Java EA
package com.commercetools.pspadapter.payone.domain.payone.model.wallet; import com.commercetools.pspadapter.payone.config.PayoneConfig; import com.commercetools.pspadapter.payone.domain.payone.model.common.PayoneRequest; import com.commercetools.pspadapter.payone.domain.payone.model.common.ClearingType; import com.commercetools.pspadapter.payone.domain.payone.model.common.RequestType; /** * @author fhaertig * @since 20.01.16 */ public class WalletPreauthorizationRequest extends PayoneRequest { private String wallettype; private int noShipping; public WalletPreauthorizationRequest(final PayoneConfig config, final ClearingType clearingType, final int noShipping) { super(config, RequestType.PREAUTHORIZATION.getType(), clearingType.getPayoneCode()); this.wallettype = clearingType.getSubType(); this.noShipping = noShipping; } //************************************************************** //* GETTER AND SETTER METHODS //************************************************************** public String getWallettype() { return wallettype; } public int getNoShipping() { return noShipping; } }
package hr.spring.urlshortener.utils; import java.security.SecureRandom; public class RandomPasswordGenerator { private static final String ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static final int SIZE = 8; private static SecureRandom random = new SecureRandom(); public static String generate() { StringBuilder sb = new StringBuilder(SIZE); for(int i = 0; i < SIZE; i++ ) sb.append(ALPHANUMERIC.charAt(random.nextInt(ALPHANUMERIC.length()))); return sb.toString(); } }
package tom.graphic.BeanUtils; import java.awt.Button; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.beans.PropertyEditorSupport; import java.util.EventObject; // Referenced classes of package tom.graphic.BeanUtils: // FileDiagButton public class FileNameEditor extends PropertyEditorSupport { String value; public FileNameEditor() { value = "noDef"; } public void actionPerformed(ActionEvent actionevent) { setAsText(((Button)actionevent.getSource()).getLabel()); } public String getAsText() { return value; } public Component getCustomEditor() { return new FileDiagButton(this); } public boolean isPaintable() { return true; } public void paintValue(Graphics g, Rectangle rectangle) { g.setColor(Color.lightGray); g.fill3DRect(rectangle.x + 2, rectangle.y + 2, rectangle.width - 2, rectangle.height - 2, true); g.setColor(Color.black); g.setClip(rectangle.x + 2, rectangle.y + 2, rectangle.width - 6, rectangle.height - 4); g.drawString(value, rectangle.x + 4, (rectangle.y + rectangle.height) - 6); } public void setAsText(String s) throws IllegalArgumentException { value = s; setValue(s); } public void setValue(Object obj) { value = (String)obj; super.setValue(obj); } public boolean supportsCustomEditor() { return true; } }
package vn.com.tma.entities; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import net.bytebuddy.build.ToStringPlugin.Exclude; @Entity @Table(name = "persons") public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // mappedBy trỏ tới tên biến persons ở trong Address. @ManyToMany(mappedBy = "persons") private Collection<Address> addresses; }
package init; import view.ViewPrincipal; /** * * @author Felipe */ public class Main { public static void main(String[] args) { ViewPrincipal vp = new ViewPrincipal(); vp.setVisible(true); } }
package com.mcf.pc.web.controller; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.mcf.base.common.annotation.SameURLData; import com.mcf.base.common.enums.CooperateType; import com.mcf.base.common.page.Pager; import com.mcf.base.model.Msg; import com.mcf.base.model.ResponseData; import com.mcf.base.pojo.Copartner; import com.mcf.service.ICopartnerService; /** * Title. <br> * Description: 合伙人Controller * <p> * Copyright: Copyright (c) 2016年12月17日 下午2:49:09 * <p> * Author: 10003/sunaiqiang saq691@126.com * <p> * Version: 1.0 * <p> */ @Controller public class FellowsController { @Autowired private ICopartnerService copartnerService; /** * 合伙人页面 * * @param model * @return */ @GetMapping("/fellows.html") public ModelAndView list(Pager pager) { ModelAndView mv = new ModelAndView(); mv.setViewName("fellows"); return mv; } /** * 申请合伙人方法 * * @param copartner * @return */ @RequestMapping(value = "/toApply", method = RequestMethod.POST) @ResponseBody @SameURLData public ResponseData toApply(Copartner copartner) { List<Msg> msgs = new ArrayList<Msg>(); if (!StringUtils.isNotBlank(copartner.getScooperateType())) { msgs.add(new Msg("cooperateType", "请选择合作类型")); } if (!StringUtils.isNotBlank(copartner.getCityName())) { msgs.add(new Msg("cityName", "请输入城市名称")); } if (!StringUtils.isNotBlank(copartner.getName())) { msgs.add(new Msg("name", "请输入姓名")); } if (!StringUtils.isNotBlank(copartner.getContactWay())) { msgs.add(new Msg("contactWay", "请输入联系方式")); } if (CooperateType.COMPANY.getValue().equals(copartner.getScooperateType())) { if (!StringUtils.isNotBlank(copartner.getScompanyScale())) { msgs.add(new Msg("companyScale", "请选择公司规模")); } if (!StringUtils.isNotBlank(copartner.getMainBusiness())) { msgs.add(new Msg("mainBusiness", "请输入主营业务")); } } boolean status = false; ResponseData responseData = null; if (msgs.size() == 0) { status = copartnerService.addCopartner(copartner); responseData = new ResponseData(status, "申请成功!", msgs); } else { responseData = new ResponseData(status, "申请失败!", msgs); } return responseData; } }
package com.stark.design23.builder; import java.util.ArrayList; import java.util.List; /** * Created by Stark on 2018/1/26. * 构建者,这里面维护车的创建逻辑 */ public class CarBuilder { private static Car getCar() { Car car = new Car(); List<Tyre> tyres = new ArrayList<>(4); for (int i = 0; i < 4; i++) { car.setTyres(tyres); } car.setBoby(new Boby()); return car; } }
package br.com.smarthouse.modelgenerics; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ModelModuleApplication { public static void main(String[] args) { SpringApplication.run(ModelModuleApplication.class, args); } }
package com.listener; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import org.springframework.web.socket.messaging.SessionDisconnectEvent; /** * @author Feinik * @Discription 监听客户端是否断开连接 * @Data 2018/12/28 * @Version 1.0.0 */ @Component public class WebSocketListener { @EventListener public void onApplicationEvent(SessionDisconnectEvent event) { System.out.println("客户端断开连接了:" + event.getUser().getName()); } }
package com.example.cse.makeupapp; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.Toast; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import com.google.firebase.auth.FirebaseAuth; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private ProgressBar progressBar; ArrayList<CosmeticModel> arrayList; final String str="http://makeup-api.herokuapp.com/api/v1/products.json"; static CosmeticViewModel cosmeticViewModel; //private ScrollView coordinatorLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView=findViewById(R.id.recycler); //coordinatorLayout=findViewById(R.id.scroll); progressBar=findViewById(R.id.progress); arrayList=new ArrayList<>(); cosmeticViewModel= ViewModelProviders.of(this).get(CosmeticViewModel.class); new MakeAsyc().execute(str); recyclerView.setLayoutManager(new GridLayoutManager(this,2)); recyclerView.setAdapter(new CosAdapter(this,arrayList)); } private boolean isOnline() { ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = conMgr.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnected() && netInfo.isAvailable(); } public class MakeAsyc extends AsyncTask<String,Void,String>{ @Override protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); super.onPreExecute(); } @Override protected String doInBackground(String... strings) { try { URL url=new URL(str); HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection(); InputStream inputStream=httpURLConnection.getInputStream(); Scanner scanner=new Scanner(inputStream); scanner.useDelimiter("\\A"); if(scanner.hasNext()){ return scanner.next(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); progressBar.setVisibility(View.GONE); if (isOnline()) { if (s != null) { try { JSONArray jsonArray = new JSONArray(s); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String id=jsonObject.getString(getString(R.string.id)); String name=jsonObject.getString(getString(R.string.name)); String image_link = jsonObject.getString(getString(R.string.image)); String description = jsonObject.getString(getString(R.string.descr)); arrayList.add(new CosmeticModel(id,name,image_link, description)); } } catch (JSONException e) { e.printStackTrace(); } }else { Toast.makeText(MainActivity.this, R.string.nodata, Toast.LENGTH_SHORT).show(); } } else { AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this); builder.setTitle(R.string.cos); builder.setMessage(R.string.check); builder.setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.cosmenu,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuid: arrayList.clear(); cosmeticViewModel.getAllFavData().observe(MainActivity.this, new Observer<List<CosmeticModel>>() { @Override public void onChanged(@Nullable List<CosmeticModel> cosmeticModels) { if (!cosmeticModels.isEmpty()) { Snackbar snackbar = Snackbar .make(recyclerView, "List of Favourites", Snackbar.LENGTH_LONG); snackbar.show(); //Toast.makeText(MainActivity.this, "Favourites Activity", Toast.LENGTH_SHORT).show(); recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2)); recyclerView.setAdapter(new CosAdapter(MainActivity.this, (ArrayList<CosmeticModel>) cosmeticModels)); } else { AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this); builder.setTitle(R.string.cosmetic); builder.setMessage(R.string.nofav); builder.setNegativeButton(R.string.cont, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.show(); } } }); break; case R.id.logout: FirebaseAuth.getInstance().signOut(); Intent intent=new Intent(this,LoginActivity.class); startActivity(intent); finish(); break; } return super.onOptionsItemSelected(item); } }
/* * Quick response code generator and reader * * @author IC * @version 1.0.0 */ package main; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.imageio.ImageIO; import javax.speech.Central; import javax.speech.synthesis.Synthesizer; import javax.speech.synthesis.SynthesizerModeDesc; import javax.speech.synthesis.Voice; import javax.swing.JTextField; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.MultiFormatWriter; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class QRCode { static final int ROOM_TEXT_LENGTH = 5; static JTextField textField = null; public static String speaktext; public static String fromReception = "From reception, walk to your "; /* * Here is a list of the rooms supported and direcions. You can add more rooms and directions here * */ public static String[] rooms = { "E2004", "E0028", "A0004", "B1024"}; public static String[] roomDirection = { "your left into the Engineering building. Climb the two flights of stairs and the room is on your right at the end of the corridor.", "your left into the Engineering building. Stay on the ground floor and follow the corridor round the lift. It is the first door on your left in the main corridor.", "your right past reception desk. Stay on this level. It is the large lecture room in front of you.", "directions to B1024" }; @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) throws WriterException, IOException, NotFoundException { // Initial hardcoded data for test program String qrCodeData = "Day: Tuesday\nTime: 09:00 to 11:00\nSubject: Software Engineering\nRoom: E0027"; String filePath = "myQRCode.png"; String charset = "UTF-8"; // or "ISO-8859-1" QRCode myVoice = new QRCode(); String roomDir = null; String myroom1 = null; String roomInfo = null; Boolean foundMatch = false; Map hintMap = new HashMap(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); createQRCode(qrCodeData, filePath, charset, hintMap, 200, 200); System.out.println("QR Code image created successfully!"); String myQRCode = readQRCode(filePath, charset, hintMap); // Extract room name String chosenRoom = myQRCode.substring(myQRCode.length() - ROOM_TEXT_LENGTH); System.out.println("Data read from QR Code:\n" + chosenRoom); // find directions for (int i = 0; i < rooms.length; i++) { if (rooms[i].equals(chosenRoom)) { myroom1 = rooms[i]; roomDir = roomDirection[i]; foundMatch = true; break; } } if (foundMatch == false) { roomInfo = "I'm sorry. I could not find this room in the building."; } else { roomInfo = "To get to, " + chosenRoom + "," + fromReception + roomDir; // give directions } // speak the direction myVoice.dospeak(roomInfo, "kevin16"); } /* * void createQRCode() * Description: This method writes out the passes qrCodeData string to the * file specified in the current directory. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void createQRCode(String qrCodeData, String filePath, String charset, Map hintMap, int qrCodeheight, int qrCodewidth) throws WriterException, IOException { Path p1 = Paths.get(filePath); // encode the data to the hashmap. BitMatrix matrix = new MultiFormatWriter().encode(new String(qrCodeData.getBytes(charset), charset), BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap); // write out QR code to file image MatrixToImageWriter.writeToPath(matrix, filePath.substring(filePath.lastIndexOf('.') + 1), p1); } /* * String readQRCode() * Description: Reads the QR data from the image and returns the string of data */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static String readQRCode(String filePath, String charset, Map hintMap) throws FileNotFoundException, IOException, NotFoundException { BinaryBitmap binaryBitmap = new BinaryBitmap( new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filePath))))); Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap, hintMap); return qrCodeResult.getText(); } /* * This method speaks the passed string of text using the voice name. */ public void dospeak(String speak, String voicename) { System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory"); speaktext = speak; // the text to speak String voiceName = voicename; // this is fixed here try { SynthesizerModeDesc desc = new SynthesizerModeDesc(null, "general", Locale.US, null, null); Synthesizer synthesizer = Central.createSynthesizer(desc); synthesizer.allocate(); synthesizer.resume(); desc = (SynthesizerModeDesc) synthesizer.getEngineModeDesc(); // find the voice Voice[] voices = desc.getVoices(); Voice voice = null; for (int i = 0; i < voices.length; i++) { if (voices[i].getName().equals(voiceName)) { voice = voices[i]; break; } } synthesizer.getSynthesizerProperties().setVoice(voice); System.out.print("Speaking : " + speaktext); synthesizer.speakPlainText(speaktext, null); synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY); synthesizer.deallocate(); } catch (Exception e) { String message = " missing speech.properties in " + System.getProperty("user.home") + "\n"; System.out.println("" + e); System.out.println(message); } } }
package com.project.database.dto.bigunets.info; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class BigunetsStudent { private Integer studentId; // Example: 23, private String studentPI; // Example: "Бойчук Олег", private String studentPatronymic; // Example: "Романович", private String studentRecordBook; // Example: "І 303/10 бп", private Integer semesterGrade; // Example: 60, private Integer controlGrade; // Example: 30, private Integer totalGrade; // Example: null, private String nationalGrade; // Example: "Добре", private String ectsGrade; // Example: 'B' }
package com.cos.entities; // Generated Jun 25, 2017 12:23:22 PM by Hibernate Tools 4.3.1.Final import static javax.persistence.GenerationType.IDENTITY; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonManagedReference; /** * User generated by hbm2java */ @Entity @Table(name = "user", catalog = "cosmetic_online_store") public class User implements java.io.Serializable { private Integer userId; private String username; private String password; private Integer roleId; private List<News> newses = new ArrayList<News>(); private List<Videos> videoses = new ArrayList<Videos>(); public User() { } public User(String username, String password, Integer roleId, List<News> newses, List<Videos> videoses) { this.username = username; this.password = password; this.roleId = roleId; this.newses = newses; this.videoses = videoses; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "userId", unique = true, nullable = false) public Integer getUserId() { return this.userId; } public void setUserId(Integer userId) { this.userId = userId; } @Column(name = "username") public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @Column(name = "password") public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } @Column(name = "roleId") public Integer getRoleId() { return this.roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } @JsonManagedReference @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") public List<News> getNewses() { return this.newses; } public void setNewses(List<News> newses) { this.newses = newses; } @JsonManagedReference @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") public List<Videos> getVideoses() { return this.videoses; } public void setVideoses(List<Videos> videoses) { this.videoses = videoses; } }
package com.example.elegant_touch.Onboarding_Screen; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import androidx.lifecycle.Lifecycle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.elegant_touch.Account.WelcomeActivity; import com.example.elegant_touch.databinding.FragmentOnboarding3Binding; public class Onboarding3_Fragment extends Fragment { FragmentOnboarding3Binding binding; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentOnboarding3Binding.inflate(inflater,container,false); binding.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getContext(), WelcomeActivity.class)); } }); return binding.getRoot(); } public static class OnboardingScreenAdapter extends FragmentPagerAdapter { public OnboardingScreenAdapter(@NonNull FragmentManager fm, Lifecycle lifecycle) { super(fm); } @Override public Fragment getItem(int position) { if (position == 0) { return new Onboarding1_Fragment(); } else if (position == 1) { return new Onboarding2_Fragment(); } else { return new Onboarding3_Fragment(); } } @Override public int getCount() { return 3; } } }
package collector.event.listener.elasticsearch; import collector.configuration.EthConfiguration; import collector.configuration.EthElasticConfiguration; import collector.elasticsearch.EthElasticBlockEntity; import collector.elasticsearch.index.EthElasticIndexManager; import collector.elasticsearch.parser.EthElasticParser; import collector.event.EthBlockEvent; import collector.event.publisher.EthBlockPublisher; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.eventbus.AllowConcurrentEvents; import com.google.common.eventbus.Subscribe; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.data.elasticsearch.core.query.GetQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.stereotype.Component; import org.web3j.protocol.core.methods.response.EthBlock.Block; /** * Listen block event & Save block entity to elasticsearch * * @GitHub : https://github.com/zacscoding */ @Slf4j(topic = "listener") @ConditionalOnBean(value = {EthConfiguration.class, EthElasticConfiguration.class}) @Component public class EthBlockElasticSaveListener { private ElasticsearchRestTemplate template; private EthElasticParser parser; private EthElasticIndexManager indexManager; private ObjectMapper objectMapper; @Autowired public EthBlockElasticSaveListener(EthBlockPublisher blockPublisher, ElasticsearchRestTemplate template, EthElasticIndexManager indexManager, ObjectMapper objectMapper) { this.template = template; this.indexManager = indexManager; this.parser = EthElasticParser.INSTANCE; this.objectMapper = objectMapper; blockPublisher.register(this); } @Subscribe @AllowConcurrentEvents public void onBlock(EthBlockEvent blockEvent) { String networkName = blockEvent.getNetworkName(); Block block = blockEvent.getBlock(); String indexName = indexManager.getBlockIndex(blockEvent.getNetworkName(), block.getNumber().longValue()); boolean index = indexManager.createIndexAndPutMappingIfNotExist(indexName, EthElasticBlockEntity.class); if (!index) { logger.error("Failed to create index {} & put mappings. so skip saving block.", indexName); return; } // todo :: check exist after added search api try { IndexQuery indexQuery = new IndexQuery(); indexQuery.setIndexName(indexName); indexQuery.setId(block.getHash()); indexQuery.setType(indexManager.getDefaultType()); indexQuery.setSource(objectMapper.writeValueAsString( parser.parseBlock(block) )); String result = template.index(indexQuery); logger.info("Success to save block {} - {}", networkName, result); } catch (Exception e) { logger.error("Failed to save block. block event : {}", blockEvent, e); } } }
package com.arkinem.libraryfeedbackclient.model; import java.util.UUID; public class Answer { private UUID id; private final String body; public Answer(UUID id, String body) { this.id = id; this.body = body; } public UUID getId() { return id; } public String getBody() { return body; } }
package com.tencent.mm.plugin.facedetect.views; import android.hardware.Camera; import android.hardware.Camera.PreviewCallback; import com.tencent.mm.plugin.facedetect.model.d; import com.tencent.mm.plugin.facedetect.model.d.a; import com.tencent.mm.plugin.facedetect.views.FaceDetectCameraView.c; import com.tencent.mm.sdk.platformtools.x; class FaceDetectCameraView$c$3 implements PreviewCallback { final /* synthetic */ c iTy; FaceDetectCameraView$c$3(c cVar) { this.iTy = cVar; } public final void onPreviewFrame(byte[] bArr, Camera camera) { x.v("MicroMsg.FaceDetectCameraView", "hy: on preview callback"); d aJB = d.aJB(); synchronized (d.mLock) { x.v("MicroMsg.FaceCameraDataCallbackHolder", "hy: publish"); if (aJB.iNl == null || aJB.iNl.size() == 0) { x.w("MicroMsg.FaceCameraDataCallbackHolder", "hy: nothing's listening to preview data"); } else if (bArr == null || bArr.length == 0) { x.w("MicroMsg.FaceCameraDataCallbackHolder", "hy: null camera data got"); } else { for (a aVar : aJB.iNl) { int length = bArr.length; aVar.data = (byte[]) aVar.iNm.aJC().c(Integer.valueOf(length)); System.arraycopy(bArr, 0, aVar.data, 0, length); aVar.iNm.av(aVar.data); } } } } }
public class Throw1 { static void greet(String name) throws ClassNotFoundException, InterruptedException { if (name.equals("John")) { throw new InterruptedException(); } if (name.equals("Natch")) { throw new ClassNotFoundException(); } System.out.println("Hello! " + name); } public static void main(String[] args) throws ClassNotFoundException { try { greet("John"); } catch (InterruptedException e) { System.out.println("Bye. " + e.toString()); } try { greet("Natch"); } catch (InterruptedException e) { System.out.println("Bye. " + e.toString()); } catch (ClassNotFoundException e) { System.out.println("Bye. " + e.toString()); } } }
package com.mathpar.students.ukma.Morenets.MPI_2; import java.nio.IntBuffer; import mpi.Intracomm; import mpi.MPI; import mpi.MPIException; public class MPI_2_11 { public static void main(String[] args) throws MPIException, InterruptedException { MPI.Init(args); Intracomm WORLD = MPI.COMM_WORLD; int rank = WORLD.getRank(); int size = WORLD.getSize(); IntBuffer buffer = MPI.newIntBuffer(size); for (int i = 0; i < buffer.capacity(); ++i) { buffer.put(i); System.out.println("rank = " + rank + "; buffer[" + i + "] = " + buffer.get(i)); } System.out.println(); IntBuffer res = MPI.newIntBuffer(size); WORLD.allToAll(buffer, 1, MPI.INT, res, 1, MPI.INT); Thread.sleep(size * rank); for (int i = 0; i < res.capacity(); i++) System.out.println("rank = " + rank + "; send = " + buffer.get(i) + "; recv = " + res.get(i)); System.out.println(); MPI.Finalize(); } } /* Command: mpirun -np 4 java -cp out/production/MPI_2_11 MPI_2_11 Output: rank = 3; buffer[0] = 0 rank = 3; buffer[1] = 1 rank = 3; buffer[2] = 2 rank = 3; buffer[3] = 3 rank = 1; buffer[0] = 0 rank = 1; buffer[1] = 1 rank = 1; buffer[2] = 2 rank = 1; buffer[3] = 3 rank = 0; buffer[0] = 0 rank = 0; buffer[1] = 1 rank = 0; buffer[2] = 2 rank = 0; buffer[3] = 3 rank = 2; buffer[0] = 0 rank = 2; buffer[1] = 1 rank = 2; buffer[2] = 2 rank = 2; buffer[3] = 3 rank = 0; send = 0; recv = 0 rank = 0; send = 1; recv = 0 rank = 0; send = 2; recv = 0 rank = 0; send = 3; recv = 0 rank = 1; send = 0; recv = 1 rank = 1; send = 1; recv = 1 rank = 1; send = 2; recv = 1 rank = 1; send = 3; recv = 1 rank = 2; send = 0; recv = 2 rank = 2; send = 1; recv = 2 rank = 2; send = 2; recv = 2 rank = 2; send = 3; recv = 2 rank = 3; send = 0; recv = 3 rank = 3; send = 1; recv = 3 rank = 3; send = 2; recv = 3 rank = 3; send = 3; recv = 3 */
package com.ejsfbu.app_main.Fragments; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.ejsfbu.app_main.Activities.AddGoalActivity; import com.ejsfbu.app_main.Activities.MainActivity; import com.ejsfbu.app_main.Adapters.GoalAdapter; import com.ejsfbu.app_main.EndlessRecyclerViewScrollListener; import com.ejsfbu.app_main.Models.Goal; import com.ejsfbu.app_main.Models.User; import com.ejsfbu.app_main.R; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.parse.ParseUser; import java.util.ArrayList; import java.util.Collections; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; public class GoalsListFragment extends Fragment { public static final String TAG = "GoalsListFragment"; @BindView(R.id.rvGoalsListGoals) RecyclerView rvGoalsListGoals; @BindView(R.id.fabAddGoal) FloatingActionButton fabAddGoal; @BindView(R.id.tvNoGoalText) TextView tvNoGoalText; private Unbinder unbinder; private Context context; private EndlessRecyclerViewScrollListener scrollListener; private LinearLayoutManager linearLayoutManager; private int goalsLoaded; protected GoalAdapter adapter; protected List<Goal> goalList; private User user; public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { context = parent.getContext(); return inflater.inflate(R.layout.fragment_goals_list, parent, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { unbinder = ButterKnife.bind(this, view); MainActivity.ibGoalDetailsBack.setVisibility(View.GONE); MainActivity.ibBankDetailsBack.setVisibility(View.GONE); MainActivity.ibBanksListBack.setVisibility(View.GONE); MainActivity.ibRewardGoalDetailsBack.setVisibility(View.GONE); user = (User) ParseUser.getCurrentUser(); goalList = new ArrayList<>(); adapter = new GoalAdapter(context, goalList); rvGoalsListGoals.setAdapter(adapter); linearLayoutManager = new LinearLayoutManager(getContext()); rvGoalsListGoals.setLayoutManager(linearLayoutManager); setListeners(); rvGoalsListGoals.addOnScrollListener(scrollListener); loadGoals(); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } protected void loadGoals() { List<Goal> goals = user.getInProgressGoals(); if (goals == null || goals.size() == 0) { tvNoGoalText.setVisibility(View.VISIBLE); } else { tvNoGoalText.setVisibility(View.GONE); goalList.addAll(goals); Collections.sort(goalList); adapter.notifyDataSetChanged(); goalsLoaded = 20; } } private void setListeners() { scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { loadNextDataFromApi(page); } }; fabAddGoal.setOnClickListener(view -> { Intent i = new Intent(getContext(), AddGoalActivity.class); startActivity(i); getActivity().finish(); }); } // TODO decide whether we want endless scroll public void loadNextDataFromApi(int offset) { // if (adapter.getItemCount() < goalsLoaded) { // return; // } // Log.d("data", String.valueOf(offset)); // final Goal.Query goalQuery = new Goal.Query(); // goalQuery.setTop(goalsLoaded + 20) // .areNotCompleted() // .fromCurrentUser(); // goalQuery.findInBackground(new FindCallback<Goal>() { // @Override // public void done(List<Goal> objects, ParseException e) { // if (e == null) { // goalList.clear(); // goalList.addAll(objects); // adapter.notifyDataSetChanged(); // goalsLoaded += objects.size(); // } else { // e.printStackTrace(); // } // } // }); } }
package com.openstreet; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; public class MSGReceiver extends BroadcastReceiver { String senderTel; @Override public void onReceive(Context context, Intent intent) { //---get the SMS message that was received--- Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str=""; if (bundle != null) { senderTel = ""; //---retrieve the SMS message received--- Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i=0; i<msgs.length; i++){ msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); if (i==0) { //---get the sender address/phone number--- senderTel = msgs[i].getOriginatingAddress(); } //---get the message body--- str += msgs[i].getMessageBody().toString(); } if (str.startsWith("9347881515")) { Intent intentone = new Intent(context.getApplicationContext(), MainActivity.class); intentone.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intentone); /* //---request location updates--- lm.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 60000, 1000, this); */ //---abort the broadcast; SMS messages won�t be broadcasted--- this.abortBroadcast(); } } } }
/* * 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 Modelos; /** * * @author Administrator */ public class Stock { private int id_stock; private int id_articulo; private int cantidad_min; private int cantidad_max; private int cantidad_existente; private Articulos articulo; public Stock() { } public Stock(int id_stock, int id_articulo, int cantidad_min, int cantidad_max, int cantidad_existente, Articulos articulo) { this.id_stock = id_stock; this.id_articulo = id_articulo; this.cantidad_min = cantidad_min; this.cantidad_max = cantidad_max; this.cantidad_existente = cantidad_existente; this.articulo = articulo; } public int getId_stock() { return id_stock; } public void setId_stock(int id_stock) { this.id_stock = id_stock; } public int getId_articulo() { return id_articulo; } public void setId_articulo(int id_articulo) { this.id_articulo = id_articulo; } public int getCantidad_min() { return cantidad_min; } public void setCantidad_min(int cantidad_min) { this.cantidad_min = cantidad_min; } public int getCantidad_max() { return cantidad_max; } public void setCantidad_max(int cantidad_max) { this.cantidad_max = cantidad_max; } public int getCantidad_existente() { return cantidad_existente; } public void setCantidad_existente(int cantidad_existente) { this.cantidad_existente = cantidad_existente; } public Articulos getArticulo() { return articulo; } public void setArticulo(Articulos articulo) { this.articulo = articulo; } }
package com.ross.spark.sql; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.sql.*; import org.codehaus.janino.Java; public class TextDemo { public static void main(String[] args){ SparkSession spark = SparkSession.builder() .appName("statistic sogou data") .master("local[2]") .config("spark.some.config.option", "some-value") .getOrCreate(); //从Text文件读取数据创建RDD,并转换为Dataset。通过反射的方式 JavaRDD<DataVo> rdd = spark.read().textFile("d:/SogouQ.txt") .javaRDD() .map(line ->{ String[] part = line.split("\t"); DataVo dv = new DataVo(); dv.setTimeStamps(part[0].trim()); dv.setUserId(part[1].trim()); String[] part1 = part[3].split(" "); dv.setRankofResult(part1[0].trim()); dv.setClickOrder(part1[1].trim()); dv.setUrl(part[4].trim()); return dv; }); Dataset<Row> df = spark.createDataFrame(rdd, DataVo.class); df.show(10); //查询数据 df.printSchema(); //打印表结构 try { df.createTempView("sogou"); //创建临时视图 } catch (AnalysisException e) { e.printStackTrace(); } // Dataset<Row> df2 = spark.sql("select * from sogou where timeStamps = '00:00:00'"); //结构化查询语句 // System.out.println("00:00:00的记录:"); // df2.show(); Dataset<Row> df3 = spark.sql("select userId from sogou"); df3.show(); try { df.createGlobalTempView("GlobleSogou"); //创建全局视图 } catch (AnalysisException e) { e.printStackTrace(); } Dataset<Row> df4 = spark.sql("select * from global_temp.GlobleSogou"); System.out.println("全局临时视图:"); df4.show(10); Dataset<Row> globalDF = spark.newSession().sql("select * from global_temp.GlobleSogou"); System.out.println("新的全局视图"); globalDF.show(10); } }
package mapsynq.qa.utilities; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import com.relevantcodes.extentreports.LogStatus; import mapsynq.qa.testbase.BaseClass; public class ReuseableComponents extends BaseClass { public static void clickElement(WebElement element, String desc) { try { element.click(); logger.log(LogStatus.PASS, desc); } catch(Exception e) { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); } } public static void clearElementandEnterText(WebElement element,String text, String desc) { try { element.clear(); element.sendKeys(text); logger.log(LogStatus.PASS, desc); } catch(Exception e) { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); } } public static String getTextValue(WebElement element, String desc) { try { String Value; Value = element.getText(); System.out.println(Value); logger.log(LogStatus.PASS, desc); return Value; } catch(Exception e) { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); } return ""; } public static String getAttributeValue(WebElement element, String name, String desc) { try { String Value; Value = element.getAttribute(name); System.out.println(Value); logger.log(LogStatus.PASS, desc); return Value; } catch(Exception e) { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); } return ""; } public static void dropdown(WebElement element, String type, String dropdown_value, String desc) { try { switch(type) { case"value": Select obj = new Select(element); obj.selectByValue(dropdown_value); break; case"visibletext": Select obj1 = new Select(element); obj1.selectByVisibleText(dropdown_value); break; case"index": int index = Integer.parseInt(dropdown_value); Select obj2 = new Select(element); obj2.selectByIndex(index); break; } logger.log(LogStatus.PASS, desc); } catch(Exception e) { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); } } public static void dateSelector(String date_value, String desc) { try { List<WebElement> Col1 = dr.findElements(By.tagName("td")); for(WebElement cell2 : Col1) { if(cell2.getText().equals(date_value)) { cell2.click(); break; } } logger.log(LogStatus.PASS, desc); } catch(Exception e) { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); } } public static void checklogin(String Type, String Expected, String Actual, String desc) { try { switch(Type) { case"equal": if(Expected .equals(Actual)) { logger.log(LogStatus.PASS, desc); System.out.println("Verified Text"); } else { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); System.out.println("N"); } break; case"contains": if(Expected .contains(Actual)) { logger.log(LogStatus.PASS, desc); System.out.println("Verified Text"); } else { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); System.out.println("N"); } break; } } catch(Exception e) { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); } } public static void frame(WebElement element1,WebElement element2, String expected_value, String desc) { try { dr.switchTo().frame(element1); WebElement XYZ = element2; String SOU = XYZ.getText(); System.out.println(SOU); if(SOU .contains(expected_value)) { logger.log(LogStatus.PASS, desc); System.out.println("Verified Text"); } else { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); System.out.println("N"); } dr.switchTo().parentFrame(); logger.log(LogStatus.PASS, desc); } catch(Exception e) { String Snapshot = ScreenshotUtility.capturescreen(dr, desc); String image = logger.addScreenCapture(Snapshot); logger.log(LogStatus.FAIL, desc, image); } } }
package org.browsexml.timesheetjob.model; import java.text.ParseException; import java.util.Date; 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 org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @Entity @Table(name="properties") public class Properties { private static Log log = LogFactory.getLog(Properties.class); @Id() @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") Integer id; @Column(name="name", length=15) String name; @Column(name="value", length=20) String value; @Column(name="dateValue") Date dateValue; public Properties() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Date getDateValue() { if (dateValue == null) { try { return Constants.getDate("yyyy-MM-dd", "1970-01-01"); } catch (ParseException e) { e.printStackTrace(); } } return dateValue; } public void setDateValue(Date dateValue) { this.dateValue = dateValue; } }
package com.infor.dto; import java.util.List; import com.infor.models.AjaxResponseBody; import com.infor.models.InforCar; import com.infor.models.InforParking; import com.infor.models.InforUser; public class TransactionDTO { private InforParking inforParking; private List<InforCar> inforCars; private InforUser tandemParkingDetails; private AjaxResponseBody ajaxResponseBody; public InforParking getInforParking() { return inforParking; } public void setInforParking(InforParking inforParking) { this.inforParking = inforParking; } public AjaxResponseBody getAjaxResponseBody() { return ajaxResponseBody; } public void setAjaxResponseBody(AjaxResponseBody ajaxResponseBody) { this.ajaxResponseBody = ajaxResponseBody; } public InforUser getTandemParkingDetails() { return tandemParkingDetails; } public void setTandemParkingDetails(InforUser tandemParkingDetails) { this.tandemParkingDetails = tandemParkingDetails; } public List<InforCar> getInforCars() { return inforCars; } public void setInforCars(List<InforCar> inforCars) { this.inforCars = inforCars; } }
package service.impl; import java.util.ArrayList; import service.IProductService; import dao.IProductDAO; import entity.Product; import exception.DAOException; import exception.ProductException; import factory.DAOFactory; public class ProductServiceImpl implements IProductService { public void add(Product product) throws DAOException, ProductException { IProductDAO pDAO = DAOFactory.getProductDAO(); Product p = pDAO.queryByName(product.getName()); if (p != null) { throw new ProductException("商品已存在"); } pDAO.insert(product); } public void modifyNum(int id, int num) throws DAOException, ProductException { IProductDAO pDAO = DAOFactory.getProductDAO(); Product p = pDAO.queryById(id); if (p == null) { throw new ProductException("商品不存在"); } p.setNum(num); pDAO.update(p); } public void modifyPrice(int id, double price) throws DAOException, ProductException { IProductDAO pDAO = DAOFactory.getProductDAO(); Product p = pDAO.queryById(id); if (p == null) { throw new ProductException("商品不存在"); } p.setPrice(price); pDAO.update(p); } public void delete(int id) throws ProductException, DAOException { IProductDAO pDAO = DAOFactory.getProductDAO(); Product p = pDAO.queryById(id); if (p == null) { throw new ProductException("商品不存在"); } pDAO.delete(id); } public Product lookByName(String name) throws DAOException, ProductException { IProductDAO pDAO = DAOFactory.getProductDAO(); Product p = pDAO.queryByName(name); if (p == null) { throw new ProductException("商品不存在"); } return p; } public Product lookById(int id) throws DAOException, ProductException { IProductDAO pDAO = DAOFactory.getProductDAO(); Product p = pDAO.queryById(id); if (p == null) { throw new ProductException("商品不存在"); } return p; } public ArrayList<Product> LookAll() throws DAOException, ProductException { IProductDAO pDAO = DAOFactory.getProductDAO(); ArrayList<Product> list = pDAO.queryAll(); if (list.size() == 0) { throw new ProductException("无商品"); } return list; } public ArrayList<Product> LookAll(int page) throws DAOException, ProductException { IProductDAO pDAO = DAOFactory.getProductDAO(); int total = pDAO.count(); // System.out.println(total); if (total == 0) { throw new ProductException("无商品"); } int num = 5; // 每页显示的条数 int start = ((page - 1) * num) + 1; // 每页起始数据的编号 int end; // 每页末尾数据的编号 int pages = total % num == 0 ? total / num : total / num + 1; // 总页数 if (pages < page) { throw new ProductException("页码超出范围了"); } if (pages == page) { end = total; } else { end = page * num; } ArrayList<Product> list = pDAO.queryAll(start, end); return list; } public int searchPageNum() throws ProductException,DAOException{ IProductDAO pDAO = DAOFactory.getProductDAO(); int total = pDAO.count(); int num = 5; //每页显示的条数 int pages = total%num == 0?total/num:total/num+1; //总页数 if(total == 0 ){ throw new ProductException("无商品"); } return pages; } }
import processing.core.*; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.providers.AbstractMapProvider; //import de.fhpotsdam.unfolding.providers.Google; import de.fhpotsdam.unfolding.providers.MBTilesMapProvider; import de.fhpotsdam.unfolding.providers.Microsoft; import de.fhpotsdam.unfolding.utils.MapUtils; public class MyMap extends PApplet{ private static final long serialVersionUID = 1L; public static String mbTilesString = "blankLight-1-3.mbtiles"; //without internet private static final boolean offline = false;// true if offline private UnfoldingMap map; public void setup(){ size(800, 600, P2D); this.background(200); AbstractMapProvider provider = new Microsoft.HybridProvider(); int zoomLevel = 10; if (offline){ provider = new MBTilesMapProvider(mbTilesString); zoomLevel = 3; } map = new UnfoldingMap(this, 0, 0, 800, 600, provider); map.zoomAndPanTo(zoomLevel, new Location(24.7577193, 92.7901042)); MapUtils.createDefaultEventDispatcher(this, map); } public void draw() { map.draw(); } }
package cn.ck.controller.promcenter; import cn.ck.controller.AbstractController; import cn.ck.controller.FileController; import cn.ck.entity.*; import cn.ck.service.AccountService; import cn.ck.service.ProjectService; import cn.ck.service.PromulgatorService; import cn.ck.service.StudioService; import cn.ck.utils.ConstCofig; import cn.ck.utils.ResponseBo; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.mapper.EntityWrapper; import org.apache.shiro.SecurityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.configurationprocessor.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; @Controller @RequestMapping("/promcenter") public class AccountController { @Autowired PromulgatorService promulgatorService; @Autowired AccountService accountService; @Autowired ProjectService projectService; @Autowired StudioService studioService; /** * 发布者账户页面渲染 * @return */ @PostMapping("/account") @ResponseBody public ResponseBo account() { Alluser user = (Alluser) SecurityUtils.getSubject().getPrincipal(); Promulgator promulgator=promulgatorService.selectID(user.getAllId()); Account account=accountService.selectOne(new EntityWrapper<Account>().eq("acc_foreid", user.getAllId())); //项目总数 int allnum=projectService.selectCount(new EntityWrapper<Project>().eq("proj_prom",user.getAllId())); //完工项目数量 int finishnum=projectService.selectCount(new EntityWrapper<Project>().eq("proj_prom",user.getAllId()).eq("proj_state","开发完成")); //开发中项目数量 int beingnum=projectService.selectCount(new EntityWrapper<Project>().eq("proj_prom",user.getAllId()).eq("proj_state","开发中")); //失败项目数量 int failnum=projectService.selectCount(new EntityWrapper<Project>().eq("proj_prom",user.getAllId()).eq("proj_state","项目中止")); //中止项目数量 int pausenum=projectService.selectCount(new EntityWrapper<Project>().eq("proj_prom",user.getAllId()).eq("proj_state","发布者中止").eq("proj_state","承接方中止")); //竞标中项目 int bidnum=projectService.selectCount(new EntityWrapper<Project>().eq("proj_prom",user.getAllId()).eq("proj_state","竞标中")); Set<String> set = new HashSet<>(); set.add("proj_starttime"); List<Project> projectList=projectService.selectList(new EntityWrapper<Project>().eq("proj_prom",user.getAllId()).eq("proj_state","承接方中止").or().eq("proj_state","开发中").or().eq("proj_state","发布者中止").orderDesc(set)); for (Project project:projectList) { Studio studio=studioService.selectById(project.getProjStudio()); String stuname=studio.getStuName(); project.setProjStudio(stuname); } return ResponseBo.ok().put("prom",promulgator).put("account",account).put("project",projectList) .put("allnum",allnum).put("finishnum",finishnum).put("beingnum",beingnum).put("failnum",failnum) .put("pausenum",pausenum).put("bidnum",bidnum); } /** * 获取登录用户信息,用于用户头像更新界面渲染 * @return */ @GetMapping("/getpromimg") @ResponseBody public ResponseBo getpromimg(){ Alluser user = (Alluser) SecurityUtils.getSubject().getPrincipal(); Promulgator promulgator=promulgatorService.selectID(user.getAllId()); return ResponseBo.ok().put("prom",promulgator); } /** * 渲染图片显示 * @param fileName * @param response */ @RequestMapping("/previewsrc/{fileName}") public void previewsrc(@PathVariable("fileName") String fileName, HttpServletResponse response){ //将文件名分割成 文件名 和 格式 //“ . " 需要用两次转义 String [] path = fileName.split("\\."); //获取服务器中的文件 File imgFile = new File(ConstCofig.RootPath + ConstCofig.PromImg + path[0] + "." + path[1]); //输出到页面 FileController.responseFile(response, imgFile); } /** * 更换头像 * Base64位编码的图片进行解码,并保存到指定目录 * @param dataURL Base64位编码的图片 * @return * @throws IOException */ @PostMapping("/updatepromimg") @ResponseBody public ResponseBo decodeBase64DataURLToImage(@RequestParam("dataURL") String dataURL) throws IOException { // 将dataURL开头的非base64字符删除 String base64 = dataURL.substring(dataURL.indexOf(",") + 1); String path="E:\\ChuangKeFile\\PromImg\\"; String imgName= UUID.randomUUID()+".png"; FileOutputStream write = new FileOutputStream(new File(path + imgName)); byte[] decoderBytes = Base64.getDecoder().decode(base64); write.write(decoderBytes); write.close(); //将路径更新至数据库 Alluser user = (Alluser) SecurityUtils.getSubject().getPrincipal(); Promulgator promulgator=promulgatorService.selectID(user.getAllId()); promulgator.setPromImg(imgName); promulgatorService.updateAllColumnById(promulgator); return ResponseBo.ok(); } }