text
stringlengths
10
2.72M
package Complex; public class Testcomplex { public static void main(String[] args) { Complex comp1=new Complex(); Complex comp2=new Complex(); Complex comp3=new Complex(); // result ucun comp1.setRealPart(5); comp1.setImaginaryPart(2); comp2.setRealPart(3); comp2.setImaginaryPart(7); System.out.println("COMP1: " + comp1); System.out.println("COMP2: " + comp2); comp3 = Complex.Topla(comp1, comp2); System.out.println("Toplama: " + comp3); comp3=Complex.Cix(comp1,comp2); System.out.println(comp3); comp3=Complex.vur(comp1, comp2); System.out.println(comp3); } }
package com.tencent.mrs.util; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import com.tencent.matrix.d.b; import com.tencent.matrix.mrs.core.MatrixReport; import com.tencent.mm.sdk.platformtools.s; public class MatrixStrategyNotifyBroadcast extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { if (intent == null) { b.e("Matrix.StrategyNotifyBroadcast", "MatrixStrategyNotifyBroadcast intent == null", new Object[0]); return; } Object j = s.j(intent, "strategy"); b.i("Matrix.StrategyNotifyBroadcast", "receive MatrixStrategyNotifyBroadcast, process: %s, strategy:%s", MatrixReport.with().getProcessName(), j); if (!TextUtils.isEmpty(j)) { MatrixReport.getMrsCallback().onStrategyNotify(j, false); } } }
package io.meksula.persister; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FormatTransformerPersisterApplication { public static void main(String[] args) { SpringApplication.run(FormatTransformerPersisterApplication.class, args); } }
package cn.itcast.demo02; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyDemo_2 { public static void main(String[] args) { long s = System.currentTimeMillis(); FileOutputStream fos = null; FileInputStream fis = null; int len = 0; try{ fos = new FileOutputStream("C:\\Users\\Justzh_liao\\Desktop\\新建文件夹\\paper1.rar"); fis = new FileInputStream("C:\\Users\\Justzh_liao\\Desktop\\新建文件夹\\paper.rar"); byte [] bytes = new byte [1024*10];//这个是CopyDemo_1的改良版,运行更快 while((len = fis.read(bytes))!= -1){ fos.write(bytes,0,len); } }catch(IOException ex){ System.out.println(ex); throw new RuntimeException("复制文件失败"); }finally{ try{ if(fos != null){ fos.close(); } }catch(IOException ex){ System.out.println(ex); throw new RuntimeException("关闭资源失败"); }finally{ try{ if(fis != null){ fis.close(); } }catch(IOException ex){ System.out.println(ex); throw new RuntimeException("关闭资源失败"); } } } long e = System.currentTimeMillis(); System.out.println(e-s); } }
package ru.otus.api.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.otus.api.dao.AccauntDao; import ru.otus.api.model.Accaunt; import ru.otus.api.sessionmanager.SessionManager; import java.util.Optional; public class DbServiceAccauntImpl implements DBServiceAccaunt { private static Logger logger = LoggerFactory.getLogger(DbServiceAccauntImpl.class); private final AccauntDao accauntDao; public DbServiceAccauntImpl(AccauntDao accauntDao) { this.accauntDao = accauntDao; } @Override public long saveAccaunt(Accaunt accaunt) { try (SessionManager sessionManager = accauntDao.getSessionManager()) { sessionManager.beginSession(); try { long accauntId = accauntDao.saveAccaunt(accaunt); sessionManager.commitSession(); logger.info("created accaunt: {}", accauntId); return accauntId; } catch (Exception ex) { logger.error(ex.getMessage(), ex); sessionManager.rollbackSession(); throw new DbServiceException(ex); } } } @Override public Optional<Accaunt> getAccaunt(long id) { try (SessionManager sessionManager = accauntDao.getSessionManager()) { sessionManager.beginSession(); try { Optional<Accaunt> accauntOptional = accauntDao.findById(id); logger.info("accaunt: {}", accauntOptional.orElse(null)); return accauntOptional; } catch (Exception ex) { logger.error(ex.getMessage(), ex); sessionManager.rollbackSession(); } return Optional.empty(); } } }
package Raghu1; public class rockk { int tod=120; int nop=79; int avgdays=((nop/tod)*100); System.out.println("Attendance Peercentage ="+avgdays); if(avgdays>75); { System.out.println("can allow for exam"); } else if(avgdays>=60&& avgdays<=75); System.out.println("Shud Pay Penalty of rs5000"); } else if(avgdays<60); System.out.println("cannot able to atten the exam"); } } }
package kr.co.sist.user.member.vo; /** * 회원정보를 추가하는 VO * @author sist38 * */ public class MemberAddVO { private String nameKorF, nameKorL, nameEngF, nameEngL, birthYear, birthMonth, birthDay, phoneType, phoneCountry, phoneNum, email, id,ip, pass, gender; public MemberAddVO() { } public MemberAddVO(String nameKorF, String nameKorL, String nameEngF, String nameEngL, String birthYear, String birthMonth, String birthDay, String phoneType, String phoneCountry, String phoneNum, String email, String id, String ip, String pass, String gender) { super(); this.nameKorF = nameKorF; this.nameKorL = nameKorL; this.nameEngF = nameEngF; this.nameEngL = nameEngL; this.birthYear = birthYear; this.birthMonth = birthMonth; this.birthDay = birthDay; this.phoneType = phoneType; this.phoneCountry = phoneCountry; this.phoneNum = phoneNum; this.email = email; this.id = id; this.ip = ip; this.pass = pass; this.gender = gender; } public String getNameKorF() { return nameKorF; } public void setNameKorF(String nameKorF) { this.nameKorF = nameKorF; } public String getNameKorL() { return nameKorL; } public void setNameKorL(String nameKorL) { this.nameKorL = nameKorL; } public String getNameEngF() { return nameEngF; } public void setNameEngF(String nameEngF) { this.nameEngF = nameEngF; } public String getNameEngL() { return nameEngL; } public void setNameEngL(String nameEngL) { this.nameEngL = nameEngL; } public String getBirthYear() { return birthYear; } public void setBirthYear(String birthYear) { this.birthYear = birthYear; } public String getBirthMonth() { return birthMonth; } public void setBirthMonth(String birthMonth) { this.birthMonth = birthMonth; } public String getBirthDay() { return birthDay; } public void setBirthDay(String birthDay) { this.birthDay = birthDay; } public String getPhoneType() { return phoneType; } public void setPhoneType(String phoneType) { this.phoneType = phoneType; } public String getPhoneCountry() { return phoneCountry; } public void setPhoneCountry(String phoneCountry) { this.phoneCountry = phoneCountry; } public String getPhoneNum() { return phoneNum; } public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
package com.securitywhitepapers.random; import java.util.Random; public class SameSeed { public static void main(String[] args) { Random r1 = new Random(1); Random r2 = new Random(1); for(int i = 0; i < 10; i++) { int v2 = r2.nextInt(); int v1 = r1.nextInt(); System.out.println(String.format("Same value: %b", v1 == v2)); } } }
package com.game.war.src; /** * * @author Venkat * version 1.0 */ public class Player { private String id; private Pile pile; public Player(String id) { this.id = id; pile = new Pile(); } public Card playCard() { if (pile.getSize() > 0) return pile.getNewCard(); else return null; } public String getId() { return id; } public Pile getPile() { return pile; } public void collectCards(Pile p) { pile.addCards(p); } public void collectCard(Card c) { pile.addCard(c); } }
package Objects.TrafficLight.TrafficLightState; import javafx.scene.image.Image; public class RedYellowState extends State { private final String NAME = "RedYellow"; private Image image; @Override public Image getImage() { if (image == null) { image = new Image("file:images/lights/long/red-yellow-s.png"); } return image; } public String getName() { return NAME; } }
package controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class DisplayServlet */ @WebServlet("/DisplayServlet") public class DisplayServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DisplayServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String displayMode = request.getParameter("display_mode"); String group = request.getParameter("group"); System.out.println("displayMode="+displayMode+"group="+group); request.getSession().setAttribute("display_mode", displayMode); request.getSession().setAttribute("group", group); request.getRequestDispatcher("display.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
package com.chuxin.family.mate; import com.chuxin.family.app.CxRootActivity; import com.chuxin.family.widgets.NiceEditText; import com.chuxin.family.R; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; /** * * @author wentong.men * */ public class CxMateAddCustom extends CxRootActivity implements OnClickListener{ private NiceEditText etValue; private String mCustomTitle; private Button mReturnButton; private Button mSaveButton; private LinearLayout naviLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cx_fa_activity_mateprofile_addcustom); naviLayout = (LinearLayout)findViewById(R.id.cx_fa_activity_title_layout); naviLayout.setVisibility(View.VISIBLE); etValue = (NiceEditText)findViewById(R.id.mateCustomerStr); etValue.addTextChangedListener(new CustomTextWatcher()); mReturnButton = (Button)findViewById(R.id.cx_fa_activity_title_back); mSaveButton = (Button)findViewById(R.id.cx_fa_activity_title_more); mSaveButton.setVisibility(View.VISIBLE); mReturnButton.setText(getString(R.string.cx_fa_navi_back)); mSaveButton.setText(getString(R.string.cx_fa_navi_save)); mReturnButton.setOnClickListener(this); mSaveButton.setOnClickListener(this); } private class CustomTextWatcher implements TextWatcher { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } public void afterTextChanged(Editable s) { mCustomTitle = s.toString(); } } @Override protected void onPause() { super.onPause(); overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out); } @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(etValue.getWindowToken(),0) ; switch(v.getId()){ case R.id.cx_fa_activity_title_back: break; case R.id.cx_fa_activity_title_more: if (mCustomTitle != null && mCustomTitle.length() > 0) { Intent mIntent = new Intent(); mIntent.putExtra("customTitle", mCustomTitle); this.setResult(0, mIntent); } break; default: break; } finish(); } }
package hirondelle.web4j.util; import junit.framework.*; //import junit.ui.TestRunner; //import junit.textui.TestRunner; import java.util.logging.*; import java.util.*; import java.math.BigDecimal; import hirondelle.web4j.util.Util; /** <a href="http://www.junit.org">JUnit</a> test cases for {@link Util}. */ public final class TESTUtil extends TestCase { /** Run the test cases. */ public static void main(String args[]) { String[] testCaseName = {TESTUtil.class.getName()}; //Select one of several types of interfaces. junit.textui.TestRunner.main(testCaseName); //junit.swingui.TestRunner.main(testCaseName); //junit.ui.TestRunner.main(testCaseName); } public TESTUtil(String aName) { super(aName); } // TEST CASES // public void testReplace(){ testReplaceError(null, null, null); testReplaceError(null, SUBSTR, REPLACEMENT); testReplaceError(INPUT, null, REPLACEMENT); testReplaceError(INPUT, SUBSTR, null); testReplaceSuccess(INPUT, SUBSTR, REPLACEMENT, RESULT); testReplaceSuccess("this is silly this is silly", SUBSTR, REPLACEMENT, "this *IS* silly this *IS* silly"); testReplaceFailure(INPUT, SUBSTR, REPLACEMENT, "this *IS* silly"); testReplaceFailure(INPUT, SUBSTR, REPLACEMENT, "this *IS* silly"); testReplaceFailure(INPUT, SUBSTR, REPLACEMENT, "this *IS* silly"); testReplaceFailure(INPUT, SUBSTR, REPLACEMENT, "this *IS* silly "); testReplaceFailure(INPUT, SUBSTR, REPLACEMENT, " this *IS* silly"); testReplaceFailure(INPUT, SUBSTR, REPLACEMENT, "this *is* silly"); testReplaceFailure(INPUT, SUBSTR, REPLACEMENT, "this IS silly"); } public void testLogOnePerLine(){ List list = new ArrayList(); list.add(null); list.add("Zebra"); list.add("aardvark"); list.add("Banana"); list.add(""); list.add("aardvark"); list.add(new BigDecimal("5.00")); String listResult = "(7) {" + NL + " ''" + NL + " '5.00'" + NL + " 'aardvark'" + NL + " 'aardvark'" + NL + " 'Banana'" + NL + " 'null'" + NL + " 'Zebra'" + NL + "}"; testLogOnePerLineSucceed(list, listResult); list = new ArrayList(); listResult = "(0) {" + NL + "}"; testLogOnePerLineSucceed(list, listResult); Map map = new LinkedHashMap(); map.put("b", "blah"); map.put("a", new BigDecimal("5.00")); map.put("Z", null); map.put(null, new Integer(3)); String mapResult = "(4) {" + NL + " 'a' = '5.00'" + NL + " 'b' = 'blah'" + NL + " 'null' = '3'" + NL + " 'Z' = 'null'" + NL + "}"; testLogOnePerLineSucceed(map, mapResult); map = new LinkedHashMap(); mapResult = "(0) {" + NL + "}"; testLogOnePerLineSucceed(map, mapResult); } public void testRemoveQuotes(){ assertTrue(Util.removeQuotes("Yes").equals("Yes")); assertTrue(Util.removeQuotes("'Yes'").equals("Yes")); assertTrue(Util.removeQuotes("'Yes").equals("Yes")); assertTrue(Util.removeQuotes("'Yes").equals("Yes")); assertTrue(Util.removeQuotes("Yes'").equals("Yes")); assertTrue(Util.removeQuotes("\"Yes\"").equals("Yes")); assertTrue(Util.removeQuotes("\"Yes").equals("Yes")); assertTrue(Util.removeQuotes("Yes\"").equals("Yes")); assertTrue(Util.removeQuotes(" Yes").equals(" Yes")); assertTrue(Util.removeQuotes(" 'Yes").equals(" 'Yes")); assertTrue(Util.removeQuotes(" 'Yes'").equals(" 'Yes")); } public void testNumDecimals(){ assertTrue(Util.hasMaxDecimals(new BigDecimal("0"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("0.0"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("0.00"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("1"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("100"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("1.0"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("1.12"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("100.1"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("100.23"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("-100"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("-1.0"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("-1.12"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("-100.1"), 2)); assertTrue(Util.hasMaxDecimals(new BigDecimal("-100.23"), 2)); assertFalse(Util.hasMaxDecimals(new BigDecimal("-100.234"), 2)); assertFalse(Util.hasMaxDecimals(new BigDecimal("1.234"), 2)); assertFalse(Util.hasMaxDecimals(new BigDecimal("1.2345"), 2)); assertFalse(Util.hasMaxDecimals(new BigDecimal("0.000"), 2)); assertFalse(Util.hasMaxDecimals(new BigDecimal("-0.000"), 2)); assertFalse(Util.hasMaxDecimals(new BigDecimal("-0.0000"), 2)); boolean hasThrownEx = false; try { Util.hasMaxDecimals(new BigDecimal("23.23"), 0); } catch (Throwable ex){ hasThrownEx = true; } assertTrue(hasThrownEx); } public void testHasNumDecimals(){ testHasNumDecimals("100", 0, PASS); testHasNumDecimals("999.82", 2, PASS); testHasNumDecimals("100.1", 1, PASS); testHasNumDecimals("-89", 0, PASS); testHasNumDecimals("-89.56321", 5, PASS); testHasNumDecimals("8.1234567890", 10, PASS); testHasNumDecimals("-89.56321", 4, FAIL); } public void testWithNoSpaces(){ testWithNoSpacesSuccess("Is Coder Key", "IsCoderKey"); } public void testBuildTimeZone(){ testTimeZoneSuccess("GMT"); testTimeZoneSuccess("America/Halifax"); testTimeZoneSuccess(" GMT "); testTimeZoneSuccess("PST"); testTimeZoneFailure("Pacific"); testTimeZoneFailure(""); testTimeZoneFailure(null); } public void testInitialCapital(){ testCap("blah", "Blah"); testCap(" blah", " blah"); testCap(" blah ", " blah "); testCap("Blah", "Blah"); testCap("b", "B"); testCap("b ", "B "); //failures testCapFails("blah", "blah"); testCapFails("blah", "BLAH"); testCapFails("blah", "Blah "); testCapFails("blah", " Blah"); //testCapFails(" ", "B "); fails } public void testQuote(){ assertTrue(Util.quote("blah").equals("'blah'")); assertTrue(Util.quote("").equals("''")); assertTrue(Util.quote(null).equals("'null'")); assertTrue(Util.quote(" ").equals("' '")); char[] word = null; assertTrue(Util.quote(word).equals("'null'")); char[] word2 = {'a', 'b'}; assertTrue(Util.quote(word2).startsWith("'[C@")); //arrays of primitives don't work well String thing = null; assertTrue(Util.quote(thing).equals("'null'")); List<String> names = Arrays.asList("blah", null); assertTrue(Util.quote(names).equals("'[blah, null]'")); } // FIXTURE // protected void setUp(){ } /** Re-set test objects. */ protected void tearDown() { } // PRIVATE // private static final String INPUT = "this is silly"; private static final String SUBSTR = " is "; private static final String REPLACEMENT = " *IS* "; private static final String RESULT = "this *IS* silly"; private static final String NL = Consts.NEW_LINE; private static final boolean PASS = true; private static final boolean FAIL = false; private static final Logger fLogger = Util.getLogger(TESTUtil.class); /** Tests conditions which should generate an exception. */ private void testReplaceError(String aInput, String aOld, String aNew){ boolean hasError = false; try { Util.replace(aInput, aOld, aNew); } catch (Throwable ex){ hasError = true; } if ( ! hasError ){ fail( "Input : " + Util.quote(aInput) + " Old : " + Util.quote(aOld) + " New : " + Util.quote(aNew) ); } } private void testReplaceSuccess( String aInput, String aSubstr, String aReplacement, String aExpectedResult ){ String result = Util.replace(aInput, aSubstr, aReplacement); if ( ! result.equals(aExpectedResult) ) { fail( Util.quote(result) + " does not equal expected result : " + Util.quote(aExpectedResult) ); } } private void testReplaceFailure( String aInput, String aSubstr, String aReplacement, String aExpectedMismatch ){ String result = Util.replace(aInput, aSubstr, aReplacement); if ( result.equals(aExpectedMismatch) ) { fail( Util.quote(result) + " equals, but expected mismatch : " + Util.quote(aExpectedMismatch) ); } } private void testLogOnePerLineSucceed(Collection aInput, String aExpectedMatch){ String result = Util.logOnePerLine(aInput); if( ! result.equals(aExpectedMatch) ){ fail( Util.quote(result) + " doesn't equal, but expected match : " + Util.quote(aExpectedMatch) ); } } private void testLogOnePerLineSucceed(Map aInput, String aExpectedMatch){ String result = Util.logOnePerLine(aInput); if( ! result.equals(aExpectedMatch) ){ fail( Util.quote(result) + " doesn't equal, but expected match : " + Util.quote(aExpectedMatch) ); } } private void testWithNoSpacesSuccess(String aInput, String aExpectedMatch){ String result = Util.withNoSpaces(aInput); if( ! result.equals(aExpectedMatch) ){ fail( Util.quote(result) + " doesn't equal, but expected match : " + Util.quote(aExpectedMatch) ); } } private void testTimeZoneSuccess(String aTimeZone){ Util.buildTimeZone(aTimeZone); } private void testTimeZoneFailure(String aTimeZone){ try { Util.buildTimeZone(aTimeZone); fail("Expected failure for time zone " + Util.quote(aTimeZone)); } catch (Throwable ex){ //expected failure } } private void testCap(String aInput, String aExpectedValue){ String value = Util.withInitialCapital(aInput); assertTrue( value.equals(aExpectedValue)); } private void testCapFails(String aInput, String aExpectedValue){ String value = Util.withInitialCapital(aInput); assertFalse( value.equals(aExpectedValue)); } private void testHasNumDecimals(String aAmount, int aNumDecimals, boolean aSucceed){ BigDecimal amount = new BigDecimal(aAmount); if (aSucceed){ assertTrue(Util.hasNumDecimals(amount, aNumDecimals)); } else { assertFalse(Util.hasNumDecimals(amount, aNumDecimals)); } } private static void log(Object aObject){ System.out.println(String.valueOf(aObject)); } }
import java.util.Scanner; public class exer27 { public static void main(String[] args) { Scanner input = new Scanner(System.in); while(true) { int i = 0; double valor = 1;; double total = 0; double din; System.out.println("PS: Para encerrar digite 0"); System.out.println("Lojas Tabajara"); while(valor != 0) { i++; System.out.println("Valor do " + i + " produto:"); valor = input.nextDouble(); total = total + valor; System.out.println("Produto " + i + ": R$ " + valor); if(valor == 0) System.out.println("Compra finalizada!"); } System.out.println("Total R$ " + total); System.out.println("Valor fornecido em dinheiro: "); din = input.nextDouble(); System.out.println("Dinheiro: "); double troco = din-total; System.out.println("Troco: R$ " + troco); } } }
package com.study.jpa.repository; import com.study.jpa.entity.Composite; import com.study.jpa.entity.CompositePk; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by francis on 2015. 12. 2.. */ public interface CompositeRepository extends JpaRepository<Composite, CompositePk> { }
/** * Copyright (c) 2004-2019 QOS.ch * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.slf4j.helpers; import java.io.ObjectStreamException; import java.io.Serializable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.event.Level; /** * An abstract implementation which delegates actual logging work to the * {@link #handleNormalizedLoggingCall(Level, Marker, String, Object[], Throwable)} method. * * @author Ceki G&uuml;lc&uuml; * @since 2.0 */ public abstract class AbstractLogger implements Logger, Serializable { private static final long serialVersionUID = -2529255052481744503L; protected String name; public String getName() { return name; } /** * Replace this instance with a homonymous (same name) logger returned * by LoggerFactory. Note that this method is only called during * deserialization. * * <p> * This approach will work well if the desired ILoggerFactory is the one * referenced by {@link org.slf4j.LoggerFactory} However, if the user manages its logger hierarchy * through a different (non-static) mechanism, e.g. dependency injection, then * this approach would be mostly counterproductive. * * @return logger with same name as returned by LoggerFactory * @throws ObjectStreamException */ protected Object readResolve() throws ObjectStreamException { // using getName() instead of this.name works even for // NOPLogger return LoggerFactory.getLogger(getName()); } @Override public void trace(String msg) { if (isTraceEnabled()) { handle_0ArgsCall(Level.TRACE, null, msg, null); } } @Override public void trace(String format, Object arg) { if (isTraceEnabled()) { handle_1ArgsCall(Level.TRACE, null, format, arg); } } @Override public void trace(String format, Object arg1, Object arg2) { if (isTraceEnabled()) { handle2ArgsCall(Level.TRACE, null, format, arg1, arg2); } } @Override public void trace(String format, Object... arguments) { if (isTraceEnabled()) { handleArgArrayCall(Level.TRACE, null, format, arguments); } } @Override public void trace(String msg, Throwable t) { if (isTraceEnabled()) { handle_0ArgsCall(Level.TRACE, null, msg, t); } } @Override public void trace(Marker marker, String msg) { if (isTraceEnabled(marker)) { handle_0ArgsCall(Level.TRACE, marker, msg, null); } } @Override public void trace(Marker marker, String format, Object arg) { if (isTraceEnabled(marker)) { handle_1ArgsCall(Level.TRACE, marker, format, arg); } } @Override public void trace(Marker marker, String format, Object arg1, Object arg2) { if (isTraceEnabled(marker)) { handle2ArgsCall(Level.TRACE, marker, format, arg1, arg2); } } @Override public void trace(Marker marker, String format, Object... argArray) { if (isTraceEnabled(marker)) { handleArgArrayCall(Level.TRACE, marker, format, argArray); } } public void trace(Marker marker, String msg, Throwable t) { if (isTraceEnabled(marker)) { handle_0ArgsCall(Level.TRACE, marker, msg, t); } } public void debug(String msg) { if (isDebugEnabled()) { handle_0ArgsCall(Level.DEBUG, null, msg, null); } } public void debug(String format, Object arg) { if (isDebugEnabled()) { handle_1ArgsCall(Level.DEBUG, null, format, arg); } } public void debug(String format, Object arg1, Object arg2) { if (isDebugEnabled()) { handle2ArgsCall(Level.DEBUG, null, format, arg1, arg2); } } public void debug(String format, Object... arguments) { if (isDebugEnabled()) { handleArgArrayCall(Level.DEBUG, null, format, arguments); } } public void debug(String msg, Throwable t) { if (isDebugEnabled()) { handle_0ArgsCall(Level.DEBUG, null, msg, t); } } public void debug(Marker marker, String msg) { if (isDebugEnabled(marker)) { handle_0ArgsCall(Level.DEBUG, marker, msg, null); } } public void debug(Marker marker, String format, Object arg) { if (isDebugEnabled(marker)) { handle_1ArgsCall(Level.DEBUG, marker, format, arg); } } public void debug(Marker marker, String format, Object arg1, Object arg2) { if (isDebugEnabled(marker)) { handle2ArgsCall(Level.DEBUG, marker, format, arg1, arg2); } } public void debug(Marker marker, String format, Object... arguments) { if (isDebugEnabled(marker)) { handleArgArrayCall(Level.DEBUG, marker, format, arguments); } } public void debug(Marker marker, String msg, Throwable t) { if (isDebugEnabled(marker)) { handle_0ArgsCall(Level.DEBUG, marker, msg, t); } } public void info(String msg) { if (isInfoEnabled()) { handle_0ArgsCall(Level.INFO, null, msg, null); } } public void info(String format, Object arg) { if (isInfoEnabled()) { handle_1ArgsCall(Level.INFO, null, format, arg); } } public void info(String format, Object arg1, Object arg2) { if (isInfoEnabled()) { handle2ArgsCall(Level.INFO, null, format, arg1, arg2); } } public void info(String format, Object... arguments) { if (isInfoEnabled()) { handleArgArrayCall(Level.INFO, null, format, arguments); } } public void info(String msg, Throwable t) { if (isInfoEnabled()) { handle_0ArgsCall(Level.INFO, null, msg, t); } } public void info(Marker marker, String msg) { if (isInfoEnabled(marker)) { handle_0ArgsCall(Level.INFO, marker, msg, null); } } public void info(Marker marker, String format, Object arg) { if (isInfoEnabled(marker)) { handle_1ArgsCall(Level.INFO, marker, format, arg); } } public void info(Marker marker, String format, Object arg1, Object arg2) { if (isInfoEnabled(marker)) { handle2ArgsCall(Level.INFO, marker, format, arg1, arg2); } } public void info(Marker marker, String format, Object... arguments) { if (isInfoEnabled(marker)) { handleArgArrayCall(Level.INFO, marker, format, arguments); } } public void info(Marker marker, String msg, Throwable t) { if (isInfoEnabled(marker)) { handle_0ArgsCall(Level.INFO, marker, msg, t); } } public void warn(String msg) { if (isWarnEnabled()) { handle_0ArgsCall(Level.WARN, null, msg, null); } } public void warn(String format, Object arg) { if (isWarnEnabled()) { handle_1ArgsCall(Level.WARN, null, format, arg); } } public void warn(String format, Object arg1, Object arg2) { if (isWarnEnabled()) { handle2ArgsCall(Level.WARN, null, format, arg1, arg2); } } public void warn(String format, Object... arguments) { if (isWarnEnabled()) { handleArgArrayCall(Level.WARN, null, format, arguments); } } public void warn(String msg, Throwable t) { if (isWarnEnabled()) { handle_0ArgsCall(Level.WARN, null, msg, t); } } public void warn(Marker marker, String msg) { if (isWarnEnabled(marker)) { handle_0ArgsCall(Level.WARN, marker, msg, null); } } public void warn(Marker marker, String format, Object arg) { if (isWarnEnabled(marker)) { handle_1ArgsCall(Level.WARN, marker, format, arg); } } public void warn(Marker marker, String format, Object arg1, Object arg2) { if (isWarnEnabled(marker)) { handle2ArgsCall(Level.WARN, marker, format, arg1, arg2); } } public void warn(Marker marker, String format, Object... arguments) { if (isWarnEnabled(marker)) { handleArgArrayCall(Level.WARN, marker, format, arguments); } } public void warn(Marker marker, String msg, Throwable t) { if (isWarnEnabled(marker)) { handle_0ArgsCall(Level.WARN, marker, msg, t); } } public void error(String msg) { if (isErrorEnabled()) { handle_0ArgsCall(Level.ERROR, null, msg, null); } } public void error(String format, Object arg) { if (isErrorEnabled()) { handle_1ArgsCall(Level.ERROR, null, format, arg); } } public void error(String format, Object arg1, Object arg2) { if (isErrorEnabled()) { handle2ArgsCall(Level.ERROR, null, format, arg1, arg2); } } public void error(String format, Object... arguments) { if (isErrorEnabled()) { handleArgArrayCall(Level.ERROR, null, format, arguments); } } public void error(String msg, Throwable t) { if (isErrorEnabled()) { handle_0ArgsCall(Level.ERROR, null, msg, t); } } public void error(Marker marker, String msg) { if (isErrorEnabled(marker)) { handle_0ArgsCall(Level.ERROR, marker, msg, null); } } public void error(Marker marker, String format, Object arg) { if (isErrorEnabled(marker)) { handle_1ArgsCall(Level.ERROR, marker, format, arg); } } public void error(Marker marker, String format, Object arg1, Object arg2) { if (isErrorEnabled(marker)) { handle2ArgsCall(Level.ERROR, marker, format, arg1, arg2); } } public void error(Marker marker, String format, Object... arguments) { if (isErrorEnabled(marker)) { handleArgArrayCall(Level.ERROR, marker, format, arguments); } } public void error(Marker marker, String msg, Throwable t) { if (isErrorEnabled(marker)) { handle_0ArgsCall(Level.ERROR, marker, msg, t); } } private void handle_0ArgsCall(Level level, Marker marker, String msg, Throwable t) { handleNormalizedLoggingCall(level, marker, msg, null, t); } private void handle_1ArgsCall(Level level, Marker marker, String msg, Object arg1) { handleNormalizedLoggingCall(level, marker, msg, new Object[] { arg1 }, null); } private void handle2ArgsCall(Level level, Marker marker, String msg, Object arg1, Object arg2) { if (arg2 instanceof Throwable) { handleNormalizedLoggingCall(level, marker, msg, new Object[] { arg1 }, (Throwable) arg2); } else { handleNormalizedLoggingCall(level, marker, msg, new Object[] { arg1, arg2 }, null); } } private void handleArgArrayCall(Level level, Marker marker, String msg, Object[] args) { Throwable throwableCandidate = MessageFormatter.getThrowableCandidate(args); if (throwableCandidate != null) { Object[] trimmedCopy = MessageFormatter.trimmedCopy(args); handleNormalizedLoggingCall(level, marker, msg, trimmedCopy, throwableCandidate); } else { handleNormalizedLoggingCall(level, marker, msg, args, null); } } abstract protected String getFullyQualifiedCallerName(); /** * Given various arguments passed as parameters, perform actual logging. * * <p>This method assumes that the separation of the args array into actual * objects and a throwable has been already operated. * * @param level the SLF4J level for this event * @param marker The marker to be used for this event, may be null. * @param messagePattern The message pattern which will be parsed and formatted * @param arguments the array of arguments to be formatted, may be null * @param throwable The exception whose stack trace should be logged, may be null */ abstract protected void handleNormalizedLoggingCall(Level level, Marker marker, String messagePattern, Object[] arguments, Throwable throwable); }
package com.zhuzhixu.adminproject.interceptor; import com.zhuzhixu.adminproject.entity.UserEntity; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object user_login = request.getSession().getAttribute("USER_LOGIN"); if(user_login == null || ((UserEntity)user_login).getUsername()==null || ((UserEntity)user_login).getUsername().isEmpty()){ request.getSession().invalidate(); response.sendRedirect("/login.do"); return false; } return true; } }
package com.formssi.frms.system.service; import java.util.List; import java.util.Map; import com.formssi.frms.common.domain.Tree; import com.formssi.frms.system.domain.SysDept; /** * 部门管理 * * @author chglee * @email 1992lcg@163.com * @date 2017-09-27 14:28:36 */ public interface DeptService { SysDept get(Long deptId); List<SysDept> list(Map<String, Object> map); int count(Map<String, Object> map); int save(SysDept sysDept); int update(SysDept sysDept); int remove(Long deptId); int batchRemove(Long[] deptIds); Tree<SysDept> getTree(); boolean checkDeptHasUser(Long deptId); }
package comp3111.webscraper; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Date; import javafx.scene.control.Hyperlink; /** * Class representing an item that has been scraped from a website. * * @author Kaushal Kalyanasundaram, Kenny Li and Ruben Wijkmark */ public class Item { private String title ; private double price ; private Hyperlink url ; private Date itemDate ; private String site ; /** * Get the title of the item * @return the items title */ public String getTitle() { return title; } /** * Set the title of the item * @param title - the title to be set */ public void setTitle(String title) { this.title = title; } /** * Get the price of the item * @return - the items price */ public double getPrice() { return price; } /** * Set the price of the item * @param price - the price to be set */ public void setPrice(double price) { this.price = price; } /** * Get the url of the item * * @return the items url */ public Hyperlink getUrl() { return url; } /** * Sets the Url of the item. * * @param url - the url to be set. */ public void setUrl(String url) { this.url = new Hyperlink(url); this.url.setOnAction(e -> { if(Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI(url)); } catch (IOException e1) { e1.printStackTrace(); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); } /** * Get the date of the item. * * @return the items date. */ public Date getItemDate() { return itemDate; } /** * Sets the date of the item. * * @param itemDate - the date to be set. */ public void setItemDate(Date itemDate) { this.itemDate = itemDate; } /** * Gets the site of the item * * @return the items site */ public String getSite() { return site; } /** * Sets the site of the item. * @param site the site to be set */ public void setSite(String site) { this.site = site; } }
package com.cht.iot.demo.pi; public class HoldingTrigger<T> { T data; long last; boolean updated = false; long threshold = 100L; Callback<T> callback; Thread thread; public HoldingTrigger(Callback<T> callback) { this.callback = callback; thread = new Thread(new Runnable() { public void run() { watch(); } }); thread.start(); } public void destroy() { thread.interrupt(); } public void setThreshold(long threshold) { this.threshold = threshold; } public synchronized void update(T data) { this.data = data; last = System.currentTimeMillis(); updated = true; notify(); } protected void watch() { try { for (;;) { synchronized (this) { if (updated == false) { wait(); } } while ((System.currentTimeMillis() - last) < threshold) { synchronized (this) { wait(threshold); } } synchronized (this) { callback.onData(data); updated = false; } } } catch (InterruptedException ie) { } } interface Callback<T> { void onData(T data); } }
/* * 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 Josue * Clase tomada del libro del curso: * No se utilizaron todos los métodos ya que no todos eran necesarios. * Se realizó la interface ya que a pesar que ya existe la clase PriorityQueue, el ejercicio exigía usar una interface que funcionara de manera similar. * @param <E> */ public interface PriorityQueue<E extends Comparable<E>> { /** * * @return */ public E getFirst(); // pre: La cola no está vacía. // post: Devuelve el valor mínimo de la cola. /** * * @return */ public E remove(); // pre: La cola no está vacía. // post: Remueve el valor mínimo de la cola y lo devuelve. /** * * @param value */ public void add(E value); // pre: El valor a añadir existe (no es nulo). // post: El valor es añadido en su posición respectiva de la cola. /** * * @return */ public boolean isEmpty(); // post: Muestra si la cola está vacía (True) o no (False). /** * * @return */ public int size(); // post: Devuelve el número de elementos de la cola. /** * */ public void clear(); // post: Vacía la cola; la deja sin elementos. }
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.UUID; public class RegisterServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { UserBean db = new UserBean(); String User_id= UUID.randomUUID().toString().replaceAll("-", ""); db.setUserid(User_id); db.setUsername(req.getParameter("name")); db.setPassword(req.getParameter("password")); db.setEmail(req.getParameter("email")); db.setGender(req.getParameter("gender")); //System.out.println(db.getUsername()); PrintWriter out = resp.getWriter(); //存入数据库 if(db.CreateUser(db.getUserid(), db.getUsername(), db.getPassword(), db.getEmail(), db.getGender())){ out.write("register success"); }else { out.write("register fail"); } out.close(); } }
/** * Created by likz on 2023/1/30 * * @author likz */ public class AppleMinBag { public static int minBags(int apple) { int bag = apple / 8; int rest = apple - bag * 8; if (rest == 0) { return bag; } else { while (bag >= 0) { if (rest % 6 == 0) { bag += rest / 6; return bag; } else { bag--; rest += 8; } } } return -1; } public static int improvementMinBags(int apple) { if (apple < 18) { return apple == 0 ? 0 : (apple == 6 || apple == 8) ? 1 : (apple == 12 || apple == 14 || apple == 16) ? 2 : -1; } return apple % 2 == 0 ? (apple - 18) / 8 + 3 : -1; } public static void main(String[] args) { // for (int apple = 1; apple < 200; apple++) { // System.out.println(apple + " : " + minBags(apple)); // } System.out.println("test begin"); for (int apple = 1; apple < 200; apple++) { if (minBags(apple) != improvementMinBags(apple)) { System.out.println("Oops!"); break; } } System.out.println("test end"); } }
package at.ebinterface.validation.web.pages.convert.result; import org.apache.wicket.markup.html.WebPage; import at.ebinterface.validation.web.pages.BasePage; /** * Used to show the results of a transformation from ebInterface to XRechnung * * @author Philip Helger */ public final class ResultPageEbiToXRechnung extends BasePage { public ResultPageEbiToXRechnung (final byte [] xml, final String sErrorLog, final Class <? extends WebPage> returnPage) { final ResultPanelEbiToXRechnung resultPanel = new ResultPanelEbiToXRechnung ("ebiToXRechnungResultPanel", xml, sErrorLog, returnPage); add (resultPanel); } }
package test.M; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class Hibernate { public static void main(String[] args) { Person decker = new Person(); decker.setID(101); decker.setFname("Peter"); decker.setLname("Decker"); Configuration con = new Configuration().configure().addAnnotatedClass(Person.class); ServiceRegistry reg = new ServiceRegistryBuilder().applySettings(con.getProperties()).buildServiceRegistry(); SessionFactory sf = con.buildSessionFactory(reg); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); session.save(decker); tx.commit(); } }
package com.fpmislata.banco.core.json; /** * * @author Samuel Lao */ public interface JsonTransformer { String objectToJson(Object o); <T> T jsonToObject(String json, Class <T> clazz); }
package dev.soapy.worldheightbooster.mixin; import dev.soapy.worldheightbooster.WorldHeightBooster; import dev.soapy.worldheightbooster.config.WorldHeightConfig; import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import java.util.List; import java.util.Set; public class FabricApiWorkaroundPlugin implements IMixinConfigPlugin { public boolean shouldUseBigChunkPacket = false; @Override public void onLoad(String mixinPackage) { WorldHeightConfig.handleConfig(WorldHeightBooster.CONFIG_PATH.resolve(WorldHeightBooster.MOD_ID + ".json")); if(WorldHeightBooster.WORLD_HEIGHT > 512) { shouldUseBigChunkPacket = true; WorldHeightBooster.LOGGER.warning("WorldHeightBooster is running in experimental mode, due to a default world height set above 512. This is incompatible with Fabric API."); WorldHeightBooster.LOGGER.warning("Do not load worlds created in higher world heights on lower world heights."); } } @Override public String getRefMapperConfig() { return null; } @Override public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { return (!targetClassName.startsWith("bigchunkpacket")) || shouldUseBigChunkPacket; } @Override public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) { } @Override public List<String> getMixins() { return null; } @Override public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } @Override public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } }
package com.jonathan.user.Infrastructure.Persistence.JPA; import com.jonathan.user.Domain.Model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; public interface IJpaUserRepository extends JpaRepository<User, Integer> { @Query("SELECT u FROM User u WHERE u.email=:email") User findByEmail(String email); }
package com.example.java; public class JavaStudy02 { static int scopeAge = 100; public static void main(String[] args) { /** 백기선 선생님의 자바 스터디 2주차 1) 프리미티브 타입 종류와 값의 범위 그리고 기본 값 2) 프리미티브 타입과 레퍼런스 타입 3) 리터럴 4) 변수 선언 및 초기화하는 방법 5) 변수의 스코프와 라이프타임 6) 타입 변환, 캐스팅 그리고 타입 프로모션 7) 1차 및 2차 배열 선언하기 8) 타입 추론, var */ // 기본형(원시형)의 종류는 정수, 실수, 논리, 문자로 나눠진다 // 정수 byte b = 1; // 초기값 0 System.out.println(Byte.MAX_VALUE); // 127 System.out.println(Byte.MIN_VALUE); // -128 short s = 1; // 초기값 0 int i = 1; // 초기값 0 long l = 0L; // 초기값 0L // 실수 float f = 0f; // 초기값 0f double d = 0d; // 초기값 0d // 논리 boolean is = false; // 초기값 false // 문자 char c = 'A'; // 초기값 '\u0000' RefTest ref = new RefTest(); RefTest ref2 = ref; System.out.println(ref); System.out.println(ref2); System.out.println("===================="); System.out.println(ref.getStr1()); System.out.println(ref2.getStr1()); System.out.println("===================="); ref2.setStr1("chagne_str1"); System.out.println(ref.getStr1()); System.out.println(ref2.getStr1()); int age; // int 타입의 age 변수 선언 double money; // double 타입의 money 변수 선언 int x, y, z; // 같은 타입의 여러개 동시 선언 // 초기화 방법도 간단하다 대입 연산자 = 를 사용해서 값을 명시하면 끝. 변수에 초기값을 주는 걸 변수의 초기화라고 뜻한다. age = 10; int test = 0; /** 자바 변수 명명 규칙이 존재 1. 첫번째 글자는 문자이거나 '$', '_' 만 가능하고 숫자로 시작할 순 없다. 2. 영어 대소문자가 구분된다. 대소문자가 다르면 다른 변수이다 (strName 과 strname 은 다른 변수이다) 3. 카멜케이스라는 번역하면 낙타법으로 첫문자는 영어소문자이면서 다른 단어가 붙을 경우 대문자로 표기한다 firstName, maxSpeed 등등 4. 변수의 길이 제한은 없다. (변수의 명이 너무 길어지는 경우도 흔하다. 보통 용어사전으로 약어를 정하고 약어를 이어붙인다. firstName -> firNm 혹은 middleName -> midNm) 5. 예악어로 사용할 수 없다. (변수명에 boolean, byte, private 같은걸 사용 못한다) */ int scopeAge = 30; System.out.println(scopeAge); fnScope(); System.out.println(scopeAge); // 클래스 변수 접근 String url = CmmnConstant.API_CALL_URL; String callNum = CmmnConstant.SEOUL_LOCAL_NUMBER; System.out.println(url); System.out.println(callNum); // 타입 변환 fnCast(); // 강제 변환 fnExpCast(); } public static void fnScope () { int scopeAge = 20; System.out.println(scopeAge); } // 자동 변환 예 public static void fnCast() { byte byteVal = 10; int intVal = byteVal; // byte -> int System.out.println(intVal); char charVal = '가'; intVal = charVal; // char -> int System.out.println(intVal); intVal = 100; long longVal = intVal; // int -> long System.out.println(intVal); intVal = 200; double douVal = intVal; // int -> double System.out.println(intVal); } public static void fnExpCast() { byte byteVal = 10; short shortVal = 20; int intVal = 100; long longVal = 1000000L; byteVal = (byte) shortVal; shortVal = (short) intVal; intVal = (int) longVal; System.out.println("byte : " + byteVal); // 20 System.out.println("short : " + shortVal); // 100 System.out.println("int : " + intVal); // 1000000 // 넘치는 값으로 강제 변환하면? shortVal = 32767; intVal = 2100000000; longVal = 2200000000L; byteVal = (byte) shortVal; shortVal = (short) intVal; intVal = (int) longVal; System.out.println("byte : " + byteVal); // -1 System.out.println("short : " + shortVal); // 29952 System.out.println("int : " + intVal); // -2094967296 fnArray(); } public static void fnArray() { // 수학 평균 점수를 구해보자 int sum = 0; int score01 = 80; // 1번 학생 int score02 = 80; // 2번 학생 int score03 = 80; // 3번 학생 int score04 = 80; int score05 = 80; // .... int score26 = 80; int score27 = 80; int score28 = 80; int score29 = 80; // 29번 학생 int score30 = 80; // 30번 학생 sum += score01; sum += score02; sum += score03; // ... sum += score29; sum += score30; int avg = sum / 30; // int[] scoreArr = {80, 80, 70, 75, 90, ... , 60, 100}; int[] arr; int arr02[]; arr = new int[]{100, 90, 80, 70, 60}; System.out.println(); // 2차 배열 int[][] doubleArr = new int[3][30]; // 3차 배열 int[][][] triArr = new int[3][5][10]; int[][][] scoreArr = { { {100, 90, 80, 70, 80} , {90, 80, 70, 60, 10} , {90, 80, 70, 60, 10} }, { {100, 90, 80, 70, 80} , {90, 80, 70, 60, 10} , {90, 80, 70, 60, 10} }, { {100, 90, 80, 70, 80} , {90, 80, 70, 60, 10} , {90, 80, 70, 60, 10} } }; System.out.println(scoreArr[0][0][0]); } } class RefTest { private String str1 = ""; private String str2 = ""; public RefTest() { this.str1 = "111"; this.str2 = "222"; } public void setStr1 (String str) { this.str1 = str; } public void setStr2 (String str) { this.str2 = str; } public String getStr1 () { return this.str1; } public String getStr2 () { return this.str2; } }
package com.awrzosek.ski_station.cong_prize_management; import com.awrzosek.ski_station.basic.BasicConsts; import java.math.BigDecimal; import java.math.RoundingMode; public class QueueManager { public static int CLIENTS_IN_MINUTE; public Long calculateWaitTime() throws StabilityException { BigDecimal utilization = BigDecimal.valueOf(CLIENTS_IN_MINUTE / BasicConsts.SERVICE_RATE_PER_MINUTE); if (utilization.compareTo(BigDecimal.ONE) < 0) { BigDecimal divisor = BigDecimal.valueOf(2 * BasicConsts.SERVICE_RATE_PER_MINUTE * (1 - utilization.doubleValue())); BigDecimal quotient = utilization.divide(divisor, 10, RoundingMode.HALF_UP); return quotient.multiply(BigDecimal.valueOf(60)).longValue(); } else throw new StabilityException("Uwaga! Długi czas oczekiwania!"); } }
package com.jayqqaa12.pop; import java.util.ArrayList; import java.util.List; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.jayqqaa12.abase.kit.ManageKit; class MenuAdapter extends BaseAdapter { List<Menu> data = new ArrayList<Menu>(); public MenuAdapter(){ data.add(new Menu(R.drawable.icon_item_directory, "toc", Menu.ATION_TOC)); data.add(new Menu(R.drawable.icon_item_bright, "night", Menu.ATION_NIGHT)); data.add(new Menu(R.drawable.icon_bookshelf_set_up, "setting", Menu.ATION_SETTING)); data.add(new Menu(R.drawable.icon_btn_font_big, "font_add", Menu.ATION_FONT_ADD)); data.add(new Menu(R.drawable.icon_btn_font_small, "font_dim", Menu.ATION_FONT_DIM)); data.add(new Menu(R.drawable.icon_item_progress, "progress", Menu.ATION_PROGRESS)); } @Override public int getCount() { return data.size(); } @Override public Menu getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = ManageKit.getInflater().inflate(R.layout.test_menu_item, null); TextView tv = (TextView) view.findViewById(R.id.m_tv); ImageView iv = (ImageView) view.findViewById(R.id.m_iv); tv.setText(getItem(position).text); iv.setImageResource(getItem(position).icon); return view; } }
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models; import java.util.Date; public class ExerciseAccountInfo { public int exerciseid; public String exerciseName; public int sets; public int reps; public double weight; public Date date; public String exerciseTypeDecr; public String username; public int getExerciseid() { return exerciseid; } public void setExerciseid(int exerciseid) { this.exerciseid = exerciseid; } public String getExerciseName() { return exerciseName; } public void setExerciseName(String exerciseName) { this.exerciseName = exerciseName; } public int getSets() { return sets; } public void setSets(int sets) { this.sets = sets; } public int getReps() { return reps; } public void setReps(int reps) { this.reps = reps; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getExerciseTypeDecr() { return exerciseTypeDecr; } public void setExerciseTypeDecr(String exerciseTypeDecr) { this.exerciseTypeDecr = exerciseTypeDecr; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((date == null) ? 0 : date.hashCode()); result = prime * result + ((exerciseName == null) ? 0 : exerciseName.hashCode()); result = prime * result + ((exerciseTypeDecr == null) ? 0 : exerciseTypeDecr.hashCode()); result = prime * result + exerciseid; result = prime * result + reps; result = prime * result + sets; result = prime * result + ((username == null) ? 0 : username.hashCode()); long temp; temp = Double.doubleToLongBits(weight); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ExerciseAccountInfo other = (ExerciseAccountInfo) obj; if (date == null) { if (other.date != null) return false; } else if (!date.equals(other.date)) return false; if (exerciseName == null) { if (other.exerciseName != null) return false; } else if (!exerciseName.equals(other.exerciseName)) return false; if (exerciseTypeDecr == null) { if (other.exerciseTypeDecr != null) return false; } else if (!exerciseTypeDecr.equals(other.exerciseTypeDecr)) return false; if (exerciseid != other.exerciseid) return false; if (reps != other.reps) return false; if (sets != other.sets) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; if (Double.doubleToLongBits(weight) != Double.doubleToLongBits(other.weight)) return false; return true; } @Override public String toString() { return "ExerciseAccountInfo [exerciseid=" + exerciseid + ", exerciseName=" + exerciseName + ", sets=" + sets + ", reps=" + reps + ", weight=" + weight + ", date=" + date + ", exerciseTypeDecr=" + exerciseTypeDecr + ", username=" + username + "]"; } public ExerciseAccountInfo(int exerciseid, String exerciseName, int sets, int reps, double weight, Date date, String exerciseTypeDecr, String username) { super(); this.exerciseid = exerciseid; this.exerciseName = exerciseName; this.sets = sets; this.reps = reps; this.weight = weight; this.date = date; this.exerciseTypeDecr = exerciseTypeDecr; this.username = username; } public ExerciseAccountInfo() { super(); // TODO Auto-generated constructor stub } }
package tw.skyarrow.ehreader; /** * Created by SkyArrow on 2014/1/25. */ public class Constant { public static final String API_URL = "http://g.e-hentai.org/api.php"; public static final String API_URL_EX = "http://exhentai.org/api.php"; public static final String BASE_URL = "http://g.e-hentai.org"; public static final String BASE_URL_EX = "http://exhentai.org"; public static final String GALLERY_URL = "http://g.e-hentai.org/g/%d/%s"; public static final String GALLERY_URL_EX = "http://exhentai.org/g/%d/%s"; public static final String PHOTO_URL = "http://g.e-hentai.org/s/%s/%d-%d"; public static final String PHOTO_URL_EX = "http://exhentai.org/s/%s/%d-%d"; public static final String IMAGE_SEARCH_URL = "http://ul.e-hentai.org/image_lookup.php"; public static final String IMAGE_SEARCH_URL_EX = "http://ul.exhentai.org/image_lookup.php"; public static final String HATHDL_URL = "http://g.e-hentai.org/hathdler.php?gid=%d&t=%s"; public static final String THUMBNAIL_URL = "http://ehgt.org/t/%s/%s/%s_l.jpg"; public static final int PHOTO_PER_PAGE = 40; public static final String FOLDER_NAME = "ehreader"; public static final String AUTHOR_PAGE = "https://twitter.com/tommy351"; public static final String HOMEPAGE = "https://github.com/tommy351/ehreader-android"; public static final String FORKPAGE = "https://github.com/xefir/ehreader-android"; }
package LC200_400.LC300_350; public class LC319_Bulb_Switcher { public int bulbSwitch(int n) { return (int) (Math.sqrt(n)); } }
package com.tencent.map.lib.thread; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy; import java.util.concurrent.TimeUnit; public class LowThreadExecutor implements Executor { private final ThreadFactory a = new 1(this); private final BlockingQueue<Runnable> b = new LinkedBlockingQueue(20); public final Executor mExecutor = new ThreadPoolExecutor(5, 128, 1, TimeUnit.SECONDS, this.b, this.a, new DiscardOldestPolicy()); public void execute(Runnable runnable) { this.mExecutor.execute(runnable); } }
package com.tiandi.logistics.entity.pojo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; /** * <p> * 配送点管理 * </p> * * @author TP * @since 2020-11-30 */ @Data @EqualsAndHashCode(callSuper = true) @TableName("tp_distribution") @ApiModel(value="Distribution对象", description="配送点管理") public class Distribution extends BaseEntity { private static final long serialVersionUID = 1L; @TableId(value = "id_tp_distribution", type = IdType.AUTO) private Integer idTpDistribution; @ApiModelProperty(value = "配送点编码") private Integer idDistribution; @ApiModelProperty(value = "配送点名称") private String nameDistribution; @ApiModelProperty(value = "所属公司") private String nameCompany; @ApiModelProperty(value = "管理员代码") private Integer idAdmin; @ApiModelProperty(value = "管理员口令") private String passwordAdmin; @ApiModelProperty(value = "内部结算价格") private BigDecimal innerPrice; @ApiModelProperty(value = "上行站点") private String upDistributions; @ApiModelProperty(value = "下行站点") private String downDistributions; @ApiModelProperty(value = "是否为主站点(0.否,1.是)") private Integer isMainDistribution; @ApiModelProperty(value = "相关主站点") private String concernedMainDistribution; @ApiModelProperty(value = "经度") private String longitude; @ApiModelProperty(value = "纬度") private String latitude; @ApiModelProperty(value = "逻辑删除") private Integer isDelete; }
package LC200_400.LC250_300; import LeetCodeUtils.TreeNode; import org.junit.Test; import java.util.ArrayList; import java.util.List; public class LC257_Binary_Tree_Paths { @Test public void test() { TreeNode r1 = new TreeNode(1), r2 = new TreeNode(2), r3 = new TreeNode(3), r4 = new TreeNode(5); r1.left = r2; r1.right = r3; binaryTreePaths(r1); } List<String> res = new ArrayList<>(); StringBuilder sb = new StringBuilder(); public List<String> binaryTreePaths(TreeNode root) { if (root != null) dfs(root); return res; } void dfs(TreeNode root) { StringBuilder sbtem = new StringBuilder(sb); sb.append(root.val); StringBuilder sbtem2 = new StringBuilder(sb); sb.append("->"); if (root.left != null) dfs(root.left); if (root.right != null) dfs(root.right); if (root.right == null && root.left == null) { sb = sbtem2; //System.out.println(sb.toString()); res.add(sb.toString()); sb = sbtem; return; } sb = sbtem; } }
package slepec.hra.rozhrani.gui; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import javax.swing.border.TitledBorder; import slepec.Play; import slepec.hra.Hra; import slepec.hra.Scenar; import slepec.hra.UdalostHry; import slepec.hra.planek.prostor.vec.VecBatoh; import slepec.hra.rozhrani.IRozhrani; import slepec.util.Observer; /** * Graficke rozhrani programu<br /> * * @author Pavel Jurca, xjurp20@vse.cz * @version 2 */ public class GUI implements IRozhrani { private static final Logger logger = Play.globalLog.getLogger(GUI.class.getName()); private final CopyOnWriteArrayList<slepec.util.Observer> listeners; private Hra hra; private final String prompt; private java.util.Map<String, ImageIcon> imagesVec; private Timer timer; private JFrame frame; private DialogOkno oknoNapovedy; private DialogOkno oknoLogu; private JMenuBar menuBar; private JMenu mSoubor; private JMenu mNapoveda; private JPanel container; private JPanel levyContainer; private JPanel panelBatohu; private JPanel panelVystupu; private PanelPlanku panelPlanku; private JTextField txtFieldVstup; private JTextArea txtAreaVystup; private JLabel lblZadnyBatoh; private final URL planekURL; private final URL napovedaURL; private URL logURL; /** * Inicializace nove hry */ private class NovaHra implements ActionListener { @Override public void actionPerformed(ActionEvent e) { hra.ukonciHru(); //Hra vzdy ceka na vstup - proto ho musime uvolnit! wakeUp(); notifyObservers(UdalostHry.NOVAHRA); } } /** * Zobrazi informacni dialog "O programu" */ private class OProgramu implements ActionListener { private JLabel lbl; public OProgramu() { lbl = new JLabel( "<html>" + "<center><br /><h3>Copyleft 2013 Pavel Jurča</h3>" + "<a href='http://jurcapavel.cz'>" + "http://jurcapavel.cz</a><br />" + "<br /><br />.<br />" + "<i>půdorys domu © 2002 GSERVIS s.r.o.</i><br />" + "<i>překreslil © 2010 Pavel Jurča</i><br />" + ".<br />" + "<i>images courtesy of FreeDigitalPhotos.net</i><br />" + ".<br /></center>" + "</html>", JLabel.CENTER); lbl.setBorder( BorderFactory.createTitledBorder( BorderFactory.createEmptyBorder(24, 24, 24, 24), "Slepec", TitledBorder.CENTER, TitledBorder.TOP, new Font(Font.MONOSPACED, Font.BOLD, 57), new Color(69, 178, 224))); } @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(frame, lbl, "O programu", JOptionPane.PLAIN_MESSAGE); } } /** * Zobrazovani zbyvajiciho casu hry v titulku okna */ private class ZbyvaCasTimer implements ActionListener { @Override public void actionPerformed(ActionEvent e) { frame.setTitle(hra.toString() + " | " + String.format(" %d min : %02d sek", (hra.getZbyvaCas() / 1000) / 60, (hra.getZbyvaCas() / 1000) % 60)); } } public GUI(Hra hra, String prompt) { this.hra = hra; this.prompt = prompt; listeners = new CopyOnWriteArrayList<>(); imagesVec = new HashMap<>(); timer = new Timer(1000, new ZbyvaCasTimer()); planekURL = GUI.class.getResource("/slepec/zdroje/planek-hry.png"); napovedaURL = GUI.class.getResource("/slepec/zdroje/napoveda.html"); initFrame(); hra.attachObserver(GUI.this); } private void initFrame() { loadImages(); frame = new JFrame(hra.toString()); container = new JPanel(new GridLayout(1, 2, 6, 6)); container.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6)); //prava strana formulare panelPlanku = new PanelPlanku(planekURL); //levyContainer => panel batohu + vystup + vstup levyContainer = new JPanel(); levyContainer.setLayout(new BoxLayout(levyContainer, BoxLayout.Y_AXIS)); levyContainer.setPreferredSize(new Dimension(550, 550)); lblZadnyBatoh = new JLabel("nemate zadny batoh", JLabel.CENTER); panelBatohu = new JPanel(new GridLayout(1, 1, 10, 10)); panelBatohu.setPreferredSize(new Dimension(550, 75)); panelBatohu.setBorder(BorderFactory.createEmptyBorder(0, 0, 6, 0)); panelBatohu.setAlignmentY(Component.TOP_ALIGNMENT); panelBatohu.add(lblZadnyBatoh); txtAreaVystup = new JTextArea(40, 20); JScrollPane scrollAreaVystup = new JScrollPane(txtAreaVystup); scrollAreaVystup.setPreferredSize(new Dimension(550, 400)); scrollAreaVystup.setAlignmentY(Component.CENTER_ALIGNMENT); txtAreaVystup.setFocusable(false); txtAreaVystup.setFont(new Font(Font.MONOSPACED, Font.BOLD, 15)); txtAreaVystup.setHighlighter(null); txtAreaVystup.setEditable(false); txtFieldVstup = new JTextField(20); txtFieldVstup.setEnabled(false); txtFieldVstup.setBorder(BorderFactory.createCompoundBorder( txtFieldVstup.getBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5))); txtFieldVstup.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15)); txtFieldVstup.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { wakeUp(); } }); panelVystupu = new JPanel(); panelVystupu.setLayout(new BorderLayout()); panelVystupu.setPreferredSize(new Dimension(550, 40)); panelVystupu.setAlignmentY(Component.BOTTOM_ALIGNMENT); panelVystupu.add(txtFieldVstup, BorderLayout.NORTH); levyContainer.add(panelBatohu); levyContainer.add(scrollAreaVystup); levyContainer.add(Box.createRigidArea(new Dimension(0, 20))); levyContainer.add(txtFieldVstup); levyContainer.add(Box.createRigidArea(new Dimension(0, 10))); container.add(levyContainer); container.add(panelPlanku); frame.add(container); frame.pack(); frame.setResizable(false); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); try { logURL = new URL("file", "", Hra.PATH_LOGS_FILE); } catch (MalformedURLException ex) { } if (null == planekURL) { logger.log(Level.WARNING, "Planek hry nebyl nalezen!"); } else if (null == napovedaURL) { logger.log(Level.WARNING, "Soubor s napovedou nebyl nalezen!"); } oknoNapovedy = new DialogOkno(frame, "Napoveda | " + hra.toString(), napovedaURL); oknoLogu = new DialogOkno(frame, "Logovani | " + hra.toString(), logURL); initMenuBar(); frame.setJMenuBar(menuBar); frame.setVisible(true); } private void initMenuBar() { menuBar = new JMenuBar(); menuBar.setFocusable(false); menuBar.setBackground(new Color(244, 244, 244)); mSoubor = new JMenu("Soubor"); mNapoveda = new JMenu("Napoveda"); mSoubor.setEnabled(false); mSoubor.setMnemonic(KeyEvent.VK_S); mSoubor.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6)); mNapoveda.setMnemonic(KeyEvent.VK_N); mNapoveda.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6)); JMenuItem novaHraIt = new JMenuItem(" > NOVA HRA"); JMenuItem exitIt = new JMenuItem(" > Exit"); JMenuItem pomocIt = new JMenuItem(" > Pomoc"); JMenuItem logovaniIt = new JMenuItem(" > Logovani"); JMenuItem oProgramuIt = new JMenuItem(" > O Programu"); novaHraIt.setBorder(mSoubor.getBorder()); exitIt.setBorder(mSoubor.getBorder()); pomocIt.setBorder(mNapoveda.getBorder()); logovaniIt.setBorder(mNapoveda.getBorder()); oProgramuIt.setBorder(mNapoveda.getBorder()); novaHraIt.addActionListener(new NovaHra()); exitIt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); pomocIt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { oknoNapovedy.zobraz(); } }); logovaniIt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { oknoLogu.zobraz(); } }); oProgramuIt.addActionListener(new OProgramu()); mSoubor.add(novaHraIt); mSoubor.addSeparator(); mSoubor.add(exitIt); mNapoveda.add(pomocIt); mNapoveda.addSeparator(); mNapoveda.add(logovaniIt); mNapoveda.addSeparator(); mNapoveda.add(oProgramuIt); menuBar.add(mSoubor); menuBar.add(mNapoveda); } private void loadImages() { for (Scenar.VecVycet vec : Scenar.VecVycet.values()) { //vsechny obrazky veci musi byt JPEG _ //s koncovkou 'jpg' psanou malymi pismeny URL imgURL = GUI.class.getResource("/images/" + vec.toString() + ".jpg"); if (imgURL != null) { String name = vec.toString().replaceFirst("\\.[^\\.]+$", ""); ImageIcon img = new ImageIcon(imgURL); ImageIcon newImg = new ImageIcon( img.getImage().getScaledInstance(75, 75, Image.SCALE_SMOOTH), name); imagesVec.put(name.toLowerCase(), newImg); } } if (imagesVec.isEmpty()) { logger.warning(String.format( "%s%n%s%s", "Nenacetly se zadne obrazky!", "Chybejici nebo vadny archiv img.jar - ", "prectete si soubor README.txt")); } } @Override public void setVystup(String vystup) { logger.info(String.format("{VYSTUP PROGRAMU}%n%s", vystup)); txtAreaVystup.append(vystup); txtAreaVystup.append("\n"); txtAreaVystup.setCaretPosition(txtAreaVystup.getDocument().getLength()); } @Override public String getVstup() { return getVstup(prompt); } @Override public synchronized String getVstup(String vyzva) { txtAreaVystup.append("#\n"); if (!vyzva.equals(prompt)) { logger.info(String.format("{VYSTUP PROGRAMU}%n%s", vyzva)); txtAreaVystup.append(vyzva + "\n"); } try { /** * Protoze hra samotna bezi ve smycce while, NEMOHOHU vratit vstup - * dokud ho opravdu neziskam */ wait(); String vstup = txtFieldVstup.getText(); logger.info(String.format("{VSTUP UZIVATELE}%n%s", vstup)); txtFieldVstup.setText(""); return vstup; } catch (InterruptedException ex) { ex.printStackTrace(System.err); } return ""; } @Override public final void attachObserver(Observer observer) { if (observer != null) { listeners.add(observer); } } @Override public final void detachObserver(Observer observer) { if (observer != null) { listeners.remove(observer); } } @Override public final void notifyObservers(UdalostHry udalost) { for (Observer o : listeners) { o.update(udalost); } } @Override public void update(UdalostHry udalost) { switch (udalost) { case ZMENIL_PROSTOR: String kdeJsem = hra.getHerniPlan().kdeJsem().toString(); for (Scenar.ProstorVycet prostor : Scenar.ProstorVycet.values()) { if (kdeJsem.equalsIgnoreCase(prostor.toString())) { panelPlanku.prekresliPozici(prostor); break; } } break; case SEBRAL_VEC: //fall through case POLOZIL_VEC: updatePanelBatohu(); break; case NOVAHRA: frame.setTitle(hra.toString()); txtFieldVstup.setText(""); txtAreaVystup.setText(""); txtFieldVstup.setEnabled(true); mSoubor.setEnabled(true); updatePanelBatohu(); if (!timer.isRunning()) { timer.setInitialDelay(25); timer.start(); } break; case KONECHRY: timer.stop(); wakeUp(); txtFieldVstup.setEnabled(false); break; } } private void updatePanelBatohu() { panelBatohu.removeAll(); VecBatoh batoh = hra.getHerniPlan().hlavniPostava().getBatoh(); if (batoh != null) { for (String vec : batoh.getSeznVeci()) { vec = vec.toLowerCase(); if (imagesVec.containsKey(vec)) { panelBatohu.add(new JLabel(imagesVec.get(vec))); } } } else { panelBatohu.add(lblZadnyBatoh); } panelBatohu.revalidate(); panelBatohu.repaint(); } /** * Probudi vlakno tohoto objektu */ private synchronized void wakeUp() { notifyAll(); } }
package com.mears.entities; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.TypeAlias; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="drivers") @TypeAlias("Driver") public class Driver { @Id private String id; private String driverNum; private String firstName; private String lastName; private String hireDate; private String password; public Driver(){ } public Driver (String driverNum, String firstName, String lastName, String hireDate, String password ) { this.setDriverNum(driverNum); this.setId(driverNum); this.setFirstName(firstName); this.setLastName(lastName); this.setHireDate(hireDate); this.setPassword(password); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDriveNum() { return driverNum; } public void setDriverNum(String driverNum) { this.driverNum = driverNum; } public String getDriverFirstName() { return firstName; } public void setFirstName (String firstName) { this.firstName = firstName; } public String getDriverLastName() { return lastName; } public void setLastName (String lastName) { this.lastName = lastName; } public String getDriverNameFirstLast() { return firstName + " " + lastName; } public String getDriverNameLastFirst() { return lastName + ", " + firstName; } public String getHireDate() { return hireDate; } public void setHireDate(String hireDate) { this.hireDate = hireDate; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String toString() { return String.format( "Driver: %s %s Number: %s", firstName, lastName, driverNum); } }
package server; import com.google.gson.Gson; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import database.MyDatabase; import database.SQLDatabase; import util.HashUtils; import java.io.File; import java.io.IOException; import java.sql.SQLException; import static util.SongUtils.*; import static util.DecodeUtils.writeJson; import static util.DecodeUtils.writeFile; import static util.StreamUtils.readStream; import static util.UserUtils.signIn; import static util.UserUtils.signUp; public class APIHandler implements HttpHandler { MyDatabase database = new SQLDatabase(); Gson gson = new Gson(); String filepath; public APIHandler(String path) throws SQLException, ClassNotFoundException { this.filepath = path; } @Override public void handle(HttpExchange exchange) throws IOException { try { String[] path = exchange.getRequestURI().getPath().substring(1).split("/"); String json = readStream(exchange.getRequestBody()); Headers headers = exchange.getRequestHeaders(); switch (path[0]) { case "": writeFile(exchange, new File(filepath + "html\\", "hub.html")); break; case "login": writeFile(exchange, new File(filepath + "html\\", "sign_in.html")); break; case "register": writeFile(exchange, new File(filepath + "html\\", "sign_up.html")); break; case "addsong": writeFile(exchange, new File(filepath + "html\\", "add_song.html")); break; case "static": if (path.length == 1) writeJson(exchange, "message", "Static files"); else if (path.length == 2) writeJson(exchange, "message", "Error"); else switch (path[1]) { case "css": writeFile(exchange, new File(filepath + "css\\", path[2])); break; case "js": writeFile(exchange, new File(filepath + "js\\", path[2])); case "song": writeFile(exchange, new File(filepath + "song\\", path[2])); break; case "assets": writeFile(exchange, new File(filepath + "assets\\", path[2])); break; default: writeJson(exchange, "error", "Could'not find file"); } break; case "api": if (path.length == 1) writeJson(exchange, "message", "This is techno's API"); else switch (path[1]) { case "sign_up": signUp(exchange, gson, database, json); break; case "sign_in": signIn(exchange, gson, database, json); break; case "new_song": checkToken(headers); addSong(exchange, gson, database, json); break; case "get_song": checkToken(headers); getArticle(exchange, gson, database); break; case "delete_song": checkToken(headers); deleteSong(exchange, gson, database, json); break; case "like": checkToken(headers); like(exchange, gson, database, json); case "top": checkToken(headers); top(exchange, gson, database); case "search": checkToken(headers); search(exchange, gson, database); } default: exchange.sendResponseHeaders(404, 0); } } catch (Exception e) { writeJson(exchange, "error", e.getMessage()); } finally { exchange.close(); } } private void checkToken(Headers headers) throws Exception { String token = headers.getFirst("Token"); if (token == null) throw new Exception("Token expected"); if (!HashUtils.checkToken(token)) throw new Exception("Invalid token"); } }
package us.bugzig.schoolproject.util; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; import us.bugzig.schoolproject.schoolproject; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class CooldownManager { private final Map<UUID, Integer> cooldowns = new HashMap<>(); public static final int DEFAULT_COOLDOWN = 1; public void setCooldown(UUID player, int time){ if(time < 1) { cooldowns.remove(player); } else { cooldowns.put(player, time); } } public int getCooldown(UUID player){ return cooldowns.getOrDefault(player, 0); } public void setTimer (Player player, Plugin plugin, int time) { setCooldown(player.getUniqueId(), time); run(player, plugin); } public void setTimer (Player player, Plugin plugin) { setCooldown(player.getUniqueId(), DEFAULT_COOLDOWN); run(player, plugin); } private void run (Player player, Plugin plugin) { new BukkitRunnable() { @Override public void run() { int timeLeft = getCooldown(player.getUniqueId()); setCooldown(player.getUniqueId(), --timeLeft); if (timeLeft == 0) { this.cancel(); } } }.runTaskTimer(plugin, 20, 20); } }
import java.util.ArrayList; import java.util.List; public class KClosest { public static List<Integer> findClosestElements(int[] arr, int k, int x) { int left = 0; int right = arr.length - 1; int pos = -1; while(left<right) { int mid = left + (right - left)/2; if (arr[mid] == x) { pos = mid; break; } else if(x < arr[mid]) { right = mid; } else { left = mid + 1; } } if (pos == -1) { left = right -1; } else { left = pos -1; right = pos; } // Check k nearest now List<Integer> result = new ArrayList<>(); for (int i=0;i<k;i++) { if(left >=0) { if (right >= arr.length || Math.abs(arr[left] - x) <= Math.abs(arr[right] - x)) { result.add(arr[left]); left--; } else { result.add(arr[right]); right++; } } else if (right<arr.length) { result.add(arr[right]); right++; } else break; } result.sort(Integer::compareTo); return result; } public static void main(String[] args) { System.out.println(findClosestElements(new int[]{1,2,3,4,5}, 4, -1)); } }
package Chapter3.StacksAndQueues.Exercise1ThreeInOne; /** * Use a single array to implement three stacks */ public class Solution { public static void main(String[] args) throws FullStackException { FixedMultiStack stack = new FixedMultiStack(3); stack.push(0, 1); stack.push(0, 2); stack.push(1, 4); stack.push(1, 5); stack.push(2, 7); stack.push(2, 8); // top elements of each stack System.out.println(stack.peek(0)); System.out.println(stack.peek(1)); System.out.println(stack.peek(2)); } }
package heirerichical_inheritance; public class classC extends classA { void mul (int a, int b){ val = a*b; System.out.println("Multiplication of two numbers : " + val); } public static void main(String[] args) { classC obj = new classC(); } }
package eg.edu.alexu.csd.oop.paint; import java.awt.EventQueue; import javax.swing.JFrame; import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JColorChooser; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.io.File; import java.awt.event.ActionEvent; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.BoxLayout; import javax.swing.JFileChooser; import javax.swing.JMenuBar; import javax.swing.JLabel; import java.awt.Panel; import java.awt.Color; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.event.KeyEvent; import java.awt.event.InputEvent; import javax.swing.JSeparator; public class PaintGui { private JButton yellow, red, green, blue, moreColors, clear; // private JTextField textField, textField_1, textField_2, textField_3, // textField_4, textField_5; // private JPanel panel_1; private JFrame frame; private JLabel status = new JLabel(); private PaintArea area = new PaintArea(); private JPanel panel; // private boolean flag = true; ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getSource().equals(yellow)) { area.yellow(); } else if (e.getSource().equals(red)) { area.red(); } else if (e.getSource().equals(green)) { area.green(); } else if (e.getSource().equals(blue)) { area.blue(); } else if (e.getSource().equals(moreColors)) { Color c = JColorChooser.showDialog(null, "Select another Color", Color.BLACK); if (c != null) { area.setColor(c); } } else if (e.getSource().equals(clear)) { area.clearAllComp(); } else if (e.paramString().contains("Plug")) { JFileChooser loadFile = new JFileChooser(); int returnVal = loadFile.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { Loader l = new Loader(); l.setPathToJar(loadFile.getSelectedFile().getPath()); area.setPath(loadFile.getSelectedFile().getPath()); String[] names = l.names(); if (names.length != 0) { frame.setVisible(false); makeButtons(names); } else { JOptionPane.showMessageDialog(null, "No classes found."); } } } else { area.setB(e.paramString()); } } }; private JMenuItem load; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { PaintGui window = new PaintGui(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public PaintGui() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 690, 580); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BorderLayout(0, 0)); panel = new JPanel(); frame.getContentPane().add(panel, BorderLayout.WEST); GridBagLayout gbl_panel = new GridBagLayout(); gbl_panel.columnWidths = new int[] { 0, 0 }; gbl_panel.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; gbl_panel.columnWeights = new double[] { 0.0, Double.MIN_VALUE }; gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE }; panel.setLayout(gbl_panel); JLabel lblColors = new JLabel("Colors"); GridBagConstraints gbc_lblColors = new GridBagConstraints(); gbc_lblColors.insets = new Insets(0, 0, 5, 0); gbc_lblColors.gridx = 0; gbc_lblColors.gridy = 0; panel.add(lblColors, gbc_lblColors); yellow = new JButton("Yellow"); GridBagConstraints gbc_yellow = new GridBagConstraints(); gbc_yellow.fill = GridBagConstraints.BOTH; gbc_yellow.insets = new Insets(0, 0, 5, 0); gbc_yellow.gridx = 0; gbc_yellow.gridy = 1; yellow.addActionListener(actionListener); panel.add(yellow, gbc_yellow); red = new JButton("Red"); GridBagConstraints gbc_red = new GridBagConstraints(); gbc_red.fill = GridBagConstraints.BOTH; gbc_red.insets = new Insets(0, 0, 5, 0); gbc_red.gridx = 0; gbc_red.gridy = 2; red.addActionListener(actionListener); panel.add(red, gbc_red); green = new JButton("Green"); GridBagConstraints gbc_green = new GridBagConstraints(); gbc_green.fill = GridBagConstraints.BOTH; gbc_green.insets = new Insets(0, 0, 5, 0); gbc_green.gridx = 0; gbc_green.gridy = 3; green.addActionListener(actionListener); panel.add(green, gbc_green); blue = new JButton("Blue"); GridBagConstraints gbc_blue = new GridBagConstraints(); gbc_blue.fill = GridBagConstraints.BOTH; gbc_blue.insets = new Insets(0, 0, 5, 0); gbc_blue.gridx = 0; gbc_blue.gridy = 4; blue.addActionListener(actionListener); panel.add(blue, gbc_blue); moreColors = new JButton("More Colors"); GridBagConstraints gbc_moreColors = new GridBagConstraints(); gbc_moreColors.fill = GridBagConstraints.BOTH; gbc_moreColors.insets = new Insets(0, 0, 5, 0); gbc_moreColors.gridx = 0; gbc_moreColors.gridy = 5; moreColors.addActionListener(actionListener); panel.add(moreColors, gbc_moreColors); JLabel lblShapes = new JLabel("Shapes"); GridBagConstraints gbc_lblShapes = new GridBagConstraints(); gbc_lblShapes.insets = new Insets(0, 0, 5, 0); gbc_lblShapes.gridx = 0; gbc_lblShapes.gridy = 6; panel.add(lblShapes, gbc_lblShapes); JButton line = new JButton("Line"); GridBagConstraints gbc_line = new GridBagConstraints(); gbc_line.fill = GridBagConstraints.BOTH; gbc_line.insets = new Insets(0, 0, 5, 0); gbc_line.gridx = 0; gbc_line.gridy = 7; line.addActionListener(actionListener); panel.add(line, gbc_line); JButton rectangle = new JButton("Rectangle"); GridBagConstraints gbc_rectangle = new GridBagConstraints(); gbc_rectangle.fill = GridBagConstraints.BOTH; gbc_rectangle.insets = new Insets(0, 0, 5, 0); gbc_rectangle.gridx = 0; gbc_rectangle.gridy = 9; rectangle.addActionListener(actionListener); panel.add(rectangle, gbc_rectangle); JButton triangle = new JButton("Triangle"); GridBagConstraints gbc_triangle = new GridBagConstraints(); gbc_triangle.fill = GridBagConstraints.BOTH; gbc_triangle.insets = new Insets(0, 0, 5, 0); gbc_triangle.gridx = 0; gbc_triangle.gridy = 10; triangle.addActionListener(actionListener); panel.add(triangle, gbc_triangle); JButton ellipse = new JButton("Ellipse"); GridBagConstraints gbc_ellipse = new GridBagConstraints(); gbc_ellipse.fill = GridBagConstraints.BOTH; gbc_ellipse.insets = new Insets(0, 0, 5, 0); gbc_ellipse.gridx = 0; gbc_ellipse.gridy = 11; ellipse.addActionListener(actionListener); panel.add(ellipse, gbc_ellipse); clear = new JButton("Clear"); GridBagConstraints gbc_clear = new GridBagConstraints(); gbc_clear.fill = GridBagConstraints.BOTH; gbc_clear.insets = new Insets(0, 0, 5, 0); gbc_clear.gridx = 0; gbc_clear.gridy = 12; clear.addActionListener(actionListener); panel.add(clear, gbc_clear); JButton delete = new JButton("Delete"); GridBagConstraints gbc_delete = new GridBagConstraints(); gbc_delete.fill = GridBagConstraints.HORIZONTAL; gbc_delete.insets = new Insets(0, 0, 5, 0); gbc_delete.gridx = 0; gbc_delete.gridy = 13; delete.addActionListener(actionListener); panel.add(delete, gbc_delete); JButton resize = new JButton("Resize"); GridBagConstraints gbc_btnNewButton = new GridBagConstraints(); gbc_btnNewButton.insets = new Insets(0, 0, 5, 0); gbc_btnNewButton.fill = GridBagConstraints.BOTH; gbc_btnNewButton.gridx = 0; gbc_btnNewButton.gridy = 14; resize.addActionListener(actionListener); panel.add(resize, gbc_btnNewButton); JButton modify = new JButton("Modify"); GridBagConstraints gbc_modify = new GridBagConstraints(); gbc_modify.insets = new Insets(0, 0, 5, 0); gbc_modify.fill = GridBagConstraints.BOTH; gbc_modify.gridx = 0; gbc_modify.gridy = 15; modify.addActionListener(actionListener); panel.add(modify, gbc_modify); JButton fill = new JButton("Fill"); GridBagConstraints gbc_fill = new GridBagConstraints(); gbc_fill.fill = GridBagConstraints.BOTH; gbc_fill.insets = new Insets(0, 0, 5, 0); gbc_fill.gridx = 0; gbc_fill.gridy = 16; fill.addActionListener(actionListener); panel.add(fill, gbc_fill); Panel panel_2 = new Panel(); frame.getContentPane().add(panel_2, BorderLayout.SOUTH); panel_2.setLayout(new BoxLayout(panel_2, BoxLayout.X_AXIS)); panel_2.add(status); frame.getContentPane().add(area, BorderLayout.CENTER); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu file = new JMenu("File"); menuBar.add(file); JMenuItem save = new JMenuItem("Save"); save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK)); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser fileChooser = new JFileChooser(); fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Save files", "json", "xml")); int returnValue = fileChooser.showSaveDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); String name = selectedFile.getName(); String ext = null; if (name.lastIndexOf(".") != -1) { ext = name.substring(name.lastIndexOf("."), name.length()); area.save(selectedFile.getAbsolutePath(), ext); } else { ext = new String(".xml"); if (!name.equals("")) area.save(selectedFile.getAbsolutePath() + ext, ext); } } } }); file.add(save); load = new JMenuItem("Load"); load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK)); load.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser fileChooser = new JFileChooser(); fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Save files", "json", "xml")); int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); if (selectedFile.exists()) { String name = selectedFile.getName(); String ext = null; if (name.lastIndexOf(".") != -1) ext = name.substring(name.lastIndexOf("."), name.length()); else { ext = new String(".xml"); } if (!name.equals("")) area.load(selectedFile.getAbsolutePath(), ext); } else { JOptionPane.showMessageDialog(null, "You must select an existing file!"); } } } }); file.add(load); JSeparator separator = new JSeparator(); file.add(separator); JMenuItem undo = new JMenuItem("Undo"); undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK)); undo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { area.undoRedo(false); } }); file.add(undo); JMenuItem redo = new JMenuItem("Redo"); redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK)); redo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { area.undoRedo(true); } }); file.add(redo); JMenu tools = new JMenu("Tools"); menuBar.add(tools); JMenuItem plugIn = new JMenuItem("Add Plug-in"); plugIn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK)); plugIn.addActionListener(actionListener); tools.add(plugIn); } public void makeButtons(String[] names) { int value = 17; for (int i = 0; i < names.length; i++) { JButton fill = new JButton(names[i]); GridBagConstraints gbc_fill = new GridBagConstraints(); gbc_fill.fill = GridBagConstraints.BOTH; gbc_fill.insets = new Insets(0, 0, 5, 0); gbc_fill.gridx = 0; gbc_fill.gridy = value; value++; fill.addActionListener(actionListener); panel.add(fill, gbc_fill); frame.setBounds(100, 100, 755, 655); } frame.setVisible(true); } }
package framework.dal; import framework.entities.Party; public interface PartyDAO extends IDAO<Party>{ }
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. **/ package com.websockets.connectors.config; public class ConnectorConstants { public final static String TOPICS = "topics"; public final static String NAME = "name"; public final static String MAX_TASKS = "tasks.max"; public final static String BOOTSTRAP_SERVERS = "bootstrap.servers"; public final static String DELIMITER = ","; }
package com.nks.whatsapp.protocol; public class RC4 { private int[] s; private int i; private int j; public RC4() { s = Util.range(0, 255); i = 0; j = 0; } public RC4(String key, int drop) { s = Util.range(0, 255); for (i = 0, j = 0; i < 256; i++) { int k = Util.ord(key.charAt(i % key.length())); j = (j + k + s[i]) & 255; swap(i, j); } i = 0; j = 0; cipher(Util.intArrayToString(Util.range(0, drop)), 0, drop); } public String cipher(String data, int offset, int length) { StringBuffer out = new StringBuffer(data); for (int n = length; n > 0; n--) { i = (i + 1) & 0xff; j = (j + s[i]) & 0xff; swap(i, j); int d = Util.ord((char)data.charAt(offset)); out.setCharAt(offset,(char)(d ^ s[(s[i] + s[j]) & 0xff])); offset++; } return out.toString(); } private void swap(int i, int j) { int c = s[i]; s[i] = s[j]; s[j] = c; } /*public static void main(String[] args) { RC4 rc4=new RC4(); System.out.println(rc4.cipher(Util.intArrayToString(Util.range(0, 255)), 0, 78)); }*/ }
import java.util.Scanner; public class Lucky7 { public static void main(String[] args) { Scanner s = new Scanner(System.in); Dice d1 = new Dice(); Dice d2 = new Dice(); int tries = 0; int money; int highestroll = 1; System.out.print("Enter the amount of money you have > "); money = s.nextInt(); int highestmoney = money; while (true) { d1.roll(); d2.roll(); tries++; int total = d1.getValue() + d2.getValue(); if (total == 7) { money += 4; if (money > highestmoney) { highestmoney = money; highestroll = tries; } } else { money--; } if (money <= 0) { break; } } System.out.format("You are broke after %d rolls.\n", tries); System.out.format("You should have quit after %d rolls when you had $%d.", highestroll, highestmoney); } }
/* * 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 loc.dtos; /** * * @author hi */ public class CommentDTO { String id; int postID, status; String email, comment, date; public CommentDTO() { } public CommentDTO(String id, String email, String comment, String date) { this.id = id; this.email = email; this.comment = comment; this.date = date; } public CommentDTO(String id, int postID, int status, String email, String comment, String date) { this.id = id; this.postID = postID; this.status = status; this.email = email; this.comment = comment; this.date = date; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getPostID() { return postID; } public void setPostID(int postID) { this.postID = postID; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
package com.tencent.mm.plugin.aa.ui; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import com.tencent.mm.plugin.aa.ui.LaunchAAByPersonAmountSelectUI.a; class LaunchAAByPersonAmountSelectUI$a$1 implements OnTouchListener { final /* synthetic */ LaunchAAByPersonAmountSelectUI$a$a eDj; final /* synthetic */ a eDk; LaunchAAByPersonAmountSelectUI$a$1(a aVar, LaunchAAByPersonAmountSelectUI$a$a launchAAByPersonAmountSelectUI$a$a) { this.eDk = aVar; this.eDj = launchAAByPersonAmountSelectUI$a$a; } public final boolean onTouch(View view, MotionEvent motionEvent) { this.eDj.eCN.d(this.eDk.eDf); return false; } }
package com.wshoto.user.anyong.ui.widget; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.DisplayMetrics; import com.umeng.message.PushAgent; import com.wshoto.user.anyong.R; import com.wshoto.user.anyong.SharedPreferencesUtils; import java.util.Locale; /** * Created by user on 2018/4/26. * 2091320109@qq.com * 封装的模板activity */ public abstract class InitActivity extends AppCompatActivity { public abstract void initView(Bundle savedInstanceState); public abstract void initData(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21) { StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.title)); } getSupportActionBar().hide(); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); if ((boolean) SharedPreferencesUtils.getParam(this, "language_auto", true)) { String country = Locale.getDefault().getCountry(); if ("CN".equals(country)) { selectLanguage("zh"); } else { selectLanguage("en"); } } else { selectLanguage((String) SharedPreferencesUtils.getParam(this, "language", "zh")); } PushAgent pushAgent = PushAgent.getInstance(this); pushAgent.onAppStart(); initView(savedInstanceState); initData(); } /** * 设置要显示的语言 * * @param language zh或者en,中文或者英文 */ protected void selectLanguage(String language) { //设置语言类型 Resources resources = getResources(); Configuration configuration = resources.getConfiguration(); DisplayMetrics displayMetrics = resources.getDisplayMetrics(); switch (language) { case "en": configuration.locale = Locale.ENGLISH; break; case "zh": configuration.locale = Locale.SIMPLIFIED_CHINESE; break; default: configuration.locale = Locale.getDefault(); break; } resources.updateConfiguration(configuration, displayMetrics); // // //保存设置语言的类型 SharedPreferencesUtils.setParam(getApplicationContext(), "language", language); } public void goActivity(Class c) { startActivity(new Intent(this, c)); } }
package org.kernelab.basis.demo; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.text.ParseException; import org.kernelab.basis.JSON; import org.kernelab.basis.JSON.JSAN; import org.kernelab.basis.Tools; public class DemoJSON { public static void main(String[] args) throws IOException, ParseException { JSON jsonA = new JSON() // .attr("a", "On\ne") // .attr("b", 2) // .attr("c", true)// .attr("d", "3.1") // .attr("e", null) // .attr("f", new JSON() // .attr("r", 1.5) // .attr("s", "Sss") // .attr("t", true) // ) // .attr("g", "2022-07-12T12:15:07.077Z") // .attr("h", new Object[] { 1, 2.1, "3", true }); Tools.debug(jsonA.valDouble("d")); Tools.debug(jsonA.toString(0)); Tools.debug(jsonA.values()); Tools.debug(jsonA.entrySet()); Tools.debug(jsonA.keySet()); Tools.debug(jsonA.valTimestamp("g")); Tools.debug(jsonA.valCalendar("g")); Tools.debug(jsonA.val("h")); JSON jsonB = new JSON(); jsonB.attrAll(jsonA); Tools.debug(jsonB.toString(0)); JSON jsonC = JSON.Parse(jsonB.toString()); Tools.debug(jsonC.toString(0)); JSAN jsanA = new JSAN().add("one").add("1").add(true).add(0.1); jsanA.attr("k1", 2); jsanA.addLast(3, null, "yes"); Writer out = new PrintWriter(System.out); JSON.Serialize(jsanA, out, 0); out.write('\n'); out.flush(); JSON jsonD = new JSON().pairs("a", jsonA, "AA", jsanA); Tools.debug(jsonD.flatten().toString(0)); JSAN table = new JSAN(); table.add(new JSAN().addAll(0, "a", 1, true, null)) // .add(new JSAN().addAll(0, "b", 2, false, new JSON().attr("a", 1))); JSON.Output(new PrintWriter(System.out, true), table, 0, " "); } }
package pl.rogalik.objects.ai.bt; import pl.rogalik.mechanics.GameEngine; import pl.rogalik.objects.Monster; public class EscapeIndicator implements Routine{ @Override public boolean execute(Monster mob, GameEngine engine) { return mob.getHp() < mob.getFearEstimator(); } }
package c6.p5; import c6.p2.Heap; import c6.p2.HeapPractise2; import java.util.Arrays; /** * Created by heshaoyi on 5/21/16. */ public class MinHeapPriority { private int[] elements; private int heapSize; public MinHeapPriority(int[] args) { this.elements = Arrays.copyOf(args, args.length + 10); this.heapSize = args.length; buildMinHeap(); } public int minmum() { assert heapSize > 0; return elements[0]; } public int extractMin() { int min = minmum(); HeapPractise2.swap(elements, 0, heapSize - 1); --heapSize; minHeaprity(0); return min; } public void decreaseKey(int point, int newValue) { assert heapSize > point; assert elements[point] >= newValue; elements[point] = newValue; int parent = Heap.parent(point); while (parent >= 0) { if (elements[parent] > elements[point]) { HeapPractise2.swap(elements, parent, point); point = parent; parent = Heap.parent(parent); } else { break; } } } /** * 6.5-6 * * @param point * @param newValue */ public void decreaseKey2(int point, int newValue) { assert heapSize > point; assert elements[point] >= newValue; elements[point] = newValue; int oriPointVal = elements[point]; int parent = Heap.parent(point); while (parent >= 0) { if (elements[parent] > oriPointVal) { elements[point] = elements[parent]; point = parent; parent = Heap.parent(parent); } else { break; } } elements[point] = oriPointVal; } public MinHeapPriority insert(int value) { if (heapSize >= elements.length) { elements = Arrays.copyOf(elements, elements.length + 10); } elements[heapSize++] = Integer.MAX_VALUE; decreaseKey(heapSize - 1, value); return this; } public void print() { Heap.prettyPrint(elements, heapSize); } private void buildMinHeap() { for (int i = heapSize / 2; i >= 0; --i) { minHeaprity(i); } } private void minHeaprity(int point) { int leftIndex = Heap.left(point); int rightIndex = Heap.right(point); int minIndex = point; if (leftIndex < heapSize && elements[minIndex] > elements[leftIndex]) { minIndex = leftIndex; } if (rightIndex < heapSize && elements[minIndex] > elements[rightIndex]) { minIndex = rightIndex; } if (minIndex != point) { HeapPractise2.swap(elements, minIndex, point); minHeaprity(minIndex); } } }
package com.tencent.mm.plugin.h.a.b.a; import com.tencent.mm.plugin.h.a.b.h; public class e extends a { static final String TAG = e.class.getName(); public static final String hia = h.hgS; public static final String hib = h.hgT; public static final String hic = h.hgU; public static final String hid = h.hgV; public byte hie; public byte hif; public byte hig; public byte hih; public byte[] hii; public int hij; public byte hik; public byte hil; public byte[] him; public e() { this.hhi = null; this.hhj = 8; this.hgC = 16; this.hie = (byte) 0; this.hif = (byte) 0; this.hig = (byte) 0; this.hih = (byte) 0; this.hii = new byte[]{(byte) 0, (byte) 0}; this.hij = -1; this.hik = (byte) 0; this.hil = (byte) 0; this.him = null; } public final byte[] atV() { byte[] bArr; if (this.hhi.equalsIgnoreCase(hia)) { Object obj = new byte[3]; System.arraycopy(Byte.valueOf(this.hie), 0, obj, 0, 1); System.arraycopy(Byte.valueOf(this.hif), 0, obj, 1, 1); System.arraycopy(Byte.valueOf(this.hig), 0, obj, 2, 1); return obj; } else if (this.hhi.equalsIgnoreCase(hib)) { bArr = new byte[1]; System.arraycopy(Byte.valueOf(this.hih), 0, bArr, 0, 1); return bArr; } else if (!this.hhi.equalsIgnoreCase(hid)) { return null; } else { bArr = new byte[this.hij]; byte b = (byte) ((this.hij >> 8) & 255); System.arraycopy(Byte.valueOf((byte) (this.hij & 255)), 0, bArr, 0, 1); System.arraycopy(Byte.valueOf(b), 0, bArr, 1, 1); System.arraycopy(Byte.valueOf(this.hik), 0, bArr, 2, 1); if (this.hij <= 3) { return bArr; } System.arraycopy(this.him, 0, bArr, 3, this.hij - 3); return bArr; } } }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.activity.model.bpm; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import javax.persistence.Entity; import org.overlord.rtgov.activity.model.ActivityType; import org.overlord.rtgov.activity.model.Context; /** * This activity type represents a BPM actvity. * */ @Entity public abstract class BPMActivityType extends ActivityType implements java.io.Externalizable { private static final int VERSION = 1; private String _processType=null; private String _instanceId=null; /** * The default constructor. */ public BPMActivityType() { } /** * The copy constructor. * * @param ba The bpm activity to copy */ public BPMActivityType(BPMActivityType ba) { super(ba); _processType = ba._processType; _instanceId = ba._instanceId; } /** * This method sets the process type. * * @param processType The process type */ public void setProcessType(String processType) { _processType = processType; updateEndpointContext(); } /** * This method gets the process type. * * @return The process type */ public String getProcessType() { return (_processType); } /** * This method sets the instance id. The information is * actually stored as a context entry for the Endpoint type. * * @param instanceId The instance id */ public void setInstanceId(String instanceId) { _instanceId = instanceId; updateEndpointContext(); } /** * This method gets the instance id. * * @return The instance id */ public String getInstanceId() { return (_instanceId); } /** * This method updates the endpoint context value * when the process type and/or instance id are * changed. */ protected void updateEndpointContext() { Context current=null; try { for (Context context : getContext()) { if (context.getType() == Context.Type.Endpoint) { current = context; break; } } if (current == null) { current = new Context(); current.setType(Context.Type.Endpoint); getContext().add(current); } String endpoint=""; if (_processType != null) { endpoint = _processType; if (_instanceId != null) { endpoint += ":"; } } if (_instanceId != null) { endpoint += _instanceId; } current.setValue(endpoint); } catch (Throwable t) { // RTGOV-278 NPE exception occurs when de-serializing // BPM activity type events with Hibernate, where the // query accesses the context information. current = null; } } /** * {@inheritDoc} */ public String toString() { return (getClass().getSimpleName()+":" +" processType="+_processType +" instanceId="+_instanceId); } /** * {@inheritDoc} */ public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeInt(VERSION); out.writeObject(_processType); out.writeObject(_instanceId); } /** * {@inheritDoc} */ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); in.readInt(); // Consume version, as not required for now _processType = (String)in.readObject(); _instanceId = (String)in.readObject(); } }
package com.hesoyam.pharmacy.storage.service.impl; import com.hesoyam.pharmacy.storage.model.Storage; import com.hesoyam.pharmacy.storage.repository.StorageRepository; import com.hesoyam.pharmacy.storage.service.IStorageService; import com.hesoyam.pharmacy.user.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service public class StorageService implements IStorageService { @Autowired private StorageRepository storageRepository; @Override public Storage create(Storage storage) { return storageRepository.save(storage); } @Override public Storage get(Long id) { return storageRepository.getOne(id); } @Override public Storage getUserStorage(User user) { return storageRepository.getStorageBySupplier_Id(user.getId()); } @Override @Transactional(propagation = Propagation.REQUIRED) public Storage update(Storage storage) { return storageRepository.save(storage); } }
package getronics.qiot.edge_service.rest.client.registration; import java.io.Serializable; import org.eclipse.microprofile.config.ConfigProvider; public class Station implements Serializable { private Integer id; private String serial; private String name; private Double longitude; private Double latitude; public Boolean active; public Station() { this.name = ConfigProvider.getConfig().getValue("name.sensor", String.class); this.longitude = ConfigProvider.getConfig().getValue("longitude.sensor", Double.class); this.latitude = ConfigProvider.getConfig().getValue("latitude.sensor", Double.class); } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getSerial() { return this.serial; } public void setSerial(String serial) { this.serial = serial; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Double getLongitude() { return this.longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return this.latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public boolean isActive() { return this.active; } public void setActive(boolean active) { this.active = active; } }
package com.amazonaws.samples; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.URL; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import proxyserver_cnv.DynamoDB.AmazonDynamoDBModule; class AutoScaleThread extends Thread { public void run(){ //System.out.println("MyThread running"); int numInstances; while(true) { if(Queuerequests.size()>0) { //check if there is running instances numInstances = EC2_launchCheck.checkInstance(); System.out.println(numInstances); } try { Thread.sleep(1000); } catch(Exception e) { e.printStackTrace(); } } } } public class ReceiveRequests extends Thread { private final static int numberOfThreads = 100; public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/", new Handler()); server.createContext("/test", new MyTestHandler()); System.out.println(server.getAddress()); System.out.println("LoadBalancer Server listens in port 8080"); server.setExecutor(Executors.newFixedThreadPool(numberOfThreads)); //Reservar 5 threads server.start(); new Queuerequests(); try { AmazonDynamoDBModule.init(); //Start dynamoDB } catch(Exception e) { e.printStackTrace(); server.stop(0); } try { EC2_launchCheck.init(); // } catch(Exception e) { e.printStackTrace(); return; } AutoScaleThread myThread = new AutoScaleThread(); myThread.start(); /*Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { //do some processing System.out.println("MyThread running"); } }; timer.schedule(task, 0l, 1000l); //call the run() method at 1 second intervals */ } //For ping purposes of the load balancer static class MyTestHandler implements HttpHandler { @Override public void handle(HttpExchange t) throws IOException { String response = "ok"; t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); } } static class Handler implements HttpHandler { public void handle(HttpExchange t) throws IOException { Queuerequests.insert(t); //insert request in queue } } }
package so.ego.space.domains.project.presentation; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import so.ego.space.domains.project.application.ProjectRegisterService; import so.ego.space.domains.project.application.dto.ProjectDeleteRequest; import so.ego.space.domains.project.application.dto.ProjectRegisterRequest; import so.ego.space.domains.project.application.dto.ProjectRegisterResponse; @RequiredArgsConstructor @RestController public class ProjectRegisterController { private final ProjectRegisterService projectRegisterService; @PostMapping("/project") public ProjectRegisterResponse addProject(@RequestBody ProjectRegisterRequest projectRegisterRequest){ return projectRegisterService.addProject(projectRegisterRequest); } }
package jsportsreg.entity; import static org.junit.Assert.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.ArrayList; import org.junit.Test; public class PersonTest { /** Tests all constructors and getters and setters. * */ @Test public void testPerson() throws Exception{ Person instance0 = new Person(); assertEquals("Person Test 1: First Name", "", instance0.getFirstName()); assertEquals("Person Test 1: Last Name", "", instance0.getLastName()); assertEquals("Person Test 1: Middle Name", "", instance0.getMiddleName() ); assertEquals("Person Test 1: Nick Name", "", instance0.getNickName() ); assertEquals("Person Test 1: Suffix Name", "", instance0.getSuffixName() ); assertEquals("Person Test 1: Home Phone Number", "", instance0.getHomePhone() ); assertEquals("Person Test 1: Mobile Phone Number", "", instance0.getMobilePhone() ); assertEquals("Person Test 1: Work Phone Number", "", instance0.getWorkPhone() ); DateFormat df = new SimpleDateFormat("MM-dd-yyyy"); Date dateTest0 = df.parse("01-01-1900"); assertEquals("Person Test 1: Birth Date", dateTest0, instance0.getBirthDate() ); assertEquals("Person Test 1: Gender", "", instance0.getGender() ); assertEquals("Person Test 1: Role", "", instance0.getRole() ); assertEquals("Person Test 1: Person ID", -1, instance0.getPersonID() ); assertEquals("Person Test 1: Player Registrations", true, instance0.getPlayerRegistrations().isEmpty() ); assertEquals("Person Test 1: Addresses", true, instance0.getAddresses().isEmpty() ); assertEquals("Person Test 1: Emergency Contacts", true, instance0.getEmergencyContacts().isEmpty() ); Date dateTest1 = df.parse("12-21-1975"); Person instance1 = new Person( 21, dateTest1, "tseiler@xcellutions.com", "Travis", "Male", "404-759-0121", "Seiler", "David", "404-890-0006", "T-Rex", "Parent/Guardian", "", "770-555-9999", new ArrayList<Address>(), new ArrayList<Person>(), new ArrayList<Player_Registration>() ); assertEquals("Person Test 2: First Name", "Travis", instance1.getFirstName()); assertEquals("Person Test 2: Last Name", "Seiler", instance1.getLastName()); assertEquals("Person Test 2: Middle Name", "David", instance1.getMiddleName() ); assertEquals("Person Test 2: Nick Name", "T-Rex", instance1.getNickName() ); assertEquals("Person Test 2: Suffix Name", "", instance1.getSuffixName() ); assertEquals("Person Test 2: Home Phone Number", "404-759-0121", instance1.getHomePhone() ); assertEquals("Person Test 2: Mobile Phone Number", "404-890-0006", instance1.getMobilePhone() ); assertEquals("Person Test 2: Work Phone Number", "770-555-9999", instance1.getWorkPhone() ); assertEquals("Person Test 2: Birth Date", dateTest1, instance1.getBirthDate() ); assertEquals("Person Test 2: Gender", "Male", instance1.getGender() ); assertEquals("Person Test 2: Role", "Parent/Guardian", instance1.getRole() ); assertEquals("Person Test 2: Person ID", 21, instance1.getPersonID() ); assertEquals("Person Test 2: Player Registrations", true, instance1.getPlayerRegistrations().isEmpty() ); assertEquals("Person Test 2: Addresses", true, instance1.getAddresses().isEmpty() ); assertEquals("Person Test 2: Emergency Contacts", true, instance1.getEmergencyContacts().isEmpty() ); instance0.setFirstName("Alexzander"); instance0.setMiddleName("Edward"); instance0.setLastName("Seiler"); instance0.setSuffixName(""); instance0.setNickName("Zander"); Date dateTest2 = df.parse("10-3-2010"); instance0.setBirthDate(dateTest2); instance0.setGender("Male"); instance0.setRole("Player"); instance0.setWorkPhone("404-555-1234"); instance0.setHomePhone("404-555-9876"); instance0.setMobilePhone("404-555-4321"); instance0.setPersonID(2010); ArrayList<Address> aList = new ArrayList<Address>(); Address addr1 = new Address(); Address addr2 = new Address(); aList.add(addr1); aList.add(addr2); instance0.setAddresses(aList); ArrayList<Player_Registration> pList = new ArrayList<Player_Registration>(); Player_Registration pr0 = new Player_Registration(); pList.add(pr0); instance0.setPlayerRegistrations(pList); ArrayList<Person> ecList = new ArrayList<Person>(); ecList.add(instance1); instance0.setEmergencyContacts(ecList); assertEquals("Person Test 3: First Name", "Alexzander", instance0.getFirstName()); assertEquals("Person Test 3: Last Name", "Seiler", instance0.getLastName()); assertEquals("Person Test 3: Middle Name", "Edward", instance0.getMiddleName() ); assertEquals("Person Test 3: Nick Name", "Zander", instance0.getNickName() ); assertEquals("Person Test 3: Suffix Name", "", instance0.getSuffixName() ); assertEquals("Person Test 3: Home Phone Number", "404-555-9876", instance0.getHomePhone() ); assertEquals("Person Test 3: Mobile Phone Number", "404-555-4321", instance0.getMobilePhone() ); assertEquals("Person Test 3: Work Phone Number", "404-555-1234", instance0.getWorkPhone() ); assertEquals("Person Test 3: Birth Date", dateTest2, instance0.getBirthDate() ); assertEquals("Person Test 3: Gender", "Male", instance0.getGender() ); assertEquals("Person Test 3: Role", "Player", instance0.getRole() ); assertEquals("Person Test 3: Person ID", 2010, instance0.getPersonID() ); assertEquals("Person Test 3: Player Registrations", 1, instance0.getPlayerRegistrations().size() ); assertEquals("Person Test 3: Addresses", 2, instance0.getAddresses().size() ); assertEquals("Person Test 3: Emergency Contacts", 1, instance0.getEmergencyContacts().size() ); } }
package uw.cse.dineon.user.restaurantselection; import uw.cse.dineon.library.checkin.IntentIntegrator; import uw.cse.dineon.user.DineOnUserApplication; import uw.cse.dineon.user.R; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; /** * @author mhotan */ public class RestaurantSelectionButtonsFragment extends Fragment implements View.OnClickListener { private static final String TAG = RestaurantSelectionButtonsFragment.class.getSimpleName(); /** * Activity that will called when user selects buttons. * on this fragments view */ private OnClickListener mListener; /** * References to Buttons on this display. */ private ImageButton mCheckInButton, mNearbyButton; private ImageButton mFriendsFavoritesButton, mUserFavoritesButton; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_restaurant_selection_buttons, container, false); // Assign buttons mNearbyButton = (ImageButton) view.findViewById(R.id.button_nearby_restaurants); mFriendsFavoritesButton = (ImageButton) view.findViewById(R.id.button_friends_favorites); mUserFavoritesButton = (ImageButton) view.findViewById(R.id.button_user_favorites); mCheckInButton = (ImageButton) view.findViewById(R.id.button_checkin); View checkInLine = (View) view.findViewById(R.id.checkinline); // Add listeners mNearbyButton.setOnClickListener(this); mFriendsFavoritesButton.setOnClickListener(this); mUserFavoritesButton.setOnClickListener(this); mCheckInButton.setOnClickListener(this); if(DineOnUserApplication.getCurrentDiningSession() != null) { mCheckInButton.setVisibility(View.GONE); checkInLine.setVisibility(View.GONE); } else { mCheckInButton.setVisibility(View.VISIBLE); checkInLine.setVisibility(View.VISIBLE); } return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof RestaurantSelectionButtonsFragment.OnClickListener) { mListener = (OnClickListener) activity; } else { throw new ClassCastException(activity.toString() + " must implemenet RestaurantSelectionButtonsFragment.OnClickListener"); } } /** * @param v View */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_nearby_restaurants: mListener.onShowNearbyRestaurants(); break; case R.id.button_friends_favorites: mListener.onShowFriendsFavoriteRestaurants(); break; case R.id.button_user_favorites: mListener.onShowUserFavorites(); break; case R.id.button_checkin: IntentIntegrator integrator = new IntentIntegrator(getActivity()); integrator.initiateScan(); break; default: Log.e(TAG, "Error onClick with unrecognized view: " + v); } } /** * Listener for Activity Callbacks. * @author mhotan */ public interface OnClickListener { /** * TODO finish. */ public void onShowNearbyRestaurants(/*TODO Potentially add Filter parameters*/); /** * TODO finish. */ public void onShowFriendsFavoriteRestaurants(/*TODO Potentially and Filter parameters*/); /** * TODO finish. */ public void onShowUserFavorites(/*TODO Potentially add Filter parameters*/); } }
package gov.virginia.dmas.serializer; import java.io.IOException; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; public class DateTimeStampDeserializer extends JsonDeserializer<Date> { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); @Override public Timestamp deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { Date cDate = null; Timestamp timestamp = null; try { cDate = dateFormat.parse(parser.getText()); long epoch = cDate.getTime(); timestamp = new Timestamp(epoch); } catch (ParseException e) { e.printStackTrace(); } return timestamp; } }
import java.util.ArrayList; public class Jugador { private String nom; private ArrayList<Carta> cartes; public Jugador(String nom) { super(); this.nom = nom; this.cartes= new ArrayList<Carta>(); } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public ArrayList<Carta> getCartes() { return cartes; } public void setCartes(ArrayList<Carta> cartes) { this.cartes = cartes; } public void darCarta(Carta carta) { cartes.add(carta); } public Carta retirarCarta(int index) { return cartes.remove(index); } public String joc() { String ma="["; for (int i=0; i<cartes.size(); i++) { if (i!=0) { ma=ma+","; } ma= ma+cartes.get(i).toString(); } ma=ma+"]"; return ma; } }
package exer2; import java.sql.Connection; import java.util.List; public class BookDAO extends BaseDAO<Book>{ public int saveBook(Connection conn,Book book) {//保存 String sql = "insert into t_book('name','author','price','sales','stock','publishing')values(?,?,?,?,?,?)"; return update(conn,sql,book.getName(), book.getAuthor(),book.getPrice(), book.getSales(),book.getStock(), book.getPublishing()); } public int updateBook(Connection conn,Book book) {// 修改 String sql = "update t_book set 'name' = ?,'author' = ?,'price' = ?,'sales' = ?,'stock' = ?,'publishing' = ? where = ?"; return update(conn,sql,book.getName(), book.getAuthor(),book.getPrice(), book.getSales(),book.getStock(), book.getPublishing(),book.getId()); } public int deleteBookById(Connection conn,Integer id) {// 根据主键删除 String sql = "delete from t_book where = ?"; return update(conn,sql,id); } public Book queryBookById(Connection conn,Integer id) {// 根据主键查询 String sql = "select id,name,author,price,sales,stock,publishing from t_book where id = ?"; return queryOne(conn,sql,id); } public List<Book> queryBooks(Connection conn,Book book) {// 查询所有 String sql = "select id,name,author,price,sales,stock,publishing from t_book"; return queryAll(conn,sql); } }
package burp; import java.awt.BorderLayout; import java.awt.Color; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.EmptyBorder; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JButton; import javax.swing.JTextArea; import java.awt.FlowLayout; import javax.swing.JSplitPane; import java.awt.Component; import javax.swing.Box; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class GUI{ private IBurpExtenderCallbacks mCall; private IExtensionHelpers helpers; private PrintWriter stdout; private PrintWriter stderr; private JPanel contentPane; private JLabel lbHost; private JTextField tfHost; private JLabel lbPort; private JTextField tfPort; private JButton btnConn; private JLabel lbConnectInfo; private JLabel lbConnectStatus; private JButton btnTest; private JSplitPane splitPane; private Component verticalStrut; private JTextArea taTestPayload; private JScrollPane spTestPayload; private JTextArea taResultPayload; private JScrollPane spResultPayload; private CloseableHttpClient client; private RequestConfig requestConfig; private boolean isSucces = false; private String testPayload[] = { "123456","a123456","123456a","5201314", "111111","woaini1314","qq123456","123123", "000000","1qaz2wsx","1q2w3e4r","qwe123", "7758521","123qwe","a123123","123456aa", "woaini520","woaini","100200","1314520" }; public GUI(IBurpExtenderCallbacks callbacks) { this.mCall = callbacks; this.helpers = callbacks.getHelpers(); this.stdout = new PrintWriter(callbacks.getStdout(), true); this.stderr = new PrintWriter(callbacks.getStderr(), true); this.requestConfig = RequestConfig.custom().setConnectionRequestTimeout(300).setConnectTimeout(300).setSocketTimeout(300).build(); this.client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); JPanel panel = new JPanel(); FlowLayout flowLayout = (FlowLayout) panel.getLayout(); flowLayout.setAlignment(FlowLayout.LEFT); contentPane.add(panel, BorderLayout.NORTH); lbHost = new JLabel("Host:"); panel.add(lbHost); tfHost = new JTextField(); tfHost.setColumns(20); tfHost.setText("127.0.0.1"); panel.add(tfHost); verticalStrut = Box.createVerticalStrut(20); panel.add(verticalStrut); lbPort = new JLabel("Port:"); panel.add(lbPort); tfPort = new JTextField(); tfPort.setText("1664"); panel.add(tfPort); tfPort.setColumns(20); btnConn = new JButton("Connect"); btnConn.setToolTipText("Test the connection phantomJS"); btnConn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { GUI.this.testConnect(); } }); panel.add(btnConn); lbConnectInfo = new JLabel("IsConnect:"); panel.add(lbConnectInfo); lbConnectStatus = new JLabel("noknow"); lbConnectStatus.setForeground(new Color(0, 0, 255)); panel.add(lbConnectStatus); btnTest = new JButton("Test"); btnTest.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { testConnect(); if(isSucces){ GUI.this.Test(); GUI.this.stdout.println("[+] test..."); }else{ JOptionPane.showMessageDialog(contentPane, "Please check if you can connect phantomJS!", "alert", JOptionPane.ERROR_MESSAGE); } } }); btnTest.setToolTipText("Start test run"); panel.add(btnTest); splitPane = new JSplitPane(); splitPane.setDividerLocation(0.5); contentPane.add(splitPane, BorderLayout.CENTER); taTestPayload = new JTextArea(); taTestPayload.setColumns(30); for (String payload : testPayload) { taTestPayload.append(payload + "\n\r"); } spTestPayload = new JScrollPane(taTestPayload, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); splitPane.setLeftComponent(spTestPayload); taResultPayload = new JTextArea(); taResultPayload.setColumns(30); spResultPayload = new JScrollPane(taResultPayload, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); splitPane.setRightComponent(spResultPayload); mCall.customizeUiComponent(panel); mCall.customizeUiComponent(btnTest); mCall.customizeUiComponent(btnConn); mCall.customizeUiComponent(taTestPayload); mCall.customizeUiComponent(splitPane); mCall.customizeUiComponent(contentPane); } public Component getComponet(){ return contentPane; } // 测试 private void Test() { taResultPayload.setText(""); String[] payloads = taTestPayload.getText().split("\n\r"); for (String payload : payloads) { String newPayload = sendTestPaylaod(payload); taResultPayload.append(newPayload + "\n\r"); } } // 发送测试payload private String sendTestPaylaod(String payload) { String newPayload = null; String currentPayload = payload; HttpPost httpPost = new HttpPost(this.getURL()); try { List nameValuePairs = new ArrayList(1); nameValuePairs.add(new BasicNameValuePair("payload", currentPayload)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse response = client.execute(httpPost); String responseAsString = EntityUtils.toString(response.getEntity()); newPayload = responseAsString; } catch (Exception e) { stderr.println(e.getMessage()); } return newPayload; } // 获取phantomJS public String getURL(){ String URL; String host = tfHost.getText().trim(); String port = tfPort.getText().trim(); URL = String.format("http://%s:%s",host,port); return URL; } //测试连接phantomJS private void testConnect(){ HttpGet httpGet = new HttpGet(this.getURL()); try { CloseableHttpResponse response = client.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); String responseAsString = EntityUtils.toString(response.getEntity()); int n = helpers.indexOf(responseAsString.getBytes(), "hello".getBytes(), false, 0, responseAsString.length()); if((statusCode == 200)&&(n != -1)){ stdout.println("[+] connect success!"); lbConnectStatus.setText("True"); isSucces = true; lbConnectStatus.setForeground(new Color(0,255,0)); }else{ stdout.println("[-] connect fail!"); lbConnectStatus.setText("False"); isSucces = false; lbConnectStatus.setForeground(new Color(255,0,0)); } } catch (Exception e) { stderr.println(e.getMessage()); stdout.println("[-] connect fail!"); lbConnectStatus.setText("False"); isSucces = false; lbConnectStatus.setForeground(new Color(255,0,0)); } } }
/** * shopmobile for tpshop * ============================================================================ * 版权所有 2015-2099 深圳搜豹网络科技有限公司,并保留所有权利。 * 网站地址: http://www.tp-shop.cn * —————————————————————————————————————— * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 . * 不允许对程序代码以任何形式任何目的的再发布。 * ============================================================================ * Author: 飞龙 wangqh01292@163.com * Date: @date 2015年10月20日 下午7:13:14 * Description: * @version V1.0 */ package com.tpshop.mallc.fragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Handler; import android.support.v4.app.Fragment; import android.view.View; import com.chanven.lib.cptr.PtrClassicFrameLayout; import com.tpshop.mallc.R; import com.tpshop.mallc.activity.common.SPIViewController; import com.tpshop.mallc.activity.person.user.SPLoginActivity; import com.tpshop.mallc.activity.person.user.SPLoginActivity_; import com.tpshop.mallc.model.SPProduct; import com.tpshop.mallc.utils.SPConfirmDialog; import com.tpshop.mallc.utils.SPDialogUtils; import com.tpshop.mallc.utils.SPLoadingDialog; import com.tpshop.mallc.utils.SPLoadingSmallDialog; import com.soubao.tpshop.utils.SPStringUtils; import org.json.JSONObject; import java.util.List; /** * @author admin * */ public abstract class SPBaseFragment extends Fragment implements SPIViewController { SPLoadingDialog mLoadingDialog; SPLoadingSmallDialog mLoadingSmallDialog; JSONObject mDataJson; /** * 跳转登录界面 */ public void gotoLogin(){ } public void init(View view){ initSubView(view); initEvent(); initData(); } /** * 取消网络请求 * @Description: TODO(这里用一句话描述这个方法的作用) * @param obj 设定文件 * @return void 返回类型 * @throws */ public void cancelRequest(Object obj){ } public void showToast(String msg){ SPDialogUtils.showToast(getActivity(), msg); } public void showToastUnLogin(){ showToast(getString(R.string.toast_person_unlogin)); } public void toLoginPage(){ toLoginPage(null); } public void toLoginPage(String from){ Intent loginIntent = new Intent(getActivity() , SPLoginActivity_.class); if(!SPStringUtils.isEmpty(from))loginIntent.putExtra(SPLoginActivity.KEY_FROM , from); startActivity(loginIntent); } public void showLoadingToast(){ showLoadingToast(null); } public void showLoadingToast(String title){ mLoadingDialog = new SPLoadingDialog(getActivity() , title); mLoadingDialog.setCanceledOnTouchOutside(false); mLoadingDialog.show(); } public void hideLoadingToast(){ if(mLoadingDialog !=null){ mLoadingDialog.dismiss(); } } public void showLoadingSmallToast(){ mLoadingSmallDialog = new SPLoadingSmallDialog(getActivity()); mLoadingSmallDialog.setCanceledOnTouchOutside(false); mLoadingSmallDialog.show(); } public void hideLoadingSmallToast(){ if(mLoadingSmallDialog!=null)mLoadingSmallDialog.dismiss(); } public void showConfirmDialog(String message , String title , final SPConfirmDialog.ConfirmDialogListener confirmDialogListener , final int actionType){ SPConfirmDialog.Builder builder = new SPConfirmDialog.Builder(getActivity()); builder.setMessage(message); builder.setTitle(title); builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); //设置你的操作事项 if(confirmDialogListener!=null)confirmDialogListener.clickOk(actionType); } }); builder.setNegativeButton(getResources().getString(R.string.cancel), new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } /** * * @Description: 初始化子类视图 * @param view 设定文件 * @return void 返回类型 * @throws */ public abstract void initSubView(View view); public abstract void initEvent(); public abstract void initData(); @Override public void gotoLoginPage() { /*if (!SPStringUtils.isEmpty(msg)){ showToast(msg); }*/ toLoginPage(); } @Override public void gotoLoginPage(String from) { toLoginPage(from); } /** * 刷新完成 */ public void refreshCompleted(Handler handler , final PtrClassicFrameLayout ptrLayout){ handler.post(new Runnable() { @Override public void run() { ptrLayout.setLoadMoreEnable(true); ptrLayout.refreshComplete(); ptrLayout.loadMoreComplete(true); } }); } /** * 加载更多完成 */ public void loadMoreComplete(Handler handler , final PtrClassicFrameLayout ptrLayout){ handler.post(new Runnable() { @Override public void run() { ptrLayout.loadMoreComplete(true); } }); } }
package ru.mindbroker.lesson02.prime; import ru.mindbroker.common.Task; import java.util.Arrays; import java.util.List; public class EratosthenesClassicBinTask implements Task { @Override public String run(List<String> data) { Integer n = Integer.valueOf(data.get(0)); return String.valueOf(calcPrimes(n)); } private int calcPrimes(Integer n) { int size = n + 1; int[] arr = new int[size / 32 + (size % 32 == 0 ? 0 : 1)]; for (int i = 2; i * i < size; i++) { int idx = i / 32; int sft = i % 32; if ((arr[idx] >> sft & 1) == 0) { for (int j = i * i; j < size; j += i) { int index= j / 32; int shift = j % 32; arr[index] = arr[index] | 1 << shift; } } } return count(arr, n); } private int count(int[] arr, int n) { int count = 0; for (int i = 2; i <= n; i++) { int idx = i / 32; int shift = i % 32; if ((arr[idx] >> shift & 1) == 0) { count++; } } return count; } }
package compressors; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import java.nio.file.Path; public class ZipCompressor implements Compressor { @Override public void extractFiles(Path filePath, Path destinationPath) { try { ZipFile zipFile = new ZipFile(filePath.toFile()); zipFile.extractAll(destinationPath.toString()); } catch (ZipException ex) { throw new UncheckedZipException(ex); } } }
package Fragments; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import android.content.Context; import android.content.res.AssetManager; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.widget.Toast; import com.example.tarea1.Database; import com.example.tarea1.R; import com.example.tarea1.Store; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class mapa extends SupportMapFragment implements LocationListener{ private static GoogleMap map; private Bundle savedInstanceSaved; Double latitud = 14.62; Double longitud = -90.56; LatLng point; LatLng point2; private List<Store> detalles = new ArrayList<Store>(); Store store; public static final LatLng GUATEMALA = new LatLng(14.62, -90.56); @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); this.savedInstanceSaved = savedInstanceState; setupMap(); } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); setupMap(); } private void setupMap() { if(map == null){ map = getMap(); if(map != null){ if(savedInstanceSaved == null){ map.setMyLocationEnabled(true); //Crea el objeto que gestiona las localizaciones LocationManager handle = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE); Criteria c = new Criteria(); c.setAccuracy(Criteria.ACCURACY_FINE); //obtiene el mejor proveedor en función del criterio asignado //(la mejor precisión posible) String provider = handle.getBestProvider(c, true); //Se activan las notificaciones de localización con los parámetros: proveedor, tiempo mínimo de actualización, distancia mínima, Locationlistener handle.requestLocationUpdates(provider, 10000, 1, this); //Obtenemos la última posición conocida dada por el proveedor Location loc = handle.getLastKnownLocation(provider); Toast.makeText(getActivity(), "entreeaqui", Toast.LENGTH_LONG).show(); if(loc != null){ map.setMyLocationEnabled(true); Toast.makeText(getActivity(), "entree", Toast.LENGTH_LONG).show(); latitud = loc.getLatitude(); longitud = loc.getLongitude(); LatLng ubicacion = new LatLng(latitud,longitud); CameraPosition camPos = new CameraPosition.Builder() .target(ubicacion) .zoom(15) .tilt(70) .build(); CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos); map.animateCamera(camUpd3); // map.addMarker(new MarkerOptions().position(point)).setTitle(detalles.get(i).getName()); //map = getMap(); Database db = new Database(getActivity(),"Tarea4",null,1); SQLiteDatabase SQLite = db.getWritableDatabase(); Cursor cursor = SQLite.rawQuery("SELECT * FROM tiendas" , null); if(cursor.moveToFirst()){ do{ String latlng = cursor.getString(cursor.getColumnIndex("location")); String name = cursor.getString(cursor.getColumnIndex("nombre")); Double latitud = Double.parseDouble(latlng.substring(0, 5)); Double longitud = Double.parseDouble(latlng .substring(6, latlng.length())); point = new LatLng(latitud,longitud); map.addMarker(new MarkerOptions().position(point)).setTitle(name); Toast.makeText(getActivity(), latlng, Toast.LENGTH_SHORT).show(); }while(cursor.moveToNext()); }else{ Toast.makeText(getActivity(), "sdfsdfsdf", Toast.LENGTH_SHORT).show(); } } } map.getUiSettings().setZoomControlsEnabled(false); } } } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub latitud = location.getLatitude(); longitud = location.getLongitude(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { getActivity().getMenuInflater().inflate(R.menu.maps_menu, menu); } @Override public void onProviderDisabled(String provider) {} @Override public void onProviderEnabled(String provider) {} @Override public void onStatusChanged(String provider, int status, Bundle extras) {} public static void modo_mapa(int Tipo){ map.setMapType(Tipo); } }
package NingGimi; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.widgets.Combo; public class Suker_INIFile { private final static int FILE_PATH_LENGTH = 256; public static final String INI_FILE_PATH = "ini\\config.ini"; public static final String TABLE_FILE_PATH = "ini\\table.cfg"; public static List<String> readFile(String filename) throws Exception { String line = null; List<String> records = new ArrayList<String>(); BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); while ((line = bufferedReader.readLine()) != null) { records.add(line); } bufferedReader.close(); return records; } public static String readIniFile(List<String> list, String key) { String temp = null; String[] seperate; String result = ""; int listSize = list.size(); for (int i = 0; i < listSize; i++) { temp = list.get(i); seperate = temp.split("=#"); if (seperate.length != 2) continue; if (seperate[0].toString().equals(key)) { result = seperate[1].toString(); break; } } return result; } public static void writeFile(List<String> val, String filename) throws IOException { BufferedWriter brOut = null; try { brOut = new BufferedWriter(new FileWriter(filename)); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (int i = 0; i < val.size(); i++) { String wr = val.get(i); try { brOut.write(wr); brOut.newLine(); } catch (IOException e) { System.out.println("fuck error"); } } brOut.close(); } public static void writeIniFile(String key, String value, List<String> writeList) { writeList.add(key + "=#" + value); } public static String makeComboList(Combo combo) { StringBuilder resultText = null; String result = null; Combo value = combo; int itemsCnt = value.getItemCount(); int i = 0; resultText = null; if (itemsCnt != 0) { resultText = new StringBuilder(itemsCnt * FILE_PATH_LENGTH); for (i = 0; i < itemsCnt-1; i++) { if (value.getItems()[i].toString().length() > 0) { resultText.append(value.getItems()[i].toString()); resultText.append(","); } } if (value.getItems()[i].toString().length() > 0) { resultText.append(value.getItems()[i].toString()); } } if (resultText != null) result = resultText.toString(); else result = ""; return result; } public static List<String> makeComboList(List<Combo> comboList) { StringBuilder resultText = null; List<String> result = new ArrayList<String>(); int j = 0; for(Iterator<Combo> it = comboList.iterator() ; it.hasNext() ; ) { Combo value = it.next(); int itemsCnt = value.getItemCount(); int i = 0; resultText = null; if (itemsCnt != 0) { resultText = new StringBuilder(itemsCnt * FILE_PATH_LENGTH); for (i = 0; i < itemsCnt-1; i++) { if (value.getItems()[i].toString().length() > 0) { resultText.append(value.getItems()[i].toString()); resultText.append(","); } } if (value.getItems()[i].toString().length() > 0) { resultText.append(value.getItems()[i].toString()); } } if (resultText != null) result.add(j++, resultText.toString()); else result.add(j++, ""); } return result; } }
package org.sbbs.base.search; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.springframework.util.Assert; import com.googlecode.genericdao.search.Filter; import com.googlecode.genericdao.search.ISearch; import com.googlecode.genericdao.search.Search; public class PropertySearchBuilder { private static final String GROUPON_FILTER_KEY = "groupon_";// and 和 or // ,如果没有或者都不是则默认为and private static final String GROUPON_OR = "or";// and 和 or // ,如果没有或者都不是则默认为and private static final String FILTER_PREFIX = "filter_"; private static final int DEFAULT_PAGE_SIZE = 20; private static final int DEFAULT_PAGE_NUMBER = 0; private static final String PAGE_KEY = "page"; private static final String PAGESIZE_KEY = "pagesize"; private static final String SORTNAME_KEY = "sortname"; private static final String SORTORDER_KEY = "sortorder"; public static Search BuildSearch( HttpServletRequest req ) { Search search = new Search(); search.addFilter( builderSearchFilters( req ) ); search = buildPager( req, search ); return search; } private static Search buildPager( HttpServletRequest req, Search search ) { String page = req.getParameter( PAGE_KEY ); String pageSize = req.getParameter( PAGESIZE_KEY ); String sortName = req.getParameter( SORTNAME_KEY ); String sortOrder = req.getParameter( SORTORDER_KEY ); boolean isAsc = ( sortOrder != null && sortOrder.equalsIgnoreCase( "asc" ) ); if ( sortName != null ) { if ( isAsc ) { search.addSortAsc( sortName ); } else { search.addSortDesc( sortName ); } } else { search.clearSorts(); } int pager, pagesize; try { pager = Integer.parseInt( page ); if(pager>0) pager--; } catch ( NumberFormatException e ) { // TODO Auto-generated catch block pager = DEFAULT_PAGE_NUMBER; } try { pagesize = Integer.parseInt( pageSize ); } catch ( NumberFormatException e ) { pagesize = DEFAULT_PAGE_SIZE; } search.setMaxResults( pagesize ); search.setPage( pager ); return search; } private static Filter builderSearchFilters( HttpServletRequest req ) { Filter filter; Map<String, Object> filterParamMap = getParametersStartingWith( req, FILTER_PREFIX ); String groupon = req.getParameter( GROUPON_FILTER_KEY ); if ( groupon != null && groupon.equalsIgnoreCase( GROUPON_OR ) ) groupon = "or"; else groupon = "and"; List srList = new ArrayList(); for ( Map.Entry<String, Object> entry : filterParamMap.entrySet() ) { String filterName = entry.getKey(); String value = (String) entry.getValue(); // 如果value值为空,则忽略此filter. if ( StringUtils.isNotBlank( value ) ) { Filter sr = buildSearchFilter( filterName, value ); srList.add( sr ); } } Filter[] sfilters = new Filter[srList.size()]; srList.toArray( sfilters ); if ( groupon.equals( GROUPON_OR ) ) { filter = Filter.or( sfilters ); } else { filter = Filter.and( sfilters ); } return filter; } /** * @param filterName * @param value * @return */ private static Filter buildSearchFilter( final String filterName, final String value ) { String firstPart = StringUtils.substringBefore( filterName, "_" ); String matchTypeCode = StringUtils.substring( firstPart, 0, firstPart.length() ); SearchOperator opr; try { opr = SearchOperator.valueOf( matchTypeCode.toLowerCase() ); } catch ( RuntimeException e ) { throw new IllegalArgumentException( "filter名称" + filterName + ":" + matchTypeCode + "没有按规则编写,无法得到属性比较类型.", e ); } String propertyNameStr = StringUtils.substringAfter( filterName, "_" ); Assert.isTrue( StringUtils.isNotBlank( propertyNameStr ), "filter名称" + filterName + "没有按规则编写,无法得到属性名称." ); Filter sr = new Filter(); sr.setProperty( propertyNameStr ); sr.setOperator( opr.getIntValue() ); if ( opr.getIntValue() == 7 || opr.getIntValue() == 70 || opr.getIntValue() == 71 || opr.getIntValue() == 72 ) { sr.setOperator( 7 ); } else { sr.setOperator( opr.getIntValue() ); } if ( opr.getIntValue() == 70 ) { sr.setValue( "%" + value + "%" ); } else if ( opr.getIntValue() == 71 ) { sr.setValue( value + "%" ); } else if ( opr.getIntValue() == 72 ) { sr.setValue( "%" + value ); } else { sr.setValue( value ); } return sr; } /** * @param request * @param prefix * @return */ private static Map<String, Object> getParametersStartingWith( ServletRequest request, String prefix ) { Assert.notNull( request, "Request must not be null" ); Assert.notNull( prefix, "filter prefix must not be null" ); Assert.hasText( prefix, "'name' must not be empty" ); Enumeration<?> paramNames = request.getParameterNames(); Map<String, Object> params = new TreeMap<String, Object>(); /* * if ( prefix == null ) { prefix = ""; } */ while ( paramNames != null && paramNames.hasMoreElements() ) { String paramName = (String) paramNames.nextElement(); if ( "".equals( prefix ) || paramName.startsWith( prefix ) ) { String unprefixed = paramName.substring( prefix.length() ); String[] values = request.getParameterValues( paramName ); if ( values == null || values.length == 0 ) { // Do nothing, no values found at all. } else if ( values.length > 1 ) { params.put( unprefixed, values ); } else { params.put( unprefixed, values[0] ); } } } return params; } }
package gestionaleDipendenti; public class Cerchio { // visto che raggio massimo è una ostante la andremo a creare come static in modo che ne esista solo una copia private static final int raggioMassimo = 1000; // Questa è una variabile di istanza cioè una variabile che appartiene agli oggetti cioè ogni cerchio avrà il suo raggio private double raggio ; // questa è una variabile statica cioè ne esistera solo una che appartiene alla classe condivisa da tutti gli oggetti. private static int numeroCerchi; public Cerchio () { numeroCerchi++; } public double calcolaPerimetro() { return 2*Math.PI*raggio; } public static void main(String[] args) { Cerchio c = new Cerchio (); Cerchio c2 = new Cerchio (); Cerchio c3 = new Cerchio (); c.raggio=10; c.calcolaPerimetro(); // le variabili statiche devono essere raggiunte dicendo nome classe.variabile statica. System.out.println(Cerchio.numeroCerchi); } }
package com.smxknife.hadoop.hdfs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import org.apache.hadoop.io.IOUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * @author smxknife * 2021/7/4 */ public class _01_Test { private Configuration conf = null; private FileSystem fs = null; @Before public void conn() throws IOException { // true表示加载配置文件,core-site.xml 、hdfs-site.xml conf = new Configuration(true); // 返回的是DistributeFileSystem,参考的是core-site.xml的配置 /* <property> <name>fs.defaultFS</name> <value>hdfs://smxknife.local:9000</value> </property> 如果是hdfs: 表示创建的是DistributeFileSystem */ fs = FileSystem.get(conf); } @Test public void makeDir() throws IOException { Path dir = new Path("/msb"); if (fs.exists(dir)) { fs.delete(dir, true); } fs.mkdirs(dir); } @Test public void upload() { Path file = new Path("/msb/hello"); try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream("./data/Hello"))) { final FSDataOutputStream fsDataOutputStream = fs.create(file); IOUtils.copyBytes(bis, fsDataOutputStream, conf, true); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Test public void blocks() throws IOException { Path file = new Path("/user/ShaoYun/data.txt"); final FileStatus fileStatus = fs.getFileStatus(file); final BlockLocation[] blockLocations = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen()); for (BlockLocation blockLocation : blockLocations) { System.out.println(blockLocation); } final FSDataInputStream fsDataInputStream = fs.open(file); System.out.println((char)fsDataInputStream.readByte()); System.out.println((char)fsDataInputStream.readByte()); System.out.println((char)fsDataInputStream.readByte()); System.out.println((char)fsDataInputStream.readByte()); System.out.println((char)fsDataInputStream.readByte()); System.out.println((char)fsDataInputStream.readByte()); System.out.println((char)fsDataInputStream.readByte()); System.out.println((char)fsDataInputStream.readByte()); System.out.println("-------------------"); fsDataInputStream.seek(1048576); System.out.println((char)fsDataInputStream.readByte()); System.out.println((char)fsDataInputStream.readByte()); System.out.println((char)fsDataInputStream.readByte()); } @After public void close() throws IOException { fs.close(); } }
package com.osce.service.system.param; import com.osce.api.system.param.PfParamService; import com.osce.dto.system.param.ParamDto; import com.osce.entity.SysParam; import com.osce.orm.system.param.PfParamDao; import com.sm.open.care.core.enums.Status; import org.apache.commons.lang3.StringUtils; import org.apache.dubbo.config.annotation.Service; import javax.annotation.Resource; import java.util.List; @Service public class PfParamServiceImpl implements PfParamService { @Resource private PfParamDao pfParamDao; @Override public List<SysParam> listParams(ParamDto dto) { if (StringUtils.isBlank(dto.getStatus())) { dto.setStatus(Status.ENABLED.getCode()); } return pfParamDao.listParams(dto); } @Override public Long count(ParamDto dto) { return pfParamDao.count(dto); } @Override public List<SysParam> listAllParam() { return pfParamDao.listAllParam(); } @Override public boolean addParam(SysParam dto) { return pfParamDao.addParam(dto) == 1 ? true : false; } @Override public boolean editParam(SysParam dto) { return pfParamDao.editParam(dto) == 1 ? true : false; } @Override public boolean isExistParam(String paramCode, String sysType) { return pfParamDao.isExistParam(paramCode, sysType) >= 1 ? true : false; } @Override public boolean changeStatus(List<Long> list, String status) { return pfParamDao.changeStatus(list, status) >= 1 ? true : false; } @Override public SysParam selectParamByCode(String paramCode) { return pfParamDao.selectParamByCode(paramCode); } }
package com.tencent.mm.plugin.appbrand.media.music; import com.tencent.mm.ipcinvoker.i; import com.tencent.mm.ipcinvoker.type.IPCBoolean; import com.tencent.mm.ipcinvoker.type.IPCString; final class AppBrandMusicClientService$a implements i<IPCString, IPCBoolean> { private AppBrandMusicClientService$a() { } public final /* synthetic */ Object av(Object obj) { return new IPCBoolean(a.ghW.uu(((IPCString) obj).value)); } }
package com.hdb.mailclient; import com.hdb.mailclient.ui.LoginFrame; //******登录界面上的main方法 public class Main { public static void main(String[] args) { LoginFrame loginFrame = new LoginFrame(); loginFrame.setVisible(true); } }
import java.time.LocalDateTime; import java.time.temporal.ChronoField; public class LocalDateTimeDemo { public static void main(String[] args) { LocalDateTime localDateTime = LocalDateTime.now(); System.out.println("DAY_OF_WEEK = "+localDateTime.get(ChronoField.DAY_OF_WEEK)); System.out.println("DAY_OF_YEAR = "+localDateTime.get(ChronoField.DAY_OF_YEAR)); System.out.println("DAY_OF_MONTH = "+localDateTime.get(ChronoField.DAY_OF_MONTH)); System.out.println("HOUR_OF_DAY = "+localDateTime.get(ChronoField.HOUR_OF_DAY)); System.out.println("MINUTE_OF_DAY = "+localDateTime.get(ChronoField.MINUTE_OF_DAY)); } }
package bean; import java.io.Serializable; public class ServcePrice implements Serializable{ public ServcePrice(int b_id, String type,int price) { super(); this.b_id = b_id; this.type = type; this.price = price; } private int b_id; private String type; private int price; public int getB_id() { return b_id; } public void setB_id(int b_id) { this.b_id = b_id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
package com.facebook.react.views.text; import android.text.TextUtils; import android.view.View; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.uimanager.BaseViewManager; import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.annotations.ReactPropGroup; import com.facebook.yoga.a; public abstract class ReactTextAnchorViewManager<T extends View, C extends ReactBaseTextShadowNode> extends BaseViewManager<T, C> { private static final int[] SPACING_TYPES = new int[] { 8, 0, 2, 1, 3 }; @ReactPropGroup(customType = "Color", names = {"borderColor", "borderLeftColor", "borderRightColor", "borderTopColor", "borderBottomColor"}) public void setBorderColor(ReactTextView paramReactTextView, int paramInt, Integer paramInteger) { float f1; float f2 = 1.0E21F; if (paramInteger == null) { f1 = 1.0E21F; } else { f1 = (paramInteger.intValue() & 0xFFFFFF); } if (paramInteger != null) f2 = (paramInteger.intValue() >>> 24); paramReactTextView.setBorderColor(SPACING_TYPES[paramInt], f1, f2); } @ReactPropGroup(defaultFloat = 1.0E21F, names = {"borderRadius", "borderTopLeftRadius", "borderTopRightRadius", "borderBottomRightRadius", "borderBottomLeftRadius"}) public void setBorderRadius(ReactTextView paramReactTextView, int paramInt, float paramFloat) { float f = paramFloat; if (!a.a(paramFloat)) f = PixelUtil.toPixelFromDIP(paramFloat); if (paramInt == 0) { paramReactTextView.setBorderRadius(f); return; } paramReactTextView.setBorderRadius(f, paramInt - 1); } @ReactProp(name = "borderStyle") public void setBorderStyle(ReactTextView paramReactTextView, String paramString) { paramReactTextView.setBorderStyle(paramString); } @ReactPropGroup(defaultFloat = 1.0E21F, names = {"borderWidth", "borderLeftWidth", "borderRightWidth", "borderTopWidth", "borderBottomWidth"}) public void setBorderWidth(ReactTextView paramReactTextView, int paramInt, float paramFloat) { float f = paramFloat; if (!a.a(paramFloat)) f = PixelUtil.toPixelFromDIP(paramFloat); paramReactTextView.setBorderWidth(SPACING_TYPES[paramInt], f); } @ReactProp(defaultBoolean = false, name = "disabled") public void setDisabled(ReactTextView paramReactTextView, boolean paramBoolean) { paramReactTextView.setEnabled(paramBoolean ^ true); } @ReactProp(name = "ellipsizeMode") public void setEllipsizeMode(ReactTextView paramReactTextView, String paramString) { if (paramString == null || paramString.equals("tail")) { paramReactTextView.setEllipsizeLocation(TextUtils.TruncateAt.END); return; } if (paramString.equals("head")) { paramReactTextView.setEllipsizeLocation(TextUtils.TruncateAt.START); return; } if (paramString.equals("middle")) { paramReactTextView.setEllipsizeLocation(TextUtils.TruncateAt.MIDDLE); return; } StringBuilder stringBuilder = new StringBuilder("Invalid ellipsizeMode: "); stringBuilder.append(paramString); throw new JSApplicationIllegalArgumentException(stringBuilder.toString()); } @ReactProp(defaultBoolean = true, name = "includeFontPadding") public void setIncludeFontPadding(ReactTextView paramReactTextView, boolean paramBoolean) { paramReactTextView.setIncludeFontPadding(paramBoolean); } @ReactProp(defaultInt = 2147483647, name = "numberOfLines") public void setNumberOfLines(ReactTextView paramReactTextView, int paramInt) { paramReactTextView.setNumberOfLines(paramInt); } @ReactProp(name = "selectable") public void setSelectable(ReactTextView paramReactTextView, boolean paramBoolean) { paramReactTextView.setTextIsSelectable(paramBoolean); } @ReactProp(customType = "Color", name = "selectionColor") public void setSelectionColor(ReactTextView paramReactTextView, Integer paramInteger) { if (paramInteger == null) { paramReactTextView.setHighlightColor(DefaultStyleValuesUtil.getDefaultTextColorHighlight(paramReactTextView.getContext())); return; } paramReactTextView.setHighlightColor(paramInteger.intValue()); } @ReactProp(name = "textAlignVertical") public void setTextAlignVertical(ReactTextView paramReactTextView, String paramString) { if (paramString == null || "auto".equals(paramString)) { paramReactTextView.setGravityVertical(0); return; } if ("top".equals(paramString)) { paramReactTextView.setGravityVertical(48); return; } if ("bottom".equals(paramString)) { paramReactTextView.setGravityVertical(80); return; } if ("center".equals(paramString)) { paramReactTextView.setGravityVertical(16); return; } StringBuilder stringBuilder = new StringBuilder("Invalid textAlignVertical: "); stringBuilder.append(paramString); throw new JSApplicationIllegalArgumentException(stringBuilder.toString()); } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\views\text\ReactTextAnchorViewManager.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.codepath.nytimes.adapters; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.codepath.nytimes.databinding.ItemArticleBinding; public class ArticleHolder extends RecyclerView.ViewHolder { public ItemArticleBinding binding; public TextView tvTitle; public ImageView imgArticle; public ArticleHolder(View itemView) { super(itemView); binding = ItemArticleBinding.bind(itemView); tvTitle = binding.tvTitle; imgArticle = binding.imgArticle; } }
package com.facebook.react.views.scroll; import android.os.SystemClock; public class OnScrollDispatchHelper { private long mLastScrollEventTimeMs = -11L; private int mPrevX = Integer.MIN_VALUE; private int mPrevY = Integer.MIN_VALUE; private float mXFlingVelocity; private float mYFlingVelocity; public float getXFlingVelocity() { return this.mXFlingVelocity; } public float getYFlingVelocity() { return this.mYFlingVelocity; } public boolean onScrollChanged(int paramInt1, int paramInt2) { boolean bool; long l1 = SystemClock.uptimeMillis(); if (l1 - this.mLastScrollEventTimeMs > 10L || this.mPrevX != paramInt1 || this.mPrevY != paramInt2) { bool = true; } else { bool = false; } long l2 = this.mLastScrollEventTimeMs; if (l1 - l2 != 0L) { this.mXFlingVelocity = (paramInt1 - this.mPrevX) / (float)(l1 - l2); this.mYFlingVelocity = (paramInt2 - this.mPrevY) / (float)(l1 - l2); } this.mLastScrollEventTimeMs = l1; this.mPrevX = paramInt1; this.mPrevY = paramInt2; return bool; } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\views\scroll\OnScrollDispatchHelper.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.xtw.msrd; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.widget.Toast; public class MountFileSystemReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { G.log("MountFileSystemReceiver begin" + intent.getAction() + ", uri : " + intent.getData()); if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) { G.initRoot(); if (TextUtils.isEmpty(G.sRootPath)) { G.log("init root error!"); Toast.makeText(context, "初始化存储路径失败!", Toast.LENGTH_LONG).show(); return; } G.log("start record by Mounter!"); RecordService.start(context); } else { RecordService.stop(context); G.sRootPath = null; G.log("stop record by Mounter!"); } G.log("MountFileSystemReceiver end" + intent.getAction() + ", uri : " + intent.getData()); } }
package edu.buet.cse.spring.ch04.v2.impl; import org.aspectj.lang.ProceedingJoinPoint; public class Audience { public void watchPerformance(ProceedingJoinPoint joinPoint) { System.out.println("The audience is taking their seats"); System.out.println("The audience is turning their cell phones off"); try { long start = System.currentTimeMillis(); joinPoint.proceed(); long end = System.currentTimeMillis(); System.out.println("Audience : CLAP CLAP CLAP"); System.out.printf("The performance took %d ms%n", end - start); } catch (Throwable t) { System.out.println("Audience : BOO ! We want our money back !"); t.printStackTrace(System.err); } } }
/* * JsonMsg.java * * MDK 4.0.1 - Clase utilizada para guardar las posiciones de las naves. * * 05/03/2016 * * Copyright Drintin© 2016 */ package uy.com.karibe.domain; public class Ship { private int gameId; private String name; private int x; private int y; private int rotation; private int health; private String state; private String nickname; public int getGameId() { return gameId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getRotation() { return rotation; } public void setRotation(int rotation) { this.rotation = rotation; } public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public Ship(int gameId, String name, int x, int y, int rotation, int health, String state, String nickname) { this.gameId = gameId; this.name = name; this.x = x; this.y = y; this.rotation = rotation; this.health = health; this.state = state; this.nickname = nickname; } }
package com.example.princ.mydthb2b.myaccountpackage; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.princ.mydthb2b.R; import org.w3c.dom.Text; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import de.hdodenhof.circleimageview.CircleImageView; public class MyAccountPojo extends RecyclerView.Adapter<MyAccountPojo.ViewHolder> { List<DetailClass> list; Context context; public MyAccountPojo(List<DetailClass> list, Context context) { this.list = list; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater=LayoutInflater.from(context); View view=layoutInflater.inflate(R.layout.item,parent,false); ViewHolder viewHolder=new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { DetailClass detailClass=list.get(position); holder.textView.setText(detailClass.getNm()); holder.circleImageView.setImageResource(detailClass.getImg()); } @Override public int getItemCount() { return list.size(); } public class ViewHolder extends RecyclerView.ViewHolder { CircleImageView circleImageView; TextView textView; public ViewHolder(@NonNull View itemView) { super(itemView); circleImageView=itemView.findViewById(R.id.image); textView=itemView.findViewById(R.id.textView1); } } }
/* * 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 JavaBean; import javax.swing.JTextField; /** * * @author Walleson Moura */ public class Os { private int id; private String data; private String tipoOs; private String status; private String nomeCliente; private int idCliente; private int idFuncionario; private int idProduto; private String eqpDesc; private String eqpSerie; private String eqpModelo; private String eqpFabric; private String defeito; private String servico; private String descricao; private float valor; private String garantia; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getTipoOs() { return tipoOs; } public void setTipoOs(String tipoOs) { this.tipoOs = tipoOs; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getNomeCliente() { return nomeCliente; } public void setNomeCliente(String nomeCliente) { this.nomeCliente = nomeCliente; } public int getIdCliente() { return idCliente; } public void setIdCliente(int idCliente) { this.idCliente = idCliente; } public int getIdFuncionario() { return idFuncionario; } public void setIdFuncionario(int idFuncionario) { this.idFuncionario = idFuncionario; } public int getIdProduto() { return idProduto; } public void setIdProduto(int idProduto) { this.idProduto = idProduto; } public String getEqpDesc() { return eqpDesc; } public void setEqpDesc(String eqpDesc) { this.eqpDesc = eqpDesc; } public String getEqpSerie() { return eqpSerie; } public void setEqpSerie(String eqpSerie) { this.eqpSerie = eqpSerie; } public String getEqpModelo() { return eqpModelo; } public void setEqpModelo(String eqpModelo) { this.eqpModelo = eqpModelo; } public String getEqpFabric() { return eqpFabric; } public void setEqpFabric(String eqpFabric) { this.eqpFabric = eqpFabric; } public String getDefeito() { return defeito; } public void setDefeito(String defeito) { this.defeito = defeito; } public String getServico() { return servico; } public void setServico(String servico) { this.servico = servico; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public float getValor() { return valor; } public void setValor(float valor) { this.valor = valor; } public String getGarantia() { return garantia; } public void setGarantia(String garantia) { this.garantia = garantia; } public void setId(JTextField txtTelaOSNumOS) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package cn.wzvtcsoft.validator.core; import cn.wzvtcsoft.validator.exceptions.StringLogicException; import org.springframework.expression.spel.standard.SpelExpressionParser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * MutationValidation 的解析器 */ public class RuleParser { /** * 属性获取的正则表达式 */ private static final String PROPERTY_REGEX = "[a-z][a-zA-Z0-9_$]*"; /** * 根据校验规则缓存属性名 */ private static final Map<String, List<String>> rulePropertyCache = new HashMap<>(); /** * spEL 解析器,用来解析 String 并执行String语法,这里用来解析并执行 String 的逻辑判断 */ public static final SpelExpressionParser parser = new SpelExpressionParser(); /** * 解析 校验规则中的属性或参数 */ public static List<String> getProperties(String rule) { if (rulePropertyCache.containsKey(rule)) { return rulePropertyCache.get(rule); } Pattern pattern = Pattern.compile(PROPERTY_REGEX); Matcher matcher = pattern.matcher(rule); List<String> list = new ArrayList<>(); while (matcher.find()) { list.add(matcher.group()); } checkStringLogic(rule, list); rulePropertyCache.put(rule, list); return list; } private static void checkStringLogic(String rule, List<String> properties) { if (!"".equals(rule)) { for (String property : properties) { rule = rule.replace(property, "true"); } try { parser.parseRaw(rule).getValue(boolean.class); } catch (Exception ex) { throw new StringLogicException("字符串逻辑异常 : " + rule); } } } /** * 对校验规则中的属性或参数 进行逻辑判断 * * @param rule 校验规则 * @param properties 要校验的属性 * @param booleans 目标属性的boolean 值 * @return 返回逻辑判断的结果 */ public static boolean executeStringValid(String rule, List<String> properties, List<Boolean> booleans) { String result = rule; for (int i = 0; i < properties.size(); i++) { result = result.replace(properties.get(i), booleans.get(i).toString()); } return RuleParser.parser.parseExpression(result).getValue(boolean.class); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.book.myjpa; /** * * @author avbravo */ public class Dog { private String id; /** * Get the value of id * * @return the value of id */ public String getId() { return id; } /** * Set the value of id * * @param id new value of id */ public void setId(String id) { this.id = id; } }
package DrawGuess; import java.io.Serializable; public class Bag implements Serializable { public int x1,x2,y1,y2,width; public int color; public String message; public String userName; public int status; // 1: plain message 2: point information 3: hint message or none-client-related message public Bag(String userName,String message) { this.message = message; this.userName = userName; this.status = 1; } public Bag(String userName,String message, int newStatus) { this.message = message; this.userName = userName; this.status = newStatus; } public Bag(){} public Bag(String userName,int x1,int x2,int y1,int y2,int color,int width){ this.userName = userName; this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; this.width = width; this.color = color; this.message = "this is not a message"; this.status = 2; } }
/* * @Author: your name * @Date: 2020-03-25 17:02:30 * @LastEditTime: 2020-04-15 18:39:03 * @LastEditors: your name * @Description: In User Settings Edit * @FilePath: \goc:\Users\liuw\Documents\note\algorithm\code\leetcode\1.two-sum\TwoSum.java */ import java.util.HashMap; public class TwoSum { public int[] run(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int val = target - nums[i]; if (map.get(val) != null) { return new int[]{map.get(val), i}; } map.putIfAbsent(nums[i], i); } return new int[2]; } }
package com.github.ezauton.visualizer.processor.factory; import com.github.ezauton.recorder.SubRecording; import com.github.ezauton.visualizer.util.DataProcessor; import java.util.Optional; public interface DataProcessorFactory { Optional<DataProcessor> getProcessor(SubRecording subRecording); }
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; //coded by jack. public class adminmenu { public static void admmenu(){ int menuselect = 0; Scanner scaninput = new Scanner(System.in); System.out.println("\n"); System.out.println("\nemployee console"); System.out.println("--------------------"); System.out.println("Select an option:"); System.out.println("1: add employee"); System.out.println("2: add new books"); System.out.println("0: Logout"); System.out.println("Enter an Option"); if (scaninput.hasNextInt()) menuselect = scaninput.nextInt(); switch (menuselect) { case 1: System.out.println("you have selected add employee "); addemployee(); admmenu(); break; case 2: System.out.println("you have selected add new books"); addbooks(); admmenu(); } } public static void addemployee() { String Password = ""; Scanner in = new Scanner(System.in); System.out.println("Enter employee Email: "); String Email = in.nextLine(); //System.out.println("Enter an Email: "); //String Email = in.nextLine(); do { System.out.println("Password must be longer than 5 characters"); System.out.println("Enter a Password: "); Password = in.nextLine(); } while (Password.length() < 6); String filepath = "employees.txt"; SaveDetails(Email, Password, filepath); //SaveDetails(Name, Email, Password, filepath, Age, Gender); //SaveDetails(Name, Password, filepath); } public static void valid() { System.out.println("Valid"); } //The function below saves a a person's details. These details will be entered using the sign up form. public static void SaveDetails(String Email, String Password, String filepath) { Scanner in = new Scanner(System.in); Email = Email; //Email = Email; Password = Password; filepath = filepath; try { FileWriter save = new FileWriter(filepath, true); BufferedWriter save_bw = new BufferedWriter(save); PrintWriter save_pw = new PrintWriter(save_bw); save_pw.println(Email + "," + Password); save_pw.flush(); save_pw.close(); System.out.println("new employee registered registered, please sign in."); } catch (Exception E) { System.out.println("Not saved"); } } public static void addbooks(){ String author; Scanner in = new Scanner(System.in); System.out.println("Enter book title "); String title = in.nextLine(); System.out.println("Enter the author"); author = in.nextLine(); System.out.println("Enter the genre"); String genre = in.nextLine(); String filepath = "books.txt"; SavebookDetails(title,author,genre,filepath); } public static void SavebookDetails(String title, String author,String genre, String filepath) { Scanner in = new Scanner(System.in); title = title; author = author; genre = genre; filepath = filepath; try { FileWriter save = new FileWriter(filepath, true); BufferedWriter save_bw = new BufferedWriter(save); PrintWriter save_pw = new PrintWriter(save_bw); save_pw.println(title + "," + author +"," + genre); save_pw.flush(); save_pw.close(); System.out.println("new book added"); } catch (Exception E) { System.out.println("Not saved"); } } }
package com.yixin.kepler.core.attachment; import com.yixin.common.exception.BzException; import com.yixin.common.utils.InvokeResult; import com.yixin.dsc.dto.DscSupplyAttachmentsDto; import com.yixin.dsc.dto.DscSupplyDto; import com.yixin.dsc.entity.order.*; import com.yixin.kepler.common.JacksonUtil; import com.yixin.kepler.common.ScriptEngineUtil; import com.yixin.kepler.common.enums.BankPhaseEnum; import com.yixin.kepler.core.constant.CommonConstant; import com.yixin.kepler.dto.OsbAttachmentDTO; import com.yixin.kepler.enity.AssetAttachmentRule; import com.yixin.kepler.enity.AssetFinanceInfo; import com.yixin.kepler.enity.AssetMainInfo; import com.yixin.kepler.enity.OsbFileLog; import net.sf.json.JSONObject; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import javax.annotation.ManagedBean; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; /** * 亿联文件上传 * @author sukang */ //@ManagedBean(value = "yILLIONUploadAttachment") @Deprecated public class YILLIONUploadAttachment extends UploadAttachmentDomain<OsbAttachmentDTO>{ private final Logger logger = LoggerFactory.getLogger(getClass()); private final static String FILE_PATH = "/yillion/%s/%s/"; /** * 附件类型(一个大类包含多个) */ private static Map<String,List<String>> attachCodeMap; static { if (attachCodeMap == null) { attachCodeMap = new HashMap<>(); } //身份证 attachCodeMap.put("applicantOrderIdPositive", Arrays.asList("applicantOrderIdPositive", "applicantOrderIdReverse")); attachCodeMap.put("leaseMainContract", Arrays.asList("leaseMainContract", "contractReverse")); } private final static String YILLION = "yillion"; @Override protected void getData() throws BzException { super.getData(); //先通过url上传 uploadFileByUrl(getAttachments()); } private List<DscFileAttachment> getAttachments() { // 获取对应的附件信息 DscSalesApplyMain main = DscSalesApplyMain.getByApplyNo(this.inputDto.get().getBzId()); return DscFileAttachment.lists(main.getId()); } @Override protected String getFinancialId() { AssetFinanceInfo assetFinanceInfo = AssetFinanceInfo.getByCode(getBankCode()); Assert.notNull(assetFinanceInfo,"未获取到资方id"); return assetFinanceInfo.getId(); } @Override public String getBankCode() { return CommonConstant.BankName.YILLION_BANK; } /** * 文件服务器路径/申请日期/订单编号/ */ @Override public String getServerFilePath() { String format = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now()); AssetMainInfo assetMainInfo = AssetMainInfo.getByApplyNo(inputDto.get().getBzId()); return String.format(FILE_PATH,format,assetMainInfo.getVenusApplyNo()); } /** * *订单编号_大类编号+子类编号+文件序号_时间戳.文件后缀 * */ @Override public String rename(AttachmentRuleParamMap paramMap, Map<String, AssetAttachmentRule> rules, List<Map<String, String>> renamedList) { //获取订单对应的附件信息 DscSalesApplyMain main = DscSalesApplyMain.getByApplyNo( this.inputDto.get().getBzId()); Map<String, List<DscFileAttachment>> attachmentMap = DscFileAttachment.get( main.getId()); //合并 dealAttachmentMap(rules, attachmentMap); //js入参 是否新车 DscSalesApplyCar salesApplyCar = DscSalesApplyCar.getBymainId(main.getId()); boolean isNew = "1".equals(salesApplyCar.getAcllx()); //js入参 客户融资额 BigDecimal frze = DscSalesApplyCost.getByMainId(main.getId()).getFrze(); //命名 for (Map.Entry<String, AssetAttachmentRule> rule : rules.entrySet()) { List<DscFileAttachment> dscFileAttachments = attachmentMap.get(rule.getKey()); int size = CollectionUtils.isEmpty(dscFileAttachments) ? 0 : dscFileAttachments.size(); logger.info("订单号{}文件类型为{},数量为{}", main.getApplyNo(), rule.getKey(), size); //验证 boolean checkRs = (boolean) ScriptEngineUtil.eval(rule.getValue().getRule(), "toDo", size, isNew); if (!checkRs) { throw new BzException("订单号(" + main.getApplyNo() + ")" + rule.getValue().getAttachMainType() + "缺少必要文件,规则为" + rule.getValue().getRule() + "入参为(" + size + "," + isNew + ")"); } else { int index = 1; if (CollectionUtils.isNotEmpty(dscFileAttachments)) { for (DscFileAttachment dscFileAttachment : dscFileAttachments) { Map<String, String> renameMap = new HashMap<>(4); renameMap.put(FILEID, dscFileAttachment.getFileId()); renameMap.put(FILENAME, getFileName(rule.getValue().getNameFormat(), index)); renamedList.add(renameMap); ++index; } } } } return renamedList.toString(); } /** *订单编号_大类编号+子类编号+文件序号_时间戳.文件后缀 * * %s_大类编号子类编号%s_YYYYMMDDhhmmss(hh为24小时制).文件后缀 */ private String getFileName(String nameFormat, int index) { AssetMainInfo assetMainInfo = AssetMainInfo.getByApplyNo(inputDto.get().getBzId()); return String.format(nameFormat, assetMainInfo.getVenusApplyNo(), String.format("%02d",index), DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now())); } @Override public void upLoadTask(String bzId, String bzType, List<Map<String, String>> renamedList) { OsbFileLog osbFileLog = osbFileDomain.createOsbFileLog(bzId, bzType, YILLION, false, "", getPackageName(), true, JacksonUtil.fromObjectToJson(renamedList), getServerFilePath()); String url = sftpConfig.getSftp().get(OsbFileDomain.OSB_DOWNLOAD_HOST) + OsbFileUrl.CMBC_OSB_UPLOAD_URI; osbFileDomain.uploadOsbData(osbFileLog, getUploadData(osbFileLog),url); } private String getUploadData(OsbFileLog osbFileLog) { logger.info("[osb文件处理]需要处理的osbFileLog:{}", JacksonUtil.fromObjectToJson(osbFileLog)); Map<String,Object> data = new HashMap<>(12); data.put("archives", osbFileLog.isArchives()); data.put("compress", osbFileLog.isCompress()); data.put("compressPackageName", osbFileLog.getCompressName()); data.put("filePath", osbFileLog.getServerFilePath()); data.put("password", osbFileLog.getCompressPwd()); data.put("serialNumber", osbFileLog.getTranNo()); data.put("server", osbFileLog.getServerType()); data.put("serverIP", osbFileLog.getServerIp()); data.put("serverPassword", osbFileLog.getServerPwd()); data.put("serverPort", osbFileLog.getServerPort()); data.put("serverUserName", osbFileLog.getServerUname()); data.put("systemId", osbFileLog.getRoutingKey()); data.put("files", osbFileLog.getFileJson()); data.put("compressFormat", osbFileLog.getCompressFormat()); logger.info("[osb文件处理]即将传递给osb的参数信息JSON:{}", data.toString()); return data.toString(); } @Override public String getPackageName() { return ""; } @Override public InvokeResult<DscSupplyDto> checkAttachmentFile(OsbAttachmentDTO osbAttachmentDTO) { // //TODO 暂时写死,文件准入通过 InvokeResult<DscSupplyDto> invokeResult = new InvokeResult<>(); // return invokeResult.success(); DscSalesApplyMain dscSalesApplyMain = DscSalesApplyMain.getByApplyNo(osbAttachmentDTO.getBzId()); Map<String, List<DscFileAttachment>> attachmentMap = DscFileAttachment.get( dscSalesApplyMain.getId()); Map<String, AssetAttachmentRule> rules = AssetAttachmentRule .getRule(dscSalesApplyMain.getCapitalId()) .get(BankPhaseEnum.get(osbAttachmentDTO.getBzType())); dealAttachmentMap(rules,attachmentMap); //将文件转成银行需要格式 dealNameFormat(attachmentMap); DscSalesApplyCar salesApplyCar = DscSalesApplyCar.getBymainId( dscSalesApplyMain.getId()); //js规则入参 boolean isNew = "1".equals(salesApplyCar.getAcllx()); //js入参 客户融资额 BigDecimal frze = DscSalesApplyCost.getByMainId( dscSalesApplyMain.getId()).getFrze(); DscSupplyDto dscSupplyDto = null; List<DscSupplyAttachmentsDto> results = null; for (Map.Entry<String, AssetAttachmentRule> rule: rules.entrySet()) { List<DscFileAttachment> list = attachmentMap.get(rule.getKey()); int size = list == null ? 0 : list.size(); boolean checkRs = (boolean)ScriptEngineUtil.eval(rule.getValue().getRule(), "toDo", size,isNew,frze); if (!checkRs) { //组装errorInfo; if (dscSupplyDto == null) { dscSupplyDto = new DscSupplyDto(); results = new ArrayList<>(); } DscSupplyAttachmentsDto attachmentsDto = new DscSupplyAttachmentsDto(1,-1); attachmentsDto.setAttName(rule.getValue().getAttachName()); String subType = rule.getValue().getAttachMainType(); String mergerAttachType = rule.getValue().getMergerAttachType(); attachmentsDto.setAttType( org.apache.commons.lang3.StringUtils.isBlank(mergerAttachType) ? subType:mergerAttachType); results.add(attachmentsDto); } } if (dscSupplyDto != null){ dscSupplyDto.setAttList(results); invokeResult.failure("缺少必要附件类型").setData(dscSupplyDto); return invokeResult; } return invokeResult.success(); } /** * 更改为银行所需文件类型 * * @author xy * @date 2018/11/5 14:54 * @return void */ private void dealNameFormat(Map<String, List<DscFileAttachment>> attachmentMap) { //身份证 attachmentMap.put("applicantOrderIdPositive",getValues(attachCodeMap.get("applicantOrderIdPositive"),attachmentMap)); //租赁合同 attachmentMap.put("leaseMainContract",getValues(attachCodeMap.get("leaseMainContract"),attachmentMap)); } }
package com.figureshop.springmvc.dataAccess.entity; import com.figureshop.springmvc.model.Translation; import javax.persistence.*; import java.io.Serializable; import java.math.BigDecimal; @Entity @Table(name = "product_item") public class ProductItemEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private int quantity; @OneToOne @JoinColumn(nullable = false) private TranslationEntity translation; @Column(nullable = false) private BigDecimal subTotal; @ManyToOne private PurchaseEntity purchase; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public PurchaseEntity getPurchase() { return purchase; } public void setPurchase(PurchaseEntity purchase) { this.purchase = purchase; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public TranslationEntity getTranslation() { return translation; } public void setTranslation(TranslationEntity translation) { this.translation = translation; } public BigDecimal getSubTotal() { return subTotal; } public void setSubTotal(BigDecimal subTotal) { this.subTotal = subTotal; } }
package fr.tenebrae.MMOCore.Skills; public class Skill { public String name; public int maxRank; }
package com.shopping.etrade.response; import java.io.Serializable; import com.shopping.etrade.dto.CardProductDTO; import lombok.Getter; import lombok.Setter; @Getter @Setter public class ResponseAddProductToCard implements Serializable { /** * */ private static final long serialVersionUID = -4340740708139734066L; private CardProductDTO cardProductDTO; }
/************************************************************************** * Developed by Language Technologies Institute, Carnegie Mellon University * Written by Richard Wang (rcwang#cs,cmu,edu) **************************************************************************/ package com.rcwang.seal.asia; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import com.rcwang.seal.expand.LangProvider; import com.rcwang.seal.util.Helper; public class HyponymProvider { public static class Hyponym { private List<String> hyponymPhrases; private List<String> listWords; private List<String> beginWords; private List<String> splitWords; private String langID; public Hyponym(String langID) { this.langID = langID; hyponymPhrases = new ArrayList<String>(); listWords = new ArrayList<String>(); beginWords = new ArrayList<String>(); splitWords = new ArrayList<String>(); } public void addBeginWords(String[] words) { add(words, beginWords); Helper.sortByLength(beginWords, false); } public void addHyponymPhrases(String[] phrases) { add(phrases, hyponymPhrases); } public void addListWords(String[] words) { add(words, listWords); } public void addSplitWords(String[] words) { add(words, splitWords); Helper.sortByLength(splitWords, false); } public List<String> getBeginWords() { return beginWords; } public List<String> getHyponymPhrases() { return hyponymPhrases; } public String getLangID() { return langID; } public String getListQuery() { StringBuffer buf = new StringBuffer("("); for (String word : listWords) { if (buf.length() > 1) buf.append(" OR "); buf.append(word); } buf.append(")"); return buf.toString(); } public List<String> getSplitWords() { return splitWords; } private void add(String[] strs, List<String> list) { for (String s : strs) if (!list.contains(s)) list.add(s); } } public static final String C = "<1>"; public static Map<String, Hyponym> hyponymMap = initialize(); public static Hyponym getHyponym(String langID) { return hyponymMap.get(langID); } public static Hyponym getLangEnglish() { Hyponym hyponym = new Hyponym(LangProvider.ENG[LangProvider.ID]); hyponym.addHyponymPhrases(new String[] { C + " such as", C + " i.e.", C + " e.g.", // C + " include", C + " including", C + " like", "and other " + C, "or other " + C, // test "such " + C + " as", // test }); hyponym.addBeginWords(new String[] { "the ", "a " }); hyponym.addSplitWords(new String[] { "i.e", "e.g", "etc", " or ", " and ", "as well as" }); hyponym.addListWords (new String[] { "list", "names", "top", "best", "hot", "popular", "famous", "common" }); return hyponym; } public static Hyponym getLangJapanese() { Hyponym hyponym = new Hyponym(LangProvider.JAP[LangProvider.ID]); hyponym.addHyponymPhrases(new String[] { C + " 例えば", C + " たとえば", C + "は 例えば", C + "は たとえば", C + "と言えば", C + "といえば", "等の" + C, "などの" + C, "とかの" + C, // "のような" + C, // test }); hyponym.addBeginWords(new String[] {}); hyponym.addSplitWords(new String[] { "例えば", "たとえば", "と言えば", "といえば", "と", "や", "および", "など", "とか", "が", "を", "に", "で", "は", "も" }); hyponym.addListWords (new String[] { "一覧", "リスト", "有名", "普及" }); return hyponym; } public static Hyponym getLangKorean() { Hyponym hyponym = new Hyponym(LangProvider.KOR[LangProvider.ID]); hyponym.addHyponymPhrases(new String[] { C + "로는", C + "으로", C + " 예를 들면", C + " 예를 들어", "등과 같은 " + C, }); hyponym.addBeginWords(new String[] {}); hyponym.addSplitWords(new String[] { "등", "과", "로", "를", "이", "가", "그", "저", "도", "에", "은", "는", "을", "고", "에", "지", "었", "와", "어", "겠", "로는", "으로", "또는", "있다", "없다", "하고", "으시", "에서", "까지", "어요", "지요", "으러", "지만", "에게", "으로", "어서", "그리고", }); hyponym.addListWords (new String[] { "목록", "리스트", "최고", "인기" }); return hyponym; } public static Hyponym getLangSChinese() { Hyponym hyponym = new Hyponym(LangProvider.CHS[LangProvider.ID]); hyponym.addHyponymPhrases(new String[] { C + " 例如", C + " 比如", C + " 包括", C + " 包含", C + " 譬如", // C + " 如", "等" + C, }); hyponym.addBeginWords(new String[] { "了", "说" }); hyponym.addSplitWords(new String[] { "例如", "比如", "包括", "包含", "譬如", "等", "和", "及", "与", "或", "加", "还有", "外加", "以及", "等等", "此外", "另外" }); hyponym.addListWords (new String[] { "列表", "名单", "清单", "一览", "有名", "着名", "热门" }); return hyponym; } public static Hyponym getLangTChinese() { Hyponym hyponym = new Hyponym(LangProvider.CHT[LangProvider.ID]); hyponym.addHyponymPhrases(new String[] { C + " 例如", C + " 比如", C + " 包括", C + " 包含", C + " 譬如", // C + " 如", "等" + C, }); hyponym.addBeginWords(new String[] { "了", "說" }); hyponym.addSplitWords(new String[] { "例如", "比如", "包括", "包含", "譬如", "等", "和", "及", "與", "或", "加", "還有", "外加", "以及", "等等", "此外", "另外" }); hyponym.addListWords (new String[] { "列表", "名單", "清單", "一覽", "有名", "著名", "熱門" }); return hyponym; } /*public static Hyponym getLangUniversal() { Hyponym hyponym = new Hyponym(LangProvider.UNI_LANG); hyponym.addHyponymPhrases(new String[] {}); hyponym.addBeginWords(new String[] {}); hyponym.addSplitWords(new String[] {}); hyponym.addListWords (new String[] {}); return hyponym; }*/ public static String getListQuery(String langID) { Hyponym hyponym = hyponymMap.get(langID); if (hyponym == null) return null; return hyponym.getListQuery(); } public static Map<String, Hyponym> initialize() { List<Hyponym> hyponymPatterns = new ArrayList<Hyponym>(); hyponymPatterns.add(getLangEnglish()); hyponymPatterns.add(getLangTChinese()); hyponymPatterns.add(getLangSChinese()); hyponymPatterns.add(getLangJapanese()); hyponymPatterns.add(getLangKorean()); // hyponymPatterns.add(getLangUniversal()); Map<String, Hyponym> hyponymMap = new HashMap<String, Hyponym>(); for (Hyponym hyponym : hyponymPatterns) hyponymMap.put(hyponym.getLangID(), hyponym); return hyponymMap; } public static String removeBeginWord(String s, String langID) { if (s == null || langID == null) return null; s = s.trim(); Hyponym hyponym = hyponymMap.get(langID); String lc = s.toLowerCase(); for (String word : hyponym.getBeginWords()) { if (lc.startsWith(word.toLowerCase())) return s.substring(word.length()); } return s; } public static List<String> split(String s, String langID) { if (s == null || langID == null) return null; Hyponym hyponym = hyponymMap.get(langID); StringBuffer buf = new StringBuffer("((?i:"); for (String word : hyponym.getSplitWords()) buf.append(Pattern.quote(word)).append("|"); // a period that (possibly) indicates the end of sentence (11/25/2008) buf.setLength(buf.length()-1); buf.append(")|(?<=[a-z]{3,})\\.)"); s = " " + s + " "; String[] splits = s.split(buf.toString()); List<String> list = new ArrayList<String>(); for (String split : splits) { split = split.trim(); if (split.length() > 0) list.add(split); } if (list.isEmpty()) list.add(s.trim()); return list; } public static boolean supports(String langID) { return hyponymMap.keySet().contains(langID); } }
/*Binary Tree Zigzag Level Order Traversal question: http://www.lintcode.com/en/problem/binary-tree-zigzag-level-order-traversal/ answer: http://www.jiuzhang.com/solutions/binary-tree-zigzag-level-order-traversal/ Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). Example Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ] */ package binaryTreeAndDivideConquer; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class BinaryTreeZigzagLevelOrderTraversal { public static ArrayList<ArrayList<Integer>> zigzagLevelTraversal(TreeNode root){ ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (root == null){ return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); boolean normalorder = true; while (!queue.isEmpty()){ ArrayList<Integer> list = new ArrayList<Integer>(); int size = queue.size(); normalorder = !normalorder; for (int i = 0; i < size; i++){ TreeNode current = queue.poll(); if (normalorder) { list.add(0, current.value); }else{ list.add(current.value); } if (current.left != null){ queue.offer(current.left); //TreeNode temp = current.left; //queue.offer(temp); } if (current.right != null){ queue.offer(current.right); //TreeNode temp = current.right; //queue.offer(temp); } } result.add(list); } return result; } public static void main(String[] args) { // TODO Auto-generated method stub /*3 / \ 9 20 / \ 15 7*/ TreeNode r1 = new TreeNode(3); TreeNode r2 = new TreeNode(9); TreeNode r3 = new TreeNode(20); TreeNode r4 = new TreeNode(15); TreeNode r5 = new TreeNode(7); r1.left = r2; r1.right = r3; r2.left = null; r2.right = null; r3.left = r4; r3.right = r5; r4.left = null; r4.right = null; r5.left = null; r5.right = null; System.out.println(zigzagLevelTraversal(r1)); } }