text
stringlengths
10
2.72M
package mb.tianxundai.com.toptoken.view; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import android.widget.TextView; import mb.tianxundai.com.toptoken.R; /** * @author txd_dbb * @emil 15810277571@163.com * create at 2018/8/2313:49 * description: */ public class RedMoneyDialog extends Dialog implements View.OnClickListener { private SignListener signListener; private Context context; private String banben; private String beizhu; private String tag; private TextView tv_operation; public RedMoneyDialog(@NonNull Context context, String banben, String beizhu,String tag, @NonNull SignListener signListener) { super(context, R.style.dialog_style); this.signListener = signListener; this.context = context; this.banben = banben; this.beizhu = beizhu; this.tag = tag; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_input_red_password); findViewById(R.id.iv_dialog_back).setOnClickListener(this); findViewById(R.id.tv_money).setOnClickListener(this); findViewById(R.id.et_psd).setOnClickListener(this); tv_operation=findViewById(R.id.tv_operation); if(tag=="chongzhi"){ tv_operation.setText(R.string.tixian_money_to_lian); }if(tag=="tixian"){ tv_operation.setText(R.string.chongzhi_money_to_lian); } // ((TextView) findViewById(R.id.banben)).setText(context.getResources().getString(R.string.faxianxin)+" : "+banben); // ((TextView) findViewById(R.id.tv_beizhu)).setText(beizhu); } @Override public void onClick(View view) { this.dismiss(); switch (view.getId()) { case R.id.tv_money: break; case R.id.et_psd: break; case R.id.iv_dialog_back: break; } } public interface SignListener { void sign(); } }
package com.paragon.brdata.remote; /** * Created by Rupesh Saxena */ interface Api { }
package org.sarge.jove.audio; import static org.lwjgl.openal.AL10.AL_NO_ERROR; import static org.lwjgl.openal.AL10.alGetError; import org.lwjgl.LWJGLException; import org.lwjgl.openal.AL; /** * LWJGL/OpenAL implementation. */ public final class LightweightAudioSystem implements AudioSystem { private final AudioListener listener = new LightweightAudioListener(); /** * Checks for an error reported by OpenAL. */ protected static void checkError( String msg ) { final int err = alGetError(); if( err != AL_NO_ERROR ) { throw new RuntimeException( "[" + err + "] " + msg ); } } @Override public void start() { // Init OpenAL try { AL.create(); } catch( LWJGLException e ) { throw new RuntimeException( e ); } // Check created if( !AL.isCreated() ) { throw new RuntimeException( "OpenAL not initialised" ); } // Clear error flag alGetError(); } @Override public void stop() { if( AL.isCreated() ) { AL.destroy(); } } @Override public AudioListener getListener() { return listener; } @Override public AudioTrack createAudioTrack() { return new LightweightAudioTrack(); } @Override public AudioPlayer createAudioPlayer() { return new LightweightAudioPlayer(); } }
/** * 24. Swap Nodes in Pairs * 用图表示的更清楚,可以把线看成node.next * 参考:https://blog.csdn.net/camellhf/article/details/72866053 * Created by mengwei on 2019/6/5. */ public class SwapNodesinPairs { public ListNode swapPairs(ListNode head) { ListNode rs = new ListNode(0); ListNode tmp = rs; tmp.next = head; // 1 ListNode first = tmp.next; while(tmp != null){ if(tmp.next == null || tmp.next.next == null){ return rs.next; } first = tmp.next; tmp.next = first.next; //2 first.next = first.next.next; //3 //这里不用first.next是因为first.next已经指向第三个节点了 tmp.next.next = first; //4 tmp = first; } return rs.next; } public static void main(String[] args) { ListNode listNode = new ListNode(1); ListNode listNode2 = new ListNode(2); listNode.next = listNode2; ListNode listNode3 = new ListNode(3); listNode2.next = listNode3; ListNode listNode4 = new ListNode(4); listNode3.next = listNode4; ListNode listNode1 = new SwapNodesinPairs().swapPairs(listNode); while(listNode1 != null){ System.out.println(listNode1.value); listNode1 = listNode1.next; } // System.out.println(listNode1.value); } }
package com.lfj.service.impl; import com.lfj.entity.UserRole; import com.lfj.mapper.UserRoleMapper; import com.lfj.service.IUserRoleService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author lfj * @since 2020-03-02 */ @Service public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService { }
package com.example.demo; import com.example.demo.producer.MessageProducer; import org.apache.activemq.command.ActiveMQQueue; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import javax.jms.Destination; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootActivemqApplicationTests { @Resource private MessageProducer messageProducer; @Test public void contextLoads() { Destination destination = new ActiveMQQueue("message.queue"); messageProducer.sendMessage(destination, "今天天气不错!"); } }
package com.corycharlton.bittrexapi.extension.okhttp; import android.support.annotation.NonNull; import com.corycharlton.bittrexapi.BittrexApiClient; import com.corycharlton.bittrexapi.Downloader; import com.corycharlton.bittrexapi.internal.NameValuePair; import com.corycharlton.bittrexapi.internal.util.Ensure; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.CacheControl; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; /** * A {@link Downloader} implementation that uses a {@link OkHttpClient} to execute requests */ public class OkHttpDownloader implements Downloader { @Override public Response execute(@NonNull Request request) throws IOException { Ensure.isNotNull("request", request); final OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(BittrexApiClient.DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS) .readTimeout(BittrexApiClient.DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS) .readTimeout(BittrexApiClient.DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS) .build(); final okhttp3.Request.Builder okhttpRequestBuilder = new okhttp3.Request.Builder(); okhttpRequestBuilder.cacheControl(CacheControl.FORCE_NETWORK); okhttpRequestBuilder.get(); okhttpRequestBuilder.url(request.url()); for (NameValuePair header : request.headers()) { okhttpRequestBuilder.addHeader(header.name(), header.value()); } final okhttp3.Response response = client.newCall(okhttpRequestBuilder.build()).execute(); int responseCode = response.code(); final ResponseBody responseBody = response.body(); if (responseCode < 200 || responseCode >= 300) { if (responseBody != null) { responseBody.close(); } throw new ResponseException(responseCode + ": " + response.message(), responseCode); } if (responseBody == null) { throw new ResponseException(responseCode + ": ResponseBody was null" , responseCode); } return new Response(responseBody.string(), responseCode); } }
package Base.copy.copy.copy.copy; import java.util.Iterator; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.ui.Select; public class Bases { //��װͨ�õ�driver���÷��� private static WebDriver driver; public static WebDriver SetDriver(String baseUrl) { System.setProperty("WebDriver.ie.driver", "C:\\Windows\\System32\\IEDriverServer.exe"); driver = new InternetExplorerDriver(); driver.get(baseUrl); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); return driver; } /** * ����SwitchWindow(); * @author Simba */ public static void mySwitchWindow(WebDriver driver) { // TODO Auto-generated method stub String currentWindow = driver.getWindowHandle(); Set handles = driver.getWindowHandles(); Iterator<String> it = handles.iterator(); while(it.hasNext()){ String handle = it.next(); if (currentWindow.equals(handle)){ continue; //������ǰѭ�� }else{ WebDriver window = driver.switchTo().window(handle); System.out.println(window.getTitle()); } } } /** * ����selectѡ��� * @author Simba * */ public static void getSelect(String idpath,int num,WebDriver driver){ Select sel = new Select(driver.findElement(By.id(idpath))); sel.selectByIndex(getRadomNum(num)); } /** * ����û������������ * @param str * @return */ public static String getUserName(String str,int max){ String FirstName = str; String UserName = ""; UserName = FirstName + getRadomNum(max); return UserName; } /** * ��װ����� * @param max * @return */ public static int getRadomNum(int max){ int num = 0; Random RadomNum = new Random(); for(int i = 1;i<=max;i++){ num = RadomNum.nextInt(max)+1; } return num; } //��װͨ�õ�driver·�� String path(){ return null; } //��װͨ�õ�ʹ��Ԫ��·���ļ�����������һ���ַ��� void get() { } }
package com.mercury.finance.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.mercury.common.db.HibernateDao; import com.mercury.finance.model.Stock; @Service @Transactional public class StockService { @Autowired @Qualifier("stockDao") private HibernateDao<Stock, Integer> stockD; public Stock findStock(String sname){ return stockD.findBy("sname", sname); } }
//designpatterns.mediator.Mediator.java package designpatterns.mediator; //³éÏóÖнéÕß public abstract class Mediator { public abstract void componentChanged(Component c); }
package bn.statc; import bn.BNException; import bn.IBayesNet; import bn.distributions.Distribution; /** * Interface for Static Bayes network-specific functions. * @author Nils F. Sandell * */ public interface IStaticBayesNet extends IBayesNet<IBNNode> { /** * Add edge from one node to another. * @param from Child node name * @param to Parent node name * @throws BNException If the nodes don't exist or can't be connected. */ public void addEdge(String from, String to) throws BNException; /** * Remove an existing edge from one node to another. * @param from Child node name * @param to Parent node name * @throws BNException If the nodes aren't connected, or they don't exist. */ public void removeEdge(String from, String to) throws BNException; /** * Add a discrete node to this network. * @param name Name of the node to add. * @param cardinality Cardinality of the node to add. * @return Interface to the new node. * @throws BNException If the new node can't be created (e.g. same name already exists) */ public IFDiscBNNode addDiscreteNode(String name, int cardinality) throws BNException; public IInfDiscEvBNNode addDiscEvidenceNode(String name, int value) throws BNException; /** * Check whether an edge exists or not. * @param from Parent node * @param to Child node * @return True if it does, else false * @throws BNException If either of the nodes specified don't exist. */ public boolean edgeExists(String from, String to) throws BNException; public Distribution getDistribution(String name) throws BNException; }
package com.kemalgulpinar.boot.issuetr.issuetracker.github; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class Actor { private final String login; private final String avatarUrl; private final String htmlIrl; @JsonCreator public Actor(@JsonProperty("login") String login, @JsonProperty("avatar_url") String avatarUrl, @JsonProperty("html_url") String htmlIrl){ this.login = login; this.avatarUrl = avatarUrl; this.htmlIrl = htmlIrl; } public String getLogin() { return login; } public String getAvatarUrl() { return avatarUrl; } public String getHtmlIrl() { return htmlIrl; } }
package ul.stage.officeassignment.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import ul.stage.officeassignment.model.Bureau; @Repository public interface BureauRepository extends JpaRepository<Bureau,Long> { }
package estruturas.pilhas; public class Main { public static void main(String[] args) { Pilha minhaPilha = new Pilha(); minhaPilha.push(new No("Conteudo 1")); minhaPilha.push(new No("Conteudo 2")); minhaPilha.push(new No("Conteudo 3")); minhaPilha.push(new No("Conteudo 4")); minhaPilha.push(new No("Conteudo 5")); minhaPilha.push(new No("Conteudo 6")); System.out.println(minhaPilha); minhaPilha.pop(); System.out.println(minhaPilha); System.out.println(minhaPilha.top()); } }
package org.crazyit.ui; import android.app.ActionBar; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends Activity { ActionBar actionBar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // 获取该Activity的ActionBar // 只有当应用主题没有关闭ActionBar时,该代码才能返回ActionBar actionBar = getActionBar(); } // 为“显示ActionBar”按钮定义事件处理方法 public void showActionBar(View source) { // 显示ActionBar actionBar.show(); } // 为“隐藏ActionBar”按钮定义事件处理方法 public void hideActionBar(View source) { // 隐藏ActionBar actionBar.hide(); } }
package com.http; import com.controllers.*; import com.sun.net.httpserver.HttpServer; import org.apache.log4j.Logger; import java.net.InetSocketAddress; import static java.lang.String.format; public class CustomHttpServer { private static final int PORT = 9001; private static final Logger LOGGER = Logger.getLogger(CustomHttpServer.class); public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0); server.createContext("/employee/post", new PostHandler()); server.createContext("/employee/get", new GetHandler()); server.createContext("/employee/put", new PutHandler()); server.createContext("/employee/delete", new DeleteHandler()); server.createContext("/employee", new GetByOffsetAndLimitHandler()); server.createContext("/status", new StatusHandler()); server.setExecutor(null); server.start(); LOGGER.info(format("[SERVER] --> WAS STARTED SERVER ON PORT %d",PORT)); } }
package com.zenwerx.findierock; import java.io.IOException; import android.app.backup.BackupAgentHelper; import android.app.backup.BackupDataInput; import android.app.backup.BackupDataOutput; import android.app.backup.SharedPreferencesBackupHelper; import android.os.ParcelFileDescriptor; import android.util.Log; public class FindieBackupAgent extends BackupAgentHelper { private final static String TAG = "findierock.BackupAgent"; @Override public void onCreate() { Log.d(TAG, "Adding shared preference helper..."); SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, "com.zenwerx.findierock_preferences"); addHelper("findieBackupHelper", helper); } @Override public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,ParcelFileDescriptor newState) throws IOException { Log.d(TAG, "I should be backing up right now..."); super.onBackup(oldState, data, newState); Log.d(TAG, "I should be done backing up right now..."); } @Override public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException { } }
package com.itinerary.guest.itinerary.service; import java.io.IOException; import java.util.List; import org.easymock.EasyMock; import org.junit.Test; import com.itinerary.guest.itinerary.clients.DiningClient; import com.itinerary.guest.itinerary.clients.ResortClient; import com.itinerary.guest.itinerary.model.Itinerary; public class ServiceImplTest { @Test public void getItinerarytest1() throws IOException { ServiceImpl serviceImpl=new ServiceImpl(); Itinerary itinerary=EasyMock.createMock(Itinerary.class); serviceImpl.setItinerary(itinerary); DiningClient diningClientMock=EasyMock.createMock(DiningClient.class); serviceImpl.setDiningClient(diningClientMock); EasyMock.expect(diningClientMock.getDining(1l)).andReturn(EasyMock.createMock(List.class)); ResortClient resortClientMock=EasyMock.createMock(ResortClient.class); serviceImpl.setResortClient(resortClientMock); EasyMock.expect(resortClientMock.getResort(1l)).andThrow(new NullPointerException()); EasyMock.replay(diningClientMock,resortClientMock); serviceImpl.getItinerary(1l); } @Test public void getItinerarytest2() throws IOException { ServiceImpl serviceImpl=new ServiceImpl(); Itinerary itinerary=EasyMock.createMock(Itinerary.class); serviceImpl.setItinerary(itinerary); DiningClient diningClientMock=EasyMock.createMock(DiningClient.class); serviceImpl.setDiningClient(diningClientMock); EasyMock.expect(diningClientMock.getDining(1l)).andThrow(new NullPointerException()); ResortClient resortClientMock=EasyMock.createMock(ResortClient.class); serviceImpl.setResortClient(resortClientMock); EasyMock.expect(resortClientMock.getResort(1l)).andReturn(EasyMock.createMock(List.class)); EasyMock.replay(diningClientMock,resortClientMock); serviceImpl.getItinerary(1l); } @Test public void getItinerarytest5() throws IOException { ServiceImpl serviceImpl=new ServiceImpl(); DiningClient diningClientMock=EasyMock.createMock(DiningClient.class); ResortClient resortClientMock=EasyMock.createMock(ResortClient.class); Itinerary itinerary=EasyMock.createMock(Itinerary.class); serviceImpl.setDiningClient(diningClientMock); serviceImpl.setResortClient(resortClientMock); serviceImpl.setItinerary(itinerary); serviceImpl.getDiningClient(); serviceImpl.getResortClient(); EasyMock.expect(diningClientMock.getDining(1l)).andReturn(EasyMock.createMock(List.class)); EasyMock.expect(resortClientMock.getResort(1l)).andReturn(EasyMock.createMock(List.class)); EasyMock.replay(diningClientMock,resortClientMock); serviceImpl.getItinerary(1l); } }
package com.niit.project.radiom.activity; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.niit.project.radiom.R; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.widget.ListView; import android.widget.SimpleAdapter; public class RankActivity extends Activity { private ListView rankList; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rank); rankList = (ListView) findViewById(R.id.rankList); sp = PreferenceManager.getDefaultSharedPreferences(this); List<Map<String, String>> data = new ArrayList<Map<String, String>>(); Map<String, String> item1 = new HashMap<String, String>(); item1.put("roundTopScore", "第一关 " + sp.getInt("round1TopScore", 0)); Map<String, String> item2 = new HashMap<String, String>(); item2.put("roundTopScore", "第二关 " + sp.getInt("round2TopScore", 0)); Map<String, String> item3 = new HashMap<String, String>(); item3.put("roundTopScore", "第三关 " + sp.getInt("round3TopScore", 0)); data.add(item1); data.add(item2); data.add(item3); rankList.setAdapter( new SimpleAdapter( this, data, R.layout.item_layout, new String[]{"roundTopScore"}, new int[]{R.id.score}) ); } }
package de.meetpub.telegrambot.messagehandlers; import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.objects.Message; import de.meetpub.telegrambot.startup.MeetPubTelegramBot.State; /** * @author Christian Bargmann <christian.bargmann@haw-hamburg.de> * @version 28.06.2017 * @see de.meetpub.telegrambot.messagehandlers * @since 28.06.2017 , 14:37:56 * */ public abstract class AbstractMessageHandler { /** * Ueberschreiben der Methode getMessageRequest in der Klasse * AbstractMessageHandler. Fuer Details zur Implementierung siehe: * * @see de.meetpub.telegrambot.messagehandlers.MessageHandler#getMessageRequest(org.telegram.telegrambots.api.objects.Message, * de.meetpub.telegrambot.startup.MeetPubTelegramBot.State) */ public SendMessage getMessageRequest(Message message, State state) { SendMessage sendMessageRequest = null; if (message.hasText()) { sendMessageRequest = handle(message, state); } return sendMessageRequest; } /** * @param message * @return */ protected abstract SendMessage handle(Message message, State state); }
package com.thegriffen.projectsoaringgriffen.utils; import android.graphics.Bitmap; public class CameraConstants { public static Bitmap bmp; public static byte[] data1; public static boolean pictureTaken = false; }
package com.fanoi.dream.module.mall.adapter; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import com.fanoi.dream.R; import com.fanoi.dream.controler.imageloader.ImageLoader; import com.fanoi.dream.model.bean.BuyComment; import com.fanoi.dream.utils.DisplayUtils; import com.fanoi.dream.widget.ImagePagerActivity; public class BuyCommetAdapter extends BaseAdapter { private ArrayList<BuyComment> datas; private Context context; private LayoutInflater inflater; private int screenWidth; private ImageLoader imageLoader; public BuyCommetAdapter(ArrayList<BuyComment> datas, Context context, ImageLoader imageLoader) { this.datas = datas; this.context = context; this.inflater = LayoutInflater.from(context); this.screenWidth = DisplayUtils.getScreenWidthAndHight(context)[0]; this.imageLoader = imageLoader; } @Override public int getCount() { return datas != null ? datas.size() : 0; } /** * 刷新 * * @param datas */ public void notifyAdapter(ArrayList<BuyComment> datas) { this.datas = datas; this.notifyDataSetChanged(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = inflater.inflate(R.layout.item_buy_comment, null); holder = new ViewHolder(); holder.name_tv = (TextView) convertView .findViewById(R.id.item_buy_comment_name); holder.stars_tv = (TextView) convertView .findViewById(R.id.item_buy_comment_starts); holder.content_tv = (TextView) convertView .findViewById(R.id.item_buy_comment_content); holder.images_gv = (GridView) convertView .findViewById(R.id.item_buy_comment_images); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } BuyComment buyComment = datas.get(position); holder.name_tv.setText(buyComment.getName()); holder.stars_tv.setText(buyComment.getCount()); holder.content_tv.setText(buyComment.getContent()); final String[] images = buyComment.getUrls(); if (images != null && images.length > 0) { holder.images_gv.setVisibility(View.VISIBLE); holder.images_gv.setAdapter(new CommentImageAdapter(images, inflater, screenWidth, imageLoader, context)); holder.images_gv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(); intent.putExtra("position", position); intent.putExtra("images", images); intent.setClass(context, ImagePagerActivity.class); context.startActivity(intent); } }); } else { holder.images_gv.setVisibility(View.GONE); } return convertView; } static class ViewHolder { TextView name_tv; TextView stars_tv; TextView content_tv; GridView images_gv; } static class CommentImageAdapter extends BaseAdapter { private String[] images; private Context context; private LayoutInflater inflater; private int screemWidth; private ImageLoader imageLoader; private CommentImageAdapter(String[] images, LayoutInflater inflater, int screemWidth, ImageLoader imageLoader, Context context) { this.images = images; this.inflater = inflater; this.screemWidth = screemWidth; this.imageLoader = imageLoader; this.context = context; } @Override public int getCount() { return images.length; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = inflater.inflate(R.layout.item_buy_comment_image, null); holder = new ViewHolder(); holder.image_iv = (ImageView) convertView .findViewById(R.id.item_buy_comment_image_imageView); holder.setImageViewSize(holder.image_iv, screemWidth, context); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // holder.image_iv.setImageResource(images[position]); imageLoader.displayFromNet(context, images[position], holder.image_iv); return convertView; } static class ViewHolder { ImageView image_iv; /** * 设置图片的长宽 * * @param imageView * @param width */ public void setImageViewSize(ImageView imageView, int width, Context context) { LayoutParams params = imageView.getLayoutParams(); int item_width = width / 4; params.height = item_width; params.width = item_width; imageView.setLayoutParams(params); } } } }
/* * 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; /** * * @author Maxime Stierli <maxime.stierli@he-arc.ch> */ public class Ajout { private Long id; private Long ajout_users; public Ajout(Long ajout_users){ this.ajout_users = ajout_users; } public Long getId() { return id; } public Long getAjout_users() { return ajout_users; } }
/* * 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 poo.estacionamiento.dao; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import poo.estacionamiento.Propietario; /** * * @author joaquinleonelrobles */ public class PropietariosDaoImpl implements PropietariosDao { private final List<Propietario> propietarios; public PropietariosDaoImpl() { propietarios = new ArrayList<>(); } @Override public void guardar(Propietario propietario) { this.propietarios.add(propietario); } @Override public Propietario buscarPorDni(int dni) { Propietario retorno = null; Iterator<Propietario> iter = propietarios.iterator(); while (iter.hasNext()) { Propietario actual = iter.next(); if (actual.getDni() == dni) { retorno = actual; break; } } return retorno; } }
public class NFCReader { private int currentNFCNumber; public boolean validateNFC(int number) { currentNFCNumber = number; return true; } public int getNFCNumber() { return currentNFCNumber; } }
package me.libme.baidu.mapdata.searchindex.point; import me.libme.kernel._c.util.MD5; import me.libme.module.es5x6.ESModel; import java.util.Collections; import java.util.Map; /** * Created by J on 2018/2/27. */ public interface Point { /** * 经度 * @return */ String longitude(); /** * 纬度 * @return */ String latitude(); /** * 名称 * @return */ String name(); /** * 地址 * @return */ String addr(); /** * 备注数据 * @return */ default Map<String,Object> data(){return Collections.EMPTY_MAP;} default ESModel esModel(){throw new UnsupportedOperationException();} default String logicUniqueId(){ return MD5.md5(name()+"|"+latitude()+"|"+longitude()); } }
package com.twitter.finatra.tests.json.internal; public enum CarMakeEnum { ford, vw; }
package org.wxy.weibo.cosmos.ui.activity; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import com.tencent.smtt.export.external.TbsCoreSettings; import com.tencent.smtt.sdk.QbSdk; import com.tencent.smtt.sdk.WebChromeClient; import com.tencent.smtt.sdk.WebView; import org.wxy.weibo.cosmos.R; import org.wxy.weibo.cosmos.ui.base.ActionbarActvity; import org.wxy.weibo.cosmos.view.X5WebView; import java.util.HashMap; public class WebActivity extends ActionbarActvity { private X5WebView web; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFormat(PixelFormat.TRANSLUCENT); } @Override protected int getContLayoutID() { return R.layout.activity_web; } @Override protected void initView() { super.initView(); web=findViewById(R.id.web); } @Override protected void init() { super.init(); Intent intent=getIntent(); String url=intent.getStringExtra("url"); web.loadUrl(url); web.setWebChromeClient(new WebChromeClient(){ @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); if (title!=null) setContTitle(title); } }); } public void getUrl(Context context,String url){ Intent intent=new Intent(context,WebActivity.class); intent.putExtra("url",url); context.startActivity(intent); } @Override public void onDestroy() { super.onDestroy(); if (web!=null) { web.destroy(); web=null; } } }
package com.deepakm.stock.bo; import com.deepakm.stock.model.Stock; /** * Created by dmarathe on 2/15/16. */ public interface StockBO { public void save(Stock stock); public void update(Stock stock); public void delete(Stock stock); public Stock findStockByCode(String code); }
package app.com.thetechnocafe.eventos; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import app.com.thetechnocafe.eventos.Utils.SharedPreferencesUtils; public class HomeStreamActivity extends AppCompatActivity { boolean LikeBtnStatus; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_stream); if(!SharedPreferencesUtils.getLoginState(getBaseContext())){ finish(); } // getIntent().getBooleanExtra("likeBtnStatus", LikeBtnStatus); FragmentManager fragmentManager = getSupportFragmentManager(); Fragment fragment = fragmentManager.findFragmentById(R.id.home_stream_fragment_container); if (fragment == null) { fragment = HomeStreamFragment.getInstance(); fragmentManager.beginTransaction().add(R.id.home_stream_fragment_container, fragment).commit(); } } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }
package cbartersolutions.medicalreferralapp.Activities; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceGroup; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import java.util.List; import cbartersolutions.medicalreferralapp.R; public class AppPreferencesActivity extends AppCompatActivity { private MainActivity.TypeofNote typeofNote; private boolean deleted_notes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_preferences); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); if(getIntent().getSerializableExtra(MainActivity.NOTE_TYPE) != null) { //take info from calling intent typeofNote = (MainActivity.TypeofNote) getIntent().getSerializableExtra(MainActivity.NOTE_TYPE); deleted_notes = getIntent().getBooleanExtra(MainActivity.DELETED_NOTES, false); } FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); SettingsFragment settingsFragment = new SettingsFragment(); fragmentTransaction.add(R.id.preferences_frame_layout, settingsFragment, "SETTINGS FRAGMENT"); fragmentTransaction.commit(); } public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MainActivity.TypeofNote typeofNote = (MainActivity.TypeofNote) getActivity().getIntent().getSerializableExtra(MainActivity.NOTE_TYPE); switch (typeofNote){ case JOB: addPreferencesFromResource(R.xml.job_app_preferences); getActivity().setTitle(getResources().getString(R.string.jobSingular) + " " + getResources().getString(R.string.title_activity_app_preferences)); break; case REFERRAL: addPreferencesFromResource(R.xml.referral_app_preferences); getActivity().setTitle(getResources().getString(R.string.referralSingular) + " " + getResources().getString(R.string.title_activity_app_preferences)); break; } getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onResume() { super.onResume(); for(int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++){ Preference preference = getPreferenceScreen().getPreference(i); if(preference instanceof PreferenceGroup){ PreferenceGroup preferenceGroup = (PreferenceGroup) preference; for(int j=0; j<preferenceGroup.getPreferenceCount(); j++){ Preference singlePref = preferenceGroup.getPreference(j); updatePreference(singlePref, singlePref.getKey()); updateIcon(singlePref.getKey()); } }else{ updatePreference(preference, preference.getKey()); updateIcon(preference.getKey()); } } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { updatePreference(findPreference(key), key); updateIcon(key); } public void updateIcon(String key){ if(key.equals("REFERRAL_DEFAULT_IMPORTANCE_ICON")||key.equals("JOB_DEFAULT_IMPORTANCE_ICON")){ ListPreference defaultIconPreference = (ListPreference)findPreference(key); if(defaultIconPreference != null) { String defaultIcon = defaultIconPreference.getValue(); switch (defaultIcon) { case "High": defaultIconPreference.setIcon(R.drawable.ic_priority_high); break; case "Medium": defaultIconPreference.setIcon(R.drawable.ic_priority_medium); break; case "Low": defaultIconPreference.setIcon(R.drawable.ic_priority_low); break; } } } if(key.equals("JOB_ASC_DESC")||key.equals("REFERRAL_ASC_DESC")){ ListPreference asc_desc = (ListPreference)findPreference(key); String choice = asc_desc.getValue(); switch (choice){ case "ASC": asc_desc.setIcon(R.drawable.ic_arrow_upward_black_24dp_xxxhdpi); break; case "DESC": asc_desc.setIcon(R.drawable.ic_arrow_downward_black_24dp_xxxhdpi); break; } } } private void updatePreference(Preference preference, String key) { if (preference == null) return; if (preference instanceof ListPreference) { ListPreference listPreference = (ListPreference) preference; listPreference.setSummary(listPreference.getEntry()); return; } if(!(preference instanceof CheckBoxPreference)) { SharedPreferences sharedPreferences = getPreferenceManager().getSharedPreferences(); preference.setSummary(sharedPreferences.getString(key, "Default")); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: onBackPressed(); break; } return true; } @Override public void onBackPressed() { super.onBackPressed(); if(getIntent().getSerializableExtra(MainActivity.NOTE_TYPE) != null) { Intent intent = new Intent(this, Activity_ListView.class); intent.putExtra(MainActivity.NOTE_TYPE, typeofNote); intent.putExtra(MainActivity.DELETED_NOTES, deleted_notes); startActivity(intent); }else{ finish(); } } }
package com.example; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; public class Threadlocaltest { public static ThreadLocal<String> st = new ThreadLocal<String>(); public String str; @BeforeMethod public void beforemethod() { System.out.println("Before Methode"); st.set("hello"); } @AfterMethod public void afterMethod() { System.out.println("Aftermethode"); } public String get() { return str; } private void set(String abc) { str=abc; } }
/* * Copyright (c) 2012, Riven * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Riven nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.indiespot.media.impl; import org.lwjgl.opengl.Display; import craterstudio.text.TextValues; import craterstudio.util.HighLevel; class VSyncSleeper { private static final long INTERVAL = 1_000_000_000L / 60; private long nextPostSync; private long errorMargin; public void setSyncErrorMargin(int millis) { this.errorMargin = (millis * 1_000_000L); } public void measureSyncTimestamp(int frames) { // ensure GPU cannot use async updates nextPostSync = System.nanoTime(); for (int i = 0; i < frames; i++) { Display.update(); long now = System.nanoTime(); System.out.println("VSyncSleeper: " + TextValues.formatNumber((now - nextPostSync) / 1_000_000.0, 2) + "ms"); nextPostSync = now; } } private void debugMeasureSyncPredictionError() { /** * result: even over thousands of frames, the error is within 1ms */ for (int i = 0; true; i++) { Display.update(); System.out.println("vsync prediction error: " + TextValues.formatNumber(// (System.nanoTime() - (nextPostSync + (i + 1) * INTERVAL)) / 1_000_000.0, 2) + "ms"); } } public void sleepUntilBeforeVsync() { this.calcNextPostVync(System.nanoTime()); long wakeupAt = this.nextPostSync - this.errorMargin; if (wakeupAt < System.nanoTime()) { return; } // System.out.println("VSyncSleeper: wait for " + // TextValues.formatNumber((wakeupAt - System.nanoTime()) / 1_000_000.0, // 2) + "ms"); while (System.nanoTime() < wakeupAt) { HighLevel.sleep(1); } } private void calcNextPostVync(long now) { long next = nextPostSync; while (next < now) { next += INTERVAL; } nextPostSync = next; } }
package com.iterlife.xspring.aop.advice; import java.lang.reflect.Method; /** *MethodAfterAdvice等价于Spring源码中的AfterReturningAdvice **/ public interface MethodAfterAdvice extends AfterAdvice { void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable; }
package com.project.tz.services; import com.project.tz.dto.CreateUpdateUserDto; import com.project.tz.dto.GetAllUsersDto; import com.project.tz.entities.Role; import com.project.tz.entities.User; import com.project.tz.repositories.RoleRepository; import com.project.tz.repositories.UserRepository; import org.aspectj.lang.annotation.Around; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @Service public class UserServiceImpl implements UserService { @Autowired UserRepository userRepository; @Autowired RoleRepository roleRepository; @PostConstruct void initDBWithRoles() { Role role1 = new Role(); role1.setRoleName("ADMIN"); Role role2 = new Role(); role2.setRoleName("OPERATOR"); Role role3 = new Role(); role3.setRoleName("STATISTIC"); roleRepository.save(role1); roleRepository.save(role2); roleRepository.save(role3); } @Override public List<GetAllUsersDto> getAllUsers() { List<User> users = userRepository.findAll(); List<GetAllUsersDto> userDtos = new ArrayList<>(); for (User user : users) { GetAllUsersDto userDto = new GetAllUsersDto(); BeanUtils.copyProperties(user, userDto); userDtos.add(userDto); } return userDtos; } @Override public User getUser(long id) { User user = userRepository.findById(id); if (user == null) throw new RuntimeException("User not found"); return user; } @Override public User createUser(CreateUpdateUserDto user) { User gettingUser = userRepository.findByUsername(user. getUsername()); if (gettingUser != null) throw new RuntimeException("User already exists"); User creatingUser = new User(); BeanUtils.copyProperties(user, creatingUser); Set<Role> roles = new HashSet<>(); if (user.getIds() != null) { for (Integer id : user.getIds()) { Role role = roleRepository.findById(id); if (role != null) roles.add(role); else throw new RuntimeException("One or more roles not found"); } } else throw new RuntimeException("Roles haven't chosen"); creatingUser.setRoles(roles); User returningUser = userRepository.save(creatingUser); return returningUser; } @Override public User updateUser(long id, CreateUpdateUserDto user) { User persistingUser = userRepository.findById(id); if (persistingUser == null) throw new RuntimeException("Couldn't update,user not found"); BeanUtils.copyProperties(user, persistingUser, "id"); Set<Role> roles = new HashSet<>(); if (user.getIds() != null) { for (Integer ids : user.getIds()) { Role role = roleRepository.findById(ids); if (role != null) roles.add(role); else throw new RuntimeException("One or more roles not found"); } } else throw new RuntimeException("Roles haven't chosen"); persistingUser.setRoles(roles); User returningUser = userRepository.save(persistingUser); return returningUser; } @Override public void deleteUser(long id) { User deletingUser = userRepository.findById(id); if (deletingUser == null) throw new RuntimeException("Couldn't delete,user not found"); userRepository.deleteById(id); } }
package org.vanilladb.comm.protocols.rb; import java.io.Serializable; public class MessageId implements Serializable, Comparable<MessageId> { private static final long serialVersionUID = 20200406001L; private int sourceProcessId; private int sequenceNumber; public MessageId(int sourceProcessId, int sequenceNumber) { this.sourceProcessId = sourceProcessId; this.sequenceNumber = sequenceNumber; } public int getSourceProcessId() { return sourceProcessId; } public int getSequenceNumber() { return sequenceNumber; } @Override public int compareTo(MessageId id) { int result = sourceProcessId - id.sourceProcessId; if (result != 0) return result; return sequenceNumber - id.sourceProcessId; } @Override public int hashCode() { int result = 17; result = 31 * result + sourceProcessId; result = 31 * result + sequenceNumber; return result; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof MessageId)) return false; MessageId target = (MessageId) obj; return this.sourceProcessId == target.sourceProcessId && this.sequenceNumber == target.sequenceNumber; } }
package com.example.cantri.doctoronline.fragments; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.cantri.doctoronline.Clinic; import com.example.cantri.doctoronline.ClinicDetailActivity; import com.example.cantri.doctoronline.R; import com.example.cantri.doctoronline.fragments.ClinicFragment.OnListFragmentInteractionListener; import java.util.List; /** * {@link RecyclerView.Adapter} that can display a and makes a call to the * specified {@link OnListFragmentInteractionListener}. * TODO: Replace the implementation with code for your data type. */ public class MyClinicRecyclerViewAdapter extends RecyclerView.Adapter<MyClinicRecyclerViewAdapter.ViewHolder> { private final List<Clinic> mValues; private final OnListFragmentInteractionListener mListener; public MyClinicRecyclerViewAdapter(List<Clinic> items, OnListFragmentInteractionListener listener) { mValues = items; mListener = listener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.fragment_clinic, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.mItem = mValues.get(position); holder.clinic_key.setText(mValues.get(position).getKey()); holder.clinic_name.setText(mValues.get(position).getName()); holder.clinic_specialty.setText(mValues.get(position).getSpecialty()); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (null != mListener) { // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected Intent intent = new Intent(v.getContext(), ClinicDetailActivity.class); intent.putExtra("detail", holder.mItem); v.getContext().startActivity(intent); } } }); } @Override public int getItemCount() { return mValues.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public Clinic mItem; TextView clinic_name, clinic_specialty, clinic_key; public ViewHolder(View view) { super(view); mView = view; clinic_name = (TextView) itemView.findViewById(R.id.clinic_name); clinic_key = (TextView) itemView.findViewById(R.id.clinic_key); clinic_specialty = (TextView) itemView.findViewById(R.id.clinic_specialty); } @Override public String toString() { return super.toString() + " '" + clinic_key.getText() + "'" + clinic_name.getText() + "'" + clinic_specialty.getText() + "'"; } } }
package io.breen.socrates.file.python; import io.breen.socrates.PostConstructionAction; import io.breen.socrates.file.File; import io.breen.socrates.test.Test; import io.breen.socrates.test.TestGroup; import io.breen.socrates.test.python.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; /** * A PythonFile is a representation of a Python module (a file ending in .py containing valid Python * code) containing source code. */ public final class PythonFile extends File implements PostConstructionAction { /** * The deduction taken when the Python module cannot be imported due to a serious error (e.g., a * syntax error). */ public double importFailureDeduction; public List<Variable> variables = Collections.emptyList(); public List<Function> functions = Collections.emptyList(); public List<Class> classes = Collections.emptyList(); /** * This empty constructor is used by SnakeYAML. */ public PythonFile() { language = "python"; contentsArePlainText = true; } public PythonFile(double importFailureDeduction) { this(); this.importFailureDeduction = importFailureDeduction; } private static boolean hasTest(List<java.lang.Object> list, Test test) { for (java.lang.Object o : list) if (o instanceof Test && o == test) return true; else if (o instanceof TestGroup) return hasTest(((TestGroup)o).members, test); return false; } @Override public void afterConstruction() { super.afterConstruction(); } @Override protected TestGroup createTestRoot() { List<java.lang.Object> tests = new LinkedList<>(); for (Variable v : variables) { Test test = new VariableExistsTest(v); if (!v.tests.isEmpty()) { List<java.lang.Object> members = new LinkedList<>(); members.add(test); members.add(new TestGroup(v.tests, 0, 0.0)); TestGroup group = new TestGroup(members, 1, 0.0); tests.add(group); } else { tests.add(test); } } for (Function f : functions) { Test test = new FunctionExistsTest(f); if (!f.tests.isEmpty()) { List<java.lang.Object> members = new LinkedList<>(); members.add(test); members.add(new TestGroup(f.tests, 0, 0.0)); TestGroup group = new TestGroup(members, 1, 0.0); tests.add(group); } else { tests.add(test); } } for (Class c : classes) { Test classExistsTest = new ClassExistsTest(c); List<java.lang.Object> subTests = new LinkedList<>(); if (!c.tests.isEmpty()) subTests.addAll(c.tests); for (Method m : c.methods) { Test methodExistsTest = new MethodExistsTest(m); List<java.lang.Object> methodSubTests = new LinkedList<>(); if (!m.tests.isEmpty()) methodSubTests.addAll(m.tests); List<java.lang.Object> decision2 = new ArrayList<>(2); decision2.add(methodExistsTest); decision2.add(new TestGroup(methodSubTests, 0, 0.0)); subTests.add(new TestGroup(decision2, 1, 0.0)); } List<java.lang.Object> decision = new ArrayList<>(2); decision.add(classExistsTest); decision.add(new TestGroup(subTests, 0, 0.0)); tests.add(new TestGroup(decision, 1, 0.0)); } TestGroup root = super.createTestRoot(); Test test = new ImportTest(this); List<java.lang.Object> members = new LinkedList<>(); members.add(test); if (!tests.isEmpty()) members.add(new TestGroup(tests, 0, 0.0)); TestGroup group = new TestGroup(members, 1, 0.0); root.members.add(group); return root; } @Override public String getFileTypeName() { return "Python source code"; } public Variable getVariableForTest(VariableTest test) { for (Variable v : variables) if (hasTest(v.tests, test)) return v; return null; } public Function getFunctionForTest(FunctionTest test) { for (Function f : functions) if (hasTest(f.tests, test)) return f; return null; } public Class getClassContainingMethod(Method method) { for (Class c : classes) if (c.methods.contains(method)) return c; return null; } public Method getMethodForTest(MethodTest test) { for (Class c : classes) for (Method m : c.methods) if (hasTest(m.tests, test)) return m; return null; } public String getModuleName() { Path p = Paths.get(path); String fileName = p.getFileName().toString(); String[] parts = fileName.split("\\."); return parts[parts.length - 2]; } }
package com.fbse.recommentmobilesystem.XZHL0001; import java.util.Properties; import android.content.Context; public class XZHL0001_Constats { public static String SERVRCEERROR=""; public static String LIEBIAOSHIBAI=""; public static String NETERROR=""; public static String SHURUMM=""; public static String SHURUMZ=""; public static String SHURUZH=""; public static String LOGINACTION=""; public static String XMLACTION=""; public static String SERVER=""; public static String NEWVERSION=""; public static String DOWNLOAD=""; public static String ZIFUXIANZHI=""; public static String FEIFALOGIN=""; public static String VERSIONFUNCTION=""; public static String LOGINING=""; //丛配置文件中读取信息 public static Properties loadIPProperties(Context context,String str) { Properties props = new Properties(); try { int id = context.getResources().getIdentifier(str, "raw", context.getPackageName()); props.load(context.getResources().openRawResource(id)); } catch (Exception e) { e.printStackTrace(); } return props; } //获取端口号,ip public static void initData(Properties pro){ String Host=pro.getProperty("xmppHost", ""); Host=Host.trim(); String port=pro.getProperty("tomcatPort", ""); port=port.trim(); String nameSpace=pro.getProperty("workspacename", ""); nameSpace=nameSpace.trim(); XZHL0001_Constats.SERVER="http://"+Host+":"+port+"/"+nameSpace+"/"; XZHL0001_Constats.LOGINACTION=XZHL0001_Constats.SERVER+"login.action"; XZHL0001_Constats.XMLACTION="http://"+Host+":"+port+"/"+"FBSEMobileSystemS1/MyXml.xml"; } //获取message public static void initStrings(Properties pro){ XZHL0001_Constats.SERVRCEERROR=pro.getProperty("E0002", ""); XZHL0001_Constats.LIEBIAOSHIBAI=pro.getProperty("E0003", ""); XZHL0001_Constats.NETERROR=pro.getProperty("E0008", ""); XZHL0001_Constats.SHURUMZ=pro.getProperty("SHURUMZ", ""); XZHL0001_Constats.SHURUZH=pro.getProperty("SHURUZH", ""); XZHL0001_Constats.SHURUMM=pro.getProperty("SHURUMM", ""); XZHL0001_Constats.NEWVERSION=pro.getProperty("I011", ""); XZHL0001_Constats.DOWNLOAD=pro.getProperty("DOWNLOAD", ""); XZHL0001_Constats.ZIFUXIANZHI=pro.getProperty("ZIFUXIANZHI", ""); XZHL0001_Constats.FEIFALOGIN=pro.getProperty("FEIFALOGIN", ""); XZHL0001_Constats.VERSIONFUNCTION=pro.getProperty("VERSIONFUNCTION", ""); XZHL0001_Constats.LOGINING=pro.getProperty("LOGINING", ""); } }
package gmail.alexdudarkov.task02.dao.util; import gmail.alexdudarkov.task02.dao.exception.DAOException; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; public class Parser { private static final String FILE_NAME = "task02.xml"; public List<String> printFile() throws DAOException { InputStream inputStream = getInputStream(); List<String> tags = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { StringBuilder stringBuilder = new StringBuilder(); char c; int fileChar; do { fileChar = reader.read(); c = (char) fileChar; if (c == '<' || fileChar == -1) { String value = stringBuilder.toString().trim(); if (!value.isEmpty()) { tags.add(value); } stringBuilder.setLength(0); } stringBuilder.append(c); if (c == '>') { stringBuilder.append(c); tags.add(stringBuilder.toString().trim()); stringBuilder.setLength(0); } } while (fileChar != -1); } catch (IOException e) { throw new DAOException(e); } return tags; } private InputStream getInputStream() throws DAOException { URL urlConfig = this.getClass().getClassLoader().getResource(FILE_NAME); if (urlConfig == null) { throw new DAOException("file not found"); } InputStream inputStream; try { URLConnection urlConnection = urlConfig.openConnection(); inputStream = urlConnection.getInputStream(); } catch (IOException e) { throw new DAOException(e); } return inputStream; } }
package com.baytie.vo; import com.sz.util.json.Alias; import java.io.Serializable; /** * Created by PRINCE on 11/28/2016. */ public class MessageVO implements Serializable{ @Alias("id") private String id; @Alias("from") private String from; @Alias("to") private String to; @Alias("message") private String message; @Alias("is_read") private String is_read; @Alias("is_deleted") private String is_deleted; @Alias("is_updated") private String is_updated; @Alias("created_time") private String created_time; @Alias("updated_time") private String updated_time; public String getId(){ return id; } public void setId(String _id){ this.id = _id; } public String getFrom(){ return from; } public void setFrom(String _from){ this.id = _from; } public String getTo(){ return to; } public void setTo(String _to){ this.to = _to; } public String getMessage(){ return message; } public void setMessage(String message1){ this.message = message1; } public String getIs_read(){ return is_read; } public void setIs_read(String is_read1){ this.is_read = is_read1; } public String getIs_deleted(){ return is_deleted; } public void setIs_deleted(String is_deleted1){ this.is_deleted = is_deleted1; } public String getIs_updated(){ return is_updated; } public void setIs_updated(String is_updated1){ this.is_updated = is_updated1; } public String getCreated_time(){ return created_time; } public void setCreated_time(String created_time1){ this.created_time = created_time1; } public String getUpdated_time(){ return updated_time; } public void setUpdated_time(String updated_time1){ this.updated_time = updated_time1; } }
package com.shahinnazarov.gradle.models; import com.shahinnazarov.gradle.models.enums.K8sImagePullPolicies; import lombok.Data; import java.util.List; import java.util.Map; @Data public class K8sPodTemplateSpecContainer { private String name; private String image; private K8sImagePullPolicies imagePullPolicy; private List<K8sServiceSpecPort> ports; private Map<String, String> environments; private List<K8sPodTemplateSpecContainerVolumeMount> volumeMounts; public K8sPodTemplateSpecContainer(String name, String image, List<K8sServiceSpecPort> ports, Map<String, String> environments, List<K8sPodTemplateSpecContainerVolumeMount> volumeMounts) { this.name = name; this.image = image; this.ports = ports; this.environments = environments; this.volumeMounts = volumeMounts; } public K8sPodTemplateSpecContainer(String name, String image, List<K8sServiceSpecPort> ports, List<K8sPodTemplateSpecContainerVolumeMount> volumeMounts) { this.name = name; this.image = image; this.ports = ports; this.volumeMounts = volumeMounts; } public K8sPodTemplateSpecContainer(String name, String image, List<K8sPodTemplateSpecContainerVolumeMount> volumeMounts) { this.name = name; this.image = image; this.volumeMounts = volumeMounts; } public K8sPodTemplateSpecContainer(String name, String image, K8sImagePullPolicies imagePullPolicy, List<K8sServiceSpecPort> ports, Map<String, String> environments) { this.name = name; this.image = image; this.imagePullPolicy = imagePullPolicy; this.ports = ports; this.environments = environments; } }
package CFG.CNForm; import CFG.Helper.LogicProposition; import java.util.*; public class CNFDataBase{ public final RuleDataBase rdb; public final ActionDataBase adb; public CNFDataBase(RuleDataBase rdb, ActionDataBase adb){ this.rdb = rdb; this.adb = adb; } public CNFDataBase(){ this(new RuleDataBase(true), new ActionDataBase()); } public void clear(){ rdb.clear(); adb.clear(); } public void advanced(boolean b){ rdb.advanced = b; } public void add(CNFDataBase db){ add(db.rdb, db.adb); } public void add(RuleDataBase rdb, ActionDataBase adb){ if(rdb!=null){ this.rdb.add(rdb); } if(adb!=null){ this.adb.add(adb); } } // Rule methods public void addRule(CNFRule r) { addRule(r.id, r.options); } public void addRule(String key, List<String> replacements) { rdb.addRule(key, replacements); } public void addRule(String key, String replacement) { rdb.addRule(key, replacement); } public void removeRule(CNFRule r) { rdb.removeRule(r.id); } public void removeRule(String key) { rdb.removeRule(key); } public int grammarSize() { return rdb.grammarSize(); } public Set<String> keySet(boolean id) { return rdb.keySet(id); } public CNFRule rule(String key) { return rdb.rule(key); } public CNFRule rule(int idx) { return rdb.rule(idx); } public TreeSet<CNFRule> rulesForOption(String opt) { return rdb.rulesForOption(opt); } // Action methods public void addAction(CNFAction a) { adb.addAction(a); } public void removeRule(CNFAction a) { adb.removeRule(a); } public int responseSize() { return adb.responseSize(); } public CNFAction action(int idx) { return adb.action(idx); } public List<CNFAction> actionForRule(String ruleID) { return adb.actionForRule(ruleID); } @Override public String toString() { return rdb+"\n"+adb; } } class RuleDataBase { /* Rule: - key |<- String - values it can take |<- Arraylist of Strings For simplicity, you'd need to be able to: - get a rule by ID |<- using a hashmap that maps an ID to a rule (1 to 1) - get a rule by index (for CYK?) |<- Arraylist of rules (1 to 1) - get all rules that can be replaced by an option |<- Hashmap that maps an option to a list of rules (1 to many) - get all options that a rule can take |<- in rule object (1 to many) */ protected final HashMap<String, CNFRule> keyToRule; // ID -> Rule protected final HashMap<String, TreeSet<CNFRule>> optionToRule; // Option -> Rules protected final List<CNFRule> ruleList; // Index -> Rule protected boolean advanced; // True if you want to work with logical components (<%dType *logical prop*%>) protected final HashMap<String, LogicProposition> logicOption; // Logic Option <%dType *logical prop*%>-> Rules public RuleDataBase(boolean advanced) { this.advanced = advanced; keyToRule = new HashMap<>(); ruleList = new ArrayList<>(); optionToRule = new HashMap<>(); // Logical add-on if(advanced) { logicOption = new HashMap<>(); }else{ logicOption = null; } CNFConverter.addSpecialChar(this); } public void clear(){ keyToRule.clear(); optionToRule.clear(); ruleList.clear(); logicOption.clear(); } public void add(RuleDataBase rdb) { for (CNFRule r : rdb.ruleList) { addRule(r); } } public void addRule(CNFRule r) { addRule(r.id, r.options); } public void addRule(String key, List<String> replacements) { replacements.forEach(r -> addRule(key, r)); } public void addRule(String key, String replacement) { if (keyToRule.containsKey(key)) { CNFRule r1 = keyToRule.get(key); r1.add(replacement); } else { CNFRule r = new CNFRule(key); r.add(replacement); r.index = ruleList.size(); ruleList.add(r); keyToRule.put(key, r); } if (!optionToRule.containsKey(replacement)) { optionToRule.put(replacement, new TreeSet<>()); } optionToRule.get(replacement).add(rule(key)); // Logical add-on if(advanced){ addRuleLogic(replacement); } } public void removeRule(CNFRule r) { removeRule(r.id); } public void removeRule(String key) { CNFRule r = keyToRule.remove(key); for (int j = r.index; j < ruleList.size(); j++) { ruleList.get(j).index--; } ruleList.remove(r.index); r.options.forEach(o -> optionToRule.get(o).remove(r)); } private void addRuleLogic(String replacement){ if(replacement.matches("<%.+%>")){ logicOption.put(replacement,LogicProposition.create(replacement)); } } public int grammarSize() { return ruleList.size(); } /** * * @param id true for all rule IDs, true for all rule options * @return */ public Set<String> keySet(boolean id) { return id? keyToRule.keySet() : optionToRule.keySet(); } public CNFRule rule(String key) { return keyToRule.get(key); } public CNFRule rule(int idx) { return ruleList.get(idx); } public TreeSet<CNFRule> rulesForOption(String opt) { TreeSet<CNFRule> rules = new TreeSet<>(); TreeSet<CNFRule> r = optionToRule.get(opt); if(r!=null) { rules.addAll(r); } if(advanced && !opt.matches(".*<\\w+>.*")){ // dk why !opt.matches(".*<\\w+>.*") rules.addAll(rulesForOptionLogic(opt)); } return rules; } private TreeSet<CNFRule> rulesForOptionLogic(String opt){ TreeSet<CNFRule> rules = new TreeSet<>(); for (String k : logicOption.keySet()) { if(logicOption.get(k).match(opt)){ rules.addAll(optionToRule.get(logicOption.get(k).full)); } } return rules; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("RULES (").append(ruleList.size()).append("):\n"); for (CNFRule rule : ruleList) { sb.append("\t-").append(rule).append("\n"); } return sb.toString(); } public static List<String> ruleIDs(TreeSet<CNFRule> r) { if (r == null || r.size()==0) { return new ArrayList<>(); } List<String> s = new ArrayList<>(); r.forEach(rule -> s.add(rule.id)); return s; } } class ActionDataBase{ /* Action: - response |<- String (!!! can take variables ex: I am not <adjective>; find a way to deal with this) - pre requisites |<- Arraylist of PreRequisites (Stores rule ID, wanted value and strength of this pre req) For simplicity, you'd need to be able to: - get action by index |<- LinkedList of Actions (1 to 1) - get all actions that use a given rule as pre req |<- Hashmap String (rule ID) to List of Actions (1 to many) - get all pre reqs needed for an action |<- in action object (many to 1) - get response for a given action |<- in action object (1 to 1) */ protected final LinkedList<CNFAction> actionList; protected final HashMap<String, List<CNFAction>> ruleToAction; public ActionDataBase() { actionList = new LinkedList<>(); ruleToAction = new HashMap<>(); } public void clear() { actionList.clear(); ruleToAction.clear(); } public void add(ActionDataBase adb) { for (CNFAction a : adb.actionList) { addAction(a); } } public void addAction(CNFAction a) { actionList.add(a); for (PreRequisite preRequisite : a.preRequisites) { if(!ruleToAction.containsKey(preRequisite.ruleID)){ ruleToAction.put(preRequisite.ruleID, new ArrayList<>()); } ruleToAction.get(preRequisite.ruleID).add(a); } } public void removeRule(CNFAction a) { actionList.remove(a); for (PreRequisite preRequisite : a.preRequisites) { ruleToAction.get(preRequisite.ruleID).remove(a); } } public int responseSize() { return actionList.size(); } public CNFAction action(int idx) { return actionList.get(idx); } public List<CNFAction> actionForRule(String ruleID) { return ruleToAction.get(ruleID); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Actions (").append(actionList.size()).append("):\n"); for (CNFAction a : actionList) { sb.append("\t-").append(a).append("\n"); } return sb.toString(); } }
/* * Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.ldap.client; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pl.edu.icm.unity.server.api.PKIManagement; import pl.edu.icm.unity.server.api.userimport.UserImportSPI; import pl.edu.icm.unity.server.api.userimport.UserImportSPIFactory; /** * Imports user from LDAP. Shares similar code and configuration with the LDAP verificator, however * does not verify user's password, and bindAs=user is not allowed. * @author K. Benedyczak */ @Component public class LdapImporterFactory implements UserImportSPIFactory { public static final String NAME = "ldap"; private final PKIManagement pkiManagement; @Autowired public LdapImporterFactory(PKIManagement pkiManagement) { this.pkiManagement = pkiManagement; } @Override public String getName() { return NAME; } @Override public UserImportSPI getInstance(Properties configuration, String idpName) { return new LdapImporter(pkiManagement, configuration, idpName); } }
//package com.example.huydaoduc.hieu.chi.hhapp.Main.Driver.RouteRequestManager; // //import android.content.Context; //import android.net.Uri; //import android.os.Bundle; //import android.support.v4.app.Fragment; //import android.support.v7.widget.LinearLayoutManager; //import android.support.v7.widget.RecyclerView; //import android.view.LayoutInflater; //import android.view.View; //import android.view.ViewGroup; // //import com.example.huydaoduc.hieu.chi.hhapp.Define; //import com.example.huydaoduc.hieu.chi.hhapp.Model.Passenger.PassengerRequest; //import com.example.huydaoduc.hieu.chi.hhapp.Model.RouteRequest.RouteRequest; //import com.example.huydaoduc.hieu.chi.hhapp.R; //import com.google.firebase.auth.FirebaseAuth; //import com.google.firebase.database.DataSnapshot; //import com.google.firebase.database.DatabaseError; //import com.google.firebase.database.DatabaseReference; //import com.google.firebase.database.FirebaseDatabase; //import com.google.firebase.database.ValueEventListener; //import com.scwang.smartrefresh.layout.SmartRefreshLayout; //import com.scwang.smartrefresh.layout.api.RefreshLayout; //import com.scwang.smartrefresh.layout.listener.OnRefreshListener; //import com.zaaach.toprightmenu.MenuItem; //import com.zaaach.toprightmenu.TopRightMenu; // //import java.util.ArrayList; //import java.util.Collections; //import java.util.List; // //public class WaitingPassengerRequestManagerFragment extends Fragment { // // private OnWaitingPassengerRequestManagerListener mListener; // public interface OnWaitingPassengerRequestManagerListener { // void onFragmentInteraction(Uri uri); // } // @Override // public void onAttach(Context context) { // super.onAttach(context); // if (context instanceof OnWaitingPassengerRequestManagerListener) { // mListener = (OnWaitingPassengerRequestManagerListener) context; // } else { // throw new RuntimeException(context.toString() // + " must implement OnRouteRequestManagerFragmentListener"); // } // } // @Override // public void onDetach() { // super.onDetach(); // mListener = null; // } // // public WaitingPassengerRequestManagerFragment() { // } // // public static WaitingPassengerRequestManagerFragment newInstance(String param1, String param2) { // WaitingPassengerRequestManagerFragment fragment = new WaitingPassengerRequestManagerFragment(); // Bundle args = new Bundle(); //// args.putString(ARG_PARAM1, param1); // fragment.setArguments(args); // return fragment; // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if (getArguments() != null) { //// mParam1 = getArguments().getString(ARG_PARAM1); // } // } // // private String getCurUid() { // return FirebaseAuth.getInstance().getCurrentUser().getUid(); // } // // RecyclerView rycv_request; // List<PassengerRequest> passengerRequests; // // DatabaseReference dbRefe; // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_waiting_passenger_request_manager, container, false); // // Init(view); // // Event(view); // // refreshList(true); // // return view; // } // // private void Init(View view) { // //view // // // recycler // initRecyclerView(view); // // passengerRequests = new ArrayList<>(); // // // init database // dbRefe = FirebaseDatabase.getInstance().getReference(); // // initRefeshLayout(view); // // } // // private void Event(View view) { // // } // // //region -------------- Recycle View ---------------- // private void initRecyclerView(View view) { // rycv_request = view.findViewById(R.id.recycler_view_requests); // LinearLayoutManager llm = new LinearLayoutManager(getContext()); // llm.setOrientation(LinearLayoutManager.VERTICAL); // rycv_request.setLayoutManager(llm); // } // // private void refreshList(boolean enableLoading) { // if (enableLoading) // startLoading(); // // FirebaseDatabase.getInstance().getReference() // .child(Define.DB_ROUTE_REQUESTS) // .child(getCurUid()) // .addListenerForSingleValueEvent(new ValueEventListener() { // @Override // public void onDataChange(DataSnapshot dataSnapshot) { // passengerRequests.clear(); // for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) { // PassengerRequest request = postSnapshot.getValue(PassengerRequest.class); // // passengerRequests.add(request); // } // // Collections.reverse(passengerRequests); // // // Route request Row click event // RouteRequestAdapter adapter = new RouteRequestAdapter(passengerRequests); // adapter.setOnItemChildClickListener((adapter1, view, position) -> { // if (view.getId() == R.id.iv_menu) { // showTopRightMenuItem(position, view); // } // if (view.getId() == R.id.btn_request_state) { // // // } // }); // // rycv_request.setAdapter(adapter); // stopLoading(); // } // // @Override // public void onCancelled(DatabaseError databaseError) { // // } // }); // } // // private void showTopRightMenuItem(int position, View view) { // TopRightMenu topRightMenu; // topRightMenu = new TopRightMenu(getActivity()); // // List<MenuItem> menuItems = new ArrayList<>(); // menuItems.add( new MenuItem(R.drawable.ic_pause_20, getString(R.string.pause))); // menuItems.add( new MenuItem(R.drawable.ic_delete_20, getString(R.string.delete))); // menuItems.add( new MenuItem(R.drawable.ic_resume_20, getString(R.string.resume))); // // topRightMenu // .setHeight(340) // .setWidth(320) // .showIcon(true) // .dimBackground(true) // .needAnimationStyle(true) // .setAnimationStyle(R.style.TRM_ANIM_STYLE) // .addMenuList(menuItems) // .setOnMenuItemClickListener(new TopRightMenu.OnMenuItemClickListener() { // @Override // public void onMenuItemClick(int menuPosition) { // String command = null; // // if (menuPosition == 0) { // command = "Pause"; // } else if (menuPosition == 1) { // command = "Delete"; // } else if (menuPosition == 2) { // command = "Resume"; // } // // changeRouteRequestState(position, command); // } // }) // .showAsDropDown(view, -250, 0); //带偏移量 // } // // //endregion // // //region -------------- Smart Refresh Layout ---------------- // // SmartRefreshLayout smartRefreshLayout; // // private void initRefeshLayout(View view) { // smartRefreshLayout = (SmartRefreshLayout) view.findViewById(R.id.refreshLayout); // smartRefreshLayout.setEnableLoadMore(false); // smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() { // @Override // public void onRefresh(RefreshLayout refreshlayout) { // refreshList(true); // } // }); // } // // private void startLoading() { // smartRefreshLayout.autoRefresh(); // // } // // private void stopLoading() { // smartRefreshLayout.finishRefresh(500); // } // // //endregion //}
/** * MIT License * <p> * Copyright (c) 2019-2022 nerve.network * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package network.nerve.converter.core.heterogeneous.callback.interfaces; import io.nuls.core.basic.Result; import java.math.BigInteger; /** * @author: Mimi * @date: 2020-02-17 */ public interface IDepositTxSubmitter { /** * @param txHash 交易hash * @param blockHeight 交易确认高度 * @param from 转出地址 * @param to 转入地址 * @param value 转账金额 * @param txTime 交易时间 * @param decimals 资产小数位数 * @param ifContractAsset 是否为合约资产 * @param contractAddress 合约地址 * @param assetId 资产ID * @param nerveAddress Nerve充值地址 * @param extend */ String txSubmit(String txHash, Long blockHeight, String from, String to, BigInteger value, Long txTime, Integer decimals, Boolean ifContractAsset, String contractAddress, Integer assetId, String nerveAddress, String extend) throws Exception; String depositIITxSubmit(String txHash, Long blockHeight, String from, String to, BigInteger erc20Value, Long txTime, Integer erc20Decimals, String erc20ContractAddress, Integer erc20AssetId, String nerveAddress, BigInteger mainAssetValue, String extend) throws Exception; String oneClickCrossChainTxSubmit(String txHash, Long blockHeight, String from, String to, BigInteger erc20Value, Long txTime, Integer erc20Decimals, String erc20ContractAddress, Integer erc20AssetId, String nerveAddress, BigInteger mainAssetValue, BigInteger mainAssetFeeAmount, int desChainId, String desToAddress, BigInteger tipping, String tippingAddress, String desExtend) throws Exception; String addFeeCrossChainTxSubmit(String txHash, Long blockHeight, String from, String to, Long txTime, String nerveAddress, BigInteger mainAssetValue, String nerveTxHash, String subExtend) throws Exception; /** * @param txHash 交易hash * @param blockHeight 交易确认高度 * @param from 转出地址 * @param to 转入地址 * @param value 转账金额 * @param txTime 交易时间 * @param decimals 资产小数位数 * @param ifContractAsset 是否为合约资产 * @param contractAddress 合约地址 * @param assetId 资产ID * @param nerveAddress Nerve充值地址 */ String pendingTxSubmit(String txHash, Long blockHeight, String from, String to, BigInteger value, Long txTime, Integer decimals, Boolean ifContractAsset, String contractAddress, Integer assetId, String nerveAddress) throws Exception; String pendingDepositIITxSubmit(String txHash, Long blockHeight, String from, String to, BigInteger erc20Value, Long txTime, Integer erc20Decimals, String erc20ContractAddress, Integer erc20AssetId, String nerveAddress, BigInteger mainAssetValue) throws Exception; String pendingOneClickCrossChainTxSubmit(String txHash, Long blockHeight, String from, String to, BigInteger erc20Value, Long txTime, Integer erc20Decimals, String erc20ContractAddress, Integer erc20AssetId, String nerveAddress, BigInteger mainAssetValue, BigInteger mainAssetFeeAmount, int desChainId, String desToAddress, BigInteger tipping, String tippingAddress, String desExtend) throws Exception; /** * 验证是否充值交易 * @param hTxHash 异构链交易hash */ Result validateDepositTx(String hTxHash) ; }
package com.teaboot.context.common; public class ValuePair { Object value; Object pair; public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public Object getPair() { return pair; } public void setPair(Object pair) { this.pair = pair; } }
package com.test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.test.base.Solution; /** * 三层遍历 * * 算法复杂度:n*log(n) + n*n*n = n*n*n * * @author YLine * * 2018年8月13日 下午2:31:37 */ public class SolutionA implements Solution { /** * 暴力 遍历,复杂度高了 * @param nums * @return */ @Override public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new ArrayList<>(); int first = 0, tempFirst; int tempOpposite; int length = nums.length; Arrays.sort(nums); if (length < 3) { return result; } while (first < length - 2) { // 如果最小的数,都大于0之后,结束循环 if (nums[first] > 0) { break; } tempOpposite = 0 - nums[first]; for (int i = first + 1; i < length; i++) { for (int j = i + 1; j < length; j++) { if (nums[i] + nums[j] == tempOpposite) { setResult(result, nums[first], nums[i], nums[j]); break; } else if (nums[i] + nums[j] > tempOpposite) { break; } } } tempFirst = first + 1; for (int i = tempFirst; i < length; i++) { if (nums[first] == nums[tempFirst]) { tempFirst++; } } first = tempFirst; } return result; } private void setResult(List<List<Integer>> result, int one, int two, int three) { for (List<Integer> list : result) { if (list.get(0) == one && list.get(1) == two) { return; } } List<Integer> tempResult = new ArrayList<>(); tempResult.add(one); tempResult.add(two); tempResult.add(three); result.add(tempResult); } }
package com.stock.entity; import lombok.*; import java.math.BigDecimal; @AllArgsConstructor @NoArgsConstructor @Builder @Data @With public class StockWithClassification { private int id; private String name; private int items; private BigDecimal valueStock; private ClassificationStock classification; private int rateConsumer; }
/* // Definition for a Node. class Node { public int val; public Node prev; public Node next; public Node child; }; */ class Solution { Node output=new Node(-1); Node pre=output; public Node flatten(Node head) { if(head==null){ return head; } recursion(head); pre=pre.next; pre.prev=null; return pre; } public void recursion(Node head){ if(head==null){ return; } output.next=head; head.prev=output; output=output.next; Node next=head.next; if( head.child!=null){ recursion(head.child); head.child=null; } recursion(next); } }
package com.frostwire.alexandria; import java.io.File; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.frostwire.alexandria.db.InternetRadioStationDB; import com.frostwire.alexandria.db.LibraryDB; import com.frostwire.alexandria.db.LibraryDatabase; import com.frostwire.alexandria.db.LibraryDatabaseEntity; import com.frostwire.alexandria.db.PlaylistDB; public class Library extends LibraryDatabaseEntity { private int _id; private String _name; private int _version; public Library(File libraryFile) { super(new LibraryDatabase(libraryFile)); LibraryDB.fill(db, this); } public int getId() { return _id; } public void setId(int id) { _id = id; } public String getName() { return _name; } public void setName(String name) { _name = name; } public int getVersion() { return _version; } public void setVersion(int version) { _version = version; } public void close() { db.close(); } public List<Playlist> getPlaylists() { // perform name sort here. It is no the best place List<Playlist> list = PlaylistDB.getPlaylists(db); Collections.sort(list, new Comparator<Playlist>() { @Override public int compare(Playlist o1, Playlist o2) { return o1.getName().compareTo(o2.getName()); } }); return list; } public Playlist getPlaylist(String name) { return PlaylistDB.getPlaylist(db, name); } public List<InternetRadioStation> getInternetRadioStations() { return InternetRadioStationDB.getInternetRadioStations(db); } public Playlist newPlaylist(String name, String description) { return new Playlist(db, LibraryDatabase.OBJECT_NOT_SAVED_ID, name, description); } public InternetRadioStation newInternetRadioStation(String name, String description, String url, String bitrate, String type, String website, String genre, String pls, boolean bookmarked) { return new InternetRadioStation(db, LibraryDatabase.OBJECT_NOT_SAVED_ID, name, description, url, bitrate, type, website, genre, pls, bookmarked); } public void dump() { db.dump(); } @Override protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } public Playlist getStarredPlaylist() { return PlaylistDB.getStarredPlaylist(db); } public void updatePlaylistItemProperties(String filePath, String title, String artist, String album, String comment, String genre, String track, String year) { PlaylistDB.updatePlaylistItemProperties(db, filePath, title, artist, album, comment, genre, track, year); } public long getTotalRadioStations() { return InternetRadioStationDB.getTotalRadioStations(db); } public void restoreDefaultRadioStations() { InternetRadioStationDB.restoreDefaultRadioStations(db); } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler.ext.matsci.client; import org.ow2.proactive.scheduler.common.exception.SchedulerException; import javax.security.auth.login.LoginException; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.security.KeyException; /** * LoginFrame * * @author The ProActive Team */ public class LoginFrame<E extends AOMatSciEnvironment> extends JDialog { /** */ private static final long serialVersionUID = 31L; private JTextField username; private JPasswordField password; private E aose; private JButton login; private boolean loginSuccessful = false; private boolean recordListener = false; private int nb_attempts = 0; public static final int MAX_NB_ATTEMPTS = 3; /** * Creates a new LoginFrame */ public LoginFrame(E aose, boolean recordListener) { this.aose = aose; this.recordListener = recordListener; initComponents(); pack(); // Center the component Toolkit tk = Toolkit.getDefaultToolkit(); Dimension size = tk.getScreenSize(); int x = (size.width / 2) - (getWidth() / 2); int y = (size.height / 2) - (getHeight() / 2); setLocation(x, y); } public void initComponents() { setDefaultCloseOperation(DISPOSE_ON_CLOSE); JPanel cp = new JPanel(new GridBagLayout()); cp.setBorder(new EmptyBorder(5, 5, 5, 5)); JLabel usernameLabel = new JLabel("Username:"); cp.add(usernameLabel, getConstraints(0, 0, 1, 1)); username = new JTextField(15); cp.add(username, getConstraints(1, 0, 1, 1)); JLabel passwordLabel = new JLabel("Password:"); cp.add(passwordLabel, getConstraints(0, 1, 1, 1)); password = new JPasswordField(15); cp.add(password, getConstraints(1, 1, 1, 1)); login = new JButton("Login"); if (recordListener) { login.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { checkLogin(); } }); } cp.add(login, getConstraints(1, 2, 1, 1)); setContentPane(cp); } public void start() { this.setVisible(true); } public JButton getLoginButton() { return login; } public boolean checkLogin() { nb_attempts++; String name = username.getText(); String pwd = new String(password.getPassword()); try { aose.login(name, pwd); dispose(); return true; } catch (KeyException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(LoginFrame.this, "Incorrect Credential Key.", "Login Error", JOptionPane.ERROR_MESSAGE); } catch (LoginException ex) { JOptionPane.showMessageDialog(LoginFrame.this, "Incorrect username/password combination.", "Login Error", JOptionPane.ERROR_MESSAGE); } catch (SchedulerException ex2) { ex2.printStackTrace(); JOptionPane.showMessageDialog(LoginFrame.this, ex2.getMessage(), "Login Error", JOptionPane.ERROR_MESSAGE); } if (nb_attempts > MAX_NB_ATTEMPTS) { dispose(); } return false; } public int getNbAttempts() { return nb_attempts; } private GridBagConstraints getConstraints(int x, int y, int width, int height) { GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = x; constraints.gridy = y; constraints.gridwidth = width; constraints.gridheight = height; constraints.anchor = constraints.CENTER; constraints.fill = constraints.BOTH; return constraints; } }
package home_work_1.txt; public class Txt2 { public static void main(String[] args) { int num = 8; int num1 = 2; int a = 5 + 2 / num; //деление потом сложение получается 5 System.out.println(a); int b = (5 + 2) / num; //сначало то что в скобках потом деление получается 0 System.out.println(b); int c = (5 + num1++) / num; //сначала ++ потом скобки и потом деление получается (5+7)/8 = 0 System.out.println(c); int d = (5 + num1++) / --num; // (5+2)/7 = 1 сначала ++ и -- потом по накатанной System.out.println(d); int e = (5 * 2 >> num1++) / num; //(10>>2)/8 = 2/8=0 num1 = 2; System.out.println(e); int test = 10 >> 2; System.out.println("тест " + test); int f = (5 + 7 > 20 ? 68 : 22 * 2 >> num1++) / --num; //(5 + 7 > 20 ? 68 : 22 * 2 >> 2) / 7; потом (12 > 20 ? 68 : 44 >> 2) / 7 потом (12 > 20 ? 68 : 44 >> 2)/7 потом (false ? 68 :11)/7 потом 11/7 b и у меня получается 1 int test1 = 44 >> 2; System.out.println("тест " + test1); System.out.println(f); //int g = (5 + 7 > 20 ? 68 >= 68 : 22 * 2 >> num1++) / --num; //ошибка компиляции тк булевое значение нельзя поделить на число boolean g1 = 6 - 2 > 3 && 12 * 12 <= 119; //4 > 3 && 24 <=119 потом true && 144 <=119 потом true && false потом false System.out.println(g1); boolean k = true && false; //false System.out.println(k); } }
package task5.tddremoveA; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class RemoveATest { /* * TODO List: * 1. First 2 char 'A' AABABA ==> BABA -success * 2. First char 'A' ABAABA ==> BAABA * 3. Second char 'A' BAAAAA ==> BAAAA * 4. First 2 char 'A'(Total String) AA ==> "" * 5. First char 'A'(Total String) ==>"" * 5. Empty char " " ==> " " */ RemoveA r; @BeforeEach void ObjectCreation() { r=new RemoveA(); } @Test void testFirst2Char() { assertEquals("BABA",r.remove("AABABA")); } @Test void testFirstChar() { assertEquals("BAABA",r.remove("ABAABA")); } @Test void testSecondChar() { assertEquals("BAAAA",r.remove("BAAAAA")); } @Test void testTotalA() { assertEquals("",r.remove("AA")); } @Test void testOnlyA() { assertEquals("",r.remove("A")); } @Test void testEmptyString() { assertEquals(" ",r.remove(" ")); } }
package sample.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import utils.Utils; @Controller public class AdminHomeController { @RequestMapping("/adminHome.html") public String showHomeAdmin(HttpServletRequest request, HttpServletResponse response) { Utils.checkRole(request, response); return "adminHome"; } }
package us.spring.dayary.common.tool; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.Key; import java.util.Base64; import java.util.HashMap; import java.util.Map; public class AES { private static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5PADDING"; private static final String AES = "AES"; private static final String UTF_8 = "UTF-8"; public static Map<String, Object> getIvKeySpec(String key) throws Exception { String iv = key; Key keySpec = new SecretKeySpec(key.getBytes(UTF_8), AES); return new HashMap<>() { { put("iv", iv); put("keySpec", keySpec); } }; } public static String encode(String str, String key) throws Exception { Map<String, Object> data = getIvKeySpec(key); String iv = (String) data.get("iv"); Key keySpec = (Key) data.get("keySpec"); Cipher c = Cipher.getInstance(AES_CBC_PKCS5PADDING); c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes())); byte[] encrypted = c.doFinal(str.getBytes(UTF_8)); String enStr = Base64.getEncoder().encodeToString(encrypted); return enStr; } public static String decode(String str, String key) throws Exception { Map<String, Object> data = getIvKeySpec(key); String iv = (String) data.get("iv"); Key keySpec = (Key) data.get("keySpec"); Cipher c = Cipher.getInstance(AES_CBC_PKCS5PADDING); c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes(UTF_8))); byte[] byteStr = Base64.getDecoder().decode(str); return new String(c.doFinal(byteStr), UTF_8); } }
package com.wz.week_3; import com.algorithm.tree.TreeNode; import java.util.ArrayList; import java.util.List; public class KthLargest { public List<Integer> list = new ArrayList<>(); public int ret; public int kthLargest(TreeNode root, int k) { if(root == null){ return 0; } kthLargest(root.right,k); int val = root.val; list.add(val); if(k == list.size()){ ret = val; return ret; } kthLargest(root.left,k); return ret; } }
/* * Copyright (C) 2011 The Baremaps 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 * * 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.baremaps.osm.model; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; public final class Node implements Entity { private final Info info; private final double lon; private final double lat; public Node(Info info, double lon, double lat) { checkNotNull(info); this.info = info; this.lon = lon; this.lat = lat; } @Override public Info getInfo() { return info; } public double getLon() { return lon; } public double getLat() { return lat; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Node node = (Node) o; return Double.compare(node.lon, lon) == 0 && Double.compare(node.lat, lat) == 0 && Objects.equal(info, node.info); } @Override public int hashCode() { return Objects.hashCode(info, lon, lat); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("info", info) .add("lon", lon) .add("lat", lat) .toString(); } }
//import java.util.Scanner; //3.求1+2+3+....+100的和。 public class zuoye3 { public static void main(String[] args) { // TODO Auto-generated method stub int i = 0 ; int sum = 0 ; while(i<100){sum+=i;i++;} System.out.println("1+2+3+....+100的和:"+sum); } }
/* * Copyright 2002-2017 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.ui.freemarker; import java.io.IOException; import freemarker.template.Configuration; import freemarker.template.TemplateException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ResourceLoaderAware; import org.springframework.lang.Nullable; /** * Factory bean that creates a FreeMarker Configuration and provides it as * bean reference. This bean is intended for any kind of usage of FreeMarker * in application code, e.g. for generating email content. For web views, * FreeMarkerConfigurer is used to set up a FreeMarkerConfigurationFactory. * * The simplest way to use this class is to specify just a "templateLoaderPath"; * you do not need any further configuration then. For example, in a web * application context: * * <pre class="code"> &lt;bean id="freemarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean"&gt; * &lt;property name="templateLoaderPath" value="/WEB-INF/freemarker/"/&gt; * &lt;/bean&gt;</pre> * See the base class FreeMarkerConfigurationFactory for configuration details. * * <p>Note: Spring's FreeMarker support requires FreeMarker 2.3 or higher. * * @author Darren Davison * @since 03.03.2004 * @see #setConfigLocation * @see #setFreemarkerSettings * @see #setTemplateLoaderPath * @see org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer */ public class FreeMarkerConfigurationFactoryBean extends FreeMarkerConfigurationFactory implements FactoryBean<Configuration>, InitializingBean, ResourceLoaderAware { @Nullable private Configuration configuration; @Override public void afterPropertiesSet() throws IOException, TemplateException { this.configuration = createConfiguration(); } @Override @Nullable public Configuration getObject() { return this.configuration; } @Override public Class<? extends Configuration> getObjectType() { return Configuration.class; } @Override public boolean isSingleton() { return true; } }
package com.example.main.requests; /** * Created by sergeigavrilko on 11.10.16. */ public final class CreateUser{ private String username; private String about; private boolean isAnonymous; private String name; private String email; private int id; public CreateUser(){ } public void setId(int id) { this.id = id; } public CreateUser(String username, String about, boolean isAnonymous, String name, String email) { this.username = username; this.about = about; this.isAnonymous = isAnonymous; this.name = name; this.email = email; } public String getUsername() { return username; } public String getAbout() { return about; } public boolean getIsAnonymous() { return isAnonymous; } public String getName() { return name; } public String getEmail() { return email; } public void setUsername(String username) { this.username = username; } public void setAbout(String about) { this.about = about; } public void setAnonymous(boolean anonymous) { isAnonymous = anonymous; } public void setName(String name) { this.name = name; } public void setEmail(String email) { this.email = email; } public int getId() { return id; } }
package com.codecool.stampcollection.repository; import com.codecool.stampcollection.model.Stamp; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface StampRepository extends JpaRepository<Stamp, Long> { List<Stamp> findAllByCountry(String country); List<Stamp> findAllByYearOfIssue(Integer year); List<Stamp> findAllByCountryAndYearOfIssue(String country, Integer year); Long countStampByCountryAndYearOfIssueAndName(String country, Integer year, String name); }
package com.gxjtkyy.standardcloud.common.domain.dto; import com.gxjtkyy.standardcloud.common.domain.info.SheetInfo; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.springframework.data.annotation.Id; import java.util.LinkedHashSet; import java.util.List; /** * 模板数据传输对象 * @Package com.gxjtkyy.standardcloud.common.domain.dto * @Author lizhenhua * @Date 2018/7/1 22:25 */ @Setter @Getter @ToString(callSuper = true) public class TemplateDTO extends BaseDTO{ /**id*/ @Id private String id; /**模板名称*/ private String templateName; /**模板描述*/ private String templateDesc; /**文档类型*/ private int docType; /**0 无效 1有效*/ private Integer status; /**模板目录*/ private List<SheetInfo> catalog; /**导航*/ private LinkedHashSet<String> navigation = new LinkedHashSet<>(); }
package kr.purred.playground.startboot.data; import lombok.Data; @Data public class PointData { private String memberID; private int point; public PointData (String memberID, int point) { this.memberID = memberID; this.point = point; } }
/* * 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 View.HomePage; import Bean.UserBean; import View.Login.LoginFrm; import View.UCManageDish.DishCtrFrm; /** * * @author ASUS */ public class HomePageFrm extends javax.swing.JFrame { /** * Creates new form HomePageFrm */ private UserBean user; public HomePageFrm(UserBean us) { initComponents(); setVisible(true); setLocationRelativeTo(null); btnManageDish.setEnabled(false); this.user=us; setInfor(); setPermisstion(); System.out.println(user.getPosition()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); btnLogout = new javax.swing.JButton(); labelInfor = new javax.swing.JLabel(); btnManageDish = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(255, 204, 204)); btnLogout.setText("log out"); btnLogout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLogoutActionPerformed(evt); } }); labelInfor.setText("jLabel1"); btnManageDish.setText("quản lý món"); btnManageDish.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnManageDishActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(labelInfor, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnLogout)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(btnManageDish, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(34, 34, 34)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelInfor, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnLogout)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 176, Short.MAX_VALUE) .addComponent(btnManageDish, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnManageDishActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnManageDishActionPerformed // TODO add your handling code here: new DishCtrFrm(); }//GEN-LAST:event_btnManageDishActionPerformed private void btnLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogoutActionPerformed // TODO add your handling code here: this.setVisible(false); new LoginFrm(); }//GEN-LAST:event_btnLogoutActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnLogout; private javax.swing.JButton btnManageDish; private javax.swing.JPanel jPanel1; private javax.swing.JLabel labelInfor; // End of variables declaration//GEN-END:variables private void setInfor() { labelInfor.setText("xin chao "+user.getPosition()+" "+user.getFullName()); } private void setPermisstion() { if(user.getPosition().equals("manager")){ btnManageDish.setEnabled(true); } } }
package com.xyzj.crawler.utils.gethtmlstring; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; /** * 爬虫辅助工具类 * * @author TongWei.Chen 2017-05-17 10:15:45 */ @Slf4j public class HttpClientHelper { public static String post(String url, Map<String, String> params,String charset) { if (StringUtils.isEmpty(charset)) { charset = "UTF-8"; } try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (!CollectionUtils.isEmpty(params)) { Set<String> keys = params.keySet(); for (String key : keys) { nameValuePairs.add(new BasicNameValuePair(key, params.get(key))); } } CloseableHttpClient httpClient = HttpClients.custom().build(); HttpPost httpPost = new HttpPost(url); UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nameValuePairs, charset); httpPost.setEntity(uefEntity); CloseableHttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, charset); response.close(); httpPost.releaseConnection(); httpClient.close(); return result; }else{ return null; } } catch (Exception e) { log.error("Exception:{}",e); return null; } } /** * 请求一个url,返回结果 * * @param url:url * @return */ public static String get(String url,String charset) { if (StringUtils.isEmpty(charset)) { charset = "UTF-8"; } try { CloseableHttpClient httpClient = HttpClients.custom().build(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, charset); response.close(); httpGet.releaseConnection(); httpClient.close(); return result; }else{ return null; } } catch (Exception e) { log.error("Exception:{}",e); return null; } } }
package JDBC; import javax.swing.plaf.nimbus.State; import java.sql.*; public class MySQL { private static String url="jdbc:mysql://localhost::3306/book"; private static String username="root"; private static String password="liu200045."; private static String driverName="com.mysql.jdbc.Driver"; static{ try{ Class.forName(driverName); }catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection()throws SQLException{ return DriverManager.getConnection(url,username,password); } public static void release(ResultSet rs, Statement st,Connection conn){ try{ if(rs!=null) rs.close(); if(st!=null) st.close(); if(conn!=null) conn.close(); } catch (SQLException e) { } } }
package com.justcode.hxl.viewutil.自定义View.绘制1_1.饼图.interfaces; import com.justcode.hxl.viewutil.自定义View.绘制1_1.饼图.entry.PieEntry; ; public interface OnSectorChangeListener <T extends PieEntry> { /** * * @param pieEntry * @param cx * @param cy * @param radius * @param source BaseSectorDrawable.Source */ void onSectorChange(T pieEntry,int cx,int cy,int radius,int source); }
package com.tntdjs.midi.controllers; import javax.sound.midi.MidiMessage; import com.tntdjs.midi.IMidiExecuter; import com.tntdjs.midi.controllers.data.config.MidiDeviceXMLHelper; import com.tntdjs.midi.controllers.data.config.objects.MidiButton; import com.tntdjs.midi.executer.ExecuterFactory; /** * * @author tsenauskas * */ public class MIDIInputReceiver extends AbstractMidiInputReceiver { private static final int BANK = 0; // private IValidation validator = new MidiButtonEnabledValidator(); /** * * @param MidiNote * @return */ protected boolean isButtonEnabled(int MidiNote) { for (MidiButton button : MidiDeviceXMLHelper.getInstance().getMidiButtonSet(BANK)) { if (button.getMidiNote().equals(MidiNote)) { // && button.getEnabled()) { // return validator.isValid(button); return button.test(); } } return false; } /** * Send */ public void send(MidiMessage msg, long timeStamp) { int offSet1 = MidiDeviceXMLHelper.getInstance().getButtonSets().get(BANK).getBank(); if (msg.getLength() > 0) { System.out.println("Offset="+offSet1); System.out.println("Message x,y,z="+msg.getMessage()[0]+", "+msg.getMessage()[1]+", "+msg.getMessage()[2]); if (Integer.valueOf(msg.getMessage()[0]).equals(offSet1)) { if (isButtonEnabled(msg.getMessage()[1])) { ((IMidiExecuter)ExecuterFactory.getInstance().getExecuterByMidiNote(msg.getMessage()[1])).executer(); } } } } }
/* * Copyright 2014 Victor Melnik <annimon119@gmail.com>, and * individual contributors as indicated by the @authors tag. * * 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.annimon.jecp; import java.util.Random; /** * Special class to provide random numbers. Introduced to improve basic java.util.Random class. * * @author aNNiMON */ public class JecpRandom { private static final Random rnd = new Random(); public static int rand(int to) { return rnd.nextInt(to); } public static int rand(int from, int to) { return rnd.nextInt(to - from) + from; } public static float rand(float from, float to) { return rnd.nextFloat() * (to - from) + from; } public static double rand(double from, double to) { return rnd.nextDouble() * (to - from) + from; } public static int randomColor(int from, int to) { if (from < 0) { from = 0; } else if (from > 255) { from = 255; } if (to < 0) { to = 0; } else if (to > 255) { to = 255; } if (from == to) { return (0xFF000000 | (from << 16) | (from << 8) | from); } else if (from > to) { final int temp = to; to = from; from = temp; } final int red = rand(from, to); final int green = rand(from, to); final int blue = rand(from, to); return (0xFF000000 | (red << 16) | (green << 8) | blue); } }
import java.util.Arrays; class ShellSort { int ShellSort(int arr[]) { int n = arr.length; for (int gap = n/2; gap > 0; gap = gap/2) { for (int i = gap; i < n; i++) { // add a[i] to the elements that have been gap // sorted save arr[i] in temp and make a hole at // position i int temp = arr[i]; // shift earlier gap-sorted elements up until // the correct location for arr[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j=j-gap) { arr[j] = arr[j - gap]; } // put temp in its correct location arr[j] = temp; } } return 0; } public static void main(String args[]) { int arr[] = {12, 11, 13, 5, 6, 19}; System.out.println("Before Sorting = "+Arrays.toString(arr)); ShellSort ob = new ShellSort(); ob.ShellSort(arr); System.out.println("After Sorting = "+Arrays.toString(arr)); } }
package com.test.demo.Exceptions; public class InvalidInputException extends Exception { /** * */ private static final long serialVersionUID = 3676048689611488603L; public InvalidInputException(String msg) { // TODO Auto-generated constructor stub super(msg); } }
package com.niit.project.radiom.view; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TimerTask; import com.niit.project.radiom.ObjectFactroy; import com.niit.project.radiom.ObjectFactroy.CaseType; import com.niit.project.radiom.ObjectFactroy.EnemyType; import com.niit.project.radiom.ObjectFactroy.PlaneType; import com.niit.project.radiom.activity.FailActivity; import com.niit.project.radiom.activity.GameActivity; import com.niit.project.radiom.activity.SuccessActivity; import com.niit.project.radiom.activity.WinActivity; import com.niit.project.radiom.music.MusicPlayer; import com.niit.project.radiom.music.MusicPlayer.MusicType; import com.niit.project.radiom.object.Background; import com.niit.project.radiom.object.BaseBullet; import com.niit.project.radiom.object.BaseBullet.BulletType; import com.niit.project.radiom.object.BulletsCase; import com.niit.project.radiom.object.Case; import com.niit.project.radiom.object.EnemyPlane; import com.niit.project.radiom.object.MedicineCase; import com.niit.project.radiom.object.Player; import com.niit.project.radiom.object.PlayerPlane; import com.niit.project.radiom.object.Round; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; public class GameView extends SurfaceView implements SurfaceHolder.Callback, Runnable { //Holder对象 private SurfaceHolder holder; //上下文对象 private GameActivity context; /** * 屏幕宽度和高度 */ private int screenWidth; private int screenHeight; /** * 一些状态位和计数器 */ private boolean gameIsRunning;//游戏是否正在运行 private boolean successed;//是否成功通关 private long planesFrameCount = 0;//用来产生敌机和工具箱的帧数计数器 private boolean musicIsPaused;//音乐是否被暂停 private boolean gameIsBreaked = false; /** * 判断双击事件的变量 * */ private long firClick; private long secClick; private int count; /** * 游戏中的一些对象 */ private ObjectFactroy factroy;//用于生产各种对象的工厂类 private Canvas canvas;//画布对象 private Background background;//背景对象 private Round round;//关卡对象 private Player player;//玩家对象 private PlayerPlane playerPlane;//玩家飞机 private List<EnemyPlane> enemyPlanes = new ArrayList<EnemyPlane>();//敌机列表 private List<BaseBullet> playerBullets = new ArrayList<BaseBullet>();//玩家的子弹列表 private List<BaseBullet> enemyBullets = new ArrayList<BaseBullet>();//敌人的子弹列表 private List<Case> cases = new ArrayList<Case>();//工具箱列表 private EnemyPlane boss1; private EnemyPlane boss2; private EnemyPlane boss3; /** * 一些类型的数组 * */ private EnemyType[] enemyTypes = new EnemyType[]{ EnemyType.simpleEnemy, EnemyType.smallEnemy1, EnemyType.smallEnemy2, EnemyType.smallEnemy3, EnemyType.smallEnemy4, EnemyType.smallEnemy5, EnemyType.smallEnemy6, EnemyType.boss1, EnemyType.boss2, EnemyType.boss3}; private BulletType[] bulletTypes = new BulletType[] { BulletType.bullet1, BulletType.bullet1_left, BulletType.bullet1_right, BulletType.bullet2, BulletType.bullet2_left, BulletType.bullet2_right, BulletType.bullet3, BulletType.bullet3_left, BulletType.bullet3_right, BulletType.bullet4, BulletType.bullet4_left, BulletType.bullet4_right, BulletType.bullet5, BulletType.bullet5_left, BulletType.bullet5_right, BulletType.bullet6, BulletType.bullet6_left, BulletType.bullet6_right, }; private CaseType[] caseTypes = new CaseType[] { CaseType.medicineCase, CaseType.bulletsCase, CaseType.bulletsCase1, CaseType.bulletsCase2 }; /** * 用于控制时间的成员 */ private TimerTask timerTask; // private Timer timer; private int tempTime = 10; //用于控制音乐播放的成员 private MusicPlayer musicPlayer; //当前关卡的最高分记录 private int currentTopScore; private SharedPreferences sp; public GameView(Context context) { super(context); // TODO Auto-generated constructor stub holder = getHolder(); holder.addCallback(this);//添加回调接口 factroy = ((GameActivity)context).getFactroy(); player = new Player("007", "大仙", 0);//初始化玩家对象 round = ((GameActivity)context).getRound();//初始化关卡对象 this.context = (GameActivity)context;//获取上下文对象 musicPlayer = new MusicPlayer(context);//初始化音乐播放对象 //获取SharedPreference对象 sp = PreferenceManager.getDefaultSharedPreferences(context); } public GameView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub holder = getHolder(); holder.addCallback(this);//添加回调接口 factroy = ((GameActivity)context).getFactroy(); player = new Player("007", "大仙", 0);//初始化玩家对象 round = ((GameActivity)context).getRound();//初始化关卡对象 this.context = (GameActivity)context;//获取上下文对象 musicPlayer = new MusicPlayer(context);//初始化音乐播放对象 //获取SharedPreference对象 sp = PreferenceManager.getDefaultSharedPreferences(context); } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub /* * 初始化一些状态位 * */ gameIsRunning = true; musicIsPaused = false; successed = true; //获取屏幕的宽度和高度 screenWidth = getWidth(); screenHeight = getHeight(); //获取当前关卡的最高分记录 switch (round.getRoundNumber()) { case 1: currentTopScore = sp.getInt("round1TopScore", 0); break; case 2: currentTopScore = sp.getInt("round2TopScore", 0); break; case 3: currentTopScore = sp.getInt("round3TopScore", 0); break; default: break; } /* * 开始定时 * */ timerTask = new TimerTask() { @Override public void run() { // TODO Auto-generated method stub gameIsRunning = false; } }; // timer = new Timer(); // timer.schedule(timerTask, round.getTime()); //创建玩家飞机 switch (round.getRoundNumber()) { case 1: playerPlane = factroy.createPlayerPlane(PlaneType.player1); break; case 2: playerPlane = factroy.createPlayerPlane(PlaneType.player2); break; case 3: playerPlane = factroy.createPlayerPlane(PlaneType.player3); break; } playerPlane.addBullet(BulletType.bullet2, 100000); //设置玩家飞机的目标坐标 playerPlane.setDestX(screenWidth /2); playerPlane.setDestY(screenHeight -40); //播放背景音乐 musicPlayer.playMusic(MusicType.background); //初始化背景对象 background = factroy.createBackground(round.getBackgroundType()); //开启线程 Thread thread = new Thread(this); thread.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub gameIsRunning = false; releaseResource(); //停止播放背景音乐 musicPlayer.stopMusic(MusicType.background); } private void releaseResource() { // TODO Auto-generated method stub if (!playerBullets.isEmpty()) playerBullets.clear(); if (!enemyPlanes.isEmpty()) enemyPlanes.clear(); if (!enemyBullets.isEmpty()) enemyBullets.clear(); } @Override public void run() { // TODO Auto-generated method stub while (gameIsRunning) { //如果游戏暂停,同时暂停背景音乐,并跳过其他操作 if (this.context.isGameIsPaused()) { if (!musicIsPaused) { musicPlayer.pauseMusic(MusicType.background); musicIsPaused = true; } continue; } if (musicIsPaused) { musicPlayer.playMusic(MusicType.background); musicIsPaused = false; } int sleepTime = 50;//线程休眠时间,单位为毫秒 try { Thread.sleep(sleepTime); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //锁定画布,开始绘图 canvas = holder.lockCanvas(); //创建敌机的帧数计数器递增 planesFrameCount ++; //创建敌机 createEnemyPlanes(); //创建boss switch (round.getRoundNumber()) { case 1: if (player.getScores() > 1000) { if (boss1 == null) { boss1 = factroy.createEnemyPlane(EnemyType.boss1); boss1.setBlood(1000); boss1.setAwardScores(500); enemyPlanes.add(boss1); } } break; case 2: if (player.getScores() > 1000 && player.getScores() <= 2000) { if (boss1 == null) { boss1 = factroy.createEnemyPlane(EnemyType.boss1); boss1.setBlood(3000); boss1.setAwardScores(500); enemyPlanes.add(boss1); } } else if (player.getScores() > 3000 && player.getScores() <= 4000) { if (boss2 == null) { boss2 = factroy.createEnemyPlane(EnemyType.boss2); boss2.setBlood(10000); boss2.setAwardScores(10000); enemyPlanes.add(boss2); } } break; case 3: if (player.getScores() > 1000 && player.getScores() <= 2000) { if (boss1 == null) { boss1 = factroy.createEnemyPlane(EnemyType.boss1); boss1.setBlood(1000); boss1.setAwardScores(500); enemyPlanes.add(boss1); } } else if ( player.getScores() > 3000 && player.getScores() <= 4000) { if (boss2 == null) { boss2 = factroy.createEnemyPlane(EnemyType.boss2); boss2.setBlood(3000); boss2.setAwardScores(1000); enemyPlanes.add(boss2); } } else if ( player.getScores() > 7000 && player.getScores() < 10000) { if (boss3 == null) { boss3 = factroy.createEnemyPlane(EnemyType.boss3); boss3.setBlood(5000); boss3.setAwardScores(30000); enemyPlanes.add(boss3); } } break; } //创建敌机子弹 createEnemyBullets(); //创建玩家子弹 createPlayerBullets(); //创建工具箱 createCases(); //移动,包括移动背景、玩家飞机、玩家子弹、所有敌机、所有敌机子弹 move(sleepTime); //工具箱生命递减 minusCaseLife(); //绘制图像,包括背景、玩家飞机、玩家子弹、所有敌机、所有敌机子弹 if (canvas == null) return; if (gameIsBreaked) return; draw(); //碰撞检测,包括玩家飞机和所有敌机、所有敌机子弹的碰撞,还包括玩家子弹和所有敌机的碰撞 detectCrash(); //检测所有敌机的状态,包括范围和血量,如果超出范围或血量为小于0则直接绘制爆炸效果并移除此敌机 detectEnemiesState(); //检测boss状态 // if (boss != null && boss.getBlood() <=0 ) { // gameIsRunning = false; // successed = true; // } if ( boss1 != null && boss1.getBlood() <= 0 ) { //绘制爆炸效果 if (canvas == null) return; if (boss1.getBoomFrameCount() < boss1.getBoomCount()) { boss1.drawBoom(canvas); boss1.addBoomFrameCount(); } else { player.addScores(boss1.getAwardScores()); //如果boss死亡,播放音效 musicPlayer.playMusic(MusicType.boom1); enemyPlanes.remove(boss1); boss1 = null; if (round.getRoundNumber() == 1) { gameIsRunning = false; successed = true; } } } if ( boss2 != null && boss2.getBlood() <= 0 ) { //绘制爆炸效果 if (canvas == null) return; if (boss2.getBoomFrameCount() < boss2.getBoomCount()) { boss2.drawBoom(canvas); boss2.addBoomFrameCount(); } else { player.addScores(boss2.getAwardScores()); //如果boss死亡,播放音效 musicPlayer.playMusic(MusicType.boom1); enemyPlanes.remove(boss2); boss2 = null; if (round.getRoundNumber() == 2) { gameIsRunning = false; successed = true; } } } if ( boss3 != null && boss3.getBlood() <= 0 ) { //绘制爆炸效果 if (canvas == null) return; if (boss3.getBoomFrameCount() < boss3.getBoomCount()) { boss3.drawBoom(canvas); boss3.addBoomFrameCount(); } else { player.addScores(boss3.getAwardScores()); //如果boss死亡,播放音效 musicPlayer.playMusic(MusicType.boom1); enemyPlanes.remove(boss3); boss3 = null; if (round.getRoundNumber() == 3) { gameIsRunning = false; successed = true; } } } //检测所有敌机子弹的状态,包括范围和是否被使用,如果超出范围或已经被使用则直接移除子弹 detectEnemyBulletsState(); //检测玩家飞机的状态,包括血量,如果血量小于0则直接绘制爆炸效果,闯关失败 detectPlayerState(); //检测玩家子弹的状态,包括范围和是否被使用,如果超出范围或已经被使用则直接移除子弹 detectPlayerBulletsState(); //检测工具箱的状态 detectCasesState(); //显示玩家血量和积分 show(); //解锁画布 holder.unlockCanvasAndPost(canvas); } //游戏结束时释放资源 releaseResource(); //取消定时器 // timer.cancel(); musicPlayer.stopMusic(MusicType.background); //根据状态跳转到相应的界面 if (!gameIsBreaked) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (successed) { Intent intent = new Intent(); //若还有下一关,则跳转到成功界面 if (round.getRoundNumber() < 3) { intent.setClass(getContext(), SuccessActivity.class); intent.putExtra("round", round.getRoundNumber()); intent.putExtra("score", player.getScores()); intent.putExtra("currentTopScore", currentTopScore); } else intent.setClass(getContext(), WinActivity.class); getContext().startActivity(intent); ((GameActivity)getContext()).finish(); } else { //跳转到失败界面 Intent intent = new Intent(); intent.setClass(getContext(), FailActivity.class); intent.putExtra("round", round.getRoundNumber()); intent.putExtra("score", player.getScores()); intent.putExtra("currentTopScore", currentTopScore); getContext().startActivity(intent); ((GameActivity)getContext()).finish(); } } } /** * 所有工具箱的生命时间减少1 */ private void minusCaseLife() { for (int i = 0; i < cases.size(); i ++) { cases.get(i).minusLife(1); } } /** * 检测工具箱的状态 */ private void detectCasesState() { for (int i = 0; i < cases.size(); i ++) { //如果工具箱已经被使用或者生命周期结束,则将其从工具箱列表中移除 if ( cases.get(i).isUsed() || cases.get(i).getLife() <= 0 ) { //移除该子弹 cases.remove(i); } //如果工具箱超出范围,则将其从工具箱列表中移除 else if ( cases.get(i).isOverRange(0, 320, 0, 450) ) { cases.remove(i); } } } /** * 创建工具箱并添加到工具箱列表中 */ private void createCases() { //从关卡类获得敌机类型-敌机数量,敌机类型-出现间隔的映射 Map<CaseType, Integer> amountMap = round.getCaseNumberMap(); Map<CaseType, Integer> delayMap = round.getCaseDelayMap(); Case baseCase = null; for (int i = 0; i < caseTypes.length; i ++) { if( amountMap.containsKey(caseTypes[i])) if ( planesFrameCount % delayMap.get(caseTypes[i]) == 1 && planesFrameCount > tempTime) { for (int j = 0; j < amountMap.get(caseTypes[i]); j ++) { baseCase = factroy.createCase(caseTypes[i]); cases.add(baseCase); } } } } /** * 展示玩家分数,关卡数,血量等等 */ private void show() { // TODO Auto-generated method stub if (canvas == null) return; Paint paint = new Paint(); paint.setColor(Color.WHITE); paint.setTextSize(16); canvas.drawText("当前关卡:" + round.getRoundNumber(), 180, 20, paint); canvas.drawText("目前最高分:" + currentTopScore, 180, 40, paint); canvas.drawText("玩家血量:" + playerPlane.getBlood(), 180, 60, paint); canvas.drawText("玩家积分:" + player.getScores(), 180, 80, paint); } /** * 创建玩家子弹 */ private void createPlayerBullets() { // TODO Auto-generated method stub playerPlane.addShootFrameCount(); for (int i = 0; i < bulletTypes.length; i ++) { if (playerPlane.getBulletsMap().containsKey(bulletTypes[i])) { if ( playerPlane.canShoot(bulletTypes[i]) ) { playerBullets.add(playerPlane.createBullet(bulletTypes[i])); //相应的子弹数量减1 playerPlane.cutBullets(bulletTypes[i], 1); } } } } /** * 检测玩家子弹的状态 */ private void detectPlayerBulletsState() { for (int i = 0; i < playerBullets.size(); i ++) { //如果子弹已经被使用,则将其从敌机子弹列表中移除 if ( playerBullets.get(i).isUsed() ) { //移除该子弹 playerBullets.remove(i); } //如果敌机子弹超出范围,则将其从敌机列表中移除 else if ( playerBullets.get(i).isOverRange(0, 320, 0, 450) ) { playerBullets.remove(i); } } } /** * 检测所有敌机子弹的状态,包括范围和是否被使用, * 如果超出范围或已经被使用则直接移除子弹 */ private void detectEnemyBulletsState() { for (int i = 0; i < enemyBullets.size(); i ++) { //如果子弹已经被使用,则将其从敌机子弹列表中移除 if ( enemyBullets.get(i).isUsed() ) { //移除该子弹 enemyBullets.remove(i); } //如果敌机子弹超出范围,则将其从敌机列表中移除 else if ( enemyBullets.get(i).isOverRange(0, screenWidth, 0, screenHeight) ) { enemyBullets.remove(i); } } } /** * 检测玩家的状态 */ private void detectPlayerState() { //如果飞机被击毁,则绘制爆炸效果,并将其从敌机列表中移除 if ( playerPlane.getBlood() <= 0 ) { //绘制爆炸效果 if (canvas == null) return; if (playerPlane.getBoomFrameCount() < playerPlane.getBoomCount()) { playerPlane.drawBoom(canvas); playerPlane.addBoomFrameCount(); } else { gameIsRunning = false; successed = false; } } } /** * 检测所有敌机的状态,包括范围和血量, * 如果超出范围或血量为小于0则直接绘制爆炸效果并移除此敌机 */ private void detectEnemiesState() { for (int i = 0; i < enemyPlanes.size(); i ++) { //如果敌机被击毁,则绘制爆炸效果,并将其从敌机列表中移除 if ( enemyPlanes.get(i).getBlood() <= 0 ) { //绘制爆炸效果 if (canvas == null) return; if (enemyPlanes.get(i).getBoomFrameCount() < enemyPlanes.get(i).getBoomCount()) { enemyPlanes.get(i).drawBoom(canvas); enemyPlanes.get(i).addBoomFrameCount(); } else { player.addScores(enemyPlanes.get(i).getAwardScores()); //如果boss死亡,播放音效 if (enemyPlanes.get(i).getType() == EnemyType.boss1 || enemyPlanes.get(i).getType() == EnemyType.boss1 || enemyPlanes.get(i).getType() == EnemyType.boss1) { musicPlayer.playMusic(MusicType.boom1); } enemyPlanes.remove(i); } } //如果敌机超出范围,则将其从敌机列表中移除 else if ( enemyPlanes.get(i).isOverRange(0, 0, 320, 450) ) { enemyPlanes.remove(i); } } } /** * 检测碰撞事件 */ private void detectCrash() { // TODO Auto-generated method stub //检测玩家飞机和敌机的碰撞 for (int i = 0; i < enemyPlanes.size(); i ++) { if ( enemyPlanes.get(i).detectCrash(playerPlane) ) { switch (enemyPlanes.get(i).getType()) { //简单敌机 case smallEnemy1: //撞机事件发生,玩家飞机扣20点血量 playerPlane.cutBlood(20); //撞机事件发生,敌方飞机扣20点血量 enemyPlanes.get(i).cutBlood(20); break; case smallEnemy2: //撞机事件发生,玩家飞机扣20点血量 playerPlane.cutBlood(20); //撞机事件发生,敌方飞机扣20点血量 enemyPlanes.get(i).cutBlood(20); break; case smallEnemy3: //撞机事件发生,玩家飞机扣20点血量 playerPlane.cutBlood(20); //撞机事件发生,敌方飞机扣20点血量 enemyPlanes.get(i).cutBlood(20); break; case smallEnemy4: //撞机事件发生,玩家飞机扣20点血量 playerPlane.cutBlood(20); //撞机事件发生,敌方飞机扣20点血量 enemyPlanes.get(i).cutBlood(20); break; case smallEnemy5: //撞机事件发生,玩家飞机扣20点血量 playerPlane.cutBlood(20); //撞机事件发生,敌方飞机扣20点血量 enemyPlanes.get(i).cutBlood(20); break; case smallEnemy6: //撞机事件发生,玩家飞机扣20点血量 playerPlane.cutBlood(20); //撞机事件发生,敌方飞机扣20点血量 enemyPlanes.get(i).cutBlood(20); break; case boss1: //撞机事件发生,玩家飞机扣100点血量 playerPlane.cutBlood(100); //撞机事件发生,敌方飞机扣100点血量 enemyPlanes.get(i).cutBlood(10); break; case boss2: //撞机事件发生,玩家飞机扣100点血量 playerPlane.cutBlood(300); //撞机事件发生,敌方飞机扣100点血量 enemyPlanes.get(i).cutBlood(10); break; case boss3: //撞机事件发生,玩家飞机扣100点血量 playerPlane.cutBlood(500); //撞机事件发生,敌方飞机扣100点血量 enemyPlanes.get(i).cutBlood(10); break; default: break; } } } //检测玩家飞机和敌机子弹的碰撞 for (int i = 0; i < enemyBullets.size(); i ++) { if (playerPlane.detectCrash(enemyBullets.get(i))) { //如果碰撞发生,玩家飞机扣血 playerPlane.cutBlood(enemyBullets.get(i).getHarm()); //如果碰撞发生,敌机子弹被使用 enemyBullets.get(i).setUsed(true); } } //检测敌机和玩家子弹的碰撞 for (int i = 0; i < enemyPlanes.size(); i ++) { for (int j = 0; j < playerBullets.size(); j ++) { if ( enemyPlanes.get(i).detectCrash(playerBullets.get(j)) ) { enemyPlanes.get(i).cutBlood(playerBullets.get(j).getHarm()); playerBullets.get(j).setUsed(true); } } } //检测玩家飞机和工具箱的碰撞 for (int i = 0; i < cases.size(); i ++) { CaseType type = cases.get(i).getType(); if ( cases.get(i).detectCrash(playerPlane) ) { switch (type) { case medicineCase: cases.get(i).setUsed(true); playerPlane.addBlood(((MedicineCase)cases.get(i)).getBloodAmount()); // Log.v("crash", "碰撞发生,玩家飞机和医药箱碰撞了"); break; default: cases.get(i).setUsed(true); Map<BulletType, Integer> map = ((BulletsCase)cases.get(i)).getBulletsMap(); for (int j = 0; j < bulletTypes.length; j ++) { if (map.containsKey(bulletTypes[j])) { playerPlane.addBullet(bulletTypes[j], map.get(bulletTypes[j])); Log.v("crash", "向飞机中添加了" + bulletTypes[j] + map.get(bulletTypes[j]) +"颗"); } } // if (map.containsKey(BulletType.bullet4)) { // playerPlane.addBullet(BulletType.bullet4, map.get(BulletType.bullet4)) // } Log.v("crash", "碰撞发生,玩家飞机和弹药箱碰撞了,此时弹药箱的bulletMap为" + map); break; } //播放音效 musicPlayer.playMusic(MusicType.getAward); } } } /** * 移动屏幕中的所有物品 * @param time */ private void move(int time) { // TODO Auto-generated method stub //移动背景 background.move(); //移动玩家飞机 playerPlane.move(time); //移动玩家飞机子弹 for (int i = 0; i < playerBullets.size(); i ++) { playerBullets.get(i).move(time); } //移动敌机 for (int i = 0; i < enemyPlanes.size(); i ++) { enemyPlanes.get(i).styleMove(time); } //移动敌机子弹 for (int i = 0; i < enemyBullets.size(); i ++) { enemyBullets.get(i).move(time); if (i == 0) { // Log.v("tag", "子弹移动完成,当前坐标x:" + enemyBullets.get(i).getCurrentX() + "y:" + enemyBullets.get(i).getCurrentY()); } } //移动工具 for (int i = 0; i < cases.size(); i ++) { cases.get(i).move(time); } } /** * 创建敌机 */ private void createEnemyPlanes() { // TODO Auto-generated method stub //从关卡类获得敌机类型-敌机数量,敌机类型-出现间隔的映射 Map<EnemyType, Integer> amountMap = round.getEnemyNumberMap(); Map<EnemyType, Integer> delayMap = round.getEnemyDelayMap(); EnemyPlane enemyPlane = null; for (int i = 0; i < enemyTypes.length; i ++) { if( amountMap.containsKey(enemyTypes[i])) if ( planesFrameCount % delayMap.get(enemyTypes[i]) == 1 && planesFrameCount > tempTime) { for (int j = 0; j < amountMap.get(enemyTypes[i]); j ++) { enemyPlane = factroy.createEnemyPlane(enemyTypes[i]); enemyPlanes.add(enemyPlane); } } } } /** * 创建敌机的子弹 */ private void createEnemyBullets() { // TODO Auto-generated method stub for (int i = 0; i < enemyPlanes.size(); i ++) { enemyPlanes.get(i).addShootFrameCount(); for (int j = 0; j < bulletTypes.length; j ++) { if (enemyPlanes.get(i).getBulletsMap().containsKey(bulletTypes[j])) { if ( enemyPlanes.get(i).canShoot(bulletTypes[j]) ) { enemyBullets.add(enemyPlanes.get(i).createBullet(bulletTypes[j])); } } } } } /** * 绘制图像 */ private void draw() { // TODO Auto-generated method stub if (canvas == null) return; background.drawSelf(canvas); //绘制玩家的子弹 for (int i = 0; i < playerBullets.size(); i ++) { if ( ! (playerBullets.get(i).isUsed()) ) playerBullets.get(i).drawSelf(canvas); } playerPlane.drawSelf(canvas); //绘制敌机子弹 for (int i = 0; i < enemyBullets.size(); i ++) { if ( ! (enemyBullets.get(i).isUsed()) ) enemyBullets.get(i).drawSelf(canvas); } //绘制敌机 for (int i = 0; i < enemyPlanes.size(); i ++) { if (enemyPlanes.get(i).getBlood() > 0) enemyPlanes.get(i).drawSelf(canvas); } //绘制工具箱 for (int i = 0; i < cases.size(); i ++) { if (!cases.get(i).isUsed() && cases.get(i).getLife() > 0) cases.get(i).drawSelf(canvas); } } /** * 触发大招 * 所有敌机扣1000点血量 * 所有敌机子弹消失 */ private void createBigBoom() { // TODO Auto-generated method stub for (int i = 0; i < enemyPlanes.size(); i ++) { enemyPlanes.get(i).cutBlood(1000); } enemyBullets.clear(); } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: //判断是否为双击事件 count++; if(count == 1){ firClick = System.currentTimeMillis(); } else if (count == 2){ secClick = System.currentTimeMillis(); if(secClick - firClick < 1000){ //双击事件 if (playerPlane.getBlood() >= 500) { createBigBoom(); playerPlane.cutBlood(100); } } count = 0; firClick = 0; secClick = 0; } case MotionEvent.ACTION_MOVE: //记录目标位置 int touchX = (int)event.getX(); int touchY = (int)event.getY(); if(touchX > screenWidth - 22) playerPlane.setDestX(screenWidth -22); else if (touchX < 22) playerPlane.setDestX(22); else playerPlane.setDestX(touchX); if(touchY > screenHeight) playerPlane.setDestY(screenHeight- 35 - 25); else if (touchY < 70 + 25) playerPlane.setDestY(35); else playerPlane.setDestY(touchY - 35 - 25); break; } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { gameIsBreaked = true; // timer.cancel(); } return super.onKeyDown(keyCode, event); } }
package dao; import java.io.Closeable; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import pojo.User; import utils.DBUtils; public class UserDao implements Closeable { private Connection connection; private PreparedStatement insertStatement; private PreparedStatement selectStatement; public UserDao()throws SQLException { this(DBUtils.getConnection()); } public UserDao(Connection connection ) throws SQLException{ this.connection = connection; this.insertStatement = connection.prepareStatement("insert into UserTable values(?,?,?,?,?)"); this.selectStatement = connection.prepareStatement("select * from UserTable where user_name=? and password=?"); } public int insertUser( User user )throws SQLException { this.insertStatement.setString(1, user.getUserName()); this.insertStatement.setString(2, user.getPassword()); this.insertStatement.setString(3, user.getEmail()); this.insertStatement.setString(4, user.getContactNumber()); this.insertStatement.setDate(5, user.getAccountCreationDate()); return this.insertStatement.executeUpdate(); } public User authenticateUser( String userName, String password )throws SQLException { this.selectStatement.setString(1, userName); this.selectStatement.setString(2, password ); try( ResultSet rs = this.selectStatement.executeQuery();) { if( rs.next()) return new User(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4), rs.getDate(5)); } return null; } @Override public void close() throws IOException { try { this.insertStatement.close(); this.selectStatement.close(); this.connection.close(); } catch( SQLException cause) { throw new IOException(cause); } } }
package com.example.shivam.maintain_notes; import android.app.ActionBar; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; public class Notes4 extends AppCompatActivity { EditText e2,e21,e22,e23,e24,e25,e26,e27,e28,e29,e30,e31,e32,e33,e34,e35,e36,e37,e38,e39; EditText e40,e41,e42,e43,e44,e45,e46,e47,e48,e49,e50,e51,e52,e53,e54,e55,e56,e57,e58,e59; Button bdelete; String string="null"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notes4); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Button bsave=(Button)findViewById(R.id.button2);//Save button bsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // 1- 10 try { FileOutputStream fos = openFileOutput("data",Context.MODE_PRIVATE); e2=(EditText)findViewById(R.id.editText2); string=e2.getText().toString(); fos.write(string.getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos1 = openFileOutput("data1",Context.MODE_PRIVATE); e21=(EditText)findViewById(R.id.editText21); string=e21.getText().toString(); fos1.write(string.getBytes()); fos1.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos2 = openFileOutput("data2",Context.MODE_PRIVATE); e22=(EditText)findViewById(R.id.editText22); string=e22.getText().toString(); fos2.write(string.getBytes()); fos2.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos3 = openFileOutput("data3",Context.MODE_PRIVATE); e23=(EditText)findViewById(R.id.editText23); string=e23.getText().toString(); fos3.write(string.getBytes()); fos3.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos4 = openFileOutput("data4",Context.MODE_PRIVATE); e24=(EditText)findViewById(R.id.editText24); string=e24.getText().toString(); fos4.write(string.getBytes()); fos4.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos5 = openFileOutput("data5",Context.MODE_PRIVATE); e25=(EditText)findViewById(R.id.editText25); string=e25.getText().toString(); fos5.write(string.getBytes()); fos5.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos6 = openFileOutput("data6",Context.MODE_PRIVATE); e26=(EditText)findViewById(R.id.editText26); string=e26.getText().toString(); fos6.write(string.getBytes()); fos6.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos7 = openFileOutput("data7",Context.MODE_PRIVATE); e27=(EditText)findViewById(R.id.editText27); string=e27.getText().toString(); fos7.write(string.getBytes()); fos7.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos8= openFileOutput("data8",Context.MODE_PRIVATE); e28=(EditText)findViewById(R.id.editText28); string=e28.getText().toString(); fos8.write(string.getBytes()); fos8.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos9 = openFileOutput("data9",Context.MODE_PRIVATE); e29=(EditText)findViewById(R.id.editText29); string=e29.getText().toString(); fos9.write(string.getBytes()); fos9.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 11 - 20 try { FileOutputStream fos = openFileOutput("data10",Context.MODE_PRIVATE); e30=(EditText)findViewById(R.id.editText30); string=e30.getText().toString(); fos.write(string.getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos1 = openFileOutput("data11",Context.MODE_PRIVATE); e31=(EditText)findViewById(R.id.editText31); string=e31.getText().toString(); fos1.write(string.getBytes()); fos1.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos2 = openFileOutput("data12",Context.MODE_PRIVATE); e32=(EditText)findViewById(R.id.editText32); string=e32.getText().toString(); fos2.write(string.getBytes()); fos2.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos3 = openFileOutput("data13",Context.MODE_PRIVATE); e33=(EditText)findViewById(R.id.editText33); string=e33.getText().toString(); fos3.write(string.getBytes()); fos3.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos4 = openFileOutput("data14",Context.MODE_PRIVATE); e34=(EditText)findViewById(R.id.editText34); string=e34.getText().toString(); fos4.write(string.getBytes()); fos4.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos5 = openFileOutput("data15",Context.MODE_PRIVATE); e35=(EditText)findViewById(R.id.editText35); string=e35.getText().toString(); fos5.write(string.getBytes()); fos5.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos6 = openFileOutput("data16",Context.MODE_PRIVATE); e36=(EditText)findViewById(R.id.editText36); string=e36.getText().toString(); fos6.write(string.getBytes()); fos6.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos7 = openFileOutput("data17",Context.MODE_PRIVATE); e37=(EditText)findViewById(R.id.editText37); string=e37.getText().toString(); fos7.write(string.getBytes()); fos7.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos8= openFileOutput("data18",Context.MODE_PRIVATE); e38=(EditText)findViewById(R.id.editText38); string=e38.getText().toString(); fos8.write(string.getBytes()); fos8.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos9 = openFileOutput("data19",Context.MODE_PRIVATE); e39=(EditText)findViewById(R.id.editText39); string=e39.getText().toString(); fos9.write(string.getBytes()); fos9.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //21-40 try { FileOutputStream fos = openFileOutput("data20",Context.MODE_PRIVATE); e40=(EditText)findViewById(R.id.editText40); string=e40.getText().toString(); fos.write(string.getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos1 = openFileOutput("data21",Context.MODE_PRIVATE); e41=(EditText)findViewById(R.id.editText41); string=e41.getText().toString(); fos1.write(string.getBytes()); fos1.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos2 = openFileOutput("data22",Context.MODE_PRIVATE); e42=(EditText)findViewById(R.id.editText42); string=e42.getText().toString(); fos2.write(string.getBytes()); fos2.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos3 = openFileOutput("data23",Context.MODE_PRIVATE); e43=(EditText)findViewById(R.id.editText43); string=e43.getText().toString(); fos3.write(string.getBytes()); fos3.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos4 = openFileOutput("data24",Context.MODE_PRIVATE); e44=(EditText)findViewById(R.id.editText44); string=e44.getText().toString(); fos4.write(string.getBytes()); fos4.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos5 = openFileOutput("data25",Context.MODE_PRIVATE); e45=(EditText)findViewById(R.id.editText45); string=e45.getText().toString(); fos5.write(string.getBytes()); fos5.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos6 = openFileOutput("data26",Context.MODE_PRIVATE); e46=(EditText)findViewById(R.id.editText46); string=e46.getText().toString(); fos6.write(string.getBytes()); fos6.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos7 = openFileOutput("data27",Context.MODE_PRIVATE); e47=(EditText)findViewById(R.id.editText47); string=e47.getText().toString(); fos7.write(string.getBytes()); fos7.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos8= openFileOutput("data28",Context.MODE_PRIVATE); e48=(EditText)findViewById(R.id.editText48); string=e48.getText().toString(); fos8.write(string.getBytes()); fos8.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos9 = openFileOutput("data29",Context.MODE_PRIVATE); e49=(EditText)findViewById(R.id.editText49); string=e49.getText().toString(); fos9.write(string.getBytes()); fos9.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 11 - 20 try { FileOutputStream fos = openFileOutput("data30",Context.MODE_PRIVATE); e50=(EditText)findViewById(R.id.editText50); string=e50.getText().toString(); fos.write(string.getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos1 = openFileOutput("data31",Context.MODE_PRIVATE); e51=(EditText)findViewById(R.id.editText51); string=e51.getText().toString(); fos1.write(string.getBytes()); fos1.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos2 = openFileOutput("data32",Context.MODE_PRIVATE); e52=(EditText)findViewById(R.id.editText52); string=e52.getText().toString(); fos2.write(string.getBytes()); fos2.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos3 = openFileOutput("data33",Context.MODE_PRIVATE); e53=(EditText)findViewById(R.id.editText53); string=e53.getText().toString(); fos3.write(string.getBytes()); fos3.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos4 = openFileOutput("data34",Context.MODE_PRIVATE); e54=(EditText)findViewById(R.id.editText54); string=e54.getText().toString(); fos4.write(string.getBytes()); fos4.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos5 = openFileOutput("data35",Context.MODE_PRIVATE); e55=(EditText)findViewById(R.id.editText55); string=e55.getText().toString(); fos5.write(string.getBytes()); fos5.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos6 = openFileOutput("data36",Context.MODE_PRIVATE); e56=(EditText)findViewById(R.id.editText56); string=e56.getText().toString(); fos6.write(string.getBytes()); fos6.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos7 = openFileOutput("data37",Context.MODE_PRIVATE); e57=(EditText)findViewById(R.id.editText57); string=e57.getText().toString(); fos7.write(string.getBytes()); fos7.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos8= openFileOutput("data38",Context.MODE_PRIVATE); e58=(EditText)findViewById(R.id.editText58); string=e58.getText().toString(); fos8.write(string.getBytes()); fos8.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileOutputStream fos9 = openFileOutput("data39",Context.MODE_PRIVATE); e59=(EditText)findViewById(R.id.editText59); string=e59.getText().toString(); fos9.write(string.getBytes()); fos9.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Intent intent=new Intent(getApplicationContext(),Notes1.class); startActivity(intent); Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show(); } }); Button bdelete=(Button)findViewById(R.id.bdelete); bdelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Delete AlertDialog.Builder builder=new AlertDialog.Builder(Notes4.this); builder.setMessage("Are you sure?").setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //code 1 -10 deleteFile("data"); deleteFile("data1"); deleteFile("data2"); deleteFile("data3"); deleteFile("data4"); deleteFile("data5"); deleteFile("data6"); deleteFile("data7"); deleteFile("data8"); deleteFile("data9"); //11-20 deleteFile("data10"); deleteFile("data11"); deleteFile("data12"); deleteFile("data13"); deleteFile("data14"); deleteFile("data15"); deleteFile("data16"); deleteFile("data17"); deleteFile("data18"); deleteFile("data19"); //21-30 deleteFile("data20"); deleteFile("data21"); deleteFile("data22"); deleteFile("data23"); deleteFile("data24"); deleteFile("data25"); deleteFile("data26"); deleteFile("data27"); deleteFile("data28"); deleteFile("data29"); //31-40 deleteFile("data30"); deleteFile("data31"); deleteFile("data32"); deleteFile("data33"); deleteFile("data34"); deleteFile("data35"); deleteFile("data36"); deleteFile("data37"); deleteFile("data38"); deleteFile("data39"); Intent intent=new Intent(getApplicationContext(),Notes1.class); startActivity(intent); Toast.makeText(getApplicationContext(), "deleted", Toast.LENGTH_SHORT).show(); } } ).setNegativeButton("cancel",null); AlertDialog alert=builder.create(); alert.show(); } }); try { FileInputStream fis=(FileInputStream)openFileInput("data"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { e2=(EditText)findViewById(R.id.editText2); e2.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis1=(FileInputStream)openFileInput("data1"); InputStreamReader isr1 = new InputStreamReader(fis1); BufferedReader bufferedReader1 = new BufferedReader(isr1); StringBuilder sb1 = new StringBuilder(); String line; while ((line = bufferedReader1.readLine()) != null) { e21=(EditText)findViewById(R.id.editText21); e21.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis2=(FileInputStream)openFileInput("data2"); InputStreamReader isr2 = new InputStreamReader(fis2); BufferedReader bufferedReader2 = new BufferedReader(isr2); StringBuilder sb2 = new StringBuilder(); String line; while ((line = bufferedReader2.readLine()) != null) { e22=(EditText)findViewById(R.id.editText22); e22.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis3=(FileInputStream)openFileInput("data3"); InputStreamReader isr3 = new InputStreamReader(fis3); BufferedReader bufferedReader3 = new BufferedReader(isr3); StringBuilder sb3 = new StringBuilder(); String line; while ((line = bufferedReader3.readLine()) != null) { e23=(EditText)findViewById(R.id.editText23); e23.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis4=(FileInputStream)openFileInput("data4"); InputStreamReader isr4 = new InputStreamReader(fis4); BufferedReader bufferedReader4 = new BufferedReader(isr4); StringBuilder sb4 = new StringBuilder(); String line; while ((line = bufferedReader4.readLine()) != null) { e24=(EditText)findViewById(R.id.editText24); e24.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis5=(FileInputStream)openFileInput("data5"); InputStreamReader isr5 = new InputStreamReader(fis5); BufferedReader bufferedReader5 = new BufferedReader(isr5); StringBuilder sb5 = new StringBuilder(); String line; while ((line = bufferedReader5.readLine()) != null) { e25=(EditText)findViewById(R.id.editText25); e25.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis6=(FileInputStream)openFileInput("data6"); InputStreamReader isr6 = new InputStreamReader(fis6); BufferedReader bufferedReader6 = new BufferedReader(isr6); StringBuilder sb6 = new StringBuilder(); String line; while ((line = bufferedReader6.readLine()) != null) { e26=(EditText)findViewById(R.id.editText26); e26.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis7=(FileInputStream)openFileInput("data7"); InputStreamReader isr7 = new InputStreamReader(fis7); BufferedReader bufferedReader7 = new BufferedReader(isr7); StringBuilder sb7 = new StringBuilder(); String line; while ((line = bufferedReader7.readLine()) != null) { e27=(EditText)findViewById(R.id.editText27); e27.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis8=(FileInputStream)openFileInput("data8"); InputStreamReader isr8 = new InputStreamReader(fis8); BufferedReader bufferedReader8 = new BufferedReader(isr8); StringBuilder sb8 = new StringBuilder(); String line; while ((line = bufferedReader8.readLine()) != null) { e28=(EditText)findViewById(R.id.editText28); e28.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis9=(FileInputStream)openFileInput("data9"); InputStreamReader isr9 = new InputStreamReader(fis9); BufferedReader bufferedReader9 = new BufferedReader(isr9); StringBuilder sb9 = new StringBuilder(); String line; while ((line = bufferedReader9.readLine()) != null) { e29=(EditText)findViewById(R.id.editText29); e29.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //11-20 try { FileInputStream fis=(FileInputStream)openFileInput("data10"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { e30=(EditText)findViewById(R.id.editText30); e30.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis1=(FileInputStream)openFileInput("data11"); InputStreamReader isr1 = new InputStreamReader(fis1); BufferedReader bufferedReader1 = new BufferedReader(isr1); StringBuilder sb1 = new StringBuilder(); String line; while ((line = bufferedReader1.readLine()) != null) { e31=(EditText)findViewById(R.id.editText31); e31.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis2=(FileInputStream)openFileInput("data12"); InputStreamReader isr2 = new InputStreamReader(fis2); BufferedReader bufferedReader2 = new BufferedReader(isr2); StringBuilder sb2 = new StringBuilder(); String line; while ((line = bufferedReader2.readLine()) != null) { e32=(EditText)findViewById(R.id.editText32); e32.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis3=(FileInputStream)openFileInput("data13"); InputStreamReader isr3 = new InputStreamReader(fis3); BufferedReader bufferedReader3 = new BufferedReader(isr3); StringBuilder sb3 = new StringBuilder(); String line; while ((line = bufferedReader3.readLine()) != null) { e33=(EditText)findViewById(R.id.editText33); e33.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis4=(FileInputStream)openFileInput("data14"); InputStreamReader isr4 = new InputStreamReader(fis4); BufferedReader bufferedReader4 = new BufferedReader(isr4); StringBuilder sb4 = new StringBuilder(); String line; while ((line = bufferedReader4.readLine()) != null) { e34=(EditText)findViewById(R.id.editText34); e34.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis5=(FileInputStream)openFileInput("data15"); InputStreamReader isr5 = new InputStreamReader(fis5); BufferedReader bufferedReader5 = new BufferedReader(isr5); StringBuilder sb5 = new StringBuilder(); String line; while ((line = bufferedReader5.readLine()) != null) { e35=(EditText)findViewById(R.id.editText35); e35.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis6=(FileInputStream)openFileInput("data16"); InputStreamReader isr6 = new InputStreamReader(fis6); BufferedReader bufferedReader6 = new BufferedReader(isr6); StringBuilder sb6 = new StringBuilder(); String line; while ((line = bufferedReader6.readLine()) != null) { e36=(EditText)findViewById(R.id.editText36); e36.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis7=(FileInputStream)openFileInput("data17"); InputStreamReader isr7 = new InputStreamReader(fis7); BufferedReader bufferedReader7 = new BufferedReader(isr7); StringBuilder sb7 = new StringBuilder(); String line; while ((line = bufferedReader7.readLine()) != null) { e37=(EditText)findViewById(R.id.editText37); e37.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis8=(FileInputStream)openFileInput("data18"); InputStreamReader isr8 = new InputStreamReader(fis8); BufferedReader bufferedReader8 = new BufferedReader(isr8); StringBuilder sb8 = new StringBuilder(); String line; while ((line = bufferedReader8.readLine()) != null) { e38=(EditText)findViewById(R.id.editText38); e38.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis9=(FileInputStream)openFileInput("data19"); InputStreamReader isr9 = new InputStreamReader(fis9); BufferedReader bufferedReader9 = new BufferedReader(isr9); StringBuilder sb9 = new StringBuilder(); String line; while ((line = bufferedReader9.readLine()) != null) { e39=(EditText)findViewById(R.id.editText39); e39.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //21-30 try { FileInputStream fis=(FileInputStream)openFileInput("data20"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { e40=(EditText)findViewById(R.id.editText40); e40.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis1=(FileInputStream)openFileInput("data21"); InputStreamReader isr1 = new InputStreamReader(fis1); BufferedReader bufferedReader1 = new BufferedReader(isr1); StringBuilder sb1 = new StringBuilder(); String line; while ((line = bufferedReader1.readLine()) != null) { e41=(EditText)findViewById(R.id.editText41); e41.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis2=(FileInputStream)openFileInput("data22"); InputStreamReader isr2 = new InputStreamReader(fis2); BufferedReader bufferedReader2 = new BufferedReader(isr2); StringBuilder sb2 = new StringBuilder(); String line; while ((line = bufferedReader2.readLine()) != null) { e42=(EditText)findViewById(R.id.editText42); e42.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis3=(FileInputStream)openFileInput("data23"); InputStreamReader isr3 = new InputStreamReader(fis3); BufferedReader bufferedReader3 = new BufferedReader(isr3); StringBuilder sb3 = new StringBuilder(); String line; while ((line = bufferedReader3.readLine()) != null) { e43=(EditText)findViewById(R.id.editText43); e43.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis4=(FileInputStream)openFileInput("data24"); InputStreamReader isr4 = new InputStreamReader(fis4); BufferedReader bufferedReader4 = new BufferedReader(isr4); StringBuilder sb4 = new StringBuilder(); String line; while ((line = bufferedReader4.readLine()) != null) { e44=(EditText)findViewById(R.id.editText44); e44.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis5=(FileInputStream)openFileInput("data25"); InputStreamReader isr5 = new InputStreamReader(fis5); BufferedReader bufferedReader5 = new BufferedReader(isr5); StringBuilder sb5 = new StringBuilder(); String line; while ((line = bufferedReader5.readLine()) != null) { e45=(EditText)findViewById(R.id.editText45); e45.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis6=(FileInputStream)openFileInput("data26"); InputStreamReader isr6 = new InputStreamReader(fis6); BufferedReader bufferedReader6 = new BufferedReader(isr6); StringBuilder sb6 = new StringBuilder(); String line; while ((line = bufferedReader6.readLine()) != null) { e46=(EditText)findViewById(R.id.editText46); e46.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis7=(FileInputStream)openFileInput("data27"); InputStreamReader isr7 = new InputStreamReader(fis7); BufferedReader bufferedReader7 = new BufferedReader(isr7); StringBuilder sb7 = new StringBuilder(); String line; while ((line = bufferedReader7.readLine()) != null) { e47=(EditText)findViewById(R.id.editText47); e47.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis8=(FileInputStream)openFileInput("data28"); InputStreamReader isr8 = new InputStreamReader(fis8); BufferedReader bufferedReader8 = new BufferedReader(isr8); StringBuilder sb8 = new StringBuilder(); String line; while ((line = bufferedReader8.readLine()) != null) { e48=(EditText)findViewById(R.id.editText48); e48.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis9=(FileInputStream)openFileInput("data29"); InputStreamReader isr9 = new InputStreamReader(fis9); BufferedReader bufferedReader9 = new BufferedReader(isr9); StringBuilder sb9 = new StringBuilder(); String line; while ((line = bufferedReader9.readLine()) != null) { e49=(EditText)findViewById(R.id.editText49); e49.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //31-40 try { FileInputStream fis=(FileInputStream)openFileInput("data30"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { e50=(EditText)findViewById(R.id.editText50); e50.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis1=(FileInputStream)openFileInput("data31"); InputStreamReader isr1 = new InputStreamReader(fis1); BufferedReader bufferedReader1 = new BufferedReader(isr1); StringBuilder sb1 = new StringBuilder(); String line; while ((line = bufferedReader1.readLine()) != null) { e51=(EditText)findViewById(R.id.editText51); e51.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis2=(FileInputStream)openFileInput("data32"); InputStreamReader isr2 = new InputStreamReader(fis2); BufferedReader bufferedReader2 = new BufferedReader(isr2); StringBuilder sb2 = new StringBuilder(); String line; while ((line = bufferedReader2.readLine()) != null) { e52=(EditText)findViewById(R.id.editText52); e52.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis3=(FileInputStream)openFileInput("data33"); InputStreamReader isr3 = new InputStreamReader(fis3); BufferedReader bufferedReader3 = new BufferedReader(isr3); StringBuilder sb3 = new StringBuilder(); String line; while ((line = bufferedReader3.readLine()) != null) { e53=(EditText)findViewById(R.id.editText53); e53.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis4=(FileInputStream)openFileInput("data34"); InputStreamReader isr4 = new InputStreamReader(fis4); BufferedReader bufferedReader4 = new BufferedReader(isr4); StringBuilder sb4 = new StringBuilder(); String line; while ((line = bufferedReader4.readLine()) != null) { e54=(EditText)findViewById(R.id.editText54); e54.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis5=(FileInputStream)openFileInput("data35"); InputStreamReader isr5 = new InputStreamReader(fis5); BufferedReader bufferedReader5 = new BufferedReader(isr5); StringBuilder sb5 = new StringBuilder(); String line; while ((line = bufferedReader5.readLine()) != null) { e55=(EditText)findViewById(R.id.editText55); e55.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis6=(FileInputStream)openFileInput("data36"); InputStreamReader isr6 = new InputStreamReader(fis6); BufferedReader bufferedReader6 = new BufferedReader(isr6); StringBuilder sb6 = new StringBuilder(); String line; while ((line = bufferedReader6.readLine()) != null) { e56=(EditText)findViewById(R.id.editText56); e56.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis7=(FileInputStream)openFileInput("data37"); InputStreamReader isr7 = new InputStreamReader(fis7); BufferedReader bufferedReader7 = new BufferedReader(isr7); StringBuilder sb7 = new StringBuilder(); String line; while ((line = bufferedReader7.readLine()) != null) { e57=(EditText)findViewById(R.id.editText57); e57.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis8=(FileInputStream)openFileInput("data38"); InputStreamReader isr8 = new InputStreamReader(fis8); BufferedReader bufferedReader8 = new BufferedReader(isr8); StringBuilder sb8 = new StringBuilder(); String line; while ((line = bufferedReader8.readLine()) != null) { e58=(EditText)findViewById(R.id.editText58); e58.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fis9=(FileInputStream)openFileInput("data39"); InputStreamReader isr9 = new InputStreamReader(fis9); BufferedReader bufferedReader9 = new BufferedReader(isr9); StringBuilder sb9 = new StringBuilder(); String line; while ((line = bufferedReader9.readLine()) != null) { e59=(EditText)findViewById(R.id.editText59); e59.setText(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.my_options_menu, menu); return true; } // menu option @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.Aboutme: { Toast.makeText(this, "My name is Shivam Taneja , Pursuing BE in IT from UIET(PU),Chandigarh", Toast.LENGTH_LONG).show(); return true; } case R.id.Contactme: { Toast.makeText(this, "E-mail me :shivamtaneja1990@gmail.com", Toast.LENGTH_LONG).show(); return true; } case R.id.rate_me: { Intent intent = new Intent(this, Notes2.class); startActivity(intent); Toast.makeText(this, "Please give me stars", Toast.LENGTH_SHORT).show(); return true; } case android.R.id.home: { Intent intent = new Intent(this, Notes1.class); startActivity(intent); } default: return true; }} @Override public void onBackPressed() { AlertDialog.Builder builder=new AlertDialog.Builder(Notes4.this); builder.setMessage("Really exit?").setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Notes4.super.onBackPressed(); } } ).setNegativeButton("cancel",null).setCancelable(false); AlertDialog alert=builder.create(); alert.show(); } }
package com.imooc.repository; import com.imooc.dataobject.ProductInfo; import org.junit.Assert; 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.test.context.junit4.SpringRunner; import java.math.BigDecimal; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class ProductInfoRepositoryTest { @Autowired private ProductInfoRepository productInfoRepository; @Test public void saveTest(){ ProductInfo productInfo = new ProductInfo(); productInfo.setProductId("123456"); productInfo.setProductName("热狗"); productInfo.setProductPrice(new BigDecimal(5)); productInfo.setProductStock(100); productInfo.setProductDescription("热狗很好吃"); productInfo.setProductIcon("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=" + "1521390499118&di=b11e48fd5741b05c4987ff10b9a171be&imgtype=0&src=http%3A%2F%2Fimg.taopic." + "com%2Fuploads%2Fallimg%2F120210%2F2506-12021010054649.jpg"); productInfo.setProductStatus(0); productInfo.setCategoryType(4); ProductInfo productInfo1 = productInfoRepository.save(productInfo); Assert.assertNotNull(productInfo1); } @Test public void findByProductStatus() throws Exception { List<ProductInfo> productInfos = productInfoRepository.findByProductStatus(0); Assert.assertTrue(productInfos.size()>0); } }
package com.mmm.service.XML; import org.aspectj.lang.ProceedingJoinPoint; /** * 纯切面 通过xml的配置 把切面织入到指定的目标方法中 */ public class MyAspectJ { //前置增强 public void before(){ System.out.println("前置增强"); } //后置增强 public void afterReturning(){ System.out.println("后置增强"); } //环绕增强 必须需要一个参数 public Object around(ProceedingJoinPoint point){ System.out.println("环绕增强进来···········"); Object result=null; try { result= point.proceed();//执行目标方法 } catch (Throwable throwable) { throwable.printStackTrace(); } System.out.println("环绕增强出去·········"); return "多米多"; } }
import java.util.Arrays; public class MiArrayList { private int size; private static final int DEFAULT_CAPACITY = 10; private int elements[]; /** * El metodo constructor se utiliza para incializar * variables a valores neutros como 0 o null. * El contructor no lleva parámetros en este caso. */ public MiArrayList() { size = 0; elements = new int[DEFAULT_CAPACITY]; } /** * Tiene la intención de retornar la longitud del objeto * @return longitud del objeto * * El size esta influenciado por las funciones add y del */ public int size() { return size; } /** * @param e el elemento a guardar * Agrega un elemento e a la última posición de la lista * */ public void add(int e) { if (size == elements.length) { //Equivalente a Arrays.copyOf(...) que es O(n); int[] otroArreglo = new int[elements.length*2]; for (int i = 0; i < elements.length; i++) // O(n) otroArreglo[i] = elements[i]; elements = otroArreglo; } elements[size] = e; size++; } /** * @param i es un íncide donde se encuentra el elemento posicionado * Retorna el elemento que se encuentra en la posición i de la lista. * */ public int get(int i) throws Exception{ if (i > size || i < 0) throw new Exception("index: " + i); for (int index = 0; index < elements.length; index++) // O(n) if (index == i) return elements[index]; return elements[i];// T(n) = O(n) !! } /** * @param index es la posicion en la cual se va agregar el elemento * @param e el elemento a guardar * Agrega un elemento e en la posición index de la lista * */ public void add(int index, int e) throws Exception { if (index > size || index < 0) // O(1) throw new Exception("index: " + index); // O(1) int[] copyArray; // O(1) if (size == elements.length) // O(1) copyArray = new int[elements.length*2]; // O(1) else copyArray = new int[elements.length]; // O(1) for(int i = 0; i < index; i++){ // O(n) copyArray[i] = elements[i]; // O(n) copyArray[index] = e; // O(1) for(i = index; i < copyArray.length; i++){ // O(n) copyArray[i+1] = elements[i]; // O(n) } size++; // O(1) elements = copyArray; // O(1) } // T(n) = O(n) !! } /** * @param index es la posicion en la cual se va eliminar el elemento * * ELimina el elemento en la posición index de la lista * */ public void del(int index){ for(int i=index; i < size; i++){ //O(n) elements[i] = elements[i+1]; } elements[size] = 0; size--;// T(n) = O(n) !! } }
package carnero.movement.ui; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Set; import java.util.concurrent.TimeUnit; import android.animation.Animator; import android.animation.ObjectAnimator; import android.content.Intent; import android.graphics.Color; import android.graphics.Path; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.text.TextUtils; import android.text.format.DateUtils; import android.view.*; import android.view.animation.PathInterpolator; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; import carnero.movement.App; import carnero.movement.R; import carnero.movement.common.*; import carnero.movement.common.model.Achvmnt; import carnero.movement.common.remotelog.RemoteLog; import carnero.movement.db.Helper; import carnero.movement.model.Checkin; import carnero.movement.model.Location; import carnero.movement.model.MovementContainer; import carnero.movement.service.FoursquareService; import carnero.movement.service.LocationService; import com.foursquare.android.nativeoauth.FoursquareOAuth; import com.foursquare.android.nativeoauth.model.AccessTokenResponse; import com.foursquare.android.nativeoauth.model.AuthCodeResponse; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.games.Games; import com.google.android.gms.games.GamesStatusCodes; import com.google.android.gms.games.achievement.Achievement; import com.google.android.gms.games.achievement.AchievementBuffer; import com.google.android.gms.games.achievement.Achievements; import com.google.android.gms.maps.*; import com.google.android.gms.maps.model.*; import com.google.example.games.basegameutils.BaseGameActivity; public class MainActivity extends BaseGameActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private Helper mMovementHelper; private Preferences mPreferences; private PagesAdapter mPagerAdapter; private boolean mHasFsqToken = true; private GoogleApiClient mGoogleApiClient; private MapDataTask mMapDataTask; private final HashMap<Long, Achvmnt> mAchievements = new HashMap<>(); // private float mMapStrokeWidth; private int mMapColorStart; private int mMapColorEnd; // private static final int HISTORY_PAGES = 31; private static final int REQUEST_FSQ_CONNECT = 1001; private static final int REQUEST_FSQ_EXCHANGE = 1002; private static final int REQUEST_ACHIEVEMENTS = 1003; // @InjectView(R.id.label) TextView vLabel; @InjectView(R.id.sub_label) TextView vSubLabel; @InjectView(R.id.achievements) LinearLayout vAchievements; @InjectView(R.id.map) MapView vMap; @InjectView(R.id.pager) ViewPager vPager; @Override protected void onCreate(Bundle state) { // Play Services: Games setRequestedClients(BaseGameActivity.CLIENT_GAMES); super.onCreate(state); final ActionBar actionBar = getSupportActionBar(); final UiToolsV21 v21Tools = UiToolsV21.getInstance(); if (actionBar != null && v21Tools != null) { v21Tools.setElevation(actionBar, 0); } // Init mMovementHelper = Helper.getInstance(); mPreferences = new Preferences(); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Games.API) .addScope(Games.SCOPE_GAMES) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mGoogleApiClient.connect(); // Load resources mMapStrokeWidth = getResources().getDimension(R.dimen.map_line_stroke); mMapColorStart = getResources().getColor(R.color.map_history_start); mMapColorEnd = getResources().getColor(R.color.map_history_end); // Start service final Intent serviceIntent = new Intent(this, LocationService.class); startService(serviceIntent); // Init layout setContentView(R.layout.activity_main); ButterKnife.inject(this); // Map MapsInitializer.initialize(this); vMap.onCreate(state); initMap(); // Set ViewPager mPagerAdapter = new PagesAdapter(); vPager.setOffscreenPageLimit(3); vPager.setAdapter(mPagerAdapter); vPager.setCurrentItem(mPagerAdapter.getCount() - 1); vPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int i) { final GraphFragment fragment = mPagerAdapter.getFragment(i); if (fragment != null) { vLabel.setText(fragment.getLabel()); vSubLabel.setText(fragment.getSubLabel()); setColors(); hideAndDisplayAchievements(); displayMapData(); } } @Override public void onPageScrolled(int i, float v, int i2) { // empty } @Override public void onPageScrollStateChanged(int i) { // empty } }); } @Override protected void onResume() { super.onResume(); vMap.onResume(); new MenuTask().start(); } @Override public void onPause() { vMap.onPause(); super.onPause(); } @Override protected void onDestroy() { vMap.onDestroy(); super.onDestroy(); if (mGoogleApiClient != null) { mGoogleApiClient.disconnect(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.activity_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.menu_foursquare).setVisible(!mHasFsqToken); menu.findItem(R.id.menu_achievements).setVisible(mGoogleApiClient.isConnected()); menu.findItem(R.id.menu_debug).setVisible(RemoteLog.isEnabled()); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_foursquare: startFsqConnection(); return true; case R.id.menu_achievements: startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), REQUEST_ACHIEVEMENTS); return true; case R.id.menu_debug: RemoteLog.forceSendLogs(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_FSQ_CONNECT: final AuthCodeResponse responseConnect = FoursquareOAuth.getAuthCodeFromResult(resultCode, data); final String code = responseConnect.getCode(); if (!TextUtils.isEmpty(code)) { startFsqExchange(code); } else { RemoteLog.e("Failed to connect to Foursquare: " + responseConnect.getException().getMessage()); } break; case REQUEST_FSQ_EXCHANGE: final AccessTokenResponse responseExchange = FoursquareOAuth.getTokenFromResult(resultCode, data); final String token = responseExchange.getAccessToken(); if (!TextUtils.isEmpty(token)) { mPreferences.saveFoursquareToken(token); invalidateOptionsMenu(); Games.Achievements.unlock(getApiClient(), getString(R.string.achievement_make_it_social)); } else { RemoteLog.e("Failed to get Foursquare token: " + responseExchange.getException().getMessage()); } FoursquareService.setAlarm(true); App.getTracker().send(new HitBuilders.EventBuilder() .setCategory("foursquare") .setAction("connection_done") .build()); break; } } @Override public void onConnected(Bundle bundle) { invalidateOptionsMenu(); new AchievementsTask().start(); } @Override public void onConnectionSuspended(int i) { invalidateOptionsMenu(); // TODO } @Override public void onConnectionFailed(ConnectionResult connectionResult) { // TODO } @Override public void onSignInSucceeded() { // TODO } @Override public void onSignInFailed() { // TODO } private void initMap() { final GoogleMap map = vMap.getMap(); map.setMyLocationEnabled(false); map.setMapType(GoogleMap.MAP_TYPE_NORMAL); final UiSettings ui = map.getUiSettings(); ui.setMyLocationButtonEnabled(false); ui.setCompassEnabled(false); ui.setZoomControlsEnabled(false); } public void setLabel(int day, String label, String subLabel) { if (day == getDay(vPager.getCurrentItem())) { vLabel.setText(label); vSubLabel.setText(subLabel); setColors(); hideAndDisplayAchievements(); displayMapData(); } } private int getDay(int position) { return (position - HISTORY_PAGES + 1); } private void setColors() { // TODO: set colorPrimary, colorPrimaryDark according to goal reach } private void hideAndDisplayAchievements() { final int count = vAchievements.getChildCount(); if (count > 0) { final UiToolsV21 v21Tools = UiToolsV21.getInstance(); for (int position = 0; position < count; position ++) { View view = vAchievements.getChildAt(position); View icon = view.findViewById(R.id.icon); if (icon == null) { continue; } EndAnimatorListener listener = new EndAnimatorListener(icon, count, position); if (v21Tools != null) { v21Tools.setHideAchievementsAnimator( icon, position, listener ); } else { listener.onAnimationEnd(null); } } } else { displayAchievements(); } } private void displayAchievements() { // Achievements final ArrayList<Achvmnt> achievements = new ArrayList<Achvmnt>(); final long[] dayTimes = Utils.getTimesForDay(getDay(vPager.getCurrentItem())); synchronized (mAchievements) { final Set<Long> keys = mAchievements.keySet(); for (Long key : keys) { Achvmnt achievement = mAchievements.get(key); if (achievement != null && key >= dayTimes[0] && key < dayTimes[1]) { achievements.add(achievement); } } } final UiToolsV21 v21Tools = UiToolsV21.getInstance(); // Add views vAchievements.removeAllViews(); int cnt = 0; for (Achvmnt achvmnt : achievements) { View view = LayoutInflater.from(this).inflate(R.layout.item_achievement, vAchievements, false); ImageView icon = (ImageView) view.findViewById(R.id.icon); icon.setContentDescription(achvmnt.description); vAchievements.addView(view); ImageLoaderSingleton.getInstance() .displayImage(achvmnt.unlockedImageUrl, icon); StartAnimatorListener listener = new StartAnimatorListener(icon); if (v21Tools != null) { v21Tools.setDisplayAchievementsAnimator( icon, cnt, achievements.size(), listener ); } else { listener.onAnimationStart(null); } cnt ++; } vAchievements.setVisibility(View.VISIBLE); } private void displayMapData() { final int day = getDay(vPager.getCurrentItem()); if (mMapDataTask != null && mMapDataTask.getDay() != day) { mMapDataTask.cancel(true); } mMapDataTask = new MapDataTask(day); mMapDataTask.start(); } private void startFsqConnection() { App.getTracker().send(new HitBuilders.EventBuilder() .setCategory("foursquare") .setAction("connection_init") .build()); final Intent intent = FoursquareOAuth.getConnectIntent( App.get(), Constants.FSQ_CLIENT_ID ); startActivityForResult(intent, REQUEST_FSQ_CONNECT); } private void startFsqExchange(String code) { final Intent intent = FoursquareOAuth.getTokenExchangeIntent( App.get(), Constants.FSQ_CLIENT_ID, Constants.FSQ_CLIENT_SECRET, code ); startActivityForResult(intent, REQUEST_FSQ_EXCHANGE); } // Classes public class PagesAdapter extends FragmentStatePagerAdapter { private final HashMap<Integer, GraphFragment> mFragments = new HashMap<Integer, GraphFragment>(); public PagesAdapter() { super(getSupportFragmentManager()); } @Override public Fragment getItem(int position) { final GraphFragment fragment = GraphFragment.newInstance(getDay(position)); mFragments.put(position, fragment); return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { mFragments.remove(position); super.destroyItem(container, position, object); } @Override public int getCount() { return HISTORY_PAGES; } public GraphFragment getFragment(int position) { return mFragments.get(position); } } /** * Check achievements queue and unlock if necessary */ public class AchievementsTask extends BaseAsyncTask { @Override public void inBackground() { // Load achievements PendingResult pending = Games.Achievements.load(mGoogleApiClient, false); Achievements.LoadAchievementsResult result = (Achievements.LoadAchievementsResult)pending .await(60, TimeUnit.SECONDS); int status = result.getStatus().getStatusCode(); if (status != GamesStatusCodes.STATUS_OK) { result.release(); return; } AchievementBuffer buffer = result.getAchievements(); int bufSize = buffer.getCount(); final HashMap<String, Integer> available = new HashMap<String, Integer>(); final HashMap<Long, Achvmnt> unlocked = new HashMap<Long, Achvmnt>(); for (int i = 0; i < bufSize; i++) { Achievement achievement = buffer.get(i); Achvmnt achvmnt = new Achvmnt(); achvmnt.id = achievement.getAchievementId(); achvmnt.state = achievement.getState(); achvmnt.lastChange = achievement.getLastUpdatedTimestamp(); achvmnt.unlockedImageUrl = achievement.getUnlockedImageUrl(); achvmnt.description = achievement.getDescription(); available.put(achvmnt.id, achvmnt.state); if (achvmnt.state == Achievement.STATE_UNLOCKED) { unlocked.put(achvmnt.lastChange, achvmnt); } } buffer.close(); result.release(); synchronized (mAchievements) { mAchievements.clear(); mAchievements.putAll(unlocked); } // Check waiting achievements final Set<String> queue = mPreferences.getAchievementsToUnlock(); if (queue == null || queue.isEmpty()) { return; // Nothing to do } // Unlock waiting achievements for (String item : queue) { int state = available.get(item); if (state == Achievement.STATE_UNLOCKED) { mPreferences.removeAchievementFromQueue(item); continue; } PendingResult updatePending = Games.Achievements.unlockImmediate(mGoogleApiClient, item); Achievements.UpdateAchievementResult updateResult = (Achievements.UpdateAchievementResult)updatePending .await(60, TimeUnit.SECONDS); if (updateResult != null) { int updateStatus = updateResult.getStatus().getStatusCode(); if (updateStatus == GamesStatusCodes.STATUS_OK) { mPreferences.removeAchievementFromQueue(item); if (item.equalsIgnoreCase(getString(R.string.achievement_100000_km))) { Games.Achievements.reveal(mGoogleApiClient, getString(R.string.achievement_384400_km)); Games.Achievements.reveal(mGoogleApiClient, getString(R.string.achievement_1_au)); } } } } } @Override public void postExecute() { // Nothing } } /** * Load data for options menu off UI */ private class MenuTask extends BaseAsyncTask { private boolean mHasToken = false; @Override public void inBackground() { mHasToken = mPreferences.hasFoursquareToken(); } @Override public void postExecute() { if (mHasFsqToken != mHasToken) { mHasFsqToken = mHasToken; invalidateOptionsMenu(); } } } private class MapDataTask extends BaseAsyncTask { private MovementContainer mContainer; private final ArrayList<Checkin> mCheckins = new ArrayList<Checkin>(); private int mDay; // final private ArrayList<PolylineOptions> mPolylines = new ArrayList<PolylineOptions>(); final private ArrayList<MarkerOptions> mMarkers = new ArrayList<MarkerOptions>(); private LatLngBounds mBounds; public MapDataTask(int day) { mDay = day; } @Override public void inBackground() { mContainer = mMovementHelper.getDataForDay(mDay); if (mContainer == null || mContainer.locations == null || mContainer.locations.isEmpty()) { return; } // Midnight final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, mDay); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); long midnight = calendar.getTimeInMillis(); // Pre-generate map polylines final int colorStartR = Color.red(mMapColorStart); final int colorStartG = Color.green(mMapColorStart); final int colorStartB = Color.blue(mMapColorStart); final double colorRStep = (Color.red(mMapColorEnd) - colorStartR) / (double)DateUtils.DAY_IN_MILLIS; final double colorGStep = (Color.green(mMapColorEnd) - colorStartG) / (double)DateUtils.DAY_IN_MILLIS; final double colorBStep = (Color.blue(mMapColorEnd) - colorStartB) / (double)DateUtils.DAY_IN_MILLIS; double[] latBounds = new double[]{Double.MAX_VALUE, Double.MIN_VALUE}; double[] lonBounds = new double[]{Double.MAX_VALUE, Double.MIN_VALUE}; LatLng latLngPrev = null; for (Location model : mContainer.locations) { LatLng latLng = new LatLng(model.latitude, model.longitude); if (latLngPrev != null) { int color = Color.argb( 255, (int)(colorStartB + (colorRStep * (model.time - midnight))), (int)(colorStartG + (colorGStep * (model.time - midnight))), (int)(colorStartB + (colorBStep * (model.time - midnight))) ); final PolylineOptions polylineOpts = new PolylineOptions(); polylineOpts.zIndex(1010); polylineOpts.width(mMapStrokeWidth); polylineOpts.color(color); polylineOpts.geodesic(true); polylineOpts.add(latLngPrev); polylineOpts.add(latLng); mPolylines.add(polylineOpts); } latLngPrev = latLng; latBounds[0] = Math.min(latBounds[0], model.latitude); latBounds[1] = Math.max(latBounds[1], model.latitude); lonBounds[0] = Math.min(lonBounds[0], model.longitude); lonBounds[1] = Math.max(lonBounds[1], model.longitude); } // Checkins ArrayList<Checkin> checkins = mMovementHelper.getCheckinsForDay(mDay); if (checkins != null) { synchronized (mCheckins) { mCheckins.clear(); mCheckins.addAll(checkins); } } // Checkin markers final BitmapDescriptor pin = BitmapDescriptorFactory.fromResource(R.drawable.ic_checkin); for (Checkin checkin : mCheckins) { String title; if (TextUtils.isEmpty(checkin.shout)) { title = checkin.name; } else { title = "\"" + checkin.shout + "\" @ " + checkin.name; } final MarkerOptions markerOpts = new MarkerOptions(); markerOpts.position(new LatLng(checkin.latitude, checkin.longitude)); markerOpts.title(title); markerOpts.icon(pin); markerOpts.anchor(0.5f, 0.5f); mMarkers.add(markerOpts); latBounds[0] = Math.min(latBounds[0], checkin.latitude); latBounds[1] = Math.max(latBounds[1], checkin.latitude); lonBounds[0] = Math.min(lonBounds[0], checkin.longitude); lonBounds[1] = Math.max(lonBounds[1], checkin.longitude); } // Map bounds if (!mContainer.locations.isEmpty() || !mCheckins.isEmpty()) { LatLng ne = new LatLng(latBounds[0], lonBounds[0]); LatLng sw = new LatLng(latBounds[1], lonBounds[1]); mBounds = new LatLngBounds(ne, sw); } } @Override public void postExecute() { // Locations final GoogleMap map = vMap.getMap(); map.clear(); // Polyline for (PolylineOptions polylineOptions : mPolylines) { map.addPolyline(polylineOptions); } // Checkins if (!mMarkers.isEmpty()) { for (MarkerOptions markerOptions : mMarkers) { map.addMarker(markerOptions); } } // Center map int mapMargin = getResources().getDimensionPixelSize(R.dimen.margin_map); map.setPadding( mapMargin, vMap.getHeight() - getResources().getDimensionPixelSize(R.dimen.map_size), // top mapMargin, mapMargin ); if (mBounds != null) { map.animateCamera( CameraUpdateFactory.newLatLngBounds( mBounds, mapMargin ) ); } else { // TODO: center to my location, zoom 14 } } public int getDay() { return mDay; } } protected class StartAnimatorListener implements Animator.AnimatorListener { private View mView; public StartAnimatorListener(View view) { mView = view; } @Override public void onAnimationStart(Animator animator) { mView.setVisibility(View.VISIBLE); } @Override public void onAnimationEnd(Animator animator) { // empty } @Override public void onAnimationCancel(Animator animator) { // empty } @Override public void onAnimationRepeat(Animator animator) { // empty } } protected class EndAnimatorListener implements Animator.AnimatorListener { private View mView; private int mTotal; private int mCurrent; public EndAnimatorListener(View view, int total, int current) { mView = view; mTotal = total; mCurrent = current; } @Override public void onAnimationStart(Animator animator) { // empty } @Override public void onAnimationEnd(Animator animator) { mView.setVisibility(View.INVISIBLE); if (mCurrent == (mTotal - 1)) { displayAchievements(); } } @Override public void onAnimationCancel(Animator animator) { // empty } @Override public void onAnimationRepeat(Animator animator) { // empty } } }
/* * Copyright 2014 Basho Technologies Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.basho.riak.client.api.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotates a field or getter/setter method pair in a class to serve as the key. * <p> * The type must be a {@code String}. * <p> * <pre> * public class MyPojo * { * {@literal @}RiakKey * public String key; * } * * public class AnotherPojo * { * private String key; * * {@literal @}RiakKey * public String getKey() * { * return key; * } * * {@literal @}RiakKey * public void setKey(String key) * { * this.key = key; * } * } * </pre> * @author Russell Brown <russelldb at basho dot com> * @author Brian Roach <roach at basho dot com> * @since 1.0 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface RiakKey { }
package actions.ajax; import com.opensymphony.xwork2.ActionSupport; import facade.GestionStratego; import facade.GestionStrategoInterface; import modele.Joueur; import org.apache.struts2.interceptor.ApplicationAware; import org.apache.struts2.interceptor.SessionAware; import java.util.Map; public class AjaxCheckCompositionJoueurAction extends ActionSupport implements ApplicationAware, SessionAware { private Map<String, Object> applicationMap; private Map<String, Object> sessionMap; static String MAFACADE = "facade"; private Joueur joueurAVerifier; private Map<Joueur, int[]> lesCompositions; private boolean compositionValide; GestionStratego facade; public final String execute() { GestionStratego facade = (GestionStratego) this.applicationMap.get("facade"); compositionValide = false; Joueur unJoueur = facade.getJoueur((String) sessionMap.get("pseudo")); lesCompositions = facade.getLesCompositions(); if(unJoueur.getPartie().getJoueurCreateur().equals(unJoueur)){ joueurAVerifier = unJoueur.getPartie().getJoueur2(); System.out.println(joueurAVerifier.getPseudo()); } else{ joueurAVerifier = unJoueur.getPartie().getJoueurCreateur(); System.out.println(joueurAVerifier.getPseudo()); } for(Map.Entry<Joueur,int[]> joueurAvecCompo : lesCompositions.entrySet()){ if(joueurAvecCompo.getKey().getPseudo().equals(joueurAVerifier.getPseudo())) compositionValide = true; } return SUCCESS; } public void setApplication(Map<String, Object> map) { if (this.facade == null) { this.facade = GestionStratego.getInstance(); map.put(MAFACADE,facade); } this.applicationMap = map; } public void setSession(Map<String, Object> map) { sessionMap = map; } public Map<String, Object> getApplicationMap() { return applicationMap; } public Map<String, Object> getSessionMap() { return sessionMap; } public Joueur getJoueurAVerifier() { return joueurAVerifier; } public void setJoueurAVerifier(Joueur joueurAVerifier) { this.joueurAVerifier = joueurAVerifier; } public Map<Joueur, int[]> getLesCompositions() { return lesCompositions; } public void setLesCompositions(Map<Joueur, int[]> lesCompositions) { this.lesCompositions = lesCompositions; } public boolean isCompositionValide() { return compositionValide; } public void setCompositionValide(boolean compositionValide) { this.compositionValide = compositionValide; } }
package com.example.words.aty; import android.app.Fragment; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import com.example.words.R; import java.util.ArrayList; /** * Created by 6gold on 2017/5/22. */ public class MyBooksActivity extends FragmentActivity implements View.OnClickListener { private ViewPager vpMyBooks; //vp private FragmentPagerAdapter myBooksPagerAdapter; //pa适配器 //fragment切换按钮 private Button btnMyBooks1; private Button btnMyBooks2; private Button btnMyBooks3; private ImageButton btnReturn; //返回按钮 //装载Fragments private ArrayList<android.support.v4.app.Fragment> myBooksFragments; //三个fragment的layout private LinearLayout ll_mybooks1; private LinearLayout ll_mybooks2; private LinearLayout ll_mybooks3; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mybooks); initViews(); initDatas(); initEvents(); resetButtons(); selectTab(0); } public void initViews() { vpMyBooks = (ViewPager) findViewById(R.id.vp_mybooks); btnMyBooks1 = (Button) findViewById(R.id.btn_mybooks_tab1); btnMyBooks2 = (Button) findViewById(R.id.btn_mybooks_tab2); btnMyBooks3 = (Button) findViewById(R.id.btn_mybooks_tab3); btnReturn = (ImageButton) findViewById(R.id.btn_return_mybooks); ll_mybooks1 = (LinearLayout) findViewById(R.id.ll_fragment_mybooks1); ll_mybooks2 = (LinearLayout) findViewById(R.id.ll_fragment_mybooks2); ll_mybooks3 = (LinearLayout) findViewById(R.id.ll_fragment_mybooks3); } public void initEvents() { //设置tab按钮点击事件 btnMyBooks1.setOnClickListener(this); btnMyBooks2.setOnClickListener(this); btnMyBooks3.setOnClickListener(this); btnReturn.setOnClickListener(this); } public void initDatas() { myBooksFragments = new ArrayList<>(); //将三个Fragment加入集合 myBooksFragments.add(new MyBooks1Fragment()); myBooksFragments.add(new MyBooks2Fragment()); myBooksFragments.add(new MyBooks3Fragment()); //初始化适配器 myBooksPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public android.support.v4.app.Fragment getItem(int position) { //从集合中获取对应位置的Fragment return myBooksFragments.get(position); } @Override public int getCount() {//获取集合中Fragment的总数 return myBooksFragments.size(); } }; //设置vp适配器 vpMyBooks.setAdapter(myBooksPagerAdapter); vpMyBooks.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override //页面滚动事件 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override //页面选中事件 public void onPageSelected(int position) { // myBooksPagerAdapter.notifyDataSetChanged(); vpMyBooks.setCurrentItem(position); resetButtons();//按钮底色全部置浅色,上面的字全部置深色 selectTab(position);//被选中按钮底色置深色,上面的字置浅色 } @Override //页面滚动状态改变事件 public void onPageScrollStateChanged(int state) { } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_mybooks_tab1: { resetButtons(); selectTab(0); break; } case R.id.btn_mybooks_tab2: { resetButtons(); selectTab(1); break; } case R.id.btn_mybooks_tab3: { resetButtons(); selectTab(2); break; } case R.id.btn_return_mybooks: { finish(); break; } } } public void resetButtons() { btnMyBooks1.setBackgroundColor(Color.parseColor("#f8f8f8")); btnMyBooks2.setBackgroundColor(Color.parseColor("#f8f8f8")); btnMyBooks3.setBackgroundColor(Color.parseColor("#f8f8f8")); btnMyBooks1.setTextColor(Color.parseColor("#333333")); btnMyBooks2.setTextColor(Color.parseColor("#333333")); btnMyBooks3.setTextColor(Color.parseColor("#333333")); } public void selectTab(int position) { switch (position) { case 0: btnMyBooks1.setBackgroundColor(Color.parseColor("#333333")); btnMyBooks1.setTextColor(Color.parseColor("#f8f8f8")); break; case 1: btnMyBooks2.setBackgroundColor(Color.parseColor("#333333")); btnMyBooks2.setTextColor(Color.parseColor("#f8f8f8")); break; case 2: btnMyBooks3.setBackgroundColor(Color.parseColor("#333333")); btnMyBooks3.setTextColor(Color.parseColor("#f8f8f8")); break; } vpMyBooks.setCurrentItem(position); } /* * @重写aty生命周期中的其它几个函数 */ @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); } } /* * 注意 * ①这里要导入的是import android.support.v4.app.Fragment;的fragment * 而不是android.app.Fragment * 因为ViewPager是import android.support.v4.app.Fragment * */
package cn.hellohao.utils; import org.springframework.context.annotation.Configuration; import org.springframework.http.CacheControl; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.util.concurrent.TimeUnit; //@Configuration public class WebConfigConfigurer extends WebMvcConfigurationSupport { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { Print.Normal("修改响应头开始"); registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/") //.setCacheControl(CacheControl.noCache()); .setCacheControl( CacheControl.maxAge(1, TimeUnit.SECONDS) .cachePublic()); } }
package com.stk123.web.action; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import com.stk123.web.core.ActionContext; public class WeixinAction { public String perform() throws Exception { ActionContext ac = ActionContext.getContext(); HttpServletRequest request = ac.getRequest(); Enumeration<String> en = request.getParameterNames(); while(en.hasMoreElements()){ String name = en.nextElement(); String value = request.getParameter(name); System.out.println(name + "=" +value); } String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String echostr = request.getParameter("echostr"); List list = new ArrayList(); list.add("stk123"); list.add(timestamp); list.add(nonce); Collections.sort(list); String s = StringUtils.join(list,""); String hashCode = hash(s, "SHA1"); System.out.println("hashCode="+hashCode); ac.setResponse(echostr); return null;//"/wx/test.html"; } public static String hash(String string, String algorithm) { if (string.isEmpty()) { return ""; } MessageDigest hash = null; try { hash = MessageDigest.getInstance(algorithm); byte[] bytes = hash.digest(string.getBytes("UTF-8")); String result = ""; for (byte b : bytes) { String temp = Integer.toHexString(b & 0xff); if (temp.length() == 1) { temp = "0" + temp; } result += temp; } return result; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; } }
/* * Copyright 2002-2021 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.web.multipart; import jakarta.servlet.http.HttpServletRequest; /** * A strategy interface for multipart file upload resolution in accordance * with <a href="https://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>. * Implementations are typically usable both within an application context * and standalone. * * <p>Spring provides the following concrete implementation: * <ul> * <li>{@link org.springframework.web.multipart.support.StandardServletMultipartResolver} * for the Servlet Part API * </ul> * * <p>There is no default resolver implementation used for Spring * {@link org.springframework.web.servlet.DispatcherServlet DispatcherServlets}, * as an application might choose to parse its multipart requests itself. To define * an implementation, create a bean with the id "multipartResolver" in a * {@link org.springframework.web.servlet.DispatcherServlet DispatcherServlet's} * application context. Such a resolver gets applied to all requests handled * by that {@link org.springframework.web.servlet.DispatcherServlet}. * * <p>If a {@link org.springframework.web.servlet.DispatcherServlet} detects a * multipart request, it will resolve it via the configured {@link MultipartResolver} * and pass on a wrapped {@link jakarta.servlet.http.HttpServletRequest}. Controllers * can then cast their given request to the {@link MultipartHttpServletRequest} * interface, which allows for access to any {@link MultipartFile MultipartFiles}. * Note that this cast is only supported in case of an actual multipart request. * * <pre class="code"> * public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) { * MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; * MultipartFile multipartFile = multipartRequest.getFile("image"); * ... * }</pre> * * Instead of direct access, command or form controllers can register a * {@link org.springframework.web.multipart.support.ByteArrayMultipartFileEditor} * or {@link org.springframework.web.multipart.support.StringMultipartFileEditor} * with their data binder, to automatically apply multipart content to form * bean properties. * * <p>As an alternative to using a {@link MultipartResolver} with a * {@link org.springframework.web.servlet.DispatcherServlet}, * a {@link org.springframework.web.multipart.support.MultipartFilter} can be * registered in {@code web.xml}. It will delegate to a corresponding * {@link MultipartResolver} bean in the root application context. This is mainly * intended for applications that do not use Spring's own web MVC framework. * * <p>Note: There is hardly ever a need to access the {@link MultipartResolver} * itself from application code. It will simply do its work behind the scenes, * making {@link MultipartHttpServletRequest MultipartHttpServletRequests} * available to controllers. * * @author Juergen Hoeller * @author Trevor D. Cook * @since 29.09.2003 * @see MultipartHttpServletRequest * @see MultipartFile * @see org.springframework.web.multipart.support.ByteArrayMultipartFileEditor * @see org.springframework.web.multipart.support.StringMultipartFileEditor * @see org.springframework.web.servlet.DispatcherServlet */ public interface MultipartResolver { /** * Determine if the given request contains multipart content. * <p>Will typically check for content type "multipart/form-data", but the actually * accepted requests might depend on the capabilities of the resolver implementation. * @param request the servlet request to be evaluated * @return whether the request contains multipart content */ boolean isMultipart(HttpServletRequest request); /** * Parse the given HTTP request into multipart files and parameters, * and wrap the request inside a * {@link org.springframework.web.multipart.MultipartHttpServletRequest} * object that provides access to file descriptors and makes contained * parameters accessible via the standard ServletRequest methods. * @param request the servlet request to wrap (must be of a multipart content type) * @return the wrapped servlet request * @throws MultipartException if the servlet request is not multipart, or if * implementation-specific problems are encountered (such as exceeding file size limits) * @see MultipartHttpServletRequest#getFile * @see MultipartHttpServletRequest#getFileNames * @see MultipartHttpServletRequest#getFileMap * @see jakarta.servlet.http.HttpServletRequest#getParameter * @see jakarta.servlet.http.HttpServletRequest#getParameterNames * @see jakarta.servlet.http.HttpServletRequest#getParameterMap */ MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException; /** * Clean up any resources used for the multipart handling, * like a storage for the uploaded files. * @param request the request to clean up resources for */ void cleanupMultipart(MultipartHttpServletRequest request); }
package com.algorithm.tree; import java.util.LinkedList; import java.util.Queue; public class MaxDepth { static int sum = 0; public static int maxDepth(TreeNode root) { Queue<TreeNode> queue = new LinkedList(); queue.add(root); while(queue.size()!=0){ int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.remove(); if(node.left!=null){ queue.add(node.left); } if(node.right!=null){ queue.add(node.right); } } sum ++; } return sum; } public static void main(String[] args) { TreeNode treeNode = new TreeNode(3); treeNode.left = new TreeNode(9); treeNode.right = new TreeNode(20); treeNode.right.left = new TreeNode(15); treeNode.right.right = new TreeNode(7); maxDepth(treeNode); } }
package com.seboid.udemcalendrier; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.graphics.drawable.Drawable; import android.net.ParseException; import android.text.Html; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; // // une classe qui charge une page web et parse le contenu JSON // NOTE: cette classe NE DOIT PAS toucher à l'interface // // http://services.murmitoyen.com/udem/evenements/2013-03-24/2013-03-30 // http://services.murmitoyen.com/udem/categorie/2/2013-01-26/2013-02-01/ // http://services.murmitoyen.com/udem/groupe/7/2013-01-26/2013-02-01/ // http://services.murmitoyen.com/udem/souscategorie/64/2013-01-26/2013-02-01/ // // on a aussi les series (tag d'un evenement en particulier) // http://services.murmitoyen.com/udem/serie/cfd4b81e5657376b6 // (dans une serie, tous les evenements sont identiques, sauf pour les dates... ce sont de vrais // evenements qui doivent etre loader dans la bd. Ensuite on peut faire des select pour ramasser tout ca... // // http://services.murmitoyen.com/udem/<type>/<id>/<start>/<end> // // type=evenements, id=null, start/end obligatoire // type=categorie|groupe|souscategorie, id, start/end obligatoire // type=serie, id, start=null,end=null // // Load les data dans la bd. // // http://developer.android.com/reference/android/util/JsonReader.html // public class EventsAPI { // les informations intéressantes //Drawable icone; long time; ArrayList<HashMap<String,String>> hmList; // null si pas d'erreur String erreur; EventsAPI(String type,String id,String start,String end) { erreur=null; time=System.currentTimeMillis(); // String url="http://services.murmitoyen.com/udem/evenements/2013-03-26/2013-03-26"; String url="http://services.murmitoyen.com/udem/"+type; if( !type.equals("evenements") ) url+="/"+id; if( !type.equals("serie") ) url+="/"+start+"/"+end; // Log.d("events","loading "+url); hmList=new ArrayList<HashMap<String,String>>(); JsonReader jr; try { // lire la page web HttpEntity page = NetUtil.getHttp(url); // on va filter les <img ... /> parce qu' elles sont base64 et trop grosses myFilterInputStream in=new myFilterInputStream(page.getContent(),"<img","/>"); jr = new JsonReader(new InputStreamReader(in, "UTF-8")); try { jr.beginObject(); while (jr.hasNext()) { String name = jr.nextName(); // Log.d("json","name is "+name); if( name.equals("donnees") ) { jr.beginArray(); while( jr.hasNext() ) { hmList.add(readBase(jr)); } jr.endArray(); }else jr.skipValue(); } jr.endObject(); } finally { jr.close(); } } catch (ClientProtocolException e) { erreur="erreur http(protocol):"+e.getMessage(); } catch (IOException e) { erreur="erreur http(IO):"+e.getMessage(); } catch (IllegalStateException e) { erreur="erreur http(State):"+e.getMessage(); } catch (ParseException e) { erreur="erreur JSON(parse):"+e.getMessage(); } time=System.currentTimeMillis()-time; } // // JSON: donnees // // id, titre, url, description, date, heure_debut, heure_fin, // date_modif, type_horaire, vignette, image // HashMap<String,String> readBase(JsonReader jr) throws IOException { HashMap<String,String> hm=new HashMap<String,String>(); jr.beginObject(); while( jr.hasNext() ) { String n= jr.nextName(); String v="null"; // les null deviennent des "null" pour l'instant if( jr.peek()==JsonToken.NULL ) jr.nextNull(); else v=jr.nextString(); // on ne doit pas convertir la description... if( !n.equals("description") ) v=Html.fromHtml(v).toString(); hm.put(n,v); } jr.endObject(); // process certains champs... //long d1=date2epoch(hm.get("date"),null); // // champs calcules // // les heures de depart et fin en long hm.put("epoch_debut", Long.toString(TempsUtil.dateHeure2epoch(hm.get("date"),hm.get("heure_debut"),true))); hm.put("epoch_fin", Long.toString(TempsUtil.dateHeure2epoch(hm.get("date"),hm.get("heure_fin"),false))); hm.put("epoch_modif", Long.toString(TempsUtil.dateHeure2epoch(hm.get("date_modif")))); return hm; } }
/** * User: kost * Date: 29.04.14 * Time: 10:27 */ public class Fog { Color color; float fogVisibility; boolean isLinear; boolean enabled; public Fog () { color = new Color(); fogVisibility = 0; isLinear = true; enabled = false; } public Fog (Color color, float fogVisibility, boolean fogType) { this.color = color; this.fogVisibility = fogVisibility; this.isLinear = fogType; enabled = true; } public float getFogInterpolant (float dv) { if (!enabled) return 1; if (dv >= fogVisibility) return 0; if (isLinear) return (fogVisibility - dv) / fogVisibility; else return (float)Math.exp(-1 * dv / (fogVisibility - dv)); } }
package Java; //parent_30412-04312_child Constructor public class ParentC { public ParentC() { this(1,2,3); System.out.println(" Parent Default Constructor "); } public ParentC(int a) { this(1,2,3,4); System.out.println(" Parent 01 parameterized Constructor "); } public ParentC(int a, int b) { this(1); System.out.println(" Parent 02 parameterized Constructor "); } public ParentC(int a, int b, int c) { System.out.println(" Parent 03 parameterized Constructor "); } public ParentC(int a, int b, int c, int d) { this(); System.out.println(" Parent 04 parameterized Constructor "); } }
package com.dimen.live.pusher; import com.dimen.jni.PusherNative; import com.dimen.listener.LiveStateChangeListener; import com.dimen.params.AudioParams; import com.dimen.params.VideoParams; import android.hardware.Camera.CameraInfo; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; public class LivePusher implements Callback { private SurfaceHolder surfaceHolder; private VideoPusher videoPusher; private AudioPusher audioPusher; private VideoParams videoParams; private PusherNative pusherNative; public LivePusher(SurfaceHolder surfaceHolder) { this.surfaceHolder = surfaceHolder; surfaceHolder.addCallback(this); prepare(); } private void prepare() { pusherNative=new PusherNative(); videoParams = new VideoParams(420, 320, CameraInfo.CAMERA_FACING_BACK); videoPusher = new VideoPusher(surfaceHolder, videoParams,pusherNative); AudioParams audioParams =new AudioParams(); audioPusher = new AudioPusher(audioParams,pusherNative); } /** * 切换摄像头 */ public void switchCamera() { videoPusher.switchCamera(); } /** * 开始推流 */ public void startPusher(String url,LiveStateChangeListener liveStateChangeListener) { // TODO Auto-generated method stub videoPusher.startPush(); audioPusher.startPush(); pusherNative.startPush(url); pusherNative.setLiveStateChangeListener(liveStateChangeListener); } /** * 停止推流 */ public void stopPusher(){ videoPusher.stopPush(); audioPusher.stopPush(); pusherNative.stopPush(); pusherNative.removeLiveStateChangeListener(); } /** * 释放资源 */ private void release(){ videoPusher.release(); audioPusher.release(); pusherNative.realease(); } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { stopPusher(); release(); } }
package com.nt.aspect; import java.util.Arrays; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class LogAroundAdvice implements MethodInterceptor{ private static Logger logger=Logger.getLogger(LogAroundAdvice.class); static { PropertyConfigurator.configure("src/main/java/com/nt/commons/log4j.properties"); } @Override public Object invoke(MethodInvocation invocation) throws Throwable { Object retVal=null; Object args[]=null; logger.info(invocation.getMethod().getName()+" with args "+Arrays.toString(invocation.getArguments())); args=invocation.getArguments(); //modify the argument values here if(((float)args[0] )<= 50000) { args[1]=((float)args[1])- 0.5f; } if(((float)args[0])<=0 || ((float)args[1]) <= 0 || ((float)args[2]) <= 0) { throw new IllegalArgumentException(); }else { retVal = invocation.proceed(); } retVal=((float)retVal)+((float)retVal)*0.01f; logger.info(invocation.getMethod().getName()+" with args "+Arrays.toString(invocation.getArguments())); return retVal; } }
package com.ut.module_lock.activity; import android.content.Intent; import android.databinding.DataBindingUtil; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.widget.CheckBox; import android.widget.TextView; import com.alibaba.android.arouter.facade.annotation.Route; import com.ut.base.BaseActivity; import com.ut.base.UIUtils.RouterUtil; import com.ut.base.Utils.DialogUtil; import com.ut.module_lock.R; import com.ut.module_lock.common.Constance; import com.ut.module_lock.databinding.ActivityEditLoopBinding; import com.ut.database.entity.Key; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * author : chenjiajun * time : 2018/12/6 * desc :修改循环钥匙页面 */ @Route(path = RouterUtil.LockModulePath.EDIT_LOOP_TIME) public class EditLoopKeyActivity extends BaseActivity { private ActivityEditLoopBinding mBinding; private Key mKey; private CheckBox checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6, checkBox7; private int mY, mM, mD; private int sY, sM, sD, eY, eM, eD; private int mHour, mMin; private int sHour, sMin; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_edit_loop); mKey = (Key) getIntent().getSerializableExtra(Constance.KEY_INFO); if (mKey == null) { if (getIntent().hasExtra("weeks")) { mKey = new Key(); mKey.setWeeks(getIntent().getStringExtra("weeks")); mKey.setStartTime(getIntent().getStringExtra("valid_time")); mKey.setEndTime(getIntent().getStringExtra("invalid_time")); mKey.setStartTimeRange(getIntent().getStringExtra("start_time_range")); mKey.setEndTimeRange(getIntent().getStringExtra("end_time_range")); } } mBinding.setKeyItem(mKey); initUI(); } private void initUI() { initDarkToolbar(); setTitle(R.string.lock_loop_key); checkBox1 = mBinding.include5.findViewById(R.id.monday); checkBox2 = mBinding.include5.findViewById(R.id.tuesday); checkBox3 = mBinding.include5.findViewById(R.id.wednesday); checkBox4 = mBinding.include5.findViewById(R.id.thursday); checkBox5 = mBinding.include5.findViewById(R.id.friday); checkBox6 = mBinding.include5.findViewById(R.id.saturday); checkBox7 = mBinding.include5.findViewById(R.id.sunday); mBinding.btnSave.setOnClickListener(v -> save()); String weeks = mKey.getWeeks(); if (weeks.contains("1")) { checkBox1.setChecked(true); } if (weeks.contains("2")) { checkBox2.setChecked(true); } if (weeks.contains("3")) { checkBox3.setChecked(true); } if (weeks.contains("4")) { checkBox4.setChecked(true); } if (weeks.contains("5")) { checkBox5.setChecked(true); } if (weeks.contains("6")) { checkBox6.setChecked(true); } if (weeks.contains("7")) { checkBox7.setChecked(true); } SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()); try { long validTime = sdf.parse(mKey.getStartTimeRange()).getTime(); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(validTime); sHour = calendar.get(Calendar.HOUR_OF_DAY); sMin = calendar.get(Calendar.MINUTE); } catch (ParseException e) { e.printStackTrace(); } if (mKey.getKeyId() > 0) { setRightArrow(mBinding.validTime); setRightArrow(mBinding.invalidTime); setRightArrow(mBinding.startDate); setRightArrow(mBinding.endDate); mBinding.validTime.setOnClickListener(v -> { mHour = sHour; mMin = sMin; chooseTime(v, getString(R.string.valid_time)); }); mBinding.invalidTime.setOnClickListener(v -> { mHour = sHour; mMin = sMin; Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, mHour); calendar.set(Calendar.MINUTE, mMin); calendar.add(Calendar.MINUTE, 15); mHour = calendar.get(Calendar.HOUR_OF_DAY); mMin = calendar.get(Calendar.MINUTE); chooseTime(v, getString(R.string.invalid_time)); }); mBinding.startDate.setOnClickListener(v -> { mY = sY; mM = sM; mD = sD; chooseDate(v, getString(R.string.lock_start_date)); }); mBinding.endDate.setOnClickListener(v -> { handleEnDate(); chooseDate(v, getString(R.string.lock_end_state)); }); } } private void handleEnDate() { if (sY > 0) { mY = sY; mM = sM; mD = sD; Calendar calendar = Calendar.getInstance(); calendar.set(mY, mM, mD); calendar.add(Calendar.DAY_OF_MONTH, 1); mY = calendar.get(Calendar.YEAR); mM = calendar.get(Calendar.MONTH); mD = calendar.get(Calendar.DAY_OF_MONTH); } } private void chooseTime(View v, String title) { DialogUtil.chooseTime(v.getContext(), title, (hour, minute) -> { String dateTime = String.format(Locale.getDefault(), "%02d", hour) + ":" + String.format(Locale.getDefault(), "%02d", minute) + ":" + String.format(Locale.getDefault(), "%02d", 0); if (getString(R.string.valid_time).equals(title)) { mKey.setStartTimeRange(dateTime); mHour = sHour = hour; mMin = sMin = minute; } else { mKey.setEndTimeRange(dateTime); } mBinding.setKeyItem(mKey); }, getString(R.string.invalid_time).equals(title)); } private void save() { StringBuilder weeks = new StringBuilder(); if (checkBox1.isChecked()) { weeks.append(weeks.length() == 0 ? "1" : ",1"); } if (checkBox2.isChecked()) { weeks.append(weeks.length() == 0 ? "2" : ",2"); } if (checkBox3.isChecked()) { weeks.append(weeks.length() == 0 ? "3" : ",3"); } if (checkBox4.isChecked()) { weeks.append(weeks.length() == 0 ? "4" : ",4"); } if (checkBox5.isChecked()) { weeks.append(weeks.length() == 0 ? "5" : ",5"); } if (checkBox6.isChecked()) { weeks.append(weeks.length() == 0 ? "6" : ",6"); } if (checkBox7.isChecked()) { weeks.append(weeks.length() == 0 ? "7" : ",7"); } mKey.setWeeks(weeks.toString()); Intent intent = new Intent(); intent.putExtra(Constance.KEY_INFO, mKey); setResult(RESULT_OK, intent); finish(); } private void chooseDate(View v, String title) { int tv_year = -1; int tv_month = -1; int tv_day = -1; if (v != null) { String timeStr = ((TextView) v).getText().toString(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = null; try { date = dateFormat.parse(timeStr); Calendar calendar = Calendar.getInstance(); // calendar.setTime(date); tv_year = calendar.get(Calendar.YEAR); tv_month = calendar.get(Calendar.MONTH) + 1; tv_day = calendar.get(Calendar.DAY_OF_MONTH); } catch (ParseException e) { e.printStackTrace(); } } DialogUtil.chooseDate(v.getContext(), title, (year, month, day) -> { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); Calendar calendar = Calendar.getInstance(); calendar.set(year, month - 1, day); if (getString(R.string.lock_start_date).equals(title)) { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); sY = year; sM = month - 1; sD = day; mKey.setStartTime(sdf.format(new Date(calendar.getTimeInMillis()))); } else { calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); mKey.setEndTime(sdf.format(new Date(calendar.getTimeInMillis()))); eY = year; eM = month - 1; eD = day; } mBinding.setKeyItem(mKey); }, tv_year, tv_month, tv_day); } private void setRightArrow(TextView textView) { Drawable dra = getResources().getDrawable(R.drawable.right_triangle); dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight()); textView.setCompoundDrawables(null, null, dra, null); } }
package com.example.wangchang.testbottomnavigationbar.fragment; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.TextView; import com.example.wangchang.testbottomnavigationbar.R; import com.example.wangchang.testbottomnavigationbar.activity.MainActivity; import com.example.wangchang.testbottomnavigationbar.activity.girl.GirlActivity; import com.example.wangchang.testbottomnavigationbar.adapter.HomeAdapter; import com.example.wangchang.testbottomnavigationbar.base.ActivityLifeCycleEvent; import com.example.wangchang.testbottomnavigationbar.base.CacheKey; import com.example.wangchang.testbottomnavigationbar.base.DataKey; import com.example.wangchang.testbottomnavigationbar.enity.ResultsEntity; import com.example.wangchang.testbottomnavigationbar.http.Api; import com.example.wangchang.testbottomnavigationbar.http.HttpUtilGank; import com.example.wangchang.testbottomnavigationbar.http.ProgressSubscriber; import com.example.wangchang.testbottomnavigationbar.util.LogUtil; import com.jude.easyrecyclerview.EasyRecyclerView; import com.jude.easyrecyclerview.adapter.BaseViewHolder; import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import rx.Observable; import static android.content.ContentValues.TAG; import static com.example.wangchang.testbottomnavigationbar.R.id.gridRv; /** * Created by WangChang on 2016/5/15. */ public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnLoadMoreListener { @BindView(gridRv) EasyRecyclerView mEasyRecyclerView; @BindView(R.id.swipeRefreshLayout) SwipeRefreshLayout swipeRefreshLayout; @BindView(R.id.home_network_error_layout) ViewStub homeNetworkErrorLayout; private Context mContext; private View rootView; private Unbinder mUnbinder; private HomeAdapter mHomeAdapter; private int page = 1; private int size = 10; private ArrayList<ResultsEntity> data; private View networkErrorView; // TextView tryagain_a_tv; public static HomeFragment newInstance(String content) { Bundle args = new Bundle(); args.putString("ARGS", content); HomeFragment fragment = new HomeFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this.getActivity(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (rootView != null) { ViewGroup viewGroup = (ViewGroup) rootView.getParent(); if (viewGroup != null) { viewGroup.removeView(rootView); } } else { rootView = inflater.inflate(R.layout.fragment_home, container, false); mUnbinder = ButterKnife.bind(this, rootView); initView(rootView); getGirls(size, page, true, CacheKey.FIRSTGETGIRLS, true, true, true); } return rootView; } private void initView(View view) { data = new ArrayList<>(); mHomeAdapter = new HomeAdapter(mContext); mEasyRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 2)); // mEasyRecyclerView.setLayoutManager(new LinearLayoutManager(mContext)); mEasyRecyclerView.setAdapterWithProgress(mHomeAdapter); mHomeAdapter.setMore(R.layout.load_more_layout, this); mHomeAdapter.setNoMore(R.layout.no_more_layout); mHomeAdapter.setError(R.layout.error_layout); swipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.GREEN, Color.RED, Color.YELLOW); swipeRefreshLayout.setProgressViewOffset(false,DataKey.swipeStart, DataKey.swipeEnd); // swipeRefreshLayout.setProgressViewEndTarget (true,200); swipeRefreshLayout.setOnRefreshListener(this); mHomeAdapter.setOnItemClickListener(new HomeAdapter.HomeItemOnclickListen() { @Override public void onItemClick(int position, BaseViewHolder viewHold) { Intent intent = new Intent(mContext, GirlActivity.class); intent.putParcelableArrayListExtra("girls", data); intent.putExtra("current", position); ActivityOptionsCompat options = ActivityOptionsCompat.makeScaleUpAnimation(viewHold.itemView, viewHold.itemView.getWidth() / 2, viewHold.itemView.getHeight() / 2, 0, 0); startActivity(intent, options.toBundle()); } }); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } private void getGirls(int count, int page, final boolean isfresh, final String cacheKey, final boolean issave, final boolean forceRefresh, final boolean isShowDialog) { Observable ob = Api.getGankService().getBeauties(count, page); HttpUtilGank.getInstance().toSubscribe(ob, new ProgressSubscriber<List<ResultsEntity>>(mContext) { @Override protected void _onError(String message) { if (isfresh) { swipeRefreshLayout.setRefreshing(false); } showError(); } @Override protected void _onNext(List<ResultsEntity> list) { if (isfresh) { refresh(list); swipeRefreshLayout.setRefreshing(false); } else { load(list); } showNormal(); } }, cacheKey, ActivityLifeCycleEvent.CREATE, MainActivity.getInstance().getLifeSubject(), issave, forceRefresh, isShowDialog); } @Override public void onRefresh() { swipeRefreshLayout.setRefreshing(true); getGirls(size, 1, true, CacheKey.FIRSTGETGIRLS, true, true, false); page = 1; } @Override public void onLoadMore() { if (data.size() % 10 == 0) { LogUtil.d(TAG, "onloadmore"); page++; getGirls(size, page, false, CacheKey.LOADMOREGIRLS + String.valueOf(page), true, false, false); } } private void refresh(List<ResultsEntity> datas) { data.clear(); data.addAll(datas); mHomeAdapter.clear(); mHomeAdapter.addAll(datas); if ((datas != null && datas.size() <= 5) || datas == null) { mHomeAdapter.stopMore(); } } public void load(List<ResultsEntity> datas) { data.addAll(datas); mHomeAdapter.addAll(datas); if ((datas != null && datas.size() == 0) || datas == null) { mHomeAdapter.stopMore(); } } public void showError() { mEasyRecyclerView.showError(); if (networkErrorView != null) { networkErrorView.setVisibility(View.VISIBLE); return; } networkErrorView = homeNetworkErrorLayout.inflate(); TextView textView = (TextView) networkErrorView.findViewById(R.id.tryagain_tv); if(textView != null) textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { swipeRefreshLayout.setRefreshing(true); getGirls(size, page, true, CacheKey.FIRSTGETGIRLS, true, false, false); } }); } public void showNormal() { if (networkErrorView != null) { networkErrorView.setVisibility(View.GONE); } } @Override public void onDestroyView() { super.onDestroyView(); /* if (mUnbinder != null) { mUnbinder.unbind(); }*/ } }
package com.example.mapplication; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.RadioButton; import android.widget.Spinner; import android.widget.TextView; public class Activity3 extends AppCompatActivity { CheckBox cb1,cb2; RadioButton rb1,rb2; TextView lb1,lb2; Spinner sp1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_3); cb1 = (CheckBox) findViewById(R.id.checkOP1); cb2 = (CheckBox) findViewById(R.id.checkOP2); rb1 = (RadioButton) findViewById(R.id.radioButtonMasculino) ; rb2 = (RadioButton) findViewById(R.id.radioButtonFemenino); lb1 = (TextView) findViewById(R.id.txtSeleccionados); lb2 = (TextView) findViewById(R.id.txtSelColor) ; sp1 = (Spinner) findViewById(R.id.spinner1); String []opciones={"BLANCO","AZUL","ROJO"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, opciones); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sp1.setAdapter(adapter); sp1.setPrompt("ELIJA COLOR"); sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { lb2.setText(sp1.getSelectedItem().toString()); } @Override public void onNothingSelected(AdapterView<?> adapterView) { return; } }); rb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if(rb1.isChecked()) lb1.setText("MASCULINO"); } }); rb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if(rb2.isChecked()) lb1.setText("FEMENINO"); } }); cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if(cb1.isChecked()) { cb1.append(" Seleccionado"); } else { cb1.setText("Opcion 1"); } } }); cb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if(cb2.isChecked()) { cb2.append(" Seleccionado"); } else { cb2.setText("Opcion 2"); } } }); } }
package Arrays; public class PosAndNeg { public static void main(String[] args) { ArrayOperation ao = ArrayOperation.getInstance(); int[] a = ao.readElement(); ao.dispArr(a); int[] c = ao.countPN(a); System.out.println("Positive :"+c[0]+" Negative: "+c[1]); } }
package com.testFileUpload.util; import org.apache.http.entity.ContentType; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.springframework.mock.web.MockMultipartFile; public class FileUtil { public static MultipartFile transferFile(String fileAbsolutePath) throws IOException { File file = new File(fileAbsolutePath); FileInputStream fileInputStream = new FileInputStream(file); MultipartFile multipartFile = new MockMultipartFile(file.getName(),file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream); return multipartFile; } }
package com.larryhsiao.nyx.core.attachments; import com.silverhetch.clotho.Source; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import static java.sql.Statement.RETURN_GENERATED_KEYS; /** * New Attachment of a Jot */ public class NewAttachment implements Source<Attachment> { private final Source<Connection> source; private final String uri; private final long jotId; public NewAttachment(Source<Connection> source, String uri, long jotId) { this.source = source; this.uri = uri; this.jotId = jotId; } @Override public Attachment value() { try (PreparedStatement stmt = source.value().prepareStatement( // language=H2 "INSERT INTO attachments(uri, jot_id) " + "VALUES (?,?)", RETURN_GENERATED_KEYS )) { stmt.setString(1, uri); stmt.setLong(2, jotId); stmt.executeUpdate(); final ResultSet res = stmt.getGeneratedKeys(); if (!res.next()) { throw new IllegalArgumentException("Creating Attachment failed, jotId: " + jotId + ", Uri: " + uri); } return new ConstAttachment(res.getLong(1), jotId, uri, 1, 0 ); } catch (Exception e) { throw new IllegalArgumentException(e); } } }
package Problem_11060; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); int[] arr = new int[N]; int[] dp = new int[N]; dp[0] = 0; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 0; i<N;i++) arr[i] = Integer.parseInt(st.nextToken()); for(int i = 0; i<N;i++) { if(dp[i] == 0 && i > 0) continue; if(arr[i] > 0) { for(int j = 1; j<=arr[i];j++) { if(i+j >= N) continue; if(dp[i+j]>dp[i]+1 || dp[i+j] == 0) dp[i+j] = dp[i]+1; } } } if(N == 1) System.out.println(0); else if(dp[N-1] == 0) System.out.println(-1); else System.out.println(dp[N-1]); } }
package com.myCompany.soapWebService; import javax.jws.WebService; @WebService public interface MyWebService { String methode(); }
package testinggame.utils; import javafx.scene.control.Alert; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; public class Error extends Exception { static String titulo = "Sistema de Mensaje"; public Error(String mensaje) { super(mensaje); } public Error(Integer codigo) { super(codigo.toString()); } public static void Mensaje(String cadena) { Alert x = new Alert(Alert.AlertType.ERROR); x.setTitle(titulo); x.setContentText(cadena); x.setGraphic(null); x.setHeaderText(null); ButtonType _Ok = new ButtonType("OK",ButtonData.OK_DONE); x.getButtonTypes().setAll(_Ok); x.showAndWait(); } }