text
stringlengths
10
2.72M
package com.helpfull.config; import com.helpfull.aop.logging.LoggingAspect; import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; @Configuration @EnableAspectJAutoProxy public class LoggingAspectConfiguration { @Bean @Profile(ApplicationConstants.SPRING_PROFILE_DEVELOPMENT) public LoggingAspect loggingAspect(Environment env) { return new LoggingAspect(env); } }
package cn.euphonium.codereviewsystemserver.entity; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class User extends Msg { String account; String password; String identity; String name; public User(int status) { this.status = status; } public User() { } }
package dbs.interfaces; public interface Database { void save(Savable object); Object retrieve(long id, Savable object); void delete(long id, Savable object); void update(long id, Savable object); }
package com.union.express.web.stowagecore.agingcycle.model; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; /** * Created by linhq on 2016/11/15 0015. */ /* 折扣(时效周期表) */ @Entity @Table(name = "aging_cycle") public class AgingCycle { //时效ID private String id; //周期 private int cycle; //时效类型id private String shippingId; @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") @Column(name = "id", unique = true, length = 32, nullable = false) public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "cycle") public int getCycle() { return cycle; } public void setCycle(int cycle) { this.cycle = cycle; } @Column(name = "shipping_id") public String getShippingId() { return shippingId; } public void setShippingId(String shippingId) { this.shippingId = shippingId; } }
package com.example.root.fingerprint; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class attendance_405 extends AppCompatActivity { private Button btnSign_attendance; private EditText edttextid; DatabaseReference databaseattendance405; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_attendance_405); databaseattendance405= FirebaseDatabase.getInstance().getReference("attendance405"); btnSign_attendance = (Button) findViewById(R.id.btnSign_attendance); edttextid =(EditText) findViewById(R.id.edttextid); btnSign_attendance.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { add_attendance(); } }); } private void add_attendance() { String attendance_id =edttextid.getText().toString().trim(); if(!TextUtils.isEmpty(attendance_id)) { String id = databaseattendance405.push().getKey(); getattendance_405 attendance405 = new getattendance_405 (attendance_id); databaseattendance405.child(id).setValue(attendance405); Toast.makeText(this, "Attendance Added Successfully", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(this, "id not detected", Toast.LENGTH_SHORT).show(); } }}
package org.digdata.swustoj.controller; import org.digdata.swustoj.base.JunitBaseController; import org.digdata.swustoj.mybatis.entiy.Tags; import org.digdata.swustoj.mybatis.entiy.UserAuth; import org.digdata.swustoj.util.JsonUtil; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; public class UserAuthControllerTest extends JunitBaseController<UserAuthController> { @Test public void select() throws Exception { ResultActions resultActions = this.mockMvc .perform(MockMvcRequestBuilders.get("/user/auth.do") .characterEncoding("UTF-8") .accept(MediaType.APPLICATION_JSON) .param("page", "1") .param("rows", "10")); System.out.println(resultActions.andReturn().getResponse() .getContentAsString()); } @Test public void add() throws Exception { UserAuth userAuth=new UserAuth("11","123"); ResultActions resultActions = this.mockMvc .perform(MockMvcRequestBuilders.post("/user/auth.do") .characterEncoding("UTF-8") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(JsonUtil.object2Json(userAuth, true))); System.out.println(resultActions.andReturn().getResponse() .getContentAsString()); } }
// ********************************************************** // 1. 제 목: Out User BEAN // 2. 프로그램명: SubjLimitBean.java // 3. 개 요: 지식노트 외부 관리자 bean // 4. 환 경: JDK 1.3 // 5. 버 젼: 1.0 // 6. 작 성: // 7. 수 정: // ********************************************************** package com.ziaan.propose; import java.sql.PreparedStatement; import java.util.ArrayList; import com.ziaan.library.ConfigSet; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.ErrorManager; import com.ziaan.library.ListSet; import com.ziaan.library.RequestBox; public class SubjLimitBean { private ConfigSet config ; private int row ; public SubjLimitBean() { try { config = new ConfigSet(); } catch( Exception e ) { e.printStackTrace(); } } public DataBox selectSubjLimit(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; String sql = ""; DataBox dbox = null; try { connMgr = new DBConnectionManager(); list = new ArrayList(); sql += " SELECT GUBUN "; sql += " , CNT "; sql += " FROM Tz_SubjLimit "; ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return dbox; } /** * 수정하여 저장할때 * @param box receive from the form object and session * @return isOk 1:update success,0:update fail * @throws Exception */ public int updateSubjLimit(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; String sql = ""; String v_gubun = box.getString("p_gubun"); // 카테고리 String v_cnt = box.getString("p_cnt" ); int isOk = 0; try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); sql = " update TZ_SubjLimit set gubun = ? , cnt = ? "; pstmt = connMgr.prepareStatement(sql); pstmt.setString(1, v_gubun); pstmt.setString(2, v_cnt ); isOk = pstmt.executeUpdate(); } catch(Exception ex) { connMgr.rollback(); ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e10 ) { } } } return isOk; } }
class Student extends Person{ private int[] testScores; /* * Class Constructor * * @param firstName - A string denoting the Person's first name. * @param lastName - A string denoting the Person's last name. * @param id - An integer denoting the Person's ID number. * @param scores - An array of integers denoting the Person's test scores. */ // Write your constructor here Student(String fName, String lName, int id,int[] scores){ super(fName,lName,id); this.testScores=scores; } /* * Method Name: calculate * @return A character denoting the grade. */ public char calculate(){ int sum=0; int n=testScores.length; for(int k=0;k<n;k++){ sum+=testScores[k]; } double average=sum/n; if(average>89){ return 'O'; } else if(average>79){ return 'E'; } else if(average>69){ return 'A'; } else if(average>54){ return 'P'; } else if(average>39){ return 'D'; } else return 'T'; } // Write your method here }
package br.edu.utfpr.pb.aula2.model; import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @Entity @Table(name = "produto") @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(of = "id") @Data public class Produto { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 100) private String nome; @Column(length = 512) private String descricao; private Double valor; @ManyToOne @JoinColumn(name = "categoria_id", referencedColumnName = "id") private Categoria categoria; @Column(name = "data_lancamento", nullable = false) private LocalDate dataLancamento; }
package br.com.ocjp7.design; public class ClassAnonima { public static void main(String[] args) { Draw dw = new Draw() { @Override public void print() { System.out.println(" Dw impl "); } }; dw.print(); new WriteDraw().printDraw( new Draw() { @Override public void print() { System.out.println(" printDraw "); } }); } } class WriteDraw{ void printDraw(Draw dw){ dw.print(); } } interface Draw{ void print(); }
package com.legaoyi; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextClosedEvent; import com.legaoyi.common.message.ExchangeMessage; import com.legaoyi.mq.MQMessageListenerManager; import com.legaoyi.protocol.server.Server; import com.legaoyi.protocol.server.ServerMessageHandler; import com.legaoyi.protocol.util.ServerRuntimeContext; @SuppressWarnings("rawtypes") public class AppApplicationListener implements ApplicationListener { private static final Logger logger = LoggerFactory.getLogger(AppApplicationListener.class); @Autowired @Qualifier("serverRuntimeContext") protected ServerRuntimeContext serverRuntimeContext; @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextClosedEvent) { stopServer(); } else if (event instanceof ApplicationReadyEvent) { startServer(); } } public void startServer() { restartNotify(1); ServerRuntimeContext.getBean("server", Server.class).start(); } private void stopServer() { restartNotify(0); // 停止接收mq消息 try { ServerRuntimeContext.getBean(MQMessageListenerManager.class).stopAll(); } catch (Exception e) { logger.error("", e); } ServerRuntimeContext.getBean("server", Server.class).stop(); } private void restartNotify(int result) { try { // 通知平台网关重启 ServerMessageHandler urgentMessageHandler = ServerRuntimeContext.getBean("urgentServerMessageHandler", ServerMessageHandler.class); Map<String, Object> map = new HashMap<String, Object>(); map.put("result", result); urgentMessageHandler.handle(new ExchangeMessage(ExchangeMessage.MESSAGEID_GATEWAY_RESTART, map, null)); } catch (Exception e) { logger.error("******handle server restart message error", e); } } }
/* * Copyright 2013 OSD and the Others. * * 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 jp.osd.japanese; import static org.testng.Assert.*; import java.lang.reflect.Constructor; import org.testng.annotations.Test; /** * {@link KanaUtils} のユニットテスト・クラスです。 * * @author itoasuka */ public class KanaUtilsTest { /** * 新たにユニットテスト・オブジェクトを構築します。 */ public KanaUtilsTest() { // 何もしない } /** * {@link KanaUtils} がインスタンス化できないようになっているかをテストします。 * * @throws Exception * 想定外のエラーが発生した場合。 */ @Test public void KanaUtil() throws Exception { Constructor<KanaUtils> c = KanaUtils.class.getDeclaredConstructor(); assertFalse(c.isAccessible()); c.setAccessible(true); c.newInstance(); } /** * {@link KanaUtils#toKatakana(String)} のユニット・テストです。以下の項目についてテストします。 * <p> * <ol> * <li>ひらがなをカタカナに変換できる。</li> * <li>記号や漢字などに対しては何もせずそのまま返す。</li> * </ol> */ @Test public void toKatakana() { // Test 1 assertEquals( "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラルレロワヲンァィゥェォャュョヮガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ", KanaUtils .toKatakana("あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらるれろわをんぁぃぅぇぉゃゅょゎがぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺぽ")); // Test 2 assertEquals("〔亜", KanaUtils.toKatakana("〔亜")); } /** * {@link KanaUtils#toHiragana(String)} のユニット・テストです。以下の項目についてテストします。 * <p> * <ol> * <li>カタカナをひらがなに変換できる。</li> * <li>記号や漢字などに対しては何もせずそのまま返す。</li> * </ol> */ @Test public void toHiragana() { assertEquals( "あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらるれろわをんぁぃぅぇぉゃゅょゎがぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺぽー", KanaUtils .toHiragana("アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラルレロワヲンァィゥェォャュョヮガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポー")); assertEquals("〔亜", KanaUtils.toHiragana("〔亜")); } /** * {@link KanaUtils#isHalfWidthKana(char)} のユニット・テストです。以下の項目についてテストします。 * <p> * <ol> * <li>半角カタカナに対して <code>true</code> を返す。</li> * <li>全角カタカナに対して <code>false</code> を返す。</li> * <li>全角英数字に対して <code>false</code> を返す。</li> * <li>半角英数字に対して <code>false</code> を返す。</li> * </ol> */ @Test public void isHalfWidthKana() { assertTrue(KanaUtils.isHalfWidthKana('ア')); assertFalse(KanaUtils.isHalfWidthKana('ア')); assertFalse(KanaUtils.isHalfWidthKana('¥')); assertFalse(KanaUtils.isHalfWidthKana('a')); } /** * {@link KanaUtils#isHiragana(char)} のユニット・テストです。以下の項目についてテストします。 * <p> * <ol> * <li>半角カタカナに対して <code>false</code> を返す。</li> * <li>全角カタカナに対して <code>false</code> を返す。</li> * <li>全角ひらがなに対して <code>true</code> を返す。</li> * <li>全角英数字に対して <code>false</code> を返す。</li> * <li>半角英数字に対して <code>false</code> を返す。</li> * </ol> */ @Test public void isHiragana() { assertFalse(KanaUtils.isHiragana('ア')); assertFalse(KanaUtils.isHiragana('ア')); assertTrue(KanaUtils.isHiragana('あ')); assertFalse(KanaUtils.isHiragana('¥')); assertFalse(KanaUtils.isHiragana('a')); } /** * {@link KanaUtils#getVowel(char)} のユニット・テストです。以下の項目についてテストします。 * <p> * <ol> * <li>あ段の全角ひらがなに対して * <code>{@link jp.osd.japanese.Vowel#A}</code> を返す。</li> * <li>あ段の全角カタカナに対して * <code>{@link jp.osd.japanese.Vowel#A}</code> を返す。</li> * <li>あ段の半角カタカナに対して * <code>{@link jp.osd.japanese.Vowel#A}</code> を返す。</li> * <li>い段の全角ひらがなに対して * <code>{@link jp.osd.japanese.Vowel#I}</code> を返す。</li> * <li>い段の全角カタカナに対して * <code>{@link jp.osd.japanese.Vowel#I}</code> を返す。</li> * <li>い段の半角カタカナに対して * <code>{@link jp.osd.japanese.Vowel#I}</code> を返す。</li> * <li>う段の全角ひらがなに対して * <code>{@link jp.osd.japanese.Vowel#U}</code> を返す。</li> * <li>う段の全角カタカナに対して * <code>{@link jp.osd.japanese.Vowel#U}</code> を返す。</li> * <li>う段の半角カタカナに対して * <code>{@link jp.osd.japanese.Vowel#U}</code> を返す。</li> * <li>え段の全角ひらがなに対して * <code>{@link jp.osd.japanese.Vowel#E}</code> を返す。</li> * <li>え段の全角カタカナに対して * <code>{@link jp.osd.japanese.Vowel#E}</code> を返す。</li> * <li>え段の半角カタカナに対して * <code>{@link jp.osd.japanese.Vowel#E}</code> を返す。</li> * <li>お段の全角ひらがなに対して * <code>{@link jp.osd.japanese.Vowel#O}</code> を返す。</li> * <li>お段の全角カタカナに対して * <code>{@link jp.osd.japanese.Vowel#O}</code> を返す。</li> * <li>お段の半角カタカナに対して * <code>{@link jp.osd.japanese.Vowel#O}</code> を返す。</li> * <li>全角の仮名以外の文字に対して <code>null</code> を返す。</li> * <li>半角の仮名以外の文字に対して <code>null</code> を返す。</li> * </ol> */ @Test public void getVowel() { assertEquals(Vowel.A, KanaUtils.getVowel('あ')); assertEquals(Vowel.A, KanaUtils.getVowel('カ')); assertEquals(Vowel.A, KanaUtils.getVowel('サ')); assertEquals(Vowel.I, KanaUtils.getVowel('ち')); assertEquals(Vowel.I, KanaUtils.getVowel('ニ')); assertEquals(Vowel.I, KanaUtils.getVowel('ヒ')); assertEquals(Vowel.U, KanaUtils.getVowel('む')); assertEquals(Vowel.U, KanaUtils.getVowel('ル')); assertEquals(Vowel.U, KanaUtils.getVowel('ウ')); assertEquals(Vowel.E, KanaUtils.getVowel('け')); assertEquals(Vowel.E, KanaUtils.getVowel('セ')); assertEquals(Vowel.E, KanaUtils.getVowel('テ')); assertEquals(Vowel.O, KanaUtils.getVowel('の')); assertEquals(Vowel.O, KanaUtils.getVowel('ホ')); assertEquals(Vowel.O, KanaUtils.getVowel('モ')); assertNull(KanaUtils.getVowel('A')); assertNull(KanaUtils.getVowel('-')); } /** * {@link KanaUtils#getConsonant(char)} のユニット・テストです。以下の項目についてテストします。 * <p> * <ol> * <li>ア行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#NONE}</code> * を返す。</li> * <li>ア行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#NONE}</code> * を返す。</li> * <li>ア行の半角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#NONE}</code> * を返す。</li> * <li>カ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#K}</code> を返す。</li> * <li>カ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#K}</code> を返す。</li> * <li>カ行の半角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#K}</code> を返す。</li> * <li>ガ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#G}</code> を返す。</li> * <li>ガ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#G}</code> を返す。</li> * <li>サ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#S}</code> を返す。</li> * <li>サ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#S}</code> を返す。</li> * <li>サ行の半角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#S}</code> を返す。</li> * <li>ザ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#Z}</code> を返す。</li> * <li>ザ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#Z}</code> を返す。</li> * <li>タ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#T}</code> を返す。</li> * <li>タ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#T}</code> を返す。</li> * <li>タ行の半角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#T}</code> を返す。</li> * <li>ダ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#D}</code> を返す。</li> * <li>ダ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#D}</code> を返す。</li> * <li>ナ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#N}</code> を返す。</li> * <li>ナ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#N}</code> を返す。</li> * <li>ナ行の半角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#N}</code> を返す。</li> * <li>ハ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#H}</code> を返す。</li> * <li>ハ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#H}</code> を返す。</li> * <li>ハ行の半角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#H}</code> を返す。</li> * <li>バ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#B}</code> を返す。</li> * <li>バ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#B}</code> を返す。</li> * <li>パ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#P}</code> を返す。</li> * <li>パ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#P}</code> を返す。</li> * <li>マ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#M}</code> を返す。</li> * <li>マ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#M}</code> を返す。</li> * <li>マ行の半角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#M}</code> を返す。</li> * <li>ヤ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#Y}</code> を返す。</li> * <li>ヤ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#Y}</code> を返す。</li> * <li>ヤ行の半角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#Y}</code> を返す。</li> * <li>ワ行の全角ひらがなに対して * <code>{@link jp.osd.japanese.Consonant#W}</code> を返す。</li> * <li>ワ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#W}</code> を返す。</li> * <li>ワ行の半角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#W}</code> を返す。</li> * <li>ヴァ行の全角カタカナに対して * <code>{@link jp.osd.japanese.Consonant#V}</code> を返す。</li> * <li>全角の仮名以外の文字に対して <code>null</code> を返す。</li> * <li>半角の仮名以外の文字に対して <code>null</code> を返す。</li> * </ol> */ @Test public void getConsonant() { assertEquals(Consonant.NONE, KanaUtils.getConsonant('あ')); assertEquals(Consonant.NONE, KanaUtils.getConsonant('イ')); assertEquals(Consonant.NONE, KanaUtils.getConsonant('ウ')); assertEquals(Consonant.K, KanaUtils.getConsonant('け')); assertEquals(Consonant.K, KanaUtils.getConsonant('コ')); assertEquals(Consonant.K, KanaUtils.getConsonant('カ')); assertEquals(Consonant.G, KanaUtils.getConsonant('ぎ')); assertEquals(Consonant.G, KanaUtils.getConsonant('グ')); assertEquals(Consonant.S, KanaUtils.getConsonant('せ')); assertEquals(Consonant.S, KanaUtils.getConsonant('ソ')); assertEquals(Consonant.S, KanaUtils.getConsonant('サ')); assertEquals(Consonant.Z, KanaUtils.getConsonant('じ')); assertEquals(Consonant.Z, KanaUtils.getConsonant('ズ')); assertEquals(Consonant.T, KanaUtils.getConsonant('て')); assertEquals(Consonant.T, KanaUtils.getConsonant('ト')); assertEquals(Consonant.T, KanaUtils.getConsonant('タ')); assertEquals(Consonant.D, KanaUtils.getConsonant('ぢ')); assertEquals(Consonant.D, KanaUtils.getConsonant('ヅ')); assertEquals(Consonant.N, KanaUtils.getConsonant('ね')); assertEquals(Consonant.N, KanaUtils.getConsonant('ノ')); assertEquals(Consonant.N, KanaUtils.getConsonant('ナ')); assertEquals(Consonant.H, KanaUtils.getConsonant('ひ')); assertEquals(Consonant.H, KanaUtils.getConsonant('フ')); assertEquals(Consonant.H, KanaUtils.getConsonant('ヘ')); assertEquals(Consonant.B, KanaUtils.getConsonant('ぼ')); assertEquals(Consonant.B, KanaUtils.getConsonant('バ')); assertEquals(Consonant.P, KanaUtils.getConsonant('ぴ')); assertEquals(Consonant.P, KanaUtils.getConsonant('プ')); assertEquals(Consonant.M, KanaUtils.getConsonant('め')); assertEquals(Consonant.M, KanaUtils.getConsonant('モ')); assertEquals(Consonant.M, KanaUtils.getConsonant('マ')); assertEquals(Consonant.Y, KanaUtils.getConsonant('ゆ')); assertEquals(Consonant.Y, KanaUtils.getConsonant('ヨ')); assertEquals(Consonant.Y, KanaUtils.getConsonant('ヤ')); assertEquals(Consonant.R, KanaUtils.getConsonant('り')); assertEquals(Consonant.R, KanaUtils.getConsonant('ル')); assertEquals(Consonant.R, KanaUtils.getConsonant('レ')); assertEquals(Consonant.W, KanaUtils.getConsonant('わ')); assertEquals(Consonant.W, KanaUtils.getConsonant('ヲ')); assertEquals(Consonant.W, KanaUtils.getConsonant('ワ')); assertEquals(Consonant.V, KanaUtils.getConsonant('ヴ')); assertNull(KanaUtils.getConsonant('A')); assertNull(KanaUtils.getConsonant('-')); } }
package exceptions.server.game; public class InvalidPlayerCommandException extends Exception { private static final long serialVersionUID = -776020891376048861L; public InvalidPlayerCommandException(String message) { super(message); } }
package com.melodygram.utils; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class CamClass { public static final int MEDIA_TYPE_IMAGE = 1; public static final int MEDIA_TYPE_VIDEO = 2; public Uri fileUri; // file url to store image/video Activity activity; static int CAMERA_CAPTURE_IMAGE_REQUEST_CODE; static String IMAGE_DIRECTORY_NAME; public CamClass(Activity activity, int CAMERA_CAPTURE_IMAGE_REQUEST_CODE, String IMAGE_DIRECTORY_NAME) { // TODO Auto-generated constructor stub this.activity = activity; CamClass.CAMERA_CAPTURE_IMAGE_REQUEST_CODE = CAMERA_CAPTURE_IMAGE_REQUEST_CODE; CamClass.IMAGE_DIRECTORY_NAME = IMAGE_DIRECTORY_NAME; } /** * Capturing Camera Image will lauch camera app requrest image capture */ public Uri captureImage() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // start the image capture Intent activity.startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); Log.v("DATA", fileUri + ""); return fileUri; } /** * ------------ Helper Methods ---------------------- * */ /** * Creating file uri to store image/video */ public Uri getOutputMediaFileUri(int type) { return Uri.fromFile(getOutputMediaFile(type)); } /** * returning image / video */ public static File getOutputMediaFile(int type) { // External sdcard location File mediaStorageDir = new File( Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME); // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else if (type == MEDIA_TYPE_VIDEO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); } else { return null; } return mediaFile; } /** * Checking device has camera hardware or not */ public boolean isDeviceSupportCamera() { if (activity.getPackageManager().hasSystemFeature( PackageManager.FEATURE_CAMERA)) { // this device has a camera return true; } else { // no camera on this device return false; } } public Bitmap getImgBmp(Activity activity, Uri fileUri) { // bimatp factory BitmapFactory.Options options = new BitmapFactory.Options(); // downsizing image as it throws OutOfMemory Exception for larger // images int actualHeight = options.outHeight; int actualWidth = options.outWidth; options.inSampleSize = ReusableLogic.calculateInSampleSize(options, actualWidth, actualHeight); final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options); // rotating the image ImageRotation imageRotation = new ImageRotation(activity, fileUri, fileUri.getPath()); //int rotate = imageRotation.getCameraPhotoOrientation(); Matrix matrix = new Matrix(); matrix.postRotate(imageRotation.getCameraPhotoOrientation()); Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); return rotatedBitmap; } }
package com.getkhaki.api.bff.web.models; public enum IntervalDte { Day, Week, Month, Year }
package com.example.sypark9646.item05; public class Dog implements Animal { @Override public void jump() { System.out.println("dog is jumping"); } }
package com.cosplay.demo.mvp.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.cosplay.demo.mvp.R; import com.cosplay.demo.mvp.bean.FHnews; import com.cosplay.demo.mvp.bean.ZhiHuBook; import java.util.List; /** * Created by zhiwei.wang on 2017/3/23. */ public class ZHbooksAdapter extends BaseAdapter{ List<ZhiHuBook.BooksBean> booksBeanList; Context context; public ZHbooksAdapter(List<ZhiHuBook.BooksBean> booksBeanList, Context context) { this.booksBeanList = booksBeanList; this.context = context; } @Override public int getCount() { return booksBeanList==null?0:booksBeanList.size(); } @Override public Object getItem(int position) { return booksBeanList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ZHbooksAdapter.ViewHolder viewHolder = null; if(convertView == null){ convertView = LayoutInflater.from(context).inflate(R.layout.fhnew_item_layout,null); viewHolder = new ZHbooksAdapter.ViewHolder(convertView); convertView.setTag(viewHolder); }else{ viewHolder = (ZHbooksAdapter.ViewHolder) convertView.getTag(); } viewHolder.tv.setText(booksBeanList.get(position).getTitle()); return convertView; } class ViewHolder { TextView tv; ImageView iv; public ViewHolder(View view) { this.tv = (TextView) view.findViewById(R.id.tv_fhnews); } } }
import java.util.*; public class GuessCapitals{ public static void main(String[]args){ HashMap<String,String> map = new HashMap<String,String>(); map.put("Alabama","Montgomery"); map.put("Alaska","Juneau"); map.put("Arizona","Phoenix"); map.put("Arkansas","Little Rock"); map.put("California","Sacramento"); map.put("Colorado","Denver"); map.put("Connecticut","Hartford"); map.put("Delaware","Dover"); map.put("Florida","Tallahassee"); map.put("Georgia","Atlanta"); map.put("Hawaii","Honolulu"); map.put("Idaho","Boise"); map.put("Illinois","Springfield"); map.put("Indiana","Indianapolis"); map.put("Iowa","Des Moines"); map.put("Kansas","Topeka"); map.put("Kentucky","Frankfort"); map.put("Louisiana","Baton Rouge"); map.put("Maine","Augusta"); map.put("Maryland","Annapolis"); map.put("Massachusetts","Boston"); map.put("Michigan","Lansing"); map.put("Minnesota","Saint Paul"); map.put("Mississippi","Jackson"); map.put("Missouri","Jefferson City"); map.put("Montana","Helena"); map.put("Nebraska","Lincoln"); map.put("Nevada","Carson City"); map.put("New Hampshire","Concord"); map.put("New Jersey","Trenton"); map.put("New Mexico","Santa Fe"); map.put("New York","Albany"); map.put("North Carolina","Raleigh"); map.put("North Dakota","Bismarck"); map.put("Ohio"," Columbus"); map.put("Oklahoma","Oklahoma City"); map.put("Oregon","Salem"); map.put("Pennsylvania","Harrisburg"); map.put("Rhode Island","Providence"); map.put("South Carolina","Columbia"); map.put("South Dakota","Pierre"); map.put("Tennessee","Nashville"); map.put("Texas","Austin"); map.put("Utah","Salt Lake City"); map.put("Vermont","Montpelier"); map.put("Virginia","Richmond"); map.put("Washington","Olympia"); map.put("West Virginia","Charleston"); map.put("Wisconsin","Madison"); map.put("Wyoming","Cheyenne"); System.out.println("What state do you want to see?"); Scanner sc = new Scanner(System.in); System.out.println("The capital is; "+map.get(sc.nextLine())); } }
package org.robotninjas.stages; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; class StageRepository implements Iterable<Stage> { private final Map<StageName, Stage> stages; public StageRepository() { this.stages = new ConcurrentHashMap<>(); } public <I> StageRepository registerStage(StageName<I> name, Stage<I> stage) { stages.put(name, stage); return this; } @SuppressWarnings("unchecked") public <I> Stage<I> getStage(StageName<I> name) { return stages.get(name); } public Iterable<Stage> stages() { return stages.values(); } @Override public Iterator<Stage> iterator() { return stages.values().iterator(); } }
package com.beike.common.enums.trx; /** * @Title: TrxLogStype.java * @Package com.beike.common.enums.trx * @Description: TODO * @date Jun 30, 2011 5:02:20 PM * @author wh.cheng * @version v1.0 */ public enum TrxLogType { TRXORDERGOODS, //商品订单操作日志 REFUND, //退款历史 //trxLog需求修改增加新类型2012年3月30日20:39:19 /** * 订单创建 */ INIT, /** * 成功 */ SUCCESS, /** * 使用 */ USED, /** * 评价 */ COMMENTED, /** * 过期 */ EXPIRED, /** * 账户退款申请 */ REFUNDACCEPT, /** * 账户退款:审批拒绝 */ REFUNDREFUSE, /** * 退款到账户 */ REFUNDTOACT, /** * 原路返回审核 */ RECHECK, /** * 退款到银行卡:复核拒绝 */ RECHECK_REFUSE, /** * 退款到银行卡 */ REFUNDTOBANK, /** * 退款到银行卡 */ REFUNDTOBANK_FAILED, /** * 凭证发送 */ VOUCHER_SEND, /** * 返现 */ REBATE; }
package ObserverPattern; public interface Observer { void updata(WeatherDataStruct weatherDataStruct); }
package modelosGerados; /** * Enum - Tipo Simples Sim, Não ou Talvez * */ public enum TsSimNao { SIM(1, "Sim"), NAO(2, "Não"), TALVEZ(3,"Talvez"); /** * Contrutor * @param codigo * @param descricao * */ TsSimNao(Integer codigo, String descricao) { this.codigo = codigo; this.descricao = descricao; } private Integer codigo; private String descricao; /** * Retorno o código do enum. * * @return Integer * */ public Integer getCodigo() { return Integer.parseInt(String.valueOf(this.codigo)); } /** * Retorna a descrição do enum. * * @return String * */ public String getDescricao() { return descricao; } /** * Método de execução. * */ public static void main(String[] args) { Integer tc = TsSimNao.NAO.codigo; String td = TsSimNao.NAO.descricao; System.out.println("Código: " + tc); System.out.println("Descrição: " + td); } }
package com.wrw.proxy.demo05; import static org.junit.Assert.*; import java.lang.reflect.Method; import org.junit.Test; import com.wrw.proxy.demo05.Proxy; import com.wrw.proxy.demo05.moveable; public class test { @Test public void test() throws Exception { Tank t = new Tank(); TimeHandler h = new TimeHandler(t); moveable m = (moveable)Proxy.newProxyInstance(moveable.class, h); m.move(); } }
package upsd.json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import upsd.domain.User; import java.util.List; public class UserJsonHelper { public JsonObject toJsonObject(User user) { return new JsonObject() .add("id", user.id()) .add("name", user.name()); } public JsonObject arrayFrom(List<User> users) { JsonArray usersArray = new JsonArray(); users.stream() .map(this::toJsonObject) .forEach(usersArray::add); return new JsonObject().add("users", usersArray); } }
package by.herzhot; /** * @author Herzhot * @version 1.0 * 09.08.2016 */ public interface ISupplierDao extends IDao<Supplier> { }
package io.nuls.base.api.provider.ledger.facade; /** * @Author: zhoulijun * @Time: 2020-05-25 10:11 * @Description: 功能描述 */ public class AssetInfo { int assetChainId; int assetId; String symbol; int decimals; int assetType; boolean canBePeriodically; public boolean isCanBePeriodically() { return canBePeriodically; } public void setCanBePeriodically(boolean canBePeriodically) { this.canBePeriodically = canBePeriodically; } public int getAssetChainId() { return assetChainId; } public void setAssetChainId(int assetChainId) { this.assetChainId = assetChainId; } public int getAssetId() { return assetId; } public void setAssetId(int assetId) { this.assetId = assetId; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public int getDecimals() { return decimals; } public void setDecimals(int decimals) { this.decimals = decimals; } public int getAssetType() { return assetType; } public void setAssetType(int assetType) { this.assetType = assetType; } }
package leetCode.copy.Array; import java.util.*; /** * 39. 组合总和 *给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 * * candidates 中的数字可以无限制重复被选取。 * 说明: * 所有数字(包括 target)都是正整数。 * 解集不能包含重复的组合。  * * 示例 1: * 输入:candidates = [2,3,6,7], target = 7, * 所求解集为: * [ * [7], * [2,2,3] * ] * * 示例 2: * 输入:candidates = [2,3,5], target = 8, * 所求解集为: * [ *   [2,2,2,2], *   [2,3,3], *   [3,5] * ] * * 提示: * 1 <= candidates.length <= 30 * 1 <= candidates[i] <= 200 * candidate 中的每个元素都是独一无二的。 * 1 <= target <= 500 * * 链接:https://leetcode-cn.com/problems/combination-sum */ public class no39_combination_sum { List<List<Integer>> result = new ArrayList<>(); /** * 转换成子问题 分治法 * @param candidates * @param target * @return */ public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); int len = candidates.length; for (int i = 0; i < len; i++) { int iter = candidates[i]; if (iter > target) break; else if (iter == target) { List<Integer> data = new ArrayList<>(); data.add(iter); result.add(data); break; } List<List<Integer>> datas = sub_combinationSum(candidates, target - iter, i); if (datas != null && datas.size() > 0) { for (List<Integer> data : datas) { data.add(iter); } result.addAll(datas); } } return result; } public List<List<Integer>> sub_combinationSum(int[] candidates, int target, int index) { List<List<Integer>> tempResult = new ArrayList<>(); for (int i = index; i < candidates.length; i++) { int iter = candidates[i]; if (iter > target) break; else if (iter == target) { List<Integer> data = new ArrayList<>(); data.add(iter); tempResult.add(data); break; } List<List<Integer>> datas = sub_combinationSum(candidates, target - iter, i); if (datas != null && datas.size() > 0) { int len = datas.size(); for (int j = 0; j < len; j++) { List<Integer> data = datas.get(j); data.add(iter); } tempResult.addAll(datas); } } return tempResult; } public static void main(String args[]) { no39_combination_sum obj = new no39_combination_sum(); List<List<Integer>> datas = obj.combinationSum(new int[]{2, 3, 6, 7}, 7); System.out.println(datas); obj.result.clear(); datas = obj.combinationSum(new int[]{2, 3, 5}, 8); System.out.println(datas); } }
package codepath.com.flixster.models; import org.json.JSONException; import org.json.JSONObject; import org.parceler.Parcel; @Parcel public class Movie { String title; String overview; String posterPath; String backdropPath; String releaseDate; int popularity; Integer voteCount; Double voteAverage; Integer id; public Movie() { } public Movie(JSONObject obj) throws JSONException { title = obj.getString("title"); overview = obj.getString("overview"); posterPath = obj.getString("poster_path"); backdropPath = obj.getString("backdrop_path"); voteAverage = obj.getDouble("vote_average"); releaseDate = obj.getString("release_date"); voteCount = obj.getInt("vote_count"); popularity = obj.getInt("popularity"); } public String getTitle() { return title; } public String getOverview() { return overview; } public String getPosterPath() { return posterPath; } public String getBackdropPath() { return backdropPath; } public Double getVoteAverage() { return voteAverage; } public String getReleaseDate() { return releaseDate; } public int getPopularity() { return popularity; } public int getVoteCount() { return voteCount; } }
package com.volunteeride.volunteeride.utility; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.ResourceBundle; /** * Created by mthosani on 12/23/15. */ public class PropertyReaderUtility { public static ResourceBundle appProperties = ResourceBundle.getBundle("assets/app"); Properties mAppProperties = new Properties(); public static String getValue(String pPropertyKey){ return appProperties.getString(pPropertyKey); } public String getValueFromProperties(String pPropertyKey) { String propertyValue = ""; try { InputStream propertiesFileInputStreamCurrentFolder = getClass() .getClassLoader().getResourceAsStream( "assets/app.properties"); mAppProperties.load(propertiesFileInputStreamCurrentFolder); propertyValue = mAppProperties .getProperty(pPropertyKey); }catch(IOException e){ handleException(e); }catch(Exception e){ handleException(e); } return propertyValue; } public void handleException(Exception e){ StackTraceElement[] stack = e.getStackTrace(); String exception = ""; for (StackTraceElement s : stack) { exception = exception + s.toString() + "\n\t\t"; } System.out .println("**************************************************** Exception thrown**************************************************" + exception); } }
package etiyaGamesVol2.core; import java.time.LocalDate; public class MernisKpsService { public boolean tcKimlikNoDogrulama(long tcKimlikNo,String ad, String soyad, LocalDate dogumYili) { return true; } }
import org.junit.Test; import static org.junit.Assert.*; public class binarTest { @Test public void add() { Binar a = new Binar(); a.add(1, 1); //a.add(1, 1); assertEquals(1, a.get(1)); //добавление элемента, даже при двух одинаковых не происходит конфликта } @Test public void get() { Binar a = new Binar(); a.add(1, 1); assertEquals(1, a.get(1)); //когда значение существует assertEquals(null, a.get(2)); //когда значение не существует } //в тестах remove проверена работа containsKey @Test public void removeLast() { //удаление значения с конца Binar a = new Binar(); a.add(1, 1); a.add(2, 2); a.add(3, 3); a.remove(3); assertEquals(true, a.containsKey(2)); assertEquals(true, a.containsKey(1)); assertEquals(false, a.containsKey(3)); } @Test public void removeFirst() { //удаление значения из начала => и при значении из середины работать будет Binar a = new Binar(); a.add(1, 1); a.add(2, 2); a.add(3, 3); a.remove(1); assertEquals(false, a.containsKey(1)); assertEquals(true, a.containsKey(2)); assertEquals(true, a.containsKey(3)); } @Test public void removeOneChild() { //у удаляемого элемента есть только правый наследник Binar a = new Binar(); a.add(1, 1); a.add(2, 2); a.remove(1); assertEquals(false, a.containsKey(1)); assertEquals(true, a.containsKey(2)); } @Test public void getChild() { Binar a = new Binar(); //a.add(1,1); a.add(2, 2); //a.add(3, 3); a.add(4, 4); a.add(1, 1); assertEquals(4, a.getRightChild(2)); // когда правый ребенок существует assertEquals(1, a.getLeftChild(2)); // когда левый ребенок существует assertEquals(null, a.getRightChild(7)); // когда правый ребенок не существует (и не существует зачение) assertEquals(null, a.getLeftChild(7)); // когда левый ребенок не существует (и не существует значение) assertEquals(null, a.getRightChild(4)); // когда правый ребенок не существует assertEquals(null, a.getLeftChild(4)); // когда левый ребенок не существует } @Test public void getParent() { Binar a = new Binar(); a.add(2, 2); a.add(1, 1); a.add(3, 3); assertEquals(null, a.getParent(2)); // когда родителя нет assertEquals(2, a.getParent(1)); //когда родитель есть assertEquals(null, a.getParent(4)); //когда значения нет в дереве } }
package info.fandroid.mindmap.database.update; import android.database.sqlite.SQLiteDatabase; import info.fandroid.mindmap.database.DBHelper; import info.fandroid.mindmap.model.ModelPlanet; /** * Created by Vitaly on 09.01.2016. */ public class DBPlanetUpdateManager extends DBUpdateManager { public DBPlanetUpdateManager(SQLiteDatabase database) { super(database); } public void id(long id, long newId) { update(DBHelper.PLANET_TABLE, DBHelper.PLANET_ID_COLUMN, id, newId); } public void rootId(long id, long newRootId) { update(DBHelper.PLANET_TABLE, DBHelper.PLANET_ROOT_ID_COLUMN, id, newRootId); } public void path(long id, String path) { update(DBHelper.PLANET_TABLE, DBHelper.PLANET_PATH_COLUMN, id, path); } public void name(long id, String name) { update(DBHelper.PLANET_TABLE, DBHelper.PLANET_NAME_COLUMN, id, name); } public void description(long id, String description) { update(DBHelper.PLANET_TABLE, DBHelper.PLANET_DESCRIPTION_COLUMN, id, description); } public void color(long id, int color) { update(DBHelper.PLANET_TABLE, DBHelper.PLANET_COLOR_COLUMN, id, color); } public void full(long id, ModelPlanet planet) { name(id, planet.getName()); description(id, planet.getDescription()); color(id, planet.getColor()); } public void reallyFull(long id, ModelPlanet planet) { full(id, planet); path(id, planet.getPath()); rootId(id, planet.getRootId()); id(id, planet.getId()); } }
package br.com.entelgy.model; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat.ISO; /** * Vote submodel. * * @author falvojr */ public class Vote { @DateTimeFormat(iso = ISO.DATE_TIME) private Date createdDate = new Date(); private String reCaptchaResponse; public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public String getReCaptchaResponse() { return reCaptchaResponse; } public void setReCaptchaResponse(String reCaptchaResponse) { this.reCaptchaResponse = reCaptchaResponse; } }
package com.softeem.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.stereotype.Repository; import com.softeem.bean.GoodsBean; import com.softeem.dao.IGoodsDao; import com.softeem.utils.DataSoureUtils; @Repository(value="goodsDaoImpl") public class GoodsDaoImpl implements IGoodsDao { private Logger logger = Logger.getLogger(GoodsDaoImpl.class); @Resource(name="dataSoureUtils") private DataSoureUtils dataSoureUtils; @Override public List<GoodsBean> selectIndexGoods(int begin, int end) { List<GoodsBean> goodsList = new ArrayList<GoodsBean>(); // 查询商品的sql String goods_sql = "select goods_id,goods_name,goods_price from tb_goods limit ?,?"; String image_sql = "select image_url from tb_image where goods_id = ?"; Connection connection = dataSoureUtils.getConnection(); PreparedStatement goodsPs = null; PreparedStatement imagePs = null; ResultSet goodsResult = null; ResultSet imageResult = null; try { goodsPs = connection.prepareStatement(goods_sql); imagePs = connection.prepareStatement(image_sql); // 查询 goodsPs.setInt(1, begin); goodsPs.setInt(2, end); goodsResult = goodsPs.executeQuery(); // 获取数据 while (goodsResult.next()) { // 创建对象 GoodsBean goodsBean = new GoodsBean(); // 从结果集获取数据 int goods_id = goodsResult.getInt("goods_id"); goodsBean.setGoods_id(goods_id); goodsBean.setGoods_name(goodsResult.getString("goods_name")); goodsBean.setGoods_price(goodsResult.getDouble("goods_price")); // 继续查询商品对应的image_url imagePs.setInt(1, goods_id); imageResult = imagePs.executeQuery(); List<String> imageList = new ArrayList<String>(); while (imageResult.next()) { imageList.add(imageResult.getString("image_url")); } goodsBean.setImageList(imageList); // 将商品数据加入到集合 goodsList.add(goodsBean); } } catch (SQLException e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { dataSoureUtils.close(goodsResult); dataSoureUtils.close(imageResult); dataSoureUtils.close(goodsPs); dataSoureUtils.close(imagePs); dataSoureUtils.close(connection); } return goodsList; } @Override public GoodsBean selectById(int id) { String goodsSql = "select * from tb_goods where goods_id = ?"; String imageSql = "select image_url from tb_image where goods_id = ?"; String sizeSql = "select size_info from tb_size where goods_id = ?"; GoodsBean goodsBean = null; Connection connection = dataSoureUtils.getConnection(); PreparedStatement goodsPs = null; PreparedStatement imagePs = null; PreparedStatement sizePs = null; ResultSet goodsRs = null; ResultSet imageRs = null; ResultSet sizeRs = null; try { goodsPs = connection.prepareStatement(goodsSql); goodsPs.setInt(1, id); // 查询 goodsRs = goodsPs.executeQuery(); if (goodsRs.next()) { goodsBean = new GoodsBean(); goodsBean.setGoods_id(goodsRs.getInt("goods_id")); goodsBean.setCate_id(goodsRs.getInt("cate_id")); goodsBean.setGoods_desc(goodsRs.getString("goods_desc")); goodsBean.setGoods_name(goodsRs.getString("goods_name")); goodsBean.setGoods_price(goodsRs.getDouble("goods_price")); // ----------查询商品对应的图片------------------- imagePs = connection.prepareStatement(imageSql); imagePs.setInt(1, goodsBean.getGoods_id()); // 查询 List<String> imageList = new ArrayList<String>(); imageRs = imagePs.executeQuery(); while (imageRs.next()) { imageList.add(imageRs.getString("image_url")); } goodsBean.setImageList(imageList); // ----------查询商品对应的图片------------------- // ----------查询商品对应的size------------------ sizePs = connection.prepareStatement(sizeSql); System.out.println(goodsBean.getGoods_id()); sizePs.setInt(1, goodsBean.getGoods_id()); sizeRs = sizePs.executeQuery(); List<String> sizeList = new ArrayList<String>(); while (sizeRs.next()) { sizeList.add(sizeRs.getString("size_info")); } goodsBean.setSizeList(sizeList); // ----------查询商品对应的size------------------ } } catch (SQLException e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { dataSoureUtils.close(sizeRs); dataSoureUtils.close(imageRs); dataSoureUtils.close(goodsRs); dataSoureUtils.close(imagePs); dataSoureUtils.close(sizePs); dataSoureUtils.close(goodsPs); dataSoureUtils.close(connection); } return goodsBean; } @Override public List<GoodsBean> selectByCate(int cateId) { List<GoodsBean> goodsList = new ArrayList<GoodsBean>(); // 查询商品的sql String goods_sql = "select goods_id,goods_name,goods_price,goods_desc,cate_id from tb_goods"; if (cateId >= 0) { // 不分类 goods_sql = "select goods_id,goods_name,goods_price,goods_desc,cate_id from tb_goods where cate_id = ?"; } String image_sql = "select image_url from tb_image where goods_id = ?"; Connection connection = dataSoureUtils.getConnection(); PreparedStatement goodsPs = null; PreparedStatement imagePs = null; ResultSet goodsResult = null; ResultSet imageResult = null; try { goodsPs = connection.prepareStatement(goods_sql); imagePs = connection.prepareStatement(image_sql); // 查询 if (cateId >= 0) { goodsPs.setInt(1, cateId); } goodsResult = goodsPs.executeQuery(); // 获取数据 while (goodsResult.next()) { // 创建对象 GoodsBean goodsBean = new GoodsBean(); // 从结果集获取数据 int goods_id = goodsResult.getInt("goods_id"); goodsBean.setGoods_id(goods_id); goodsBean.setGoods_name(goodsResult.getString("goods_name")); goodsBean.setGoods_price(goodsResult.getDouble("goods_price")); goodsBean.setGoods_desc(goodsResult.getString("goods_desc")); goodsBean.setCate_id(goodsResult.getInt("cate_id")); // 继续查询商品对应的image_url imagePs.setInt(1, goods_id); imageResult = imagePs.executeQuery(); List<String> imageList = new ArrayList<String>(); while (imageResult.next()) { imageList.add(imageResult.getString("image_url")); } goodsBean.setImageList(imageList); // 将商品数据加入到集合 goodsList.add(goodsBean); } } catch (SQLException e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { dataSoureUtils.close(goodsResult); dataSoureUtils.close(imageResult); dataSoureUtils.close(goodsPs); dataSoureUtils.close(imagePs); dataSoureUtils.close(connection); } return goodsList; } /** * * @param pageNum * : 页码 * @param pageSize * : 每页的数量 * @param cateId * @return */ @Override public List<GoodsBean> selectByPageAndCate(int pageNum, int pageSize, int cateId) { List<GoodsBean> goodsList = new ArrayList<GoodsBean>(); // 查询商品的sql: ? < 0 ---> cateId < 0 , String goods_sql = "select * from tb_goods where ? < 0 limit ?,?"; if (cateId >= 0) { // 不分类 goods_sql = "select * from tb_goods where cate_id = ? limit ?,?"; } String image_sql = "select image_url from tb_image where goods_id = ?"; Connection connection = dataSoureUtils.getConnection(); PreparedStatement goodsPs = null; PreparedStatement imagePs = null; ResultSet goodsResult = null; ResultSet imageResult = null; try { goodsPs = connection.prepareStatement(goods_sql); imagePs = connection.prepareStatement(image_sql); // 查询 int begin = (pageNum - 1) * pageSize; if (begin < 0) begin = 0; goodsPs.setInt(1, cateId); goodsPs.setInt(2, begin); goodsPs.setInt(3, pageSize); goodsResult = goodsPs.executeQuery(); // 获取数据 while (goodsResult.next()) { // 创建对象 GoodsBean goodsBean = new GoodsBean(); // 从结果集获取数据 int goods_id = goodsResult.getInt("goods_id"); goodsBean.setGoods_id(goods_id); goodsBean.setGoods_name(goodsResult.getString("goods_name")); goodsBean.setGoods_price(goodsResult.getDouble("goods_price")); goodsBean.setGoods_desc(goodsResult.getString("goods_desc")); goodsBean.setCate_id(goodsResult.getInt("cate_id")); // 继续查询商品对应的image_url imagePs.setInt(1, goods_id); imageResult = imagePs.executeQuery(); List<String> imageList = new ArrayList<String>(); while (imageResult.next()) { imageList.add(imageResult.getString("image_url")); } goodsBean.setImageList(imageList); // 将商品数据加入到集合 goodsList.add(goodsBean); } } catch (SQLException e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { dataSoureUtils.close(goodsResult); dataSoureUtils.close(imageResult); dataSoureUtils.close(goodsPs); dataSoureUtils.close(imagePs); dataSoureUtils.close(connection); } return goodsList; } @Override public int selectTotalPage(int cateId, int pageSize) { String sql = "select count(goods_id) from tb_goods"; if (cateId >= 0) { sql = "select count(goods_id) from tb_goods where cate_id = " + cateId; } Connection connection = dataSoureUtils.getConnection(); Statement statement = null; ResultSet resultSet = null; try { statement = connection.createStatement(); resultSet = statement.executeQuery(sql); int totalSize = 0; //获取总的数据条数 if (resultSet.next()) { totalSize = resultSet.getInt(1); } //计算总页数 int pageCount = totalSize / pageSize; if (totalSize % pageSize != 0) { pageCount++; } return pageCount; } catch (SQLException e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { dataSoureUtils.close(resultSet); dataSoureUtils.close(statement); dataSoureUtils.close(connection); } return 0; } }
package rafaxplayer.cheftools.providers.fragment; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import butterknife.BindView; import butterknife.ButterKnife; import rafaxplayer.cheftools.Globalclasses.BaseActivity; import rafaxplayer.cheftools.Globalclasses.GlobalUttilities; import rafaxplayer.cheftools.Globalclasses.models.Supplier; import rafaxplayer.cheftools.R; import rafaxplayer.cheftools.database.DBHelper; import rafaxplayer.cheftools.database.SqliteWrapper; public class ProviderNewEdit_Fragment extends Fragment { @BindView(R.id.editnameprovider) EditText Nametxt; @BindView(R.id.editTelefono) EditText Telefonotxt; @BindView(R.id.editEmail) EditText Emailtxt; @BindView(R.id.editDireccion) EditText Direcciontxt; @BindView(R.id.editCategoria) EditText Categoriatxt; @BindView(R.id.editcomment) EditText Comentariostxt; @BindView(R.id.buttonSave) Button save; @BindView(R.id.searchContact) ImageButton searchContact; private SqliteWrapper sql; private int ID; public static ProviderNewEdit_Fragment newInstance(int id) { ProviderNewEdit_Fragment f = new ProviderNewEdit_Fragment(); Bundle args = new Bundle(); args.putInt("id", id); f.setArguments(args); return f; } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_provider_new_edit, container, false); ButterKnife.bind(this, v); return v; } @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { save(); } }); getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); searchContact.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(contactPickerIntent, GlobalUttilities.CONTACT_SELECT); } }); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sql = new SqliteWrapper(getActivity()); sql.open(); if (getArguments() != null) { this.ID = getArguments().getInt("id"); } this.setRetainInstance(true); } @Override public void onResume() { super.onResume(); if (!sql.IsOpen()) { sql.open(); } if (this.ID != 0) { displayWithId(this.ID); } else { ((BaseActivity) getActivity()).setTittleDinamic(getString(R.string.menu_new_provider)); } } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(android.view.Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. inflater.inflate(R.menu.menu_save, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_save) { save(); return true; } return onOptionsItemSelected(item); } private void save() { if (!sql.IsOpen()) { sql.open(); } Supplier pro = new Supplier(Nametxt.getText().toString(), Telefonotxt.getText().toString(), Emailtxt.getText().toString(), Direcciontxt.getText().toString(), Comentariostxt.getText().toString(), Categoriatxt.getText().toString() ); if (this.ID == 0) { if (TextUtils.isEmpty(Nametxt.getText())) { Toast.makeText(getActivity(), getString(R.string.dlgerror_namerecipe), Toast.LENGTH_LONG).show(); GlobalUttilities.animateView(getActivity(), Nametxt); return; } if (sql.CheckIsDataAlreadyInDBorNot(DBHelper.TABLE_PROVEEDORES, DBHelper.NAME, Nametxt.getText().toString())) { Toast.makeText(getActivity(), getString(R.string.dlgerror_dataexist), Toast.LENGTH_LONG).show(); GlobalUttilities.animateView(getActivity(), Nametxt); return; } long id = sql.InsertObject(pro); if (id != -1) { new MaterialDialog.Builder(getActivity()) .title(R.string.dlgsucces_saved) .content(R.string.dlgnew_saved) .positiveText(R.string.yes) .negativeText(R.string.not) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { refresh(); Nametxt.requestFocus(); dialog.dismiss(); } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { getActivity().onBackPressed(); dialog.dismiss(); } }) .show(); } } else { long count = sql.UpdateWithId(pro, this.ID); if (count > 0) { Toast.makeText(getActivity(), getString(R.string.dlgok_update), Toast.LENGTH_LONG).show(); if (getActivity().getSupportFragmentManager().findFragmentByTag("detalle") != null) { getActivity().getSupportFragmentManager().findFragmentByTag("detalle").onResume(); } getActivity().onBackPressed(); } } sql.close(); } private void displayWithId(int id) { if (!sql.IsOpen()) { sql.open(); } Supplier pro = (Supplier) sql.SelectWithId("Provider", DBHelper.TABLE_PROVEEDORES, id); if (pro != null) { Nametxt.setText(pro.getName()); Telefonotxt.setText(pro.getTelefono()); Emailtxt.setText(pro.getEmail()); Direcciontxt.setText(pro.getDireccion()); Categoriatxt.setText(pro.getCategoria()); Comentariostxt.setText(pro.getComentario()); this.ID = id; ((BaseActivity) getActivity()).setTittleDinamic(getString(R.string.menu_edit_provider) + " " + pro.getName()); } sql.close(); } private void refresh() { Nametxt.setText(""); Telefonotxt.setText(""); Direcciontxt.setText(""); Emailtxt.setText(""); Categoriatxt.setText(""); Comentariostxt.setText(""); this.ID = 0; } @Override public void onPause() { super.onPause(); sql.close(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == GlobalUttilities.CONTACT_SELECT) { Uri result = data.getData(); String email = getContactData(result, ContactsContract.CommonDataKinds.Email.CONTENT_URI, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?", new String[]{result.getLastPathSegment()}, ContactsContract.CommonDataKinds.Email.DATA ); String phone = getContactData(result, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{result.getLastPathSegment()}, ContactsContract.CommonDataKinds.Phone.DATA ); String name = getContactData(result, result, null, null, ContactsContract.Contacts.DISPLAY_NAME ); Nametxt.setText(name); Emailtxt.setText(email); Telefonotxt.setText(phone); if (email.length() == 0) { Toast.makeText(getActivity(), "Email not found", Toast.LENGTH_SHORT).show(); } if (phone.length() == 0) { Toast.makeText(getActivity(), "Phone not found", Toast.LENGTH_SHORT).show(); } if (name.length() == 0) { Toast.makeText(getActivity(), "Name not found", Toast.LENGTH_SHORT).show(); } } } else { Log.e("Activity", "Failed to pick contact"); } } private String getContactData(Uri data, Uri uri, String selection, String[] args, String column) { String infoContact = ""; Cursor cursor = null; try { Log.v("INFO CONTACT", "Got a contact result: " + data.toString()); // query for everything email cursor = getActivity().getContentResolver().query(uri, null, selection, args, null); int Idx = cursor.getColumnIndex(column); // let's just get the first email if (cursor.moveToFirst()) { infoContact = cursor.getString(Idx); Log.v("INFO CONTACT", "Got name: " + infoContact); } else { Log.w("INFO CONTACT", "No results"); } } catch (Exception e) { Log.e("INFO CONTACT", "Failed to get name data", e); } finally { if (cursor != null) { cursor.close(); } } return infoContact; } }
package org.yoqu.fish.rpc.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import org.yoqu.fish.common.ServerInfo; import org.yoqu.fish.rpc.coder.DeCoder; import org.yoqu.fish.rpc.coder.EnCoder; import java.io.Closeable; import java.io.IOException; /** * @author yoqu * @date 2018/2/5 - 下午3:58 */ public class NettyClient implements Closeable { protected Bootstrap bootstrap; protected EventLoopGroup group; protected String host; protected int port; public NettyClient(ServerInfo serverInfo) { this.host = serverInfo.getHost(); this.port = serverInfo.getPort(); init(); } private void init() { bootstrap = new Bootstrap(); group = new NioEventLoopGroup(4); bootstrap.group(group) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, true) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel channel) throws Exception { initClientChannel(channel); } }); } private void initClientChannel(SocketChannel channel) { channel.pipeline().addLast("encode", new EnCoder()); channel.pipeline().addLast("decode", new DeCoder()); channel.pipeline().addLast("handler", new ClientHandler()); } public ChannelFuture connect() { ChannelFuture connect = bootstrap.connect(host, port); connect.awaitUninterruptibly(); return connect; } @Override public void close() throws IOException { } }
package co.ga.nyc; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Scanner; public class Game { private static ArrayList<Player> players; private String recordsFile = "records.txt"; public Game() { } public static void printMenu() throws IOException { Scanner scanner = new Scanner(System.in); // Welcome and Title System.out.println("\n"); System.out.println("==================== Main Menu =========================\n"); System.out.println("Choose an action:\n"); System.out.println("1. Type 'play' to play 'Rock, Paper, Scissors.'"); System.out.println("2. Type 'history' to view your game history."); System.out.println("3. Type 'quit' to stop playing."); String menuInputInt = scanner.nextLine().toLowerCase(); Game game = new Game(); switch (menuInputInt) { case "play": players = game.choosePlayers(); players.forEach( (player) -> { String pickedMove = null; try { pickedMove = player.chooseMove(); } catch (IOException e) { e.printStackTrace(); } player.setCurrentMove(pickedMove); }); game.compareMoves(players.get(0), players.get(1)); break; case "history": System.out.println("View Previous Records"); System.out.println("====================="); game.readFromFile("records.txt"); printMenu(); break; case "quit": System.out.println("Thanks for playing"); System.exit(0); break; default: System.out.println("Invalid output detected, please try again."); printMenu(); break; } scanner.close(); } public ArrayList<Player> choosePlayers() { players = new ArrayList<>(); Scanner scanner = new Scanner (System.in); System.out.println("Will you be playing with 2 players or vs. the computer? ('2 players' or 'vs computer')"); String playerResponse = scanner.nextLine().toLowerCase(); // TODO: Validate empty player.name String inputs if (playerResponse.contains("pl")) { // silly linguistic hack System.out.println("Human vs Human Game: detected"); System.out.println("What is Player 1's name?"); String nameInput1 = scanner.nextLine(); System.out.println("What is Player 2's name?"); String nameInput2 = scanner.nextLine(); Player player1 = new Human(nameInput1); Player player2 = new Human(nameInput2); player1.setName(nameInput1); player2.setName(nameInput2); players.add(player1); players.add(player2); } else if (playerResponse.contains("mp")) { // silly linguistic hack System.out.println("Human vs Bot Game: detected"); System.out.println("What's the player's name?"); String nameInput = scanner.nextLine(); Player player = new Human(nameInput); Player bot = new Bot(); player.setName(nameInput); players.add(player); players.add(bot); } else { System.out.println("Sorry, I didn't quite catch that, try '2 players' or 'vs computer'."); choosePlayers(); } return players; } // Method to compare moves thrown public void compareMoves(Player player1, Player player2) throws IOException { // TODO: Add setTimeout like function for count down with s.out String player1Move = player1.getCurrentMove(); String player2Move = player2.getCurrentMove(); System.out.println(player1.getName() + " chose " + player1.getCurrentMove()); System.out.println(player2.getName() + " chose " + player2.getCurrentMove()); // TODO: DRY this out. if(player1Move.equals(player2Move)){ System.out.println("You both threw " + player1.getCurrentMove()); System.out.println("It's a Draw"); writeToFile(recordsFile, player1, player2,"draw"); } else if(player1Move.equals("rock") && player2Move.equals("scissors")) { System.out.println("Rock Smashes Scissors"); System.out.println(player1.getName() + " beats " + player2.getName()); player1.setWins(player1.getWins()+1); writeToFile(recordsFile, player1, player2, "win"); } else if(player1Move.equals("rock") && player2Move.equals("paper")) { System.out.println("Paper covers Rock"); System.out.println(player2.getName() + " beats " + player1.getName()); player1.setLosses(player1.getLosses()+1); writeToFile(recordsFile, player1, player2,"loss"); } else if(player1Move.equals("scissors") && player2Move.equals("rock")) { System.out.println("Rock smashes Scissors"); System.out.println(player2.getName() + " beats " + player1.getName()); player1.setLosses(player1.getLosses()+1); writeToFile(recordsFile, player1, player2, "loss"); } else if(player1Move.equals("scissors") && player2Move.equals("paper")) { System.out.println("Scissors cuts Paper"); System.out.println(player1.getName() + " beats " + player2.getName()); player1.setWins(player1.getWins()+1); writeToFile(recordsFile, player1, player2, "win"); } else if(player1Move.equals("paper") && player2Move.equals("rock")) { System.out.println("Paper covers Rock"); System.out.println(player1.getName() + " beats " + player2.getName()); player1.setWins(player1.getWins()+1); writeToFile(recordsFile, player1, player2, "win"); } else if(player1Move.equals("paper") && player2Move.equals("scissors")) { System.out.println("Scissors cuts Paper"); System.out.println(player1.getName() + " beats " + player2.getName()); player1.setWins(player1.getWins()+1); writeToFile(recordsFile, player1, player2, "loss"); } else { System.out.println("Something went terribly wrong, please quit and restart the game:"); } printMenu(); } // private void refactorWinner(Player player1, Player player2){ // if(player1.getCurrentMove().equals(player2.getCurrentMove())){ // System.out.println(player1.getName() + " chose " + player1.getCurrentMove()); // } // } // TODO: will include function to see current wins/losses for pair of existing players. // Where to include in options? // TODO: need to ensure saving user instance to keep wins/losses record properly public static void userStats(Player player){ System.out.println(player.getName() + "stats:"); String resultString = String.format("%s went %d - %d", player.getName(), player.getWins(), player.getLosses()); System.out.println(resultString); } // TODO: consider exercising ArrayList recordList for read AND write public void readFromFile(String filename) throws IOException { ArrayList<String> recordList = new ArrayList<String>(); String file = filename; BufferedReader reader = new BufferedReader(new FileReader(file)); try { String currentLine = reader.readLine(); while (currentLine != null) { // record format: name,wins,loses String[] data = currentLine.split(","); String result = ""; try { result += String.format("%s picked %s and %s picked %s. It was a %s", data[0], data[1], data[2], data[3], data[4]); } catch(Exception e){ result = "invalid record on file"; } recordList.add(result); currentLine = reader.readLine(); } }catch(IOException e){ System.out.println("Unable to read records, please contact dev"); System.out.println(e); }finally{ reader.close(); } recordList.forEach( record -> System.out.println(record + "\n")); } public void writeToFile(String filename, Player player1, Player player2, String result) throws IOException { Path path = Paths.get(filename); BufferedWriter bufferedWriter = new BufferedWriter((new FileWriter(filename, true))); String record = player1.getName()+ "," + player1.getCurrentMove() + "," + player2.getName() + "," + player2.getCurrentMove() + "," + result; bufferedWriter.write("\n"); bufferedWriter.write(record); bufferedWriter.close(); } }
package ConnectFourPackage; import javafx.scene.paint.Color; import java.util.ArrayList; /** * Created by 40095 on 1/24/15. */ public class SmartAi extends Connect4Player implements Connect4AI { ArrayList<Group> winningGroups, losingGroups, zugzwangGroups, winnableGroups, groups; //Winning groups is all groups that can be won on the next play //Losing groups is all the groups that will lead to defeat in the next play //future threats are all groups with three of a kind, but the 4th tile is not playable (Zugzwang) //winnableGroups is all groups that do not contain the opponents tile //groups is all groups /* Order of precedence for plays to make: 1) plays that make you win immediately Pick first group from left 2) plays that keep you from losing immediately Pick first group from left 3) plays that are in a winnable group AND not zugzwang Pick winnable group with most of your own tokens 4) zugzwang plays Pick first group from left */ public SmartAi() { // getGroups(); groups = new ArrayList<>(69); winningGroups = new ArrayList<Group>(); losingGroups = new ArrayList<Group>(); zugzwangGroups = new ArrayList<Group>(); winnableGroups = new ArrayList<>(); } private void getGroups() { // Initialize and place the groups int[] dRows = {-1, 0, 1, 1}; int[] dCols = {1, 1, 1, 0}; int fRow, fCol; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { // start @ i,j // // if 0 < i + 3 * dCol <= board[0].length, 0 < j + 3 * dRow <= board.length // create new group from i,j with specified increment pair // // possible directions are: diagonal up, right, diagonal down, down // / -1 row +1 col // > 0 row +1 col // \ +1 row +1 col // | +1 row 0 col for (int k = 0; k < dRows.length; k++) { fRow = i + 3 * dRows[k]; fCol = j + 3 * dCols[k]; // switch (k) { // case 0: // System.out.print("/ "); // break; // case 1: // System.out.print("> "); // break; // case 2: // System.out.print("\\ "); // break; // case 3: // System.out.print("| "); // break; // } if (fRow >= 0 && fRow <= board.length - 1 && fCol >= 0 && fCol <= board[0].length - 1) { // System.out.println("Group: [" + j + "][" + i + "] to [" + fRow + "][" + fCol + "] is possible"); groups.add(new Group(board, i, j, dCols[k], dRows[k])); } } } } } private boolean isPlayable(int row, int col) { if (row == 5) return board[row][col].equals(Color.WHITE); return board[row][col].equals(Color.WHITE) && !board[row + 1][col].equals(Color.WHITE); } private int tilesBelowSpace(int row, int col) { int count = 0; for (int i = row; i < 5; i++) { if (board[i][col].equals(Color.WHITE)) { count++; } } return count; } private int winningCol() { refreshGroups(); if (winnableGroups.size() > 0) { return winningGroups.get(0).dangerousCol(); } if (losingGroups.size() > 0) { return losingGroups.get(0).dangerousCol(); } return 1; } private void setWinningGroups() { winnableGroups.clear(); for (Group group : groups) { if (group.dangerousCol() > 0 && group.dangerousRow() > 0) { if (group.getDangerous() != -1 && group.getCriticalColor().equals(token) && isPlayable(group.dangerousCol(), group.dangerousRow())) { winningGroups.add(group); } } } } private void setLosingGroups() { losingGroups.clear(); for (Group group : groups) { if (group.dangerousCol() > 0 && group.dangerousRow() > 0) { if (group.getDangerous() != -1 && !group.getCriticalColor().equals(token) && isPlayable(group.dangerousCol(), group.dangerousRow())) { losingGroups.add(group); } } } } private void setWinnableGroups() { for (Group g : groups) { if (token.equals(Color.RED)) { if (g.doesNotContain(Color.YELLOW)) { winnableGroups.add(g); } } else { if (g.doesNotContain(Color.RED)) { winnableGroups.add(g); } } } } private void setZugzwangGroups() { for (Group g : groups) { if (!isPlayable(g.dangerousRow(), g.dangerousCol())) //if the group is not playable zugzwangGroups.add(g); } } private void refreshGroups() { setWinningGroups(); setLosingGroups(); setWinnableGroups(); setZugzwangGroups(); } public int makePlay() { if (winningCol() != -1) { // System.out.println("Playing critical column"); // if (winningGroups.size() == 0) // System.out.println("Not on my watch"); // else // System.out.println("I win!"); return winningCol(); } else { // System.out.println("playing random"); } return -1; } @Override public int getMove(Color[][] board, Color me) { this.token = me; this.board = board; getGroups(); return makePlay(); } }
package com.t11e.discovery.datatool.column; import java.sql.ResultSet; import java.sql.SQLException; import com.t11e.discovery.datatool.JsonUtil; public class JsonColumnProcessor implements IColumnProcessor { public static final JsonColumnProcessor INSTANCE = new JsonColumnProcessor(); @Override public Object processColumn(final ResultSet rs, final int column) throws SQLException { Object result = null; final String value = rs.getString(column); if (!rs.wasNull()) { try { result = JsonUtil.decode(value); } catch (final Exception e) { // Swallow } } return result; } }
package servlets; import java.io.IOException; import java.io.PrintWriter; 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 cadastroUsuario */ @WebServlet(urlPatterns = { "/newUser" }) public class NovoUsuario extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public NovoUsuario() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String nome = request.getParameter("name"); String email = request.getParameter("mail"); String senha = request.getParameter("password"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<p>" + nome + "</p>"); out.println("<p>" + email + "</p>"); out.println("<p>" + senha + "</p>"); out.println("</body>"); out.println("</html>"); } }
package cn.sort.mergeSort; import java.util.Arrays; /** * @author Chay * @date 2021/6/8 17:22 */ public class MergeSortTest { public static int[] mergeSort(int[] input, int left, int right) { if (left == right) { return new int[]{input[right]}; } int mid = (right + left)/2; //左半边归并排序递归 int[] leftArr = mergeSort(input, left, mid); //右半边归并排序递归 int[] rightArr = mergeSort(input, mid + 1, right); //新的存放结果数组 int[] newResultArr = new int[leftArr.length + rightArr.length]; int m=0,i=0,j=0; while(i < leftArr.length && j < rightArr.length) { //把小元素归并到结果数组中 newResultArr[m++] = leftArr[i] < rightArr[j] ? leftArr[i++] : rightArr[j++]; } //左右子序列剩余的元素直接合并到结果数组中 while(i < leftArr.length) { newResultArr[m++] = leftArr[i++]; } while(j < rightArr.length) { newResultArr[m++] = rightArr[j++]; } return newResultArr; } public static void main(String[] args) { System.out.println(Arrays.toString(mergeSort(new int[]{2,1,3,8,4,5,3}, 0, 6))); } }
package com.dataart.was.actions; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.sql.SQLException; public interface Action { void execute(HttpServletRequest request) throws SQLException, IOException, ServletException; }
package arraysnstrings; import static org.junit.Assert.*; import org.junit.Test; public class MatrixSpinalTest { @Test public void test() { int[][] matrix = new int[][]{ new int[]{1,2,3,4}, new int[]{10,11,12, 5}, new int[]{9,8,7,6} }; MatrixSpinal.printSpinal(matrix); } }
package com.example.snapup_android.service; import java.sql.Time; public interface TimeTableService { //根据车次和站点编号查询列车到达时间: public Time getArrivalTime(String num_code, String station_code); //根据车次和站点编号查询列车离开时间: public Time getDepartTime(String num_code, String station_code); }
package me.sky.boss.utils.config; import com.google.common.base.Charsets; import com.google.common.io.ByteStreams; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginAwareness; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.logging.Level; public class Config { private File f; private FileConfiguration cfg; private String path_; private String fileName_; private Plugin main; public Config(String path, String fileName, Plugin javaPluginExtender) { main = javaPluginExtender; path_ = path; fileName_ = fileName; } public void reloadConfig() { cfg = YamlConfiguration.loadConfiguration(f); InputStream defConfigStream = this.getResource(fileName_); if (defConfigStream != null) { cfg.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream, Charsets.UTF_8))); } } public Config create() { f = new File(path_, fileName_); cfg = YamlConfiguration.loadConfiguration(f); return this; } public void setDefault(String filename) { InputStream defConfigStream = main.getResource(filename); if (defConfigStream == null) return; YamlConfiguration defConfig; if ((isStrictlyUTF8())) { defConfig = YamlConfiguration .loadConfiguration(new InputStreamReader(defConfigStream, Charsets.UTF_8)); } else { defConfig = new YamlConfiguration(); byte[] contents; try { contents = ByteStreams.toByteArray(defConfigStream); } catch (IOException e) { main.getLogger().log(Level.SEVERE, "Unexpected failure reading " + filename, e); return; } String text = new String(contents, Charset.defaultCharset()); if (!(text.equals(new String(contents, Charsets.UTF_8)))) { main.getLogger() .warning( "Default system encoding may have misread " + filename + " from plugin jar"); } try { defConfig.loadFromString(text); } catch (InvalidConfigurationException e) { main.getLogger().log(Level.SEVERE, "Cannot load configuration from jar", e); } } cfg.setDefaults(defConfig); } @SuppressWarnings("deprecation") private boolean isStrictlyUTF8() { return main.getDescription().getAwareness().contains( PluginAwareness.Flags.UTF8); } public void saveConfig() { try { cfg.save(f); } catch (IOException e) { e.printStackTrace(); } } public FileConfiguration getConfig() { return cfg; } public File toFile() { return f; } public void saveDefaultConfig() { if (!exists()) { saveResource(fileName_, false); } } public void saveResource(String resourcePath, boolean replace) { if (resourcePath != null && !resourcePath.equals("")) { resourcePath = resourcePath.replace('\\', '/'); InputStream in = this.getResource(resourcePath); if (in == null) { throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + toFile()); } else { File outFile = new File(path_, resourcePath); int lastIndex = resourcePath.lastIndexOf(47); File outDir = new File(path_, resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0)); if (!outDir.exists()) { outDir.mkdirs(); } try { if (outFile.exists() && !replace) { main.getLogger().log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists."); } else { OutputStream out = new FileOutputStream(outFile); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); in.close(); } } catch (IOException var10) { main.getLogger().log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, var10); } } } else { throw new IllegalArgumentException("ResourcePath cannot be null or empty"); } } public InputStream getResource(String filename) { if (filename == null) { throw new IllegalArgumentException("Filename cannot be null"); } else { try { URL url = this.getClass().getClassLoader().getResource(filename); if (url == null) { return null; } else { URLConnection connection = url.openConnection(); connection.setUseCaches(false); return connection.getInputStream(); } } catch (IOException var4) { return null; } } } public boolean exists() { return f.exists(); } }
package PeakIndexinaMountainArray852; /** * @ClassName Solution01 * @Description https://leetcode-cn.com/problems/peak-index-in-a-mountain-array/ * @Author tangchao@mfexcel.com * @Date 2019/10/21 10:20 * @Version 1.0 */ public class Solution01 { // 二分查找也可 public int peakIndexInMountainArray(int[] A) { int result = 0; for (int i = 1; i < A.length; i++) { if (A[i-1] > A[i]) { result = i - 1; break; } } return result; } }
/* * MPS SDK Demo application */ package demo1; import java.lang.Math; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Vector; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ericsson.snf.mps.LocationData; import com.ericsson.snf.mps.GatewayException; import com.ericsson.snf.mps.LocationFailure; import com.ericsson.snf.mps.req.LocationResult; import common.ConnectionManager; import common.Util; import com.ericsson.snf.mps.LocatedMobileStation; import com.ericsson.snf.mps.MobileStation; import com.ericsson.snf.mps.gad.CircularArcArea; import com.ericsson.snf.mps.gad.CircularArea; import com.ericsson.snf.mps.gad.Coordinate; import com.ericsson.snf.mps.gad.EllipticalArea; import com.ericsson.snf.mps.gad.GadShape; import com.ericsson.snf.mps.gad.Point; import com.ericsson.snf.mps.gad.Polygon; import com.ericsson.snf.mps.rep.LocationReport; import com.ericsson.snf.mps.req.LocationResult; import demo2.DemoPushHandler; import demo3.LocatedCallServlet; /** * It is better to use the java.lang.StringBuffer to concatenate strings, but * the += operator is used in the example applications for easier reading. */ public class MTLRResult extends HttpServlet { private static final String TABLE_HEAD = "<table width='450' border='0'>" + "<tr><th>MSISDN</th><th>Time</th></tr>"; private static final String TABLE_END = "</table>"; private static final String NEW = "<BR><BR><a href='demo1'>New search</a>"; /** * * @param request * @param response * @exception ServletException, IOException */ public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(Util.CONTENT_TYPE); response.setHeader(Util.CACHE_CONT, Util.NO_CACHE); response.setDateHeader(Util.DATE, System.currentTimeMillis()); response.setContentType("text/plain"); String html = "";//Util.getHeader(MTLRForm.NAME) +"<body>"; Vector msSet=new Vector(2,2); String value = null; int i; String mobileId=""; // Get the location of the mobile try { mobileId=request.getParameter("msisdn0"); String[] target={mobileId}; LocationResult result=ConnectionManager.getInstance().getLocation(target); MobileStation ms=new MobileStation(mobileId); LocationData lms=result.getLocationData(ms); LocatedMobileStation ld=(LocatedMobileStation)lms; GadShape locShape = ld.getLocationShape(); Coordinate coord = locShape.getReferencePoint(); html+="x: " + coord.getX() + "y: " + coord.getY(); }catch (Exception ex) { System.out.println(ex.getMessage()); html += "Error: Could not obtain location" + ex.getMessage(); } response.setContentLength(html.length()); PrintWriter out = response.getWriter(); out.println(html); } // Now let's open and read a file... try { if ( !data.exists() || !data.canRead() ) { System.out.println( "Ack! I'm a silly programming language which can't read " + data ); return; } // Now to do something... try { FileReader fr = new FileReader ( data ); BufferedReader in = new BufferedReader( fr ); String line, cinema; Boolean flag; String [] ccoords; int proximity = 1000; while ((line = in.readLine()) != null) { if (line.endsWith(":")) { flag = false; cinema = line.replace(':',','); } else if (line.startsWith("#")) { ccoords = ((line.replace('#',' ')).trim()).split(":"); if ( ((coord.getX() - (atoi(ccoords[0])).abs < proximity) && ((coord.getY() - (atoi(ccoords[1])).abs < proximity)) { flag = true; } else { flag = false; } } else if ((flag == true) && (line.length() > 2)) { System.out.println(line); } } } catch ( FileNotFoundException e ) { System.out.println( "Ack! I'm a silly programming language who can't find your file!" ); }
package com.mark.ninjagold; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Random; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class NinjaGoldController { Random rand = new Random(); static int yourGold = 0; int gold; String item; DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy, HH:mm:ss"); LocalDateTime timeNow = LocalDateTime.now(); static ArrayList<String> log = new ArrayList<String>(); @RequestMapping("/") public String game(HttpSession session) { if (session.getAttribute("yourGold") == null || session.getAttribute("yourGold").equals("")) { session.setAttribute("yourGold", yourGold); } if(yourGold < -5) { return "fail.jsp"; } return "index.jsp"; } @RequestMapping("/farm") public String farm(HttpSession session) { gold = rand.nextInt(11) + 10; yourGold += gold; item = "You did work on the farm and earned "+gold+" gold. <"+timeNow.format(timeFormat)+">"; log.add(item); session.setAttribute("log", log); session.setAttribute("yourGold", yourGold); return "redirect:/"; } @RequestMapping("/cave") public String cave(HttpSession session) { gold = rand.nextInt(6) + 5; yourGold += gold; item = "You did work in the Cave and earned "+gold+" gold. <"+timeNow.format(timeFormat)+">"; log.add(item); session.setAttribute("log", log); session.setAttribute("yourGold", yourGold); return "redirect:/"; } @RequestMapping("/house") public String house(HttpSession session) { gold = rand.nextInt(3) + 3; item = "You did work in the house and earned "+gold+" gold. <"+timeNow.format(timeFormat)+">"; log.add(item); session.setAttribute("log", log); yourGold += gold; session.setAttribute("yourGold", yourGold); return "redirect:/"; } @RequestMapping("/casino") public String casino(HttpSession session) { gold = rand.nextInt(100) - 50; if(gold > 0) { item = "You gambled at the casino and won "+ gold +" gold! <" + timeNow.format(timeFormat) + ">"; } else if(gold < 0) { item = "You gambled at the casino and lost " + gold + " <" + timeNow.format(timeFormat) + ">"; } else { item = "You gambled at the casino and broke even... <"+timeNow.format(timeFormat)+">"; } log.add(item); session.setAttribute("log", log); yourGold += gold; session.setAttribute("yourGold", yourGold); return "redirect:/"; } @RequestMapping("/reset") public String reset(HttpSession session) { yourGold = 0; log.clear(); session.setAttribute("log", log); session.setAttribute("yourGold", yourGold); return "redirect:/"; } }
/** * Top-level SockJS types. */ @NonNullApi @NonNullFields package org.springframework.web.socket.sockjs; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
package com.lesports.airjordanplayer; import com.lesports.airjordanplayer.data.VideoStreamItem; import com.letv.pp.func.CdeHelper; /** * Created by litzuhsien on 8/12/15. */ public class DefaultStreamProvider implements VideoStreamProvider { private CdeHelper mCdeHelper; public DefaultStreamProvider() { mCdeHelper = VideoPlayerInfrastructureContext.getGlobalCdeHelper(); } @Override public void execute(VideoStreamItem item, VideoStreamProviderCallback callback) { String linkshellUri = mCdeHelper.getLinkshellUrl(item.getPreferredSchedulingUri()); if (callback != null) { callback.onCompletion(linkshellUri, 0); } } @Override public void cancel() { } }
package com.mycontacts.activity; import android.Manifest; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.Toast; import com.mycontacts.R; import com.mycontacts.controller.ContactListAdapter; import com.mycontacts.model.Contact_Model; import java.util.ArrayList; public class AllContacts extends AppCompatActivity { ArrayList<Contact_Model> contactArrayList; RecyclerView recycle; ContactListAdapter adapter; ProgressDialog pd; String contactNumbers; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact); recycle = (RecyclerView) findViewById(R.id.recycle); LinearLayoutManager layoutManager = new LinearLayoutManager(AllContacts.this); recycle.setLayoutManager(layoutManager); try { // check permission if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { getPermission(); }else{ new LoadContacts().execute();// Execute the async task } } catch (Exception e) { e.printStackTrace(); } // fetchContacts(); } public void getPermission() { try { int readContactsFlag = 0; int permissionCount = 0; int permissionCountNew = 0; int flag = 0; //** check permission is GRANTED or Not in Marshmallow */ int readContacts = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS); if (readContacts != PackageManager.PERMISSION_GRANTED) { readContactsFlag = 1; permissionCount += 1; flag = 1; } String[] permissionCArr = new String[permissionCount]; if (readContactsFlag == 1) { permissionCArr[permissionCountNew] = Manifest.permission.READ_CONTACTS; permissionCountNew += 1; } if (flag == 1) { ActivityCompat.requestPermissions( this, permissionCArr, 155 ); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 155) { if (grantResults.length > 0) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { new LoadContacts().execute();// Execute the async task } } } } // Async task to load contacts private class LoadContacts extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { contactArrayList = fetchContacts();// Get contacts array list from this // method return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // If array list is not null and is contains value if (contactArrayList != null && contactArrayList.size() > 0) { adapter = null; if (adapter == null) { adapter = new ContactListAdapter(AllContacts.this, contactArrayList); recycle.setAdapter(adapter); // adapter.notifyDataSetChanged(); } adapter.notifyDataSetChanged(); } else { // If adapter is null then show toast Toast.makeText(AllContacts.this, "There are no contacts.", Toast.LENGTH_LONG).show(); } // Hide dialog if showing if (pd.isShowing()) pd.dismiss(); } @Override protected void onPreExecute() { super.onPreExecute(); // Show Dialog pd = ProgressDialog.show(AllContacts.this, "Loading Contacts", "Please Wait..."); } } private ArrayList<Contact_Model> fetchContacts() { contactArrayList = new ArrayList<>(); Uri uri = ContactsContract.Contacts.CONTENT_URI; // Contact URI String order = ContactsContract.Contacts.SORT_KEY_PRIMARY + " ASC"; String[] projection = new String[]{ContactsContract.RawContacts._ID, ContactsContract.RawContacts.ACCOUNT_TYPE}; // String selection = ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'com.anddroid.contacts.sim' " // + " AND " + ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'com.google' "; String selection = ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'com.anddroid.contacts.sim' "; ContentResolver contentResolver = getContentResolver(); Cursor contactsCursor = getContentResolver().query( uri, null, null, null, order); //ContactsContract.Contacts.DISPLAY_NAME + " ASC "); int count = contactsCursor.getCount(); Log.e("Count", "Contact Count " + count); // Move cursor at starting if (contactsCursor.moveToNext()) { do { long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID")); // Get contact ID Uri dataUri = ContactsContract.Data.CONTENT_URI; // URI to get data of contacts Cursor dataCursor = getContentResolver().query( dataUri, null, ContactsContract.Data.CONTACT_ID + " = " + contactId, null, null);// Return data cursor Re-presentation to contact ID // Strings to get all details String displayName = ""; String nickName = ""; String homePhone = ""; String mobilePhone = ""; String workPhone = ""; String homeEmail = ""; String workEmail = ""; String companyName = ""; String title = ""; String photoURL = ""; // Now start the cusrsor if (dataCursor.moveToFirst()) { displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));// get the contact name int photoUriIndex = dataCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI); photoURL = dataCursor.getString(photoUriIndex); do { String mimeType = dataCursor.getString(dataCursor.getColumnIndex("mimetype")); String contentTypeName = ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE; String contentTypePhone = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE; String contentTypeEmail = ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE; String contentTypeOrganization = ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE; String contentTypePhoto = ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE; if (mimeType.equals(contentTypeName)) { nickName = dataCursor.getString(dataCursor.getColumnIndex("data1")); // Get Nick Name } // In this get All contact numbers like home,mobile, work, etc and add them to numbers string // if (mimeType.equals(contentTypePhone)) { if (contentTypePhone.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) { int phoneType = dataCursor.getInt(dataCursor.getColumnIndex("data2")); // Get Nick Name switch (dataCursor.getInt(dataCursor.getColumnIndex("data2"))) { case ContactsContract.CommonDataKinds.Phone.TYPE_HOME: homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1")); contactNumbers += "Home Phone : " + homePhone + "\n"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_WORK: workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1")); contactNumbers += "Work Phone : " + workPhone + "\n"; break; case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE: mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1")); contactNumbers += "Mobile Phone : " + mobilePhone + "\n"; break; } } // In this get all Emails like home, work etc and add them to email string if (mimeType.equals(contentTypeEmail)) { int emailType = dataCursor.getInt(dataCursor.getColumnIndex("data2")); switch (emailType) { case ContactsContract.CommonDataKinds.Email.TYPE_HOME: homeEmail = dataCursor.getString(dataCursor.getColumnIndex("data1")); break; case ContactsContract.CommonDataKinds.Email.TYPE_WORK: workEmail = dataCursor.getString(dataCursor.getColumnIndex("data1")); break; } } if (mimeType.equals(contentTypeOrganization)) { companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));// get company name title = dataCursor.getString(dataCursor.getColumnIndex("data4"));// get Company title } if (mimeType.equals(contentTypePhoto)) { // photoURL = dataCursor.getString(dataCursor.getColumnIndex("data15")); // get photo in byte } } while (dataCursor.moveToNext()); Contact_Model contactModel = new Contact_Model(); contactModel.setContactId(Long.toString(contactId)); contactModel.setContactNumberHome(homePhone); contactModel.setContactNumberWork(workPhone); contactModel.setContactNumberMobile(mobilePhone); contactModel.setContactEmailHome(homeEmail); contactModel.setContactEmailWork(workEmail); contactModel.setContactOtherDetails(companyName); contactModel.setContactPhoto(photoURL); if (!mobilePhone.equals("") || !mobilePhone.equals("null")) { contactModel.setContactName(displayName); contactModel.setContactNikName(nickName); contactModel.setContactNumberMobile(mobilePhone); } contactArrayList.add(contactModel); } } while (contactsCursor.moveToNext()); } return contactArrayList; } }
package com.snowinpluto.tools; import com.snowinpluto.tools.analysis.BeanAnalyst; import com.snowinpluto.tools.test.bean.LoginAccount; import org.junit.Test; public class BeanAnalystTest { @Test public void test_01() { BeanAnalyst analyst = new BeanAnalyst(); analyst.analysis(LoginAccount.class); } }
import java.util.Vector; import static java.lang.Math.*; class retta extends inputitem { private razionale a, b , c ; public retta(razionale x,razionale y, razionale l){ a = x; b = y; c = l; //chiamo i costruttori per garantire il controllo sui segni } public retta(){ this(new razionale(),new razionale(),new razionale()); } public retta(double n, double m,double o){ this(new razionale(n),new razionale(m),new razionale(o)); } public razionale getA(){ return a; } public razionale getB(){ return b; } public razionale getC(){ return c; } public String toString(){ String ret = new String(); if( a.getnum() != 0 ) ret = ret + a + " x" ; if( b.getnum() != 0 ) { if( b.sign() == true ) ret = ret + " +"; ret = ret + b + " y" ; } if( c.getnum() != 0 ){ if( c.sign() == true ) ret = ret + " +"; ret = ret + c ; } return ret; } public double distancePuntoRetta(punto p){ return ( (abs( (a.multiply(p.getx())).converti() + (b.multiply(p.gety())).converti() + c.converti() ) ) /(sqrt(pow(a.converti(),2) + pow(b.converti(),2)))); } public double distanceRettaRetta(retta r){ punto x = new punto(); razionale neg = new razionale(-1,1); razionale zero = new razionale(); if(r.a.getnum() == 0){ x = new punto(zero,neg.multiply(r.c.multiply(r.b.inverso()))); } else if(r.b.getnum() == 0 ){ x = new punto(((r.c.multiply(r.a.inverso())).multiply(neg)),zero); } else{ x = new punto(zero,(neg.multiply(r.c.multiply(r.b.inverso())))); } return distancePuntoRetta(x); } private boolean isParallels(retta r2 ){ razionale neg = new razionale(-1,1); razionale zero = new razionale(); double coeffA = neg.multiply((this.a.multiply(this.b.inverso()))).converti(); double coeffB = neg.multiply((r2.a.multiply(r2.b.inverso()))).converti(); if(coeffA == coeffB) return true; else return false; } private boolean isPerpendicolari( retta r2){ razionale neg = new razionale(-1,1); if( neg.multiply((this.a.multiply(this.b.inverso()))).equals(neg.multiply(neg.multiply((r2.a.multiply(r2.b.inverso())).inverso()))) ) return true; else return false; } //retta perpendicolare a un altra e passante per un punto public retta rettaperpendicolare(punto p ){ razionale neg = new razionale(-1,1); razionale zero = new razionale(); if( b.getnum() != 0 && a.getnum() != 0 ){ //trovo il coefficente angolare razionale m = new razionale(a.multiply(neg),b); //trovo l'antireciproco del coefficente angolare razionale new_m = new razionale(m.inverso()).multiply(neg); //trovo c => y1 + m*x1 razionale c = new razionale(new_m.multiply(p.getx())); c = new razionale( (c.multiply(neg)).add(p.gety())); return new retta(new_m,neg,c); }else{ if( a.equals(0) ){ return new retta( neg,zero,p.getx() ); } else return new retta( zero,neg,p.gety() ); } } public retta rettaparallela(punto p){ razionale neg = new razionale(-1,1); razionale zero = new razionale(); if( b.getnum() != 0 && a.getnum() != 0){ //disuguaglianza double ==> primitivi //trovo il coefficente angolare razionale m = new razionale( a.multiply(neg),b ); //trovo c => y1 + m*x1 razionale c = m.multiply(p.getx()) ; c = (c.multiply(neg)).add(p.gety()); return new retta(m,neg,c); } else{ if(getA().getnum() == 0){ return new retta(zero,neg,p.gety()); } else return new retta(neg,zero,p.getx()); } } //dato una x ritorna il punto rispettivo public punto printCoord_x(razionale x) throws eccezioni{ razionale neg = new razionale(-1,1); razionale y = new razionale(1,1); if(getB().getnum() == 0 && getA().getnum() == 0){ throw new implicit(); } else if(getB().getnum() == 0){ x = new razionale ( getC().multiply(neg) , getA() ); } else{ y = new razionale( (getA().multiply(neg)).multiply(x).add(getC().multiply(neg)) ,getB()); } return new punto(x,y); } //mi serve per disegnare... la facciooo ? /*public Vector<punto> print_rect() { }*/ public Vector<punto> intersectretta(retta r1){ Vector<punto> p = new Vector<punto>(); razionale neg = new razionale(-1,1); if(isParallels(r1) == true) return p; razionale det = new razionale ( getA().multiply(r1.getB()).add( neg.multiply(r1.getA().multiply(getB()) ) )); if(det.getnum() != 0){ razionale detx = new razionale(((getC().multiply(neg)).multiply(r1.getB())).add(neg.multiply((r1.getC().multiply(neg)).multiply(getB()))),det) ; razionale dety = new razionale(((getA().multiply(neg)).multiply(r1.getC())).add(neg.multiply((r1.getA().multiply(neg)).multiply(getC()))),det) ; p.add(new punto(detx,dety)); } else{ razionale x = new razionale( ((getC().multiply((r1.getB()).multiply(getB().inverso()))).add(neg.multiply(r1.getC()))),(r1.getA()).add(neg.multiply(getA().multiply((r1.getB()).multiply(getB().inverso()))))); razionale y = new razionale((getA().multiply(x)).multiply(neg.multiply(getB())).add(getC().multiply((neg.multiply(getB())).inverso()))); p.add(new punto(x,y)); } return p; } public double distance(inputitem i) throws eccezioni{ if(i instanceof retta){ if((this.intersect(i)).size() == 1) return 0; retta r = (retta)i; return distanceRettaRetta(r); } else if(i instanceof punto){ punto p = (punto)i; return distancePuntoRetta(p); } else{ return i.distance(this); } } public Vector<punto> intersect(inputitem i){ Vector<punto> v = new Vector<punto>(); if(i instanceof retta){ retta r = (retta)i; return intersectretta(r); } else if(i instanceof punto){ punto p = (punto)i ; if(distancePuntoRetta(p) == 0) { v.add(p); } } else{ return i.intersect(this); } return v;//i.intersect(this); } public void pars_rect(String retta) throws eccezioni { retta = retta.replace(" ",""); //inserisco = a prescindere retta = retta + '='; String s = new String(); retta r; // raz = verifica se è una frazione . // incx = incy = serve per verificare se trova due volte la // la x o la y . boolean raz = false , incx = false , incy = false , doub = false , segno = false ; //n = num , d = den , x = coeff x , y = coeff y , tn = termine noto double n=0,d=0,x=0,y=0,tn=0; int sign = 1; double virgola = 1 , n1; String rect[] = new String[retta.length()]; rect = retta.split(""); for(int i = 0 ; i < rect.length; i++){ //vado a verificare ci sia solo una x e una y altrimenti non e' nella forma prevista if(rect[i].equals("y") && incy == false) incy = true ; else if(rect[i].equals("y") && incy == true) throw new implicit(); if(rect[i].equals("x") && incx == false) incx = true ; else if(rect[i].equals("x") && incx == true) throw new implicit(); if( !rect[i].equals("*") && !rect[i].equals("=") ) { if( rect[i].equals("-") || rect[i].equals("+") ){ //verifico se il termine noto è a primo o secondo membro if(s.length() > 0){ n1 = Integer.parseInt(s); tn = n1 / virgola; virgola = 1; doub = false; if( ( !(b.getnum() == 0) || (a.getnum() == 0) ) && segno == false ) throw new input_error(); c = new razionale(sign*tn,1); sign = 1; segno = false; s = ""; } if( rect[i].equals("-") ) sign = -1; segno = true; } else if( rect[i].equals("/") ){ n1 = Integer.parseInt(s); n = n1 / virgola; virgola = 1; doub = false; s = ""; raz = true; } else { //caso in cui ci sia un x o y al denominatore if( ( rect[i].equals("x") || rect[i].equals("y") ) && raz == true ) throw new input_error(); if( rect[i].equals("x") || rect[i].equals("y") ){ if( s.length() == 0) s="1"; n1 = Integer.parseInt(s); x = n1 / virgola; virgola = 1; doub = false; if((b.getnum() != 0 || c.getnum() != 0) && segno == false) throw new input_error(); if(rect[i].equals("x")) a = new razionale(sign*x,1); else b = new razionale(sign*x,1); sign = 1; segno = false; s = ""; } else{ if(raz == true){ //vuol dire che sono a denominatore while( !rect[i].equals("x") && !rect[i].equals("y") && !rect[i].equals("=") && !rect[i].equals("+") && !rect[i].equals("-") ) { if(doub == true) virgola *= 10 ; if( rect[i].equals(".") ){ doub = true; } else if(rect[i].equals("0") && s.length() == 0) throw new input_error(); else s = s + rect[i]; i++; } n1 = Integer.parseInt(s); d = n1 / virgola; virgola = 1; doub = false; if( rect[i].equals("x") ){ if((b.getnum() != 0 || c.getnum() != 0) && segno == false ) throw new input_error(); a = new razionale(sign*n,d); segno = false; sign = 1; }else if( rect[i].equals("y") ){ if((a.getnum() != 0 || c.getnum() != 0) && segno == false ) throw new input_error(); b = new razionale(sign*n,d); sign = 1; segno = false; }else { if( (a.getnum() != 0 || b.getnum() != 0) && segno == false ) throw new input_error(); c = new razionale(sign*n,d); sign = 1; segno = false; } //decremento cosi posso ripartire il ciclo dal segno if(rect[i].equals("-") || rect[i].equals("+")) --i; n=0;d=1; s = ""; raz = false; } else{ //verifico se rect[i] == numero if( rect[i].equals('.') ){ doub = true; } else { try{ Integer.parseInt(rect[i]); } catch(java.lang.NumberFormatException nfe){ throw new not_numeric(); } if(doub == true) virgola *= 10 ; s = s + rect[i]; } //inserito un input errato: carattere non riconosciuto } } } } else if( rect[i].equals('=') || i == rect.length - 1 ){ //termine noto ==> tn if(s.length() > 0){ n1 = Integer.parseInt(s); tn = n1 / virgola; virgola = 1; doub = false; if(( !(b.getnum() == 0) || !(a.getnum() == 0) ) && segno == false) throw new input_error(); c = new razionale(sign*tn,1); segno = false; s = ""; } sign = 1; break; }else { s = ""; n=0;d=0; } } if( a.getnum() == 0 && b.getnum()== 0) { throw new input_error(); } } }
package com; import javafx.beans.property.ReadOnlyStringProperty; import javafx.beans.property.ReadOnlyStringWrapper; /** * Created by Administrator on 2017/07/15. */ public class Main10{ public static void main(String[] args) { ReadOnlyStringWrapper userName = new ReadOnlyStringWrapper("moreyoung"); ReadOnlyStringProperty readOnlyUserName = userName.getReadOnlyProperty(); System.out.println(readOnlyUserName); } }
/* * 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 model.character.constants; import model.character.Modifier; import model.character.ModifierValues; /** * * @author Dr.Chase */ public final class RacialModifiers { /** * Modifiers for humans. */ public static final ModifierValues HumanModifierValues; public static final Modifier HUMAN_MODIFIER; public static final ModifierValues DwarfModifierValues; public static final Modifier DWARF_MODIFIER; public static final ModifierValues ElfModifierValues; public static final Modifier ELF_MODIFIER; public static final ModifierValues OrcModifierValues; public static final Modifier ORC_MODIFIER; public static final ModifierValues TrollModifierValues; public static final Modifier TROLL_MODIFIER; static { // ModifierValues(int bodyModifier, int agilityModifier, int strengthModifier, int charismaModifier, int intelligenceModifier, int willpowerModifier) HumanModifierValues = new ModifierValues(0, 0, 0, 0, 0, 0); HUMAN_MODIFIER = new Modifier(false, HumanModifierValues); DwarfModifierValues = new ModifierValues(1, 0, 2, 0, 0, 1); DWARF_MODIFIER = new Modifier(true, DwarfModifierValues); ElfModifierValues = new ModifierValues(0, 1, 0, 2, 0, 0); ELF_MODIFIER = new Modifier(true, ElfModifierValues); OrcModifierValues = new ModifierValues(3, 0, 2, -1, -1, 0); ORC_MODIFIER = new Modifier(true, OrcModifierValues); TrollModifierValues = new ModifierValues(5, -1, 4, -2, -2, 0); TROLL_MODIFIER = new Modifier(true, TrollModifierValues); } }
package com.distributie.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import com.distributie.beans.BeanClientAlarma; import com.distributie.beans.BeanEvenimentStop; import com.distributie.enums.EnumNetworkStatus; import com.distributie.enums.EnumOperatiiEvenimente; import com.distributie.listeners.AsyncTaskListener; import com.distributie.listeners.JavaWSListener; import com.distributie.listeners.OperatiiEvenimenteListener; public class OperatiiEvenimente implements AsyncTaskListener, JavaWSListener { private EnumOperatiiEvenimente numeOperatie; private Context context; private OperatiiEvenimenteListener listener; private HashMap<String, String> params; public OperatiiEvenimente(Context context) { this.context = context; } public void saveNewStop(HashMap<String, String> params) { numeOperatie = EnumOperatiiEvenimente.SAVE_NEW_STOP; performOperation(numeOperatie, params); } public void getEvenimentStop(HashMap<String, String> params) { numeOperatie = EnumOperatiiEvenimente.CHECK_STOP; this.params = params; callJavaWS(); } public void setSfarsitIncarcare(HashMap<String, String> params) { numeOperatie = EnumOperatiiEvenimente.SET_SFARSIT_INC; performOperation(numeOperatie, params); } public void getSfarsitIncarcare(HashMap<String, String> params) { numeOperatie = EnumOperatiiEvenimente.GET_SFARSIT_INC; performOperation(numeOperatie, params); } private void performOperation(EnumOperatiiEvenimente numeOperatie, HashMap<String, String> params) { AsyncTaskWSCall call = new AsyncTaskWSCall(numeOperatie.getNumeComanda(), params, (AsyncTaskListener) this, context); call.getCallResults(); } private void callJavaWS() { JavaWSCall call = new JavaWSCall(numeOperatie.toString(), params, (AsyncTaskListener) this, context); call.getCallResults(); } public void setOperatiiEvenimenteListener(OperatiiEvenimenteListener listener) { this.listener = listener; } @Override public void onTaskComplete(String methodName, String result, EnumNetworkStatus networkStatus) { if (listener != null) listener.opEventComplete(result, numeOperatie); } public void setEventListener(OperatiiEvenimenteListener event) { this.listener = event; } @Override public void onJWSComplete(String methodName, String result) { if (listener != null) { listener.opEventComplete(result, numeOperatie); } } public BeanEvenimentStop deserializeEvenimentStop(String serializedEvent) { BeanEvenimentStop evenimentStop = new BeanEvenimentStop(); try { JSONObject jsonObject = new JSONObject(serializedEvent); evenimentStop.setIdEveniment(Long.valueOf(jsonObject.getString("idEveniment"))); evenimentStop.setEvenimentSalvat(Boolean.valueOf(jsonObject.getString("evenimentSalvat"))); JSONArray jsonArray = new JSONArray(jsonObject.getString("clienti")); List<BeanClientAlarma> listClienti = new ArrayList<BeanClientAlarma>(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject object = jsonArray.getJSONObject(i); BeanClientAlarma client = new BeanClientAlarma(); client.setCodClient(object.getString("codClient")); client.setCodAdresa(object.getString("codAdresa")); client.setCodBorderou(object.getString("codBorderou")); client.setNume(object.getString("numeClient")); listClienti.add(client); } evenimentStop.setClientiAlarma(listClienti); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return evenimentStop; } }
package org.zalando.riptide.failsafe; import net.jodah.failsafe.function.ContextualSupplier; import org.apiguardian.api.API; import static org.apiguardian.api.API.Status.EXPERIMENTAL; @API(status = EXPERIMENTAL) @FunctionalInterface public interface TaskDecorator { <T> ContextualSupplier<T> decorate(ContextualSupplier<T> supplier); static TaskDecorator identity() { return new TaskDecorator() { @Override public <T> ContextualSupplier<T> decorate(final ContextualSupplier<T> supplier) { return supplier; } }; } }
package com.xt.together.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Invite implements Serializable{ /** * */ private static final long serialVersionUID = 8828074149463173688L; private String id; private String name; private String address; private String date; private String invite; private String invited; private String phone; private String image; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getInvite() { return invite; } public void setInvite(String invite) { this.invite = invite; } public String getInvited() { return invited; } public void setInvited(String invited) { this.invited = invited; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Invite(String id, String name, String address, String date, String invite, String invited, String phone, String image) { this.id = id; this.name = name; this.address = address; this.date = date; this.invite = invite; this.invited = invited; this.phone = phone; this.image = image; } }
package com.cambi.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.testng.Assert; import com.cambi.selenium.framework.BasePage; public class TermsAndConditionsLink extends BasePage { public TermsAndConditionsLink(WebDriver driver) { super(driver); // TODO Auto-generated constructor stub } @FindBy(xpath = "//android.widget.TextView[@text='Terms and Conditions']") public WebElement termsAndCondtionlink; @FindBy(id = "io.cambi:id/terms") public WebElement termsAndCondtionPage; @FindBy(xpath = "//android.widget.Button[@text='OK']") public WebElement okBttn; public void tapOnTermsAndConditions() { Assert.assertTrue(isElementPresent(termsAndCondtionlink), "Terms And Conditions is not appearing"); clickOn(termsAndCondtionlink); } public void termsAndCondtionsPage() { Assert.assertTrue(isElementPresent(termsAndCondtionPage), "Terms And Conditions page is not appearing"); Assert.assertTrue(isElementPresent(okBttn), "Ok button is not appearing"); clickOn(termsAndCondtionPage); clickOn(okBttn); } }
package com.alpha.toy.vo; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; public class ToDoBoardVo { private int tdboard_no; private int room_no; private String content; private String detailContent; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date startDate; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date finishDate; private String complete; public ToDoBoardVo() { super(); } public ToDoBoardVo(int tdboard_no, int room_no, String content, String detailContent, Date startDate, Date finishDate, String complete) { super(); this.tdboard_no = tdboard_no; this.room_no = room_no; this.content = content; this.detailContent = detailContent; this.startDate = startDate; this.finishDate = finishDate; this.complete = complete; } public int getTdboard_no() { return tdboard_no; } public void setTdboard_no(int tdboard_no) { this.tdboard_no = tdboard_no; } public int getRoom_no() { return room_no; } public void setRoom_no(int room_no) { this.room_no = room_no; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getDetailContent() { return detailContent; } public void setDetailContent(String detailContent) { this.detailContent = detailContent; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getFinishDate() { return finishDate; } public void setFinishDate(Date finishDate) { this.finishDate = finishDate; } public String getComplete() { return complete; } public void setComplete(String complete) { this.complete = complete; } }
package main; import java.io.File; import java.io.FileWriter; import java.io.InputStream; import java.util.Scanner; import javax.swing.text.Document; import org.apache.jena.query.QueryExecution; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QuerySolution; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.util.FileManager; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class Main { public static void main(String[] args) { /*Model model = ModelFactory.createDefaultModel(); InputStream in = FileManager.get().open("OntologiaProjeto.rdf"); if (in == null) throw new IllegalArgumentException("File: OntologiaProjeto.rdf not found"); model.read(in, null); String query = "PREFIX CarOnt:<http://www.w3.org/2002/07/owl#Thing>\nSELECT ?brand {\n?car CarOnt:hasBrand ?brand.\n}"; try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) { ResultSet results = qexec.execSelect(); System.out.println("ENTREI!"); for ( ; results.hasNext() ; ){ System.out.println("ENTREI!"); QuerySolution soln = results.nextSolution() ; System.out.println(soln); //RDFNode x = soln.get("x") ; // Get a result variable by name. //Resource r = soln.getResource("x") ; // Get a result variable - must be a resource //Literal l = soln.getLiteral("x") ; // Get a result variable - must be a literal System.out.println(x); } } System.out.print("Teste"); */ try { Scanner scanner = new Scanner( new File("OntologiaProjeto.rdf") ); String text = scanner.useDelimiter("\\A").next(); scanner.close(); // Put this call in a finally block //System.out.println(text); String[] lines = text.split("\\r?\\n"); String StringFinal = ""; int contador = 0; for(String line : lines) { System.out.println("--"+contador); contador++; if(line.contains("</rdf:RDF>")) { StringFinal+="\n---------------------------------------\n"; } StringFinal+=line+"\n"; //System.out.println(line); } FileWriter f2 = new FileWriter("OntologiaProjeto.rdf", false); f2.write(StringFinal); f2.close(); }catch (Exception e) { System.out.println(e); // TODO: handle exception } } public void crawler() { Document docu = Jsoup.connect("https://www.standvirtual.com/destaques/").get(); } }
package com.culturaloffers.maps.repositories; import com.culturaloffers.maps.model.Subtype; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static com.culturaloffers.maps.constants.SubtypeConstants.*; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource("classpath:test-types.properties") public class SubtypeRepositoryIntegrationTest { @Autowired private SubtypeRepository subtypeRepository; @Test public void okTestFindByName(){ Subtype subtype = subtypeRepository.findByName(DB_SUBTYPE); assertEquals(DB_SUBTYPE, subtype.getName()); } @Test public void failTestFindByName(){ Subtype subtype = subtypeRepository.findByName(NOT_DB_SUBTYPE); assertNull(subtype); } @Test public void okTestFindByNameAndIdNot(){ Subtype subtype = subtypeRepository.findByNameAndIdNot(DB_SUBTYPE, VALID_DB_SUBTYPE_ID); assertNull(subtype); } @Test public void failTestFindByNameAndIdNot(){ Subtype subtype = subtypeRepository.findByNameAndIdNot(DB_SUBTYPE, INVALID_DB_SUBTYPE_ID); assertNotNull(subtype); } @Test public void okTestFindByOfferTypeId(){ List<Subtype> subtype = subtypeRepository.findByOfferTypeId(DB_OFFER_TYPE_ID); assertEquals(2, subtype.size()); } @Test public void failTestFindByOfferTypeId(){ List<Subtype> subtype = subtypeRepository.findByOfferTypeId(NOT_DB_OFFER_TYPE_ID); assertEquals(0, subtype.size()); } @Test public void testFindAllByOfferTypeId(){ Pageable pageable = PageRequest.of(PAGEABLE_PAGE,PAGEABLE_SIZE); Page<Subtype> subtypes = subtypeRepository.findAllByOfferTypeId(DB_OFFER_TYPE_ID, pageable); assertEquals(PAGE_SIZE, subtypes.getNumberOfElements()); } @Test public void failFindAllByOfferTypeId(){ Pageable pageable = PageRequest.of(PAGEABLE_PAGE,PAGEABLE_SIZE); Page<Subtype> subtypes = subtypeRepository.findAllByOfferTypeId(NOT_DB_OFFER_TYPE_ID, pageable); assertEquals(0, subtypes.getNumberOfElements()); } }
package com.company.seccion4; import com.company.seccion2.interfaces.*; import java.util.List; import java.util.Random; import static com.company.seccion2.Funciones.*; public class Main { public static void main(String[] args) { List<Integer> numeros = proveer(31, new Proveedor() { @Override public Integer obtener() { return new Random().nextInt(100); } }); System.out.println(numeros); List<Integer> filtrados = filtrar(numeros, new Predicado() { @Override public Boolean test(Integer integer) { return integer % 2 == 0; } }); System.out.println(filtrados); List<Integer> transformados = transformar(filtrados, new Funcion() { @Override public Integer aplicar(Integer i) { return i * i; } }); System.out.println(transformados); Consumidor impresor = new Consumidor() { @Override public void aceptar(Integer i) { System.out.println(i); } }; //imprime los cuadrados List<Integer> actuados = actuar(transformados, impresor); consumir(actuados, impresor); int total = reducir(actuados, 0, new FuncionBinaria() { @Override public Integer aplicar(Integer total, Integer numero) { return total + numero; } }); System.out.println(total); } }
package app.akeorcist.deviceinformation.utility; import android.content.Context; import android.content.SharedPreferences; import app.akeorcist.deviceinformation.constants.Constants; /** * Created by Ake on 2/25/2015. */ public class DevicePreferences { private final static String PREFERENCE_DEVICE = "device_pref"; private final static String KEY_DEVICE_EXIST = "is_exist"; private final static String KEY_CURRENT_DEVICE = "current_device"; private final static String KEY_DEVICE_NAME = "device_name"; private final static String KEY_DEVICE_IMAGE = "device_image"; private final static String KEY_DEVICE_MODEL = "device_model"; private final static String KEY_OTHER_DEVICE_NAME = "other_device_name"; private final static String KEY_OTHER_DEVICE_IMAGE = "other_device_image"; private final static String KEY_OTHER_DEVICE_MODEL = "other_device_model"; private final static String KEY_BRAND = "brand"; private final static String KEY_MODEL = "model"; private final static String KEY_VERSION = "version"; private final static String KEY_FINGERPRINT = "fingerprint"; private final static String KEY_NAME_AND_IMAGE = "name_and_image"; private static void setDevicePreference(Context context, String key, String value) { SharedPreferences.Editor editor = getDevicePreference(context).edit(); editor.putString(key, value); editor.commit(); } private static void setDevicePreference(Context context, String key, boolean value) { SharedPreferences.Editor editor = getDevicePreference(context).edit(); editor.putBoolean(key, value); editor.commit(); } public static SharedPreferences getDevicePreference(Context context) { return context.getSharedPreferences(PREFERENCE_DEVICE, Context.MODE_PRIVATE); } public static void setDeviceExist(Context context) { setDevicePreference(context, KEY_DEVICE_EXIST, true); } public static boolean isDeviceExist(Context context) { return getDevicePreference(context).getBoolean(KEY_DEVICE_EXIST, false); } public static void clearCurrentDevice(Context context) { setDevicePreference(context, KEY_CURRENT_DEVICE, Constants.FILE_DEVICE_INFO); } public static void setCurrentDevice(Context context, String fingerprint) { setDevicePreference(context, KEY_CURRENT_DEVICE, fingerprint); } public static String getCurrentDevice(Context context) { return getDevicePreference(context).getString(KEY_CURRENT_DEVICE, Constants.FILE_DEVICE_INFO); } public static void setDeviceBrand(Context context, String brand) { setDevicePreference(context, KEY_BRAND, brand); } public static String getDeviceBrand(Context context) { return getDevicePreference(context).getString(KEY_BRAND, ""); } public static void setDeviceModel(Context context, String model) { setDevicePreference(context, KEY_MODEL, model); } public static String getDeviceModel(Context context) { return getDevicePreference(context).getString(KEY_MODEL, ""); } public static void setDeviceVersion(Context context, String version) { setDevicePreference(context, KEY_VERSION, version); } public static String getDeviceVersion(Context context) { return getDevicePreference(context).getString(KEY_VERSION, ""); } public static void setDeviceFingerprint(Context context, String fingerprint) { setDevicePreference(context, KEY_FINGERPRINT, fingerprint); } public static String getDeviceFingerprint(Context context) { return getDevicePreference(context).getString(KEY_FINGERPRINT, ""); } public static void setDeviceName(Context context, String name) { setDevicePreference(context, KEY_DEVICE_NAME, name); } public static String getDeviceName(Context context) { return getDevicePreference(context).getString(KEY_DEVICE_NAME, ""); } public static void setDeviceModelName(Context context, String name) { setDevicePreference(context, KEY_DEVICE_MODEL, name); } public static String getDeviceModelName(Context context) { return getDevicePreference(context).getString(KEY_DEVICE_MODEL, ""); } public static void setDeviceImage(Context context, String name) { setDevicePreference(context, KEY_DEVICE_IMAGE, name); } public static String getDeviceImage(Context context) { return getDevicePreference(context).getString(KEY_DEVICE_IMAGE, ""); } public static void setOtherDeviceName(Context context, String name) { setDevicePreference(context, KEY_OTHER_DEVICE_NAME, name); } public static String getOtherDeviceName(Context context) { return getDevicePreference(context).getString(KEY_OTHER_DEVICE_NAME, ""); } public static void setOtherDeviceModelName(Context context, String name) { setDevicePreference(context, KEY_OTHER_DEVICE_MODEL, name); } public static String getOtherDeviceModelName(Context context) { return getDevicePreference(context).getString(KEY_OTHER_DEVICE_MODEL, ""); } public static void setOtherDeviceImage(Context context, String name) { setDevicePreference(context, KEY_OTHER_DEVICE_IMAGE, name); } public static String getOtherDeviceImage(Context context) { return getDevicePreference(context).getString(KEY_OTHER_DEVICE_IMAGE, ""); } public static void setNameAndImageDownloaded(Context context) { setDevicePreference(context, KEY_NAME_AND_IMAGE, true); } public static void clearNameAndImage(Context context) { setDevicePreference(context, KEY_NAME_AND_IMAGE, false); } public static boolean isNameAndImageDownloaded(Context context) { return getDevicePreference(context).getBoolean(KEY_NAME_AND_IMAGE, false); } }
package asgard_private_school; import Entity.Assignment; import Entity.Course; import Entity.Student; import Entity.Trainer; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * * @author ReMieL */ public class Database { public static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; public static final String DB_URL = "jdbc:mysql://localhost/asgard_private_school?serverTimezone=UTC"; public static final String USERNAME = "odin"; public static final String PASSWORD = "root"; public static List<Student> getAllStudents() { List<Student> students = new ArrayList<>(); Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = "SELECT ID, FIRST_NAME, LAST_NAME, DATE_OF_BIRTH, TUITION_FEES FROM STUDENTS"; preparedStatement = conn.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int studentId = resultSet.getInt(1); String studentFirstName = resultSet.getString(2); String studentLastName = resultSet.getString(3); Date dateOfBirth = resultSet.getDate(4); double tuitionFees = resultSet.getDouble(5); Student student = new Student(studentId, studentFirstName, studentLastName, dateOfBirth, tuitionFees); students.add(student); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } return students; } public static List<Trainer> getAllTrainers() { List<Trainer> trainers = new ArrayList(); Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = "SELECT ID, FIRST_NAME, LAST_NAME, SUBJECT FROM TRAINERS"; preparedStatement = conn.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int trainerId = resultSet.getInt(1); String trainerFirstName = resultSet.getString(2); String trainerLastName = resultSet.getString(3); String trainerSubject = resultSet.getString(4); Trainer trainer = new Trainer(trainerId, trainerFirstName, trainerLastName, trainerSubject); trainers.add(trainer); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } return trainers; } public static List<Course> getAllCourses() { List<Course> courses = new ArrayList<>(); Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = "SELECT ID, TITLE, STREAM, TYPE, START_DATE, END_DATE FROM COURSES"; preparedStatement = conn.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int coursetId = resultSet.getInt(1); String courseTitle = resultSet.getString(2); String courseStream = resultSet.getString(3); String courseType = resultSet.getString(4); Date courseStartDate = resultSet.getDate(5); Date courseEndDate = resultSet.getDate(6); Course course = new Course(coursetId, courseTitle, courseStream, courseTitle, courseStartDate, courseEndDate); courses.add(course); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } return courses; } public static List<Assignment> getAllAssignments() { List<Assignment> assignments = new ArrayList(); Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = "SELECT ID, TITLE, DESCRIPTION, SUB_DATE, TOTAL_MARK FROM ASSIGNMENTS"; preparedStatement = conn.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int assignmentId = resultSet.getInt(1); String assignmentTitle = resultSet.getString(2); String assignmentDescription = resultSet.getString(3); Date assignmentSubDate = resultSet.getDate(4); double assignmentTotalMark = resultSet.getDouble(5); Assignment assignment = new Assignment(assignmentId, assignmentTitle, assignmentTitle, assignmentSubDate, assignmentTotalMark); assignments.add(assignment); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } return assignments; } public static void getStudentsPerCourse() { Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = "SELECT TITLE , FIRST_NAME , LAST_NAME \n" + "FROM COURSES ,STUDENTS, STUDENTS_PER_COURSE\n" + "WHERE STUDENTS_PER_COURSE.STUDENT_ID = STUDENTS.ID\n" + "AND COURSES.ID = STUDENTS_PER_COURSE.COURSE_ID"; preparedStatement = conn.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println("=========================================================================="); String courseTitle = resultSet.getString("TITLE"); String studentFirstName = resultSet.getString("FIRST_NAME"); String studentLastName = resultSet.getString("LAST_NAME"); System.out.println("Course Title: " + courseTitle + "\tStudent First Name : " + studentFirstName + " \tStudent Last Name: " + studentLastName); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } public static void getAllTrainersPerCourse() { Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = "SELECT TITLE , FIRST_NAME , LAST_NAME \n" + "FROM COURSES ,TRAINERS, TRAINERS_PER_COURSE\n" + "WHERE TRAINERS_PER_COURSE.TRAINER_ID = TRAINERS.ID\n" + "AND COURSES.ID = TRAINERS_PER_COURSE.COURSE_ID"; preparedStatement = conn.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println("====================================================================="); String courseTitle = resultSet.getString("TITLE"); String trainerFirstName = resultSet.getString("FIRST_NAME"); String trainerLastName = resultSet.getString("LAST_NAME"); System.out.println("Course Title: " + courseTitle + "\tTrainer First Name : " + trainerFirstName + " \tTrainer Last Name: " + trainerLastName); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } public static void getallAssignmentsPerCourse() { Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = "SELECT COURSES.TITLE , COURSES.STREAM, COURSES.TYPE, ASSIGNMENTS.TITLE, ASSIGNMENTS.DESCRIPTION, \n" + "FROM COURSES ,ASSIGNMENTS, ASSIGNMENTS_PER_COURSE\n" + "WHERE ASSIGNMENTS_PER_COURSE.ASSIGNMENT_ID = ASSIGNMENTS.ID\n" + "AND COURSES.ID = ASSIGNMENTS_PER_COURSE.COURSE_ID"; preparedStatement = conn.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println("====================================================================="); String courseTitle = resultSet.getString("COURSES.TITLE"); String courseStream = resultSet.getString("COURSES.STREAM"); String courseType = resultSet.getString("COURSES.TYPE"); String assignTitle = resultSet.getString("ASSIGNMENTS.TITLE"); String assignDescr = resultSet.getString("ASSIGNMENTS.DESCRIPTION"); System.out.println("Course Title: " + courseTitle + " \tCourse Stream : " + courseStream + " \tCourse Type : " + courseType + " \tAssignment Title : " + assignTitle + " \tAssignment Description: " + assignDescr); System.out.println("====================================================================="); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } public static void getAllAssignmentsPerCoursePerStudent() { Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = "SELECT COURSES.ID, COURSES.TITLE , COURSES.STREAM, COURSES.TYPE, ASSIGNMENTS.ID, ASSIGNMENTS.TITLE, ASSIGNMENTS.DESCRIPTION, STUDENTS.ID, STUDENTS.FIRST_NAME, STUDENTS.LAST_NAME \n" + "FROM COURSES ,ASSIGNMENTS, STUDENTS, ASSIGNMENTS_PER_COURSE_PER_STUDENT\n" + "WHERE ASSIGNMENTS_PER_COURSE_PER_STUDENT.ASSIGNMENT_ID = ASSIGNMENTS.ID\n" + "AND ASSIGNMENTS_PER_COURSE_PER_STUDENT.COURSE_ID = COURSES.ID AND ASSIGNMENTS_PER_COURSE_PER_STUDENT.STUDENT_ID = STUDENTS.ID"; preparedStatement = conn.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int courseId = resultSet.getInt("COURSES.ID"); String courseTitle = resultSet.getString("COURSES.TITLE"); String courseStream = resultSet.getString("COURSES.STREAM"); String courseType = resultSet.getString("COURSES.TYPE"); int assignmentId = resultSet.getInt("ASSIGNMENTS.ID"); String assignTitle = resultSet.getString("ASSIGNMENTS.TITLE"); String assignDescr = resultSet.getString("ASSIGNMENTS.DESCRIPTION"); int studentId = resultSet.getInt("STUDENTS.ID"); String studentFirstName = resultSet.getString("FIRST_NAME"); String studentLastName = resultSet.getString("LAST_NAME"); System.out.println("Course Id: " + courseId + " \tCourse Title: " + courseTitle + " \tCourse Stream : " + courseStream + " \tCourse Type : " + courseType + " \tAssignments Id: " + assignmentId + " \tAssignment Title : " + assignTitle + " \tAssignment Description: " + assignDescr + " \tStudent Id: " + studentId + " \tStudent First Name: " + studentFirstName + " \tStudent Last Name: " + studentLastName ); System.out.println("====================================================================================================================="); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } public static Map<Student, Integer> getStudentsWhoBelongtoMorethanOneCourse() { Map<Student, Integer> studentsMap = new HashMap<>(); Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = " SELECT STUDENTS_PER_COURSE.STUDENT_ID, STUDENTS.FIRST_NAME, STUDENTS.LAST_NAME, COUNT(STUDENTS_PER_COURSE.STUDENT_ID) AS TOTAL_COURSES " + "FROM STUDENTS, STUDENTS_PER_COURSE " + "WHERE STUDENTS.ID = STUDENTS_PER_COURSE.STUDENT_ID " + "GROUP BY STUDENTS_PER_COURSE.STUDENT_ID " + "HAVING COUNT(STUDENTS_PER_COURSE.STUDENT_ID) > 1 " + "ORDER BY STUDENTS_PER_COURSE.STUDENT_ID "; preparedStatement = conn.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int studentId = resultSet.getInt("STUDENTS.ID"); String studentFirstName = resultSet.getString("STUDENTS.FIRST_NAME"); String studentLastName = resultSet.getString("STUDENTS.LAST_NAME"); int count = resultSet.getInt("TOTAL_COURSES"); Student student = new Student(studentId, USERNAME, USERNAME); studentsMap.put(student, count); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } return studentsMap; } public static int insertNewTrainer(String firstName, String lastName, String subject) { int rowsAffected = 0; Connection connection = null; PreparedStatement preparedStatement = null; try { Class.forName(JDBC_DRIVER); connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = " INSERT INTO TRAINERS(FIRST_NAME, LAST_NAME, SUBJECT) VALUES (?, ?, ?) "; preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, firstName); preparedStatement.setString(2, lastName); preparedStatement.setString(3, subject); rowsAffected = preparedStatement.executeUpdate(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return rowsAffected; } public static int selectStudentId() { List<Student> students = getAllStudents(); Scanner input = new Scanner(System.in); boolean studentExists = false; int studentId = -1; do { System.out.println("This is the List Of Students: "); students.forEach((student) -> { System.out.println("Id: " + student.getStudentID() + " \tStudent First Name: " + student.getFirstName() + " \tStudent Last Name: " + student.getLastName() + " \tStudent Date Of Birth: " + student.getDateOfBirth()); }); System.out.print("\n> "); studentId = UtilityClass.readInt("Select the id of the Student you would like to enlist: ", "Please enter a valid number"); for (Student s : students) { if (s.getStudentID() == studentId) { studentExists = true; break; } } if (!studentExists) { System.out.println("This Student does not exist. Select another Student id."); } } while (!studentExists); return studentId; } public static int selectCourseId() { List<Course> courses = getAllCourses(); Scanner input = new Scanner(System.in); boolean courseExists = false; int courseId = -1; do { System.out.println("This is the List Of Courses: "); courses.forEach((course) -> { System.out.println("Id: " + course.getCourseId() + " \tCourse Title: " + course.getCourseTitle() + " \tCourse Stream: " + course.getCourseStream() + " \tCourse Type: " + course.getCourseType() + " \tCourse Start Date: " + course.getCourseStartDate() + " \tCourse End Date:" + course.getCourseEndDate()); }); System.out.print("\n> "); courseId = UtilityClass.readInt("Select the id of the Course you would like to choose: ", "Please enter a valid number"); for (Course c : courses) { if (c.getCourseId() == courseId) { courseExists = true; break; } } if (!courseExists) { System.out.println("This Course does not exist. Select another Course id."); } } while (!courseExists); return courseId; } public static int insertStudentToCourse(int studentId, int courseId) { int rowsAffected = 0; Connection connection = null; PreparedStatement preparedStatement = null; try { Class.forName(JDBC_DRIVER); connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = " INSERT INTO STUDENTS_PER_COURSE(COURSE_ID, STUDENT_ID) VALUES (?, ?) "; preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, courseId); preparedStatement.setInt(2, studentId); rowsAffected = preparedStatement.executeUpdate(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return rowsAffected; } public static int selectTrainerId(){ List<Trainer> trainers = getAllTrainers(); Scanner input = new Scanner(System.in); boolean trainerExists = false; int trainerId = -1; do { System.out.println("This is the List Of Trainers: "); trainers.forEach((trainer) -> { System.out.println(" Trainer Id: " + trainer.getTrainerId() + " \tTrainer First Name: " + trainer.getTrainerFirstName() + " \tTrainer Last Name : " + trainer.getTrainerLastName() + " \tTrainer Subject: " + trainer.getTrainerSubject() ); }); System.out.print("\n> "); trainerId = UtilityClass.readInt("Select the id of the Trainer you would like to choose: ", "Please enter a valid number"); for (Trainer t : trainers) { if (t.getTrainerId()== trainerId) { trainerExists = true; break; } } if (!trainerExists) { System.out.println("This Trainer does not exist. Select another Trainer id."); } } while (!trainerExists); return trainerId; } public static int insertTrainerToCourse(int trainerId, int courseId){ int rowsAffected = 0; Connection connection = null; PreparedStatement preparedStatement = null; try { Class.forName(JDBC_DRIVER); connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = " INSERT INTO TRAINERS_PER_COURSE(COURSE_ID, STUDENT_ID) VALUES (?, ?) "; preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, courseId); preparedStatement.setInt(2, trainerId); rowsAffected = preparedStatement.executeUpdate(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return rowsAffected; } public static int selectAssignmentId (){ List<Assignment> assignments= getAllAssignments(); Scanner input = new Scanner(System.in); boolean assignmentExists = false; int assignmentId = -1; do { System.out.println("This is the List Of the Assignments: "); assignments.forEach((assign) -> { System.out.println(" Assignment Id: " + assign.getAssignmentId() + " \tAssignment Title: " + assign.getAssignmentTitle() + " \tAssignment Description : " + assign.getAssignmentDesc() + " \tAssignment Submision Date: " + assign.getAssignSubDate() ); }); System.out.print("\n> "); assignmentId = UtilityClass.readInt("Select the id of the Assignment you would like to choose: ", "Please enter a valid number"); for (Assignment a : assignments) { if (a.getAssignmentId() == assignmentId) { assignmentExists = true; break; } } if (!assignmentExists) { System.out.println("This Assignment does not exist. Select another Assignment id."); } } while (!assignmentExists); return assignmentId; } public static int insertAssignmentToStudentsToCourses ( int assignmentId, int studentId, int courseId){ int rowsAffected = 0; Connection connection = null; PreparedStatement preparedStatement = null; try { Class.forName(JDBC_DRIVER); connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); String query = " INSERT INTO ASSIGNMENTS_PER_COURSE_PER_STUDENT(COURSE_ID, ASSIGNMENT_ID, STUDENT_ID) VALUES (?, ?, ?) "; preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, courseId); preparedStatement.setInt(2, assignmentId); preparedStatement.setInt(3, studentId); rowsAffected = preparedStatement.executeUpdate(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return rowsAffected; } }
package me.randomusers.model; import me.randomusers.model.StructuredName; import me.randomusers.model.StructuredPicture; import me.randomusers.model.StructuredPostal; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; @ApiModel(description = "") public class UserData { @SerializedName("gender") private String gender = null; @SerializedName("email") private String email = null; @SerializedName("username") private String username = null; @SerializedName("password") private String password = null; @SerializedName("salt") private String salt = null; @SerializedName("md5") private String md5 = null; @SerializedName("sha1") private String sha1 = null; @SerializedName("sha256") private String sha256 = null; @SerializedName("registered") private String registered = null; @SerializedName("dob") private String dob = null; @SerializedName("phone") private String phone = null; @SerializedName("cell") private String cell = null; @SerializedName("DNI") private String DNI = null; @SerializedName("version") private String version = null; @SerializedName("nationality") private String nationality = null; @SerializedName("name") private StructuredName name = null; @SerializedName("location") private StructuredPostal location = null; @SerializedName("picture") private StructuredPicture picture = null; /** **/ @ApiModelProperty(value = "") public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } /** **/ @ApiModelProperty(value = "") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } /** **/ @ApiModelProperty(value = "") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } /** **/ @ApiModelProperty(value = "") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } /** **/ @ApiModelProperty(value = "") public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } /** **/ @ApiModelProperty(value = "") public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } /** **/ @ApiModelProperty(value = "") public String getSha1() { return sha1; } public void setSha1(String sha1) { this.sha1 = sha1; } /** **/ @ApiModelProperty(value = "") public String getSha256() { return sha256; } public void setSha256(String sha256) { this.sha256 = sha256; } /** **/ @ApiModelProperty(value = "") public String getRegistered() { return registered; } public void setRegistered(String registered) { this.registered = registered; } /** **/ @ApiModelProperty(value = "") public String getDob() { return dob; } public void setDob(String dob) { this.dob = dob; } /** **/ @ApiModelProperty(value = "") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } /** **/ @ApiModelProperty(value = "") public String getCell() { return cell; } public void setCell(String cell) { this.cell = cell; } /** **/ @ApiModelProperty(value = "") public String getDNI() { return DNI; } public void setDNI(String DNI) { this.DNI = DNI; } /** **/ @ApiModelProperty(value = "") public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } /** **/ @ApiModelProperty(value = "") public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } /** **/ @ApiModelProperty(value = "") public StructuredName getName() { return name; } public void setName(StructuredName name) { this.name = name; } /** **/ @ApiModelProperty(value = "") public StructuredPostal getLocation() { return location; } public void setLocation(StructuredPostal location) { this.location = location; } /** **/ @ApiModelProperty(value = "") public StructuredPicture getPicture() { return picture; } public void setPicture(StructuredPicture picture) { this.picture = picture; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UserData {\n"); sb.append(" gender: ").append(gender).append("\n"); sb.append(" email: ").append(email).append("\n"); sb.append(" username: ").append(username).append("\n"); sb.append(" password: ").append(password).append("\n"); sb.append(" salt: ").append(salt).append("\n"); sb.append(" md5: ").append(md5).append("\n"); sb.append(" sha1: ").append(sha1).append("\n"); sb.append(" sha256: ").append(sha256).append("\n"); sb.append(" registered: ").append(registered).append("\n"); sb.append(" dob: ").append(dob).append("\n"); sb.append(" phone: ").append(phone).append("\n"); sb.append(" cell: ").append(cell).append("\n"); sb.append(" DNI: ").append(DNI).append("\n"); sb.append(" version: ").append(version).append("\n"); sb.append(" nationality: ").append(nationality).append("\n"); sb.append(" name: ").append(name).append("\n"); sb.append(" location: ").append(location).append("\n"); sb.append(" picture: ").append(picture).append("\n"); sb.append("}\n"); return sb.toString(); } }
import java.util.Scanner; public class Homework3 { public static void main(String[] args) { //클래스명(객체명/함수명) 변수명 = new 클래스명(객체명/함수명)(); 저금통1 box1 = new 저금통1(); for (int i = 0; i < 999999; i++) { System.out.println("원하시는 메뉴를 선택해주세요."); System.out.println("1 : 돈 입금"); System.out.println("2 : 돈 입금 + 메세지 입력"); System.out.println("종료를 원하시면 crash를 입력하세요."); Scanner s = new Scanner(System.in); String userInputString = s.nextLine(); if(userInputString.equals("1")) { System.out.println("입금할 금액을 입력하세요 : "); Scanner s1 = new Scanner(System.in); String userInputString1 = s1.nextLine(); box1.deposit(Integer.parseInt(userInputString1)); System.out.println("당신이 입금한 금액 : "+ userInputString1); box1.withdraw(); }else if(userInputString.equals("2")){ System.out.println("입금할 금액을 입력하세요 : "); Scanner s2 = new Scanner(System.in); String userInputString2 = s2.nextLine(); box1.deposit(Integer.parseInt(userInputString2)); System.out.println("메세지를 입력하세요 : "); Scanner s3 = new Scanner(System.in); String userInputString3 = s3.nextLine(); System.out.println("당신이 입금한 금액 : "+ userInputString2 +" 메세지 : "+ userInputString3); //System.out.println("당신이 입금한 총금액은 "); box1.withdraw(); }else if(userInputString.equals("crash")) { break; } //System.out.println(userInputString); //int convertNumber = Integer.parseInt(userInputString); // "123" => 123 // 123 => "123" "" + 123 } } }
package com.itheima.day_08.demo_10; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class Demo_10 { //复制文本内容到另一个文本中 public static void main(String[] args) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("day-08/fos.txt"); //读取的目标文件 fos = new FileOutputStream("day-08/copy.txt"); //写入的目标文件 int b; while ((b = fis.read()) != -1) { //在读到文件末尾前顺序读入内容 // System.out.print((char) b); fos.write(b); //将读取的内容依次写入另一个文本中 } } catch (IOException e) { e.printStackTrace(); } finally { //关流释放资源,能关一个是一个 try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
package com.udemy.primeiroprojetospringbatch.listener; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.annotation.AfterJob; import org.springframework.batch.core.annotation.BeforeJob; import org.springframework.stereotype.Component; @Component public class JobLoggerListener { private static String START_MESSAGE = "%s is beginning execution"; private static String END_MESSAGE = "%s has completed with the status %s"; @BeforeJob public void beforeJob(JobExecution jobExecution) { System.out.println(String.format(START_MESSAGE, jobExecution.getJobInstance().getJobName())); } @AfterJob public void afterJob(JobExecution jobExecution) { // jobExecution.setStatus(BatchStatus.ABANDONED); System.out.println( String.format(END_MESSAGE, jobExecution.getJobInstance().getJobName(), jobExecution.getStatus())); } }
package com.yuneec.test; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.yuneec.IPCameraManager.IPCameraManager; import com.yuneec.flightmode15.R; import com.yuneec.uartcontroller.UARTController; public class TransmitterTest extends Activity implements OnClickListener { private Button mBtTransmitTest; private Button mChangeRateBtn; private UARTController mController; private int mCurrentRate = -1; private TextView mCurrentRateTxt; private EditText mEditTxt; private Button mReadRateBtn; private boolean mTransmitTesting; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.transmitter_test_main); getWindow().addFlags(128); this.mBtTransmitTest = (Button) findViewById(R.id.bt_transmit_test); this.mBtTransmitTest.setOnClickListener(this); this.mCurrentRateTxt = (TextView) findViewById(R.id.current_rate_txt); this.mChangeRateBtn = (Button) findViewById(R.id.change_rate); this.mChangeRateBtn.setOnClickListener(this); this.mReadRateBtn = (Button) findViewById(R.id.read_rate); this.mReadRateBtn.setOnClickListener(this); this.mEditTxt = (EditText) findViewById(R.id.edit_txt); this.mTransmitTesting = false; } protected void onResume() { super.onResume(); this.mController = UARTController.getInstance(); this.mBtTransmitTest.setText(this.mTransmitTesting ? R.string.str_stop_transmit_test : R.string.str_start_transmit_test); this.mCurrentRateTxt.setText(getString(R.string.str_rate_text, new Object[]{IPCameraManager.HTTP_RESPONSE_CODE_UNKNOWN})); } protected void onPause() { super.onPause(); if (this.mController != null && this.mTransmitTesting) { this.mController.exitTransmitTest(true); this.mBtTransmitTest.setText(R.string.str_stop_transmit_test); this.mTransmitTesting = false; } if (this.mController != null) { this.mController = null; } this.mCurrentRate = -1; } private void readRate() { int value = -1; if (this.mController != null) { value = this.mController.readTransmitRate(); } if (value != -1) { this.mCurrentRateTxt.setText(getString(R.string.str_rate_text, new Object[]{Integer.valueOf(value)})); return; } this.mCurrentRateTxt.setText(getString(R.string.str_rate_text, new Object[]{IPCameraManager.HTTP_RESPONSE_CODE_UNKNOWN})); } private void changeRate() { String inputValue = this.mEditTxt.getText().toString(); if (!inputValue.isEmpty()) { this.mCurrentRate = Integer.parseInt(inputValue); if (this.mController != null) { Log.i("wangkang", "res=" + this.mController.writeTransmitRate(this.mCurrentRate)); } } } public void onClick(View v) { switch (v.getId()) { case R.id.bt_transmit_test: if (this.mController == null) { return; } if (this.mTransmitTesting) { this.mController.exitTransmitTest(true); this.mBtTransmitTest.setText(R.string.str_start_transmit_test); this.mTransmitTesting = false; return; } this.mController.enterTransmitTest(true); this.mBtTransmitTest.setText(R.string.str_stop_transmit_test); this.mTransmitTesting = true; return; case R.id.read_rate: readRate(); return; case R.id.change_rate: changeRate(); return; default: return; } } }
package org.yxm.modules.wan; import java.util.List; import org.yxm.modules.wan.entity.WanTabEntity; /** * WanFragment UI层接口 */ public interface IWanView { void onInitTabLayout(List<WanTabEntity> tabs); }
package com.zjf.myself.codebase.dialog; import android.app.Activity; import com.jzxiang.pickerview.TimePickerDialog; import com.jzxiang.pickerview.config.PickerConfig; import com.jzxiang.pickerview.data.Type; import com.jzxiang.pickerview.data.WheelCalendar; import com.jzxiang.pickerview.listener.OnDateSetListener; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.activity.BaseAct; import com.zjf.myself.codebase.application.AppController; import com.zjf.myself.codebase.util.CallBack; import com.zjf.myself.codebase.util.TimeUtil; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Administrator on 2016/12/27. */ public class DateDialog extends TimePickerDialog implements OnDateSetListener { PickerConfig mPickerConfig; private CallBack callBack; public DateDialog(){ mPickerConfig=new PickerConfig(); mPickerConfig.mCallBack=this; mPickerConfig.mCancelString="取消"; mPickerConfig.mSureString="确定"; mPickerConfig.mTitleString="时间"; mPickerConfig.mYear="年"; mPickerConfig.mMonth="月"; mPickerConfig.mDay="日"; mPickerConfig.mHour="时"; mPickerConfig.mMinute="分"; mPickerConfig.cyclic=true; long minTime= TimeUtil.getLongTime("1900:01:01","yyyy:MM:dd"); //生日最小是清朝 mPickerConfig.mMinCalendar= new WheelCalendar(minTime); mPickerConfig.mMaxCalendar=new WheelCalendar(System.currentTimeMillis()); mPickerConfig.mCurrentCalendar=new WheelCalendar(System.currentTimeMillis()); Activity curAct= AppController.getInstance().getTopAct(); mPickerConfig.mThemeColor=curAct.getResources().getColor(R.color.green_main); mPickerConfig.mType=Type.YEAR_MONTH_DAY; mPickerConfig.mWheelTVNormalColor=curAct.getResources().getColor(R.color.grey_444444); mPickerConfig.mWheelTVSelectorColor=curAct.getResources().getColor(R.color.green_2F8505); mPickerConfig.mWheelTVSize=16; initialize(mPickerConfig); } public void setCurrentSelectDate(long time){ mPickerConfig.mCurrentCalendar=new WheelCalendar(time); } public void setCallBack(CallBack callBack){ this.callBack=callBack; } public void show(){ BaseAct activity= (BaseAct) AppController.getInstance().getTopAct(); show(activity.getSupportFragmentManager(),"hour_minute"); } public String getDateToString(long time) { SimpleDateFormat sf = new SimpleDateFormat("yyyy:MM:dd:HH:mm:ss"); Date d = new Date(time); return sf.format(d); } @Override public void onDateSet(TimePickerDialog timePickerDialog, long l) { if(callBack!=null) callBack.onCall(l); } }
package yedamOracle.com; public class MethodSample { public static void main(String[] args) { int i = multi (3, 5); System.out.println(i); } public static int multi(int a, int b) { //입력받은 두수의 곱을 계산하는 메소드 return(a*b); } }
package com.gaoshin.top.plugin.dialer; import android.content.Context; import android.widget.LinearLayout; import com.gaoshin.top.plugin.LabeledTextEdit; public class CallShortcutEditor extends LinearLayout { private LabeledTextEdit phoneEditor; public CallShortcutEditor(Context context) { super(context); setOrientation(LinearLayout.VERTICAL); setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); phoneEditor = new LabeledTextEdit(context, "Phone Number (optional):", 1); addView(phoneEditor); } public void setValue(String str) { phoneEditor.setValue(str); } public String getValue() { return phoneEditor.getValue(); } }
package com.example.compasso.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; @Table @Entity @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class Client { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "name", length = 100, nullable = false) private String name; @Column(name = "gender", length = 20, nullable = false) private String gender; @Column(name = "birthday", length = 20, nullable = false) private String birthday; @Column(name = "age", nullable = false) private int age; @OneToOne(fetch = FetchType.EAGER) private City city; }
package cursojavamodulo2; public abstract class Figura { public final static double PI = Math.PI; protected Punto p; public abstract double area(); public void mover(double dx, double dy) { p.setX(p.getX() + dx); p.setY(p.getY() + dy); System.out.println("Figura movida a la posición (" + p.getX() + "," + p.getY() + ")"); } public void pintar() { System.out.println("Pintando figura en la posición (" + p.getX() + "," + p.getY() + ")"); } }
package testing; import static org.junit.Assert.*; import org.junit.Test; import obj.Recipe; public class RecipeTest { Recipe r = new Recipe(10, 6, "Best Food", "Seriously, the best", "Comfort"); @Test public void testConstructor() { fail("Not yet implemented"); } public void testChanges() { assertEquals(true, r.getChanges()); r.setChanges(false); assertEquals(false, r.getChanges()); } @Test public void testIDChange() { testChanges(); } @Test public void testUserIDChange() { testChanges(); } @Test public void testNameChange() { testChanges(); } @Test public void testDescriptionChange() { testChanges(); } @Test public void testTypeChange() { testChanges(); } @Test public void testCookTime() { testChanges(); } @Test public void testInstructions() { testChanges(); } }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.core.lang; /** * 一种可变long类型的实现. * <p> * 部分方法实现直接调用(JDK8)Long类中的静态方法 * * @author 小流氓[176543888@qq.com] * @since 3.2 */ public class MutableLong extends Number implements Comparable<MutableLong>, Mutable<Number> { private static final long serialVersionUID = -5425153499522349930L; private long value; public MutableLong() { } public MutableLong(long value) { this.value = value; } public MutableLong(Number value) { this(value.longValue()); } public MutableLong(String value) { this.value = Long.parseLong(value); } @Override public Long getValue() { return Long.valueOf(value); } @Override public void setValue(Number value) { this.value = value.longValue(); } /** * 设置值,在直接使用此类时,可以不用进行装箱操作 * * @param value 值 */ public void setValue(long value) { this.value = value; } @Override public int compareTo(MutableLong anotherInteger) { return Long.compare(value, anotherInteger.value); } @Override public int intValue() { return (int) value; } @Override public long longValue() { return value; } @Override public float floatValue() { return value; } @Override public double doubleValue() { return value; } @Override public int hashCode() { return Long.hashCode(value); } @Override public boolean equals(Object obj) { if (obj instanceof MutableLong) { return value == ((MutableLong) obj).longValue(); } return false; } @Override public String toString() { return Long.toString(value); } /** * 获得当前值后进行加一操作. * <p> * i++ * * @return 获得当前值后进行加一操作 */ public final long getAndIncrement() { final long oldValue = value; this.value++; return oldValue; } /** * 获得当前值后进行减一操作. * <p> * i-- * * @return 获得当前值后进行减一操作 */ public final long getAndDecrement() { final long oldValue = value; this.value--; return oldValue; } /** * 获得当前值后进行加法操作. * * @param delta 要加的值 * @return 获得当前值后进行加法操作 */ public final long getAndAdd(long delta) { final long oldValue = value; this.value += delta; return oldValue; } /** * 先加一再获取. * <p> * ++i * * @return 先加一再获取 */ public final long incrementAndGet() { return ++value; } /** * 先减一再获取. * <p> * --i * * @return 先减一再获取 */ public final long decrementAndGet() { return --value; } /** * 加上指定值后再返回. * * @param delta 指定值 * @return 加上指定值后再返回 */ public final long addAndGet(long delta) { return value += delta; } }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * 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.alibaba.druid.sql.ast.statement; import com.alibaba.druid.DbType; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLObject; import com.alibaba.druid.sql.ast.SQLStatementImpl; import java.util.ArrayList; import java.util.List; public abstract class SQLPrivilegeStatement extends SQLStatementImpl { protected final List<SQLPrivilegeItem> privileges = new ArrayList<SQLPrivilegeItem>(); protected List<SQLExpr> users = new ArrayList<SQLExpr>(); protected SQLObject resource; // mysql protected SQLObjectType resourceType; public SQLPrivilegeStatement() { } public SQLPrivilegeStatement(DbType dbType) { super(dbType); } public List<SQLExpr> getUsers() { return users; } public void addUser(SQLExpr user) { if (user == null) { return; } user.setParent(this); this.users.add(user); } public void setUsers(List<SQLExpr> users) { this.users = users; } public SQLObject getResource() { return resource; } public void setResource(SQLObject x) { if (x != null) { x.setParent(this); } this.resource = x; } public void setResource(SQLExpr resource) { if (resource != null) { resource.setParent(this); } this.resource = resource; } public List<SQLPrivilegeItem> getPrivileges() { return privileges; } public SQLObjectType getResourceType() { return resourceType; } public void setResourceType(SQLObjectType x) { this.resourceType = x; } }
package com.ch1.springbootsecuritysession.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity /* 스프링 필터체인에 시큐리티필터 등록 */ @EnableGlobalMethodSecurity( securedEnabled = true , /* @secure 어노테이셜 활성화 */ prePostEnabled = true /* @preAuthorize 어노테이셜 활성화 */ ) public class SecurityCofig extends WebSecurityConfigurerAdapter{ @Bean public BCryptPasswordEncoder endcodeStr() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests() .antMatchers("/user/**").authenticated() .antMatchers("/manager/**").access("hasRole('ROLE_MANAGER') or hsaRole('ROLE_ADMIN')") .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") .anyRequest().permitAll() .and() .formLogin() .loginPage("/loginForm") .loginProcessingUrl("/login") .defaultSuccessUrl("/"); } }
package com.appmanage.mapper; import com.appmanage.entity.AppInfo; import com.appmanage.entity.AppInfoExample; import com.appmanage.entity.SelectAPPInfo; import java.util.List; public interface AppInfoMapper { int deleteByPrimaryKey(Long id); int insert(AppInfo record); int insertSelective(AppInfo record); List<AppInfo> selectByExample(AppInfoExample example); AppInfo selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(AppInfo record); int updateByPrimaryKey(AppInfo record); List<AppInfo> selectManageMain(SelectAPPInfo sai); AppInfo selectOne(Long id); }
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; /** * Pc */ public class Pc extends Player { private static final Character[] _suits = { 'D', 'C', 'H', 'S' }; private ArrayList<Card> _unknownCards; private HashMap<Card, Integer> _worth; public Pc(String name) { this.name = name; this._hand = new ArrayList<Card>(); this._points = new ArrayList<Card>(); this._populateUnknownCards(); } public void draw(Card card) { this._hand.add(card); if (Game.getDeck().size() == 0 || Game.getDeck().size() == 1) { this._unknownCards.add(Game.getTrump()); } this._unknownCards.remove(card); } public Card play() { System.out.println(this._hand); //For testing purposes this._evaluateFirst(); Card card = this._pickLowest(); this._hand.remove(card); return card; } public Card play(Card played) { System.out.println(this._hand); //For testing purposes this._unknownCards.remove(played); this._evaluateLast(played); Card card = this._pickLowest(); this._hand.remove(card); return card; } private void _evaluateLast(Card played) { this._worth = new HashMap<Card, Integer>(); Integer cardWorth; for (Card card : this._hand) { cardWorth = 0; if (card.getSuit().compareTo(played.getSuit()) == 0) { // Se a tua carta e a carta jogada são do mesmo naipe cardWorth--; cardWorth -= this._isCardDirectlyBelow(card, played); cardWorth += this._evaluateBelow(card); cardWorth += this._evaluateChanceToPass(card); } else { if(card.getSuit().compareTo(Game.getTrump().getSuit())==0) { // Se a tua carta é um trunfo if(played.getValue()>=2) { cardWorth -= this._evaluateTrumpValue(card); } else { cardWorth += 2; } } else if (played.getSuit().compareTo(Game.getTrump().getSuit())==0) { // Se a carta do oponente é um trunfo cardWorth = this._giveWorth(card); } else { // Se são naipes diferentes cardWorth = this._giveWorth(card); if (cardWorth < 1) { cardWorth -= 2; } } } this._worth.put(card, cardWorth); } } private int _evaluateTrumpValue(Card card) { int trumpWorth; switch(card.getValue()) { case 11: trumpWorth = 1; break; case 10: trumpWorth = 2; break; case 4: trumpWorth = 3; break; case 3: trumpWorth = 4; break; case 2: trumpWorth = 5; break; default: trumpWorth = 6; break; } return trumpWorth; } private int _isCardDirectlyBelow(Card card, Card played) { switch (card.getIdentity()) { case "A": if (played.getIdentity().compareTo("7") == 0) { return 50; } else if (played.getIdentity().compareTo("K") == 0) { return 1; } break; case "7": if (played.getIdentity().compareTo("K") == 0) { return 50; } else if (played.getIdentity().compareTo("J") == 0) { return 1; } break; case "K": if (played.getIdentity().compareTo("J") == 0) { return 50; } else if (played.getIdentity().compareTo("Q") == 0) { return 1; } break; case "J": if(played.getValue() < 3) return 50; break; case "Q": if(played.getValue() < 2) return 50; break; default: break; } return 0; } private int _evaluateChanceToPass(Card card) { double beingEatenChance; int eatingCards = 0, edibleCards = 0; for (Card cardIn : this._unknownCards) { if (cardIn.getSuit().compareTo(card.getSuit()) == 0) { if (cardIn.getValue() > card.getValue()) { eatingCards++; } else { edibleCards++; } } else if (cardIn.getSuit().compareTo(Game.getTrump().getSuit()) == 0) { eatingCards++; } } beingEatenChance = ((eatingCards - edibleCards) / (eatingCards + edibleCards)) * 100; if (beingEatenChance >= 55) { return -1; } return 1; } private int _evaluateBelow(Card card) { int nrCardsBelow = 0; for (Card cardIn : this._unknownCards) { if (cardIn.getSuit().compareTo(card.getSuit()) == 0) { switch (card.getIdentity()) { case "A": if (cardIn.getIdentity().compareTo("7") == 0 || cardIn.getIdentity().compareTo("K") == 0) { nrCardsBelow++; } break; case "K": if (cardIn.getIdentity().compareTo("J") == 0 || cardIn.getIdentity().compareTo("Q") == 0) { nrCardsBelow++; } break; case "7": if (cardIn.getIdentity().compareTo("K") == 0 || cardIn.getIdentity().compareTo("J") == 0) { nrCardsBelow++; } break; default: break; } if (nrCardsBelow == 2) { return 2; } } } return -1; } public void seePlayedCard(Card card) { this._unknownCards.remove(card); } private void _populateUnknownCards() { this._unknownCards = new ArrayList<Card>(); for (Character suit : _suits) { for (Integer i = 1; i < 11; i++) { if (i != 1 && i <= 7) { this._unknownCards.add(new Card(i.toString(), suit)); } else { switch (i) { case 1: this._unknownCards.add(new Card("A", suit)); break; case 8: this._unknownCards.add(new Card("J", suit)); break; case 9: this._unknownCards.add(new Card("Q", suit)); break; case 10: this._unknownCards.add(new Card("K", suit)); break; default: break; } } } } this._unknownCards.remove(Game.getTrump()); } private void _evaluateFirst() { this._worth = new HashMap<Card, Integer>(); Integer cardWorth; for (Card card : this._hand) { cardWorth = this._giveWorth(card); cardWorth += this._evaluateBySuit(card); if (!this.trumpsExist()) { cardWorth += this._checkEaters(card); } this._worth.put(card, cardWorth); } } private int _giveWorth(Card card) { int result = 0; switch (card.getIdentity()) { case "A": result = 9; break; case "7": result = 8; break; case "K": result = 4; break; case "J": result = 2; break; case "Q": result = 1; break; default: result = 0; break; } return result; } private int _evaluateBySuit(Card card) { if (card.getSuit().compareTo(Game.getTrump().getSuit()) == 0) { return 3; } return 0; } private int _checkEaters(Card card) { boolean noEatNoEaten = false, eatNoEaten = false, noEatEaten = false, eatEaten = false; for (Card inCard : this._unknownCards) { if (inCard.getSuit().compareTo(card.getSuit()) == 0) { noEatNoEaten = true; if (inCard.getValue() < card.getValue()) { noEatNoEaten = false; eatNoEaten = true; } if (inCard.getValue() > card.getValue()) { noEatNoEaten = false; noEatEaten = true; } if (eatNoEaten && noEatEaten) { eatEaten = true; } } } if (noEatNoEaten) { return -10; } else if (eatEaten) { return 7; } else if (noEatEaten) { return 6; } else if (eatNoEaten) { return 1; } return 0; } private Card _pickLowest() { Card result = null; Integer worth = 100; for (Map.Entry<Card, Integer> pair : this._worth.entrySet()) { if (pair.getValue() < worth) { result = pair.getKey(); worth = pair.getValue(); } else if (pair.getValue() == worth) { if (result.getValue() > pair.getKey().getValue()) { result = pair.getKey(); worth = pair.getValue(); } } } return result; } private boolean trumpsExist() { for (Card card : this._unknownCards) { if (card.getSuit().compareTo(Game.getTrump().getSuit()) == 0) { return true; } } return false; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.docs.core.aot.hints.testing; import org.junit.jupiter.api.Test; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.aot.hint.predicate.RuntimeHintsPredicates; import static org.assertj.core.api.Assertions.assertThat; public class SpellCheckServiceTests { // tag::hintspredicates[] @Test void shouldRegisterResourceHints() { RuntimeHints hints = new RuntimeHints(); new SpellCheckServiceRuntimeHints().registerHints(hints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.resource().forResource("dicts/en.txt")) .accepts(hints); } // end::hintspredicates[] // Copied here because it is package private in SpellCheckService static class SpellCheckServiceRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { hints.resources().registerPattern("dicts/*"); } } }
package com.davivienda.utilidades.log; import com.davivienda.utilidades.Constantes; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Set; import java.util.logging.Logger; import javax.xml.namespace.QName; import javax.xml.soap.SOAPException; import javax.xml.ws.handler.MessageContext; import javax.xml.ws.handler.soap.SOAPHandler; import javax.xml.ws.handler.soap.SOAPMessageContext; public class SaraSOAPHandler implements SOAPHandler<SOAPMessageContext> { private static final Logger logger = Logger.getLogger(Constantes.LOGGER_APP); /** * Metodo que genera los request y response de los servicios en formato xml * * @param context * @return boolean * @throws SOAPException * @throws IOException */ @Override public boolean handleMessage(SOAPMessageContext context) { try { boolean direction = ((Boolean) context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY)).booleanValue(); String pre = ""; if (direction) { pre = "REQ: "; } else { pre = "RES: "; } ByteArrayOutputStream out = new ByteArrayOutputStream(); context.getMessage().writeTo(out); String strMsg = new String(out.toByteArray()); logger.finest(pre + strMsg); } catch (Exception e) { String error = "Se ha generado un error en la interceptaci?n del mensaje SOAP para hacer log. "; logger.warning(error + e == null ? "" : e.getMessage()); } return true; } /** * Auto-generated method stub */ @Override public boolean handleFault(SOAPMessageContext context) { return false; } /** * Auto-generated method stub */ @Override public void close(MessageContext context) { } /** * Auto-generated method stub */ @Override public Set<QName> getHeaders() { return null; } }
/* * Copyright (c) 2016. Osred Brockhoist <osred.brockhoist@hotmail.com>. All Rights Reserved. */ package com.flyingosred.app.perpetualcalendar.database.holiday; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import com.flyingosred.app.perpetualcalendar.database.data.Data; import com.flyingosred.app.perpetualcalendar.database.excel.ExcelHelper; import com.flyingosred.app.perpetualcalendar.database.library.PerpetualCalendarContract; import com.flyingosred.app.perpetualcalendar.database.util.Utils; public class HolidayData extends Data { private static final int EXCEL_COL_NAME = 1; private final List<HolidayDataItem> mDataList = new ArrayList<>(); private final Map<Date, List<HolidayDataItem>> mDataMap = new LinkedHashMap<>(); public HolidayData(XSSFSheet sheet) { super(sheet); parse(sheet); } @Override public int getId(Calendar calendar) { return PerpetualCalendarContract.INVALID; } public String getString(Calendar calendar) { StringBuilder sb = new StringBuilder(); int offWork = PerpetualCalendarContract.INVALID; for (int i = 0; i < mDataList.size(); i++) { HolidayDataItem item = mDataList.get(i); Calendar tempCalendar = Calendar.getInstance(); tempCalendar.setTime(item.getDate()); if (Utils.isSameDay(calendar, tempCalendar)) { if (item.getType() != null) { if (sb.length() > 0) { sb.append(","); } sb.append(item.formatString()); } if (item.getOffWork() != PerpetualCalendarContract.INVALID) { offWork = item.getOffWork(); } } } if (offWork != PerpetualCalendarContract.INVALID) { sb.append("#"); sb.append(offWork); } if (sb.length() > 0) { return sb.toString(); } return null; } public String getRegion() { return mDataMap.get(mDataMap.keySet().toArray()[0]).get(0).getRegion(); } private void parse(XSSFSheet sheet) { int rows = sheet.getPhysicalNumberOfRows(); String sheetName = sheet.getSheetName(); String regionName = sheetName.replace(HolidayDatabase.EXCEL_HOLIDAY_SHEET_NAME_SUFFIX, "").toLowerCase(); for (int i = EXCEL_ROW_DATA_START; i < rows; i++) { XSSFRow row = sheet.getRow(i); String nameFormula = ExcelHelper.getCellFormula(row, EXCEL_COL_NAME); String refType = null; int id = PerpetualCalendarContract.INVALID; if (nameFormula != null) { String[] nameFormulaParts = nameFormula.split("!"); String refSheetName = nameFormulaParts[0]; String refCellName = nameFormulaParts[1]; refType = getNamePrefix(refSheetName).toLowerCase(); String refCellIndex = refCellName.replaceAll("[^\\d.]", ""); int index = Integer.parseInt(refCellIndex); id = index - EXCEL_ROW_DATA_START; } int cols = row.getPhysicalNumberOfCells(); for (int j = EXCEL_COL_DATA_START; j < cols; j = j + 2) { Date date = ExcelHelper.getDateCellValue(row, j); int offWork = ExcelHelper.getIntCellValue(row, j + 1); HolidayDataItem item = new HolidayDataItem(regionName, refType, id, date, offWork); System.out.println("Creating holiday data " + item.toString()); mDataList.add(item); List<HolidayDataItem> dateList; if (mDataMap.containsKey(date)) { dateList = mDataMap.get(date); } else { dateList = new ArrayList<>(); mDataMap.put(date, dateList); } dateList.add(item); } } } }
package atm; import java.awt.Container; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; public class Widthdraw extends JFrame{ public Container c; public Font f; public JLabel j; public JTextField tf; public JButton btn1,btn2; public static String wid; public static double wid2; Widthdraw() { display(); } public void display() { c = this.getContentPane(); c.setLayout(null); f = new Font("Arial", Font.BOLD,15); j = new JLabel("AMOUNT : "); j.setFont(f); j.setBounds(20,70,100,30); c.add(j); tf = new JTextField(); tf.setBounds(130,70,180,30); c.add(tf); btn1 = new JButton("WITHDRAW"); btn1.setBounds(40,130,120,40); btn1.setFont(f); c.add(btn1); btn1.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { wid = tf.getText(); wid2 = Integer.parseInt(wid); CheckBalance menu = new CheckBalance(); if(wid2<=menu.amount) { menu.amount = menu.amount-wid2; JOptionPane.showMessageDialog(null,"Yor Are Successfully Widthdraw "+wid2+" taka"); tf.setText(""); } else{ JOptionPane.showMessageDialog(null, "You Have Not Enough Money Please Check Your Balance"); } } }); btn2 = new JButton("BACK"); btn2.setBounds(190,130,100,40); btn2.setFont(f); c.add(btn2); btn2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { dispose(); MainMenu menu = new MainMenu(); menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); menu.setBounds(400,200,350,300); menu.setVisible(true); menu.setTitle("ATM"); } }); } public static void main(String[] args) { Widthdraw menu = new Widthdraw(); menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); menu.setBounds(400,200,350,300); menu.setVisible(true); menu.setTitle("ATM"); } }
package com.adityathebe.bitcoin.transaction; public class TransactionInput { public static final String NO_SEQUENCE = "FFFFFFFF"; private String txId; private UTXO prevOut; private Integer n; private String scriptSig; private Integer scriptSigLen; private String nSequence; public TransactionInput(UTXO utxo, int outputIndex) { this.prevOut = utxo; this.n = outputIndex; this.nSequence = NO_SEQUENCE; } }
package stepDefinitions; import TestingCommon.RestFWLogger; import cucumber.TestContext; import io.cucumber.java.After; import io.cucumber.java.Before; public class Hooks { TestContext testContext; public Hooks(TestContext context) { testContext = context; } @Before public void BeforeSteps() { RestFWLogger.initLogger(); RestFWLogger.startTestCase(); } @After public void AfterSteps() { RestFWLogger.endTestCase(); } }
/* * 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 leand */ public class Client { // Voici la classe CLient de notre projet // Ajout d'un commentaire // J'ai ajouté un autre commentaire. Agathe // Creation de Conflit }
package uk.co.reliquia.healthapp; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.DataSetObserver; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.NumberPicker; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; /* * MealsFragment - The meals calculator fragment */ public class MealsFragment extends Fragment { // The argument name for the section number private static final String ARG_SECTION_NUMBER = "section_number"; // The title of the page that this fragment will sit in public static final String PAGE_TITLE = "Meals"; private Spinner MealSpinner; private NumberPicker PortionsNumberPicker; private TextView CaloriesTextView; private Button AddButton, ClearButton; private ListView CaloriesListView; private ArrayAdapter<CharSequence> mealNamesAdapter; private ArrayAdapter<Integer> mealCaloriesAdapter; private ArrayAdapter<MealInfo> mealsAdapter; private SharedPreferences prefs; private ArrayList<MealInfo> mealList; public static int CaloriesIn; /* * createInstance - Creates a new instance of this fragment for the given section number */ public static MealsFragment createInstance(int sectionNumber) { // Initialise it MealsFragment fragment = new MealsFragment(); // Setup the args Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); // Return it return fragment; } /* * MealsFragment - Default constructor */ public MealsFragment() { } /* * onCreateView - Called when the view for this fragment is created */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Create the fragment view View rootView = inflater.inflate(R.layout.fragment_meals, container, false); // Get shared prefs prefs = AppContext.getSharedPreferences(); // Get widgets we need to access MealSpinner = (Spinner)rootView.findViewById(R.id.MealSpinner); PortionsNumberPicker = (NumberPicker)rootView.findViewById(R.id.PortionsNumberPicker); CaloriesTextView = (TextView)rootView.findViewById(R.id.CaloriesTextView); AddButton = (Button)rootView.findViewById(R.id.AddButton); ClearButton = (Button)rootView.findViewById(R.id.ClearButton); CaloriesListView = (ListView)rootView.findViewById(R.id.CaloriesListView); // Get adapters and setup the spinners mealNamesAdapter = ArrayAdapter.createFromResource(AppContext.getContext(), R.array.meal_names, android.R.layout.simple_spinner_dropdown_item); MealSpinner.setAdapter(mealNamesAdapter); MealSpinner.setSelection(prefs.getInt("mealSelection", 0)); PortionsNumberPicker.setMinValue(1); PortionsNumberPicker.setMaxValue(5); PortionsNumberPicker.setValue(prefs.getInt("portionsSelection", 1)); // Initialise the list and load from prefs mealList = new ArrayList<MealInfo>(); int mealCount = prefs.getInt("mealCount", 0); for (int i = 0; i < mealCount; i++) { mealList.add(new MealInfo( prefs.getInt(String.format("meal%dPortions", i), 1), prefs.getInt(String.format("meal%dCalories", i), 100), prefs.getString(String.format("meal%dName", i), "Missing") )); } mealsAdapter = new ArrayAdapter<MealInfo>(AppContext.getContext(), android.R.layout.simple_list_item_1, mealList); CaloriesListView.setAdapter(mealsAdapter); // Hook the buttons AddButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Get the selected items int selMeal = MealSpinner.getSelectedItemPosition(); int selPortions = PortionsNumberPicker.getValue(); // Lookup the calories int calories = getResources().getIntArray(R.array.meal_calories)[selMeal]; // Insert the entry mealList.add(new MealInfo( selPortions, calories, (String) mealNamesAdapter.getItem(selMeal) )); // Recalculate and save calculate(); save(); mealsAdapter.notifyDataSetChanged(); } }); ClearButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Clear all items mealList.clear(); // Recalculate and save calculate(); save(); mealsAdapter.notifyDataSetChanged(); } }); // Initial calculate calculate(); // Return the view return rootView; } private void calculate() { // Declare total calories int totalCalories = 0; // Loop each meal for (int i = 0; i < mealList.size(); i++) { MealInfo info = mealList.get(i); totalCalories += info.Calories * info.Portions; } // Update UI if (totalCalories == 0) CaloriesTextView.setText(""); else CaloriesTextView.setText(String.format("You have consumed %d calories!", totalCalories)); // Update static CaloriesIn = totalCalories; MainActivity.mViewPager.getAdapter().notifyDataSetChanged(); } private void save() { // Get editable prefs SharedPreferences.Editor editor = prefs.edit(); // Write count editor.putInt("mealCount", mealList.size()); // Loop each exercise for (int i = 0; i < mealList.size(); i++) { MealInfo info = mealList.get(i); // Write it editor.putInt(String.format("meal%dDuration", i), info.Portions); editor.putInt(String.format("meal%dCalories", i), info.Calories); editor.putString(String.format("meal%dName", i), info.Name); } // Commit changes editor.apply(); } }
public interface ListOfStrings { void add(String s); int size(); void set(int i, String s); String get(int i); }
package com.gabriel.projetocarrinho.model; /** * Created by gabriel on 05/07/19. */ public class Produto { private int id; private String nome; private Double preco; public Produto(){} public Produto(int id, String nome, Double preco) { this.id = id; this.nome = nome; this.preco = preco; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Double getPreco() { return preco; } public void setPreco(Double preco) { this.preco = preco; } @Override public String toString() { return "**Produto**\nid: " + getId() + "\nNome: " + getNome() + "\nPreco: " + getPreco() + "\n"; } }
package com.sample.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; public class SpringApplication { @SuppressWarnings("unused") public static void main(String[] args) { ApplicationContext Context=new ClassPathXmlApplicationContext("application-contect.xml"); JdbcTemplate jdbcTemplate=Context.getBean("template",JdbcTemplate.class); int t=jdbcTemplate.update("insert into rental_location values(?,?,?,?,?,?,?)",2,"Grostore","add1","add2","city2","state2","600028"); System.out.println(t); } }
package br.ufes.dcel.movieTheather; import java.util.Date; public class Movie { private String title, author, originCountry, urlCover; private Category category; private long releaseYear; private long durationMin; Date dateRelease; }
package com.touchtrip.main.model.vo; import java.io.Serializable; public class MainTop6Famous implements Serializable{ private String tArea; private String tName; private String tContent; private String tAdress; private String tPhone; private String tReview; private double tScore; public MainTop6Famous() { super(); } public MainTop6Famous(String tArea, String tName, String tContent, String tAdress, String tPhone, String tReview, double tScore) { super(); this.tArea = tArea; this.tName = tName; this.tContent = tContent; this.tAdress = tAdress; this.tPhone = tPhone; this.tReview = tReview; this.tScore = tScore; } @Override public String toString() { return "MainTop6Famous [tArea=" + tArea + ", tName=" + tName + ", tContent=" + tContent + ", tAdress=" + tAdress + ", tPhone=" + tPhone + ", tReview=" + tReview + ", tScore=" + tScore + "]"; } public String gettArea() { return tArea; } public void settArea(String tArea) { this.tArea = tArea; } public String gettName() { return tName; } public void settName(String tName) { this.tName = tName; } public String gettContent() { return tContent; } public void settContent(String tContent) { this.tContent = tContent; } public String gettAdress() { return tAdress; } public void settAdress(String tAdress) { this.tAdress = tAdress; } public String gettPhone() { return tPhone; } public void settPhone(String tPhone) { this.tPhone = tPhone; } public String gettReview() { return tReview; } public void settReview(String tReview) { this.tReview = tReview; } public double gettScore() { return tScore; } public void settScore(double tScore) { this.tScore = tScore; } }
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class ConcreteCommand here. * * @author (your name) * @version (a version number or a date) */ public class StartCommand extends Actor implements ICommand { StartScreen startReceiver = new StartScreen(); World pw = null; public StartCommand(World world) { pw = world; } public void executeCommand() { startReceiver.doAction(pw); } public void setReceiverScreen(StartScreen receiver) { startReceiver = receiver; } public void act() { // Add your action code here. } }
/* * 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.grameenfoundation.ictc.domains; import com.grameenfoundation.ictc.domain.commons.GeneralInterface; import com.grameenfoundation.ictc.domain.commons.Status; import com.grameenfoundation.ictc.utils.ICTCRelationshipTypes; import com.grameenfoundation.ictc.utils.Neo4jServices; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; /** * * @author Joseph George Davis * @date Jul 16, 2015 12:08:21 PM * description: */ public class Biodata extends Status implements GeneralInterface { public static String FIRST_NAME = "firstname"; public static String LAST_NAME = "lastname"; public static String NICKNAME ="nickname"; public static String COMMUNITY="community"; public static String VILLAGE ="village"; public static String DISTRICT ="district"; public static String REGION ="region"; public static String AGE = "age"; public static String GENDER ="gender"; public static String MARITAL_STATUS ="maritalstatus"; public static String NUMBER_OF_CHILDREN = "numberofchildren"; public static String NUMBER_OF_DEPENDANTS ="numberofdependants"; public static String EDUCATION ="education"; public static String MAJOR_CROP ="majorcrop"; public static String CLUSTER = "cluster"; public static String FARMERID = "farmerid"; //public static String ID ="id"; Node underlyingNode; public Biodata(Node underlyingNode) { super(underlyingNode); this.underlyingNode = underlyingNode; } public String getFirstname() { try { return (String) underlyingNode.getProperty(FIRST_NAME); } catch (Exception e) { e.printStackTrace(); } return null; } public void setFirstname(String firstname) { underlyingNode.setProperty(FIRST_NAME,firstname); } public String getLastname() { try { return (String) underlyingNode.getProperty(LAST_NAME); } catch (Exception e) { } return null; } public void setLastname(String lastname) { underlyingNode.setProperty(LAST_NAME,lastname); } public String getNickname() { try { return (String) underlyingNode.getProperty(NICKNAME); } catch (Exception e) { } return null; } public void setNickname(String nickname) { underlyingNode.setProperty(NICKNAME,nickname); } public String getCommunity() { try { return (String) underlyingNode.getProperty(COMMUNITY); } catch (Exception e) { } return null; } public void setCommunity(String community) { underlyingNode.setProperty(COMMUNITY,community); } public String getDistrict() { try { return (String) underlyingNode.getProperty(DISTRICT); } catch (Exception e) { } return null; } public void setDistrict(String district) { underlyingNode.setProperty(DISTRICT,district); } public String getVillage() { try { return (String) underlyingNode.getProperty(VILLAGE); } catch (Exception e) { } return null; } public void setVillage(String village) { underlyingNode.setProperty(VILLAGE,village); } public String getRegion() { try { return (String) underlyingNode.getProperty(REGION); } catch (Exception e) { } return null; } public void setRegion(String region) { underlyingNode.setProperty(REGION,region); } public String getAge() { try { return (String) underlyingNode.getProperty(AGE); } catch (Exception e) { } return null; } public void setAge(String age) { underlyingNode.setProperty(AGE,age); } public String getGender() { try { return (String) underlyingNode.getProperty(GENDER); } catch (Exception e) { } return null; } public void setGender(String gender) { underlyingNode.setProperty(GENDER,gender); } public String getMaritalstatus() { try { return (String) underlyingNode.getProperty(MARITAL_STATUS); } catch (Exception e) { } return null; } public void setMaritalstatus(String maritalstatus) { underlyingNode.setProperty(MARITAL_STATUS,maritalstatus); } public String getNumberofchildren() { try { return (String) underlyingNode.getProperty(NUMBER_OF_CHILDREN); } catch (Exception e) { } return null; } public void setNumberofchildren(String numberofchildren) { underlyingNode.setProperty(NUMBER_OF_CHILDREN,numberofchildren); } public String getNumberofdependants() { try { return (String) underlyingNode.getProperty(NUMBER_OF_DEPENDANTS); } catch (Exception e) { } return null; } public void setNumberofdependants(String numberofdependants) { underlyingNode.setProperty(NUMBER_OF_DEPENDANTS,numberofdependants); } public String getMajorCrop() { try { return (String) underlyingNode.getProperty(MAJOR_CROP); } catch (Exception e) { } return null; } public void setMajorCrop(String majorcrop) { underlyingNode.setProperty(MAJOR_CROP,majorcrop); } public String getEducation() { try { return (String) underlyingNode.getProperty(EDUCATION); } catch (Exception e) { } return null; } public void setCluster(String cluster) { underlyingNode.setProperty(CLUSTER,cluster); } public void setEducation(String education) { underlyingNode.setProperty(EDUCATION,education); } public String getCluster() { try { return (String) underlyingNode.getProperty(CLUSTER); } catch (Exception e) { } return null; } public void setFarmerID(String farmerID) { underlyingNode.setProperty(FARMERID,farmerID); } public String getFarmerID() { try { return (String) underlyingNode.getProperty(FARMERID); } catch (Exception e) { } return null; } public void setFarmManagement(Node farmManagement) { underlyingNode.createRelationshipTo(farmManagement, ICTCRelationshipTypes.HAS_FARM_MANAGEMENT); } public FarmManagement getFarmManagement() { return new FarmManagement(Neo4jServices.findNodeFromRelation(underlyingNode, Direction.OUTGOING, ICTCRelationshipTypes.HAS_FARM_MANAGEMENT)); } public void setFarmOperation(Node farmOperation) { underlyingNode.createRelationshipTo(farmOperation, ICTCRelationshipTypes.HAS_FARM_OPERATION); } public Operations getFarmOperation() { return new Operations(Neo4jServices.findNodeFromRelation(underlyingNode, Direction.OUTGOING, ICTCRelationshipTypes.HAS_FARM_OPERATION)); } public void setHarvest(Node harvest) { underlyingNode.createRelationshipTo(harvest, ICTCRelationshipTypes.HAS_HARVEST); } public Operations getHavest() { return new Operations(Neo4jServices.findNodeFromRelation(underlyingNode, Direction.OUTGOING, ICTCRelationshipTypes.HAS_HARVEST)); } public void setPostHarvest(Node postHarvest) { underlyingNode.createRelationshipTo(postHarvest, ICTCRelationshipTypes.HAS_POSTHARVEST); } public PostHarvest getPostHavest() { return new PostHarvest(Neo4jServices.findNodeFromRelation(underlyingNode, Direction.OUTGOING, ICTCRelationshipTypes.HAS_POSTHARVEST)); } public void setStorage(Node storage) { underlyingNode.createRelationshipTo(storage, ICTCRelationshipTypes.HAS_STORAGE); } public Storage getStorage() { return new Storage(Neo4jServices.findNodeFromRelation(underlyingNode, Direction.OUTGOING, ICTCRelationshipTypes.HAS_STORAGE)); } public void setMarketing(Node marketing) { underlyingNode.createRelationshipTo(marketing, ICTCRelationshipTypes.HAS_MARKETING); } public Marketing getMarketing() { return new Marketing(Neo4jServices.findNodeFromRelation(underlyingNode, Direction.OUTGOING, ICTCRelationshipTypes.HAS_MARKETING)); } public void setTechNeeds(Node techNeeds) { underlyingNode.createRelationshipTo(techNeeds, ICTCRelationshipTypes.HAS_TECHNEEDS); } public Marketing getTechNeeds() { return new Marketing(Neo4jServices.findNodeFromRelation(underlyingNode, Direction.OUTGOING, ICTCRelationshipTypes.HAS_TECHNEEDS)); } public void setFMP(Node fmp) { underlyingNode.createRelationshipTo(fmp, ICTCRelationshipTypes.HAS_FARM_MANAGEMENT_PLAN); } public FarmManagementPlan getFMP() { return new FarmManagementPlan(Neo4jServices.findNodeFromRelation(underlyingNode, Direction.OUTGOING, ICTCRelationshipTypes.HAS_FARM_MANAGEMENT_PLAN)); } }
//*Vladimir Ventura // 00301144 // Computer Science 2 - Data Structures // Project 2 - War Game: Main // // This file runs the War game. Sadly there's no fancy graphics. // The only requirement to run this program is to have all files in the same place.*// public class Main { public static void main(String[] args) { WarManager wm = new WarManager(); wm.setup(); wm.deal(); wm.play(); } }
package Programa_Principal; import Interfce_Grafica.Menu; public class Sistema { public static void main(String[] args){ Menu m = new Menu(); m.setMenu(m.getTelaPesquisa()); } }
package implementation; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JButton; import interfaces.IGuiControl; public class Delete implements IGuiControl{ @Override public JButton create(MainWindow parent) { JButton btnDelete = new JButton("Delete"); btnDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selectedIndex = parent.tAppointments.getSelectedRow(); if(selectedIndex < parent.appointments.size() && selectedIndex > -1) { parent.appointments.remove(selectedIndex); parent.updateTable(); } } }); return btnDelete; } }