text
stringlengths
10
2.72M
package com.lfd.day0117_02_datasave; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private EditText etUserName = null; private EditText etUserPass = null; private CheckBox cbSave = null; // private File internalFile = new File( // "data/data/com.lfd.day0117_02_datasave/info.txt"); private File internalFile = null; private File extStorageFile = null; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sp = getSharedPreferences("info", MODE_PRIVATE); //internalFile = new File(getFilesDir(),"info.txt"); internalFile = new File(getCacheDir(),"info.txt"); //(设备空间不足-会被删除)获取缓存文件夹,package/cache/info.txt extStorageFile = new File(Environment.getExternalStorageDirectory(),"info.txt"); //获取sd卡的状态 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ internalFile = extStorageFile; } etUserName = (EditText) findViewById(R.id.etUserName); etUserPass = (EditText) findViewById(R.id.etUserPass); cbSave = (CheckBox) findViewById(R.id.cbSave); // List<String> infos = getInfo(internalFile); // if (!infos.isEmpty()) { // etUserName.setText(infos.get(0)); // etUserPass.setText(infos.get(1)); // } etUserName.setText(sp.getString("username", "")); etUserPass.setText(sp.getString("password", "")); System.out.println(internalFile.getAbsolutePath()); } public void login(View view) { if (cbSave.isChecked()) { // 保存到internal storage,不需要权限 // saveInfo(etUserName.getText().toString(), etUserPass.getText() // .toString(), internalFile); saveInfo(etUserName.getText().toString(), etUserPass.getText() .toString()); Toast.makeText(this, "登录成功", Toast.LENGTH_LONG).show(); } } /** * 保存用户名和密码 * * @param un * @param up * @param file */ public void saveInfo(String un, String up, File file) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(file)); writer.write(un); writer.newLine(); writer.write(up); } catch (IOException e) { e.printStackTrace(); } finally { try { if(writer!=null){ writer.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 读取用户名和密码 * * @param file * @return */ public List<String> getInfo(File file) { if (!file.exists()) { return Collections.emptyList(); } List<String> list = new ArrayList<String>(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String str = null; while ((str = reader.readLine()) != null) { list.add(str); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } return list; } /** * * @param file * @return long[] size 2 total,available */ @SuppressLint("NewApi") @SuppressWarnings("deprecation") public long[] getStorageSize(File file){ long availableBlocks; long blockCount; long blockSize; StatFs fs = new StatFs(internalFile.getPath()); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ availableBlocks = fs.getAvailableBlocksLong(); blockCount = fs.getBlockCountLong(); blockSize = fs.getBlockSizeLong(); }else{ availableBlocks = fs.getAvailableBlocks(); blockCount = fs.getBlockCount(); blockSize = fs.getBlockCount(); } return new long[]{blockSize*blockCount,blockSize*availableBlocks}; } public void pref(View view){ startActivity(new Intent(this,MainActivity2.class)); } public void saveInfo(String un,String up){ Editor edit = sp.edit(); edit.putString("username", un); edit.putString("password", up); edit.commit(); } }
public abstract class ManushDec implements Manush { Manush manush; public ManushDec(Manush m) { manush = m; } public String makeManush() { return manush.makeManush(); } }
/* redid shortTermScheduler, now named Dispatcher, in the current iteration the next hexAddr was never added intern CPU was never able to execute */ package OS; /** * Created by wei on 2/17/2017. */ /* public class ShortTermScheduler { private Dispatcher dispatcher; public ShortTermScheduler(Dispatcher dispatcher){ this.dispatcher = dispatcher; } public void FIFOShortTermScheduler(){ dispatcher.dispatchProgramCounter(); } /* private LinkedList<ControlBlock> readyQueue = new LinkedList<ControlBlock>(); //protected CPU[] cpus; private Dispatcher dispatcher; protected RamMemory ram; private ControlBlock currentProcess; private final int READY = 2; private final int FINISHED = 3; //public ShortTermScheduler(RamMemory ram, Dispatcher dispatcher, CPU[] cpus) { public ShortTermScheduler(RamMemory ram, Dispatcher dispatcher) { this.ram = ram; this.dispatcher = dispatcher; //this.cpus = cpus; } public void FIFOShortTermScheduler() { clearFinishedProcesses(); FIFOScheduleHelper(ram.getPCBListOnRam()); if (currentProcess == null || currentProcess.getStatus() == FINISHED) { currentProcess = dispatcher.dispatchProcessToCPU(readyQueue); //currentProcess.setExecutionStartingTime();// **********FOR TIME RECORD********** } System.out.println("I am here!!!!"); } public void PriorityShortTermScheduler() { clearFinishedProcesses(); try { PriorityScheduleHelper(ram.getPCBListOnRam()); } catch (NullPointerException E) { //X } if (currentProcess == null || currentProcess.getStatus() != FINISHED) {//X currentProcess = dispatcher.dispatchProcessToCPU(readyQueue);//X try{ currentProcess.setExecutionStartingTime();//X FOR TIME RECORD }catch (NullPointerException N){ } } } //private void FIFOScheduleHelper(ControlBlock[] pcbList, List<ControlBlock> currentProcesses) { private void FIFOScheduleHelper(ControlBlock[] pcbList) { for (ControlBlock pcb : pcbList) { if (pcb != null&& pcb.isInMemory() && !readyQueue.contains(pcb) && !pcb.equals(currentProcess)&& // !currentProcesses.contains((pcb))&& pcb.getStatus() != FINISHED) { addPCBToReadyQueue(pcb); } } } //private void FIFOScheduleHelper(ControlBlock[] pcbList, List<ControlBlock> currentProcesses) { private void PriorityScheduleHelper(ControlBlock[] pcbList){ for (ControlBlock pcb : pcbList) { if (pcb != null&& pcb.isInMemory() && !readyQueue.contains(pcb) && !pcb.equals(currentProcess)&& // !currentProcesses.contains((pcb))&& pcb.getPriority() <= currentProcess.getPriority()) { addPCBToReadyQueue(pcb); } } } public void clearFinishedProcesses() { ControlBlock[] PCBList = ram.getPCBListOnRam(); for (ControlBlock pcb: PCBList) { //Remove from memory if finished if (pcb != null && pcb.isInMemory() && pcb.getStatus() == FINISHED) {// NEED TO SET PCB STATUS TO "FINISHED" IN CPU RUN!!!!!!!!!!!!!!!!!!!!!!!!! //ram.removePCBFromMemory(pcb.getProgramCounter()); } } } public void addPCBToReadyQueue(ControlBlock pcb){ readyQueue.add(pcb); pcb.setInReadyQueueTime();// used to record arrival time pcb.setStatus(READY); } } }*/
package com.store.controller; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.store.pojo.Building; import com.store.service.BuildingService; import com.store.service.BuildingServiceImpl; import com.store.service.RoleService; import com.store.service.RoleServiceImpl; /** * Servlet implementation class BuildingIndexServlet */ @WebServlet("/roleDel") public class RoleDelServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public RoleDelServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //添加 Servelt //获取到参数中的 id String sid=request.getParameter("id"); RoleService bs=new RoleServiceImpl(); //调用删除的方法 bs.delSysRole(sid); response.sendRedirect("roleIndex"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.ing.product.model; import java.io.Serializable; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="product_group") public class ProductsGroup implements Serializable, Comparable{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column(name="proct_group_name") private String productGroupName; @Column(name="count") private int count; @OneToMany(mappedBy="productsGroup",cascade = CascadeType.ALL) public List<ProductName> productName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getProductGroupName() { return productGroupName; } public void setProductGroupName(String productGroupName) { this.productGroupName = productGroupName; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } @Override public int compareTo(Object pg) { int compareCount = ((ProductsGroup)pg).getCount(); return compareCount-this.getCount(); } }
package prototype.design.pattern.example; public class TestPrototype { public static void main(String args[]){ Wolf wolf=new Wolf(); // Perform operation on Wolf object // Needed a Wolf object again Wolf clonedWolf=(Wolf)wolf.createClone(); System.out.println("Original Wolf object hashcode : "+wolf.hashCode()); System.out.println("Cloned Wolf object hashcode : "+clonedWolf.hashCode()); } }
package com.xlickr.service; import com.xlickr.beans.User; import com.xlickr.hibernate.entities.FlickrUser; public interface UserService { public void saveNewUser(User user); public FlickrUser getFlickrUser(String username); public Long saveNewUserAlbums(String userName, String albumName, String albumDescription, Boolean isprivate); }
package com.mindnotix.service; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.os.SystemClock; import android.util.Log; import java.util.Timer; import java.util.TimerTask; public class MyService extends Service { public int counter = 0; private Timer timer; private TimerTask timerTask; private String TAG = "PERUSU"; public MyService() { } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); startTimer(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Log.i(TAG, "ondestroy!"); } public void startTimer() { timer = new Timer(); timerTask = new TimerTask() { public void run() { Log.i(TAG, "in timer ++++ " + (counter++)); } }; //schedule the timer, to wake up every 1 second timer.schedule(timerTask, 1000, 1000); // } @Override public void onTaskRemoved(Intent rootIntent) { Log.d(TAG, "onTaskRemoved"); Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass()); restartServiceIntent.setPackage(getPackageName()); PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarmService.set( AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePendingIntent); super.onTaskRemoved(rootIntent); } @Override public IBinder onBind(Intent intent) { return null; } }
package cn.backbone.tem.net; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; /** * Created by admin on 2016/8/31. */ public class SendThread implements Runnable { String host, sendMessage; int port, i; public int flag; public Socket socket; private Handler handler; public SendThread(String host, int port, int i, String sendMessage, int flag, Handler handler) { Log.d("chang","sendstart+gouzao"); System.out.print("1111"); this.host = host; this.port = port; this.i = i; this.sendMessage = sendMessage; this.flag = flag; this.handler = handler; } public void closeSocket() throws IOException { socket.close(); } public boolean socketisok(){ return socket.isConnected(); } @Override public void run() { Log.d("chang","sendstart"); try { socket = new Socket(host,port); //BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); while (flag == 1){ if (socket.isConnected()) { if (!socket.isOutputShutdown()) { Thread.sleep(i * 1000); out.println(sendMessage); Log.d("chang","sendOK"); } } } } catch (Exception e) { e.printStackTrace(); }finally { if(socket == null){ handler.sendEmptyMessage(22); } } } }
package com.bravi.prova.repositories; import com.bravi.prova.models.Person; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface PersonRepository extends JpaRepository<Person, Long> { List<Person> findAllByName(String name); List<Person> findAllByCpf(String cpf); }
/** * Copyright 2013 Netflix, 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 rx.schedulers; import java.util.PriorityQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import rx.Scheduler; import rx.Subscription; import rx.functions.Action0; import rx.subscriptions.BooleanSubscription; import rx.subscriptions.Subscriptions; /** * Schedules work on the current thread but does not execute immediately. Work is put in a queue and executed after the current unit of work is completed. */ public class TrampolineScheduler extends Scheduler { private static final TrampolineScheduler INSTANCE = new TrampolineScheduler(); /* package */static TrampolineScheduler instance() { return INSTANCE; } @Override public Worker createWorker() { return new InnerCurrentThreadScheduler(); } /* package accessible for unit tests */TrampolineScheduler() { } private static final ThreadLocal<PriorityQueue<TimedAction>> QUEUE = new ThreadLocal<PriorityQueue<TimedAction>>(); private final AtomicInteger counter = new AtomicInteger(0); private class InnerCurrentThreadScheduler extends Scheduler.Worker implements Subscription { private final BooleanSubscription innerSubscription = new BooleanSubscription(); @Override public Subscription schedule(Action0 action) { return enqueue(action, now()); } @Override public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) { long execTime = now() + unit.toMillis(delayTime); return enqueue(new SleepingAction(action, this, execTime), execTime); } private Subscription enqueue(Action0 action, long execTime) { if (innerSubscription.isUnsubscribed()) { return Subscriptions.empty(); } PriorityQueue<TimedAction> queue = QUEUE.get(); boolean exec = queue == null; if (exec) { queue = new PriorityQueue<TimedAction>(); QUEUE.set(queue); } final TimedAction timedAction = new TimedAction(action, execTime, counter.incrementAndGet()); queue.add(timedAction); if (exec) { while (!queue.isEmpty()) { if (innerSubscription.isUnsubscribed()) { return Subscriptions.empty(); } queue.poll().action.call(); } QUEUE.set(null); return Subscriptions.empty(); } else { return Subscriptions.create(new Action0() { @Override public void call() { PriorityQueue<TimedAction> _q = QUEUE.get(); if (_q != null) { _q.remove(timedAction); } } }); } } @Override public void unsubscribe() { QUEUE.set(null); // this assumes we are calling unsubscribe from the same thread innerSubscription.unsubscribe(); } @Override public boolean isUnsubscribed() { return innerSubscription.isUnsubscribed(); } } private static class TimedAction implements Comparable<TimedAction> { final Action0 action; final Long execTime; final Integer count; // In case if time between enqueueing took less than 1ms private TimedAction(Action0 action, Long execTime, Integer count) { this.action = action; this.execTime = execTime; this.count = count; } @Override public int compareTo(TimedAction that) { int result = execTime.compareTo(that.execTime); if (result == 0) { return count.compareTo(that.count); } return result; } } }
package listaJava5Polimorfismo; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class Exercicio3 { public static void main(String[] args) { /* * Crie uma um programa para trabalhar com estoque de uma loja, * o programa deverá trabalhar com Collection do tipo List do Java para manipular os dados desse estoque, * o programa deverá atender as seguintes funcionalidades: Armazenar dados da List Remover dados da list; Atualizar dados da list. Apresentar todos os dados da list. */ int index; List<Produto> lista = new ArrayList<Produto>(); //Set lista = new LinkedHashSet(); Produto produto1 = new Produto("Televisão", 1, 2500.99, "Preta", 10); Produto produto2 = new Produto("Geladeira", 2, 1500.99, "Inox", 10); Produto produto3 = new Produto("Smartphone",3, 2000.99, "Branco", 10); Produto produto4 = new Produto("Forno", 4, 800.99, "Preto", 10); Produto produto5 = new Produto("Notebook", 5, 5500.99, "Branco", 10); //Cachorro c2 = new Cachorro("Cachorro3", 3, "marrom"); lista.add(produto1); lista.add(produto2); lista.add(produto3); lista.add(produto4); lista.add(produto5); //lista.add(c2); System.out.println("----------LISTA DEPOIS DE ADICIONAR----------"); for (Object obj : lista) { System.out.println(obj.toString()); System.out.println("\n"); System.out.println("\n"); } lista.remove(produto4); lista.remove(produto2); System.out.println("----------LISTA DEPOIS DE REMOVER----------"); for (Object obj : lista) { System.out.println(obj.toString()); System.out.println("\n"); System.out.println("\n"); } lista.add(produto4); index = lista.indexOf(produto4); produto4.setPreco(999.00); lista.set(index, produto4); System.out.println("----------LISTA DEPOIS DE MODIFICAR ----------"); for (Object obj : lista) { System.out.println(obj.toString()); System.out.println("\n"); System.out.println("\n"); } } }
package com.komaxx.komaxx_gl.bound_meshes; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.graphics.RectF; import android.opengl.GLES20; import com.komaxx.komaxx_gl.RenderContext; import com.komaxx.komaxx_gl.math.GlRect; import com.komaxx.komaxx_gl.math.Vector; import com.komaxx.komaxx_gl.primitives.TexturedQuad; import com.komaxx.komaxx_gl.primitives.TexturedVertex; /** * This is a simplification of the BoundFreeMesh. It has always four vertices. * * @author Matthias Schicker */ public class BoundFreeQuad extends ABoundMesh { public static final byte VERTEX_UPPER_LEFT = 0; public static final byte VERTEX_LOWER_LEFT = 1; public static final byte VERTEX_LOWER_RIGHT = 2; public static final byte VERTEX_UPPER_RIGHT = 3; protected final TexturedVertex[] vertices; protected boolean positionDirty = true; protected boolean texCoordsDirty = true; protected final FloatBuffer vertexBuffer; public BoundFreeQuad(){ vertices = new TexturedVertex[TexturedQuad.VERTEX_COUNT]; for (int i = 0; i < TexturedQuad.VERTEX_COUNT; i++) vertices[i] = new TexturedVertex(); vertexBuffer = TexturedQuad.allocateQuads(1); indexBuffer = TexturedQuad.allocateQuadIndexArray(1); } public void setTexCoordsUv(byte vertex, float u, float v) { vertices[vertex].setUvCoords(u, v); texCoordsDirty = true; } public void setTexCoordsUv(RectF r) { vertices[VERTEX_UPPER_LEFT].setUvCoords(r.left, r.top); vertices[VERTEX_UPPER_RIGHT].setUvCoords(r.right, r.top); vertices[VERTEX_LOWER_LEFT].setUvCoords(r.left, r.bottom); vertices[VERTEX_LOWER_RIGHT].setUvCoords(r.right, r.bottom); texCoordsDirty = true; } public void positionXY(byte vertex, float x, float y) { vertices[vertex].setPositionXY(x, y); positionDirty = true; } public void positionXYZ(byte vertex, float x, float y, float z) { vertices[vertex].setPosition(x, y, z); positionDirty = true; } /** * Use this to place the quad along a vector. */ private static float[] tmpVector1 = new float[4]; private static float[] tmpVector2 = new float[4]; public void positionAlong2(float[] a, float[] b, float thickness){ float[] aToB = Vector.aToB2(tmpVector1, a, b); float[] normal = Vector.normal2(tmpVector2, aToB); Vector.normalize2(normal); Vector.scalarMultiply2(normal, thickness*0.5f); Vector.aPlusB2(vertices[VERTEX_UPPER_LEFT].getPosition(), a, normal); Vector.aMinusB2(vertices[VERTEX_UPPER_RIGHT].getPosition(), a, normal); Vector.aPlusB2(vertices[VERTEX_LOWER_LEFT].getPosition(), b, normal); Vector.aMinusB2(vertices[VERTEX_LOWER_RIGHT].getPosition(), b, normal); positionDirty = true; } @Override public int render(RenderContext rc, ShortBuffer frameIndexBuffer){ if (!visible) return 0; boolean vboDirty = false; if (positionDirty){ int offset = 0; for (int i = 0; i < 4; i++){ // upper left vertex vertices[i].writePosition(vertexBuffer, offset); offset += TexturedVertex.STRIDE_FLOATS; } positionDirty = false; vboDirty = true; } if (texCoordsDirty){ int offset = 0; for (int i = 0; i < 4; i++){ // upper left vertex vertices[i].writeUvCoords(vertexBuffer, offset); offset += TexturedVertex.STRIDE_FLOATS; } texCoordsDirty = false; vboDirty = true; } if (vboDirty){ vertexBuffer.position(0); GLES20.glBufferSubData(GLES20.GL_ARRAY_BUFFER, firstByteIndex, vertexBuffer.capacity()*4, vertexBuffer); vboDirty = false; } frameIndexBuffer.put(indexBuffer); return 6; } @Override public int getMaxVertexCount() { return TexturedQuad.VERTEX_COUNT; } @Override public int getMaxIndexCount() { return TexturedQuad.INDICES_COUNT; } public boolean contains(float[] xy) { return getBoundingBox().contains(xy) //&& fineContains(xy) ; } private static GlRect tmpBoundingBox = new GlRect(); private GlRect getBoundingBox() { float[] position = vertices[0].getPosition(); tmpBoundingBox.set(position[0], position[1], position[0], position[1]); tmpBoundingBox.enlarge(vertices[1].getPosition()); tmpBoundingBox.enlarge(vertices[2].getPosition()); tmpBoundingBox.enlarge(vertices[3].getPosition()); return tmpBoundingBox; } }
package com.example.zealience.oneiromancy.ui.fragment; import android.annotation.TargetApi; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import androidx.core.widget.NestedScrollView; import android.text.TextUtils; import android.view.View; import android.widget.LinearLayout; import android.widget.RatingBar; import android.widget.TextView; import com.alibaba.android.arouter.launcher.ARouter; import com.example.zealience.oneiromancy.R; import com.example.zealience.oneiromancy.api.ApiManager; import com.example.zealience.oneiromancy.api.ApiRequest; import com.steven.base.app.SharePConstant; import com.example.zealience.oneiromancy.constant.SnowConstant; import com.example.zealience.oneiromancy.entity.EventEntity; import com.example.zealience.oneiromancy.entity.LuckEntity; import com.steven.base.bean.UserInfo; import com.example.zealience.oneiromancy.ui.activity.CustomViewActivity; import com.example.zealience.oneiromancy.ui.activity.user.MyAddressActivity; import com.example.zealience.oneiromancy.ui.activity.SetingActivity; import com.example.zealience.oneiromancy.ui.activity.SignInActivity; import com.example.zealience.oneiromancy.ui.activity.user.UserInfolActivity; import com.example.zealience.oneiromancy.ui.widget.ConstellationSelectDialog; import com.steven.base.util.UserHelper; import com.hjq.bar.OnTitleBarListener; import com.hjq.bar.TitleBar; import com.hw.ycshareelement.YcShareElement; import com.hw.ycshareelement.transition.IShareElements; import com.hw.ycshareelement.transition.ShareElementInfo; import com.hw.ycshareelement.transition.TextViewStateSaver; import com.steven.base.ARouterPath; import com.steven.base.app.GlideApp; import com.steven.base.base.BaseFragment; import com.steven.base.rx.BaseObserver; import com.steven.base.rx.RxHelper; import com.steven.base.util.DisplayUtil; import com.steven.base.util.GsonUtil; import com.steven.base.util.SPUtils; import com.steven.base.widget.CustomLayoutGroup; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import de.hdodenhof.circleimageview.CircleImageView; /** * @user steven * @createDate 2019/3/6 18:02 * @description 我的页面 */ @TargetApi(Build.VERSION_CODES.M) public class MeFragment extends BaseFragment implements View.OnClickListener, IShareElements, View.OnScrollChangeListener { private NestedScrollView me_scroll_view; private CircleImageView ivMeHead; private CustomLayoutGroup customLayout_collection; private CustomLayoutGroup customLayoutSignIn; private CustomLayoutGroup customLayoutAddress; private CustomLayoutGroup customLayout_wee_video; private TitleBar me_title_bar; private TextView tv_user_nick; private TextView tv_set_constellation; private CustomLayoutGroup rl_my_constellation; private CustomLayoutGroup rl_date; private CustomLayoutGroup rl_luck_color; private CustomLayoutGroup rl_luck_number; private CustomLayoutGroup rl_friend; /** * 今日概述 */ private TextView tv_summary; private RatingBar rating_all; private RatingBar rating_health; private RatingBar rating_love; private RatingBar rating_money; private RatingBar rating_work; private LinearLayout ll_luck_content; public static MeFragment newInstance(String title) { Bundle bundle = new Bundle(); bundle.putString("title", title); MeFragment meFragment = new MeFragment(); meFragment.setArguments(bundle); return meFragment; } @Override public int getLayoutId() { return R.layout.fragment_me; } @Override public void initPresenter() { } @Override public void initView(Bundle savedInstanceState) { me_title_bar = (TitleBar) rootView.findViewById(R.id.me_title_bar); me_scroll_view = (NestedScrollView) rootView.findViewById(R.id.me_scroll_view); tv_user_nick = (TextView) rootView.findViewById(R.id.tv_user_nick); ivMeHead = (CircleImageView) rootView.findViewById(R.id.iv_me_head); customLayout_collection = (CustomLayoutGroup) rootView.findViewById(R.id.customLayout_collection); customLayoutSignIn = (CustomLayoutGroup) rootView.findViewById(R.id.customLayout_signIn); customLayoutAddress = (CustomLayoutGroup) rootView.findViewById(R.id.customLayout_address); customLayout_wee_video = (CustomLayoutGroup) rootView.findViewById(R.id.customLayout_wee_video); tv_set_constellation = (TextView) rootView.findViewById(R.id.tv_set_constellation); customLayout_collection = (CustomLayoutGroup) rootView.findViewById(R.id.customLayout_collection); rl_my_constellation = (CustomLayoutGroup) rootView.findViewById(R.id.rl_my_constellation); rl_date = (CustomLayoutGroup) rootView.findViewById(R.id.rl_date); rl_luck_color = (CustomLayoutGroup) rootView.findViewById(R.id.rl_luck_color); rl_luck_number = (CustomLayoutGroup) rootView.findViewById(R.id.rl_luck_number); rl_friend = (CustomLayoutGroup) rootView.findViewById(R.id.rl_friend); tv_summary = (TextView) rootView.findViewById(R.id.tv_summary); rating_all = (RatingBar) rootView.findViewById(R.id.rating_all); rating_health = (RatingBar) rootView.findViewById(R.id.rating_health); rating_love = (RatingBar) rootView.findViewById(R.id.rating_love); rating_money = (RatingBar) rootView.findViewById(R.id.rating_money); rating_work = (RatingBar) rootView.findViewById(R.id.rating_work); ll_luck_content = (LinearLayout) rootView.findViewById(R.id.ll_luck_content); me_title_bar.setRightIcon(R.mipmap.icon_set); GlideApp.with(_mActivity) .load(UserHelper.getUserInfo(_mActivity).getHeadImageUrl()) .placeholder(R.mipmap.icon_user) .into(ivMeHead); tv_user_nick.setText(UserHelper.getUserInfo(_mActivity).getNick()); customLayout_collection.setOnClickListener(this); customLayoutAddress.setOnClickListener(this); customLayoutSignIn.setOnClickListener(this); customLayout_wee_video.setOnClickListener(this); ivMeHead.setOnClickListener(this); tv_set_constellation.setOnClickListener(this); me_scroll_view.setOnScrollChangeListener(this); me_title_bar.setOnTitleBarListener(new OnTitleBarListener() { @Override public void onLeftClick(View v) { } @Override public void onTitleClick(View v) { } @Override public void onRightClick(View v) { startActivity(SetingActivity.class); } }); EventBus.getDefault().register(this); getUserLuckData(); } /** * 获取用户当天运势 */ private void getUserLuckData() { UserInfo userInfo = UserHelper.getUserInfo(_mActivity); if (!TextUtils.isEmpty(userInfo.getConstellation())) { tv_set_constellation.setVisibility(View.GONE); ll_luck_content.setVisibility(View.VISIBLE); mRxManager.add(ApiManager.getInstance().getUserLuckData(ApiRequest.getUserLuckData(userInfo.getConstellation(), "")).compose(RxHelper.customResult()).subscribeWith(new BaseObserver<LuckEntity>(_mActivity, false) { @Override protected void onSuccess(LuckEntity luckEntity) { if (luckEntity != null) { rl_my_constellation.setTv_right(luckEntity.getName()); rl_date.setTv_right(luckEntity.getDatetime()); rl_luck_color.setTv_right(luckEntity.getColor()); rl_luck_number.setTv_right(luckEntity.getNumber() + ""); rl_friend.setTv_right(luckEntity.getQFriend()); tv_summary.setText(luckEntity.getSummary()); rating_all.setRating(calculateRatingNum(luckEntity.getAll())); rating_health.setRating(calculateRatingNum(luckEntity.getHealth())); rating_love.setRating(calculateRatingNum(luckEntity.getLove())); rating_money.setRating(calculateRatingNum(luckEntity.getMoney())); rating_work.setRating(calculateRatingNum(luckEntity.getWork())); } } @Override protected void onError(String message) { } })); } else { ll_luck_content.setVisibility(View.GONE); tv_set_constellation.setVisibility(View.VISIBLE); } } /** * 计算星星的个数 * * @param value * @return */ private int calculateRatingNum(String value) { if (value.contains("%")) { int i = Integer.parseInt(value.substring(0, value.length() - 1)); if (i == 0) { return 0; } else if (i > 0 && i < 20) { return 1; } else if (i >= 20 && i < 40) { return 2; } else if (i >= 40 && i < 60) { return 3; } else if (i >= 60 && i < 80) { return 4; } else if (i >= 80 && i < 100) { return 5; } } return 0; } @Override public void onError(String msg) { } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); } @Override public void onClick(View v) { if (v == ivMeHead) { Intent intent = new Intent(_mActivity, UserInfolActivity.class); Bundle optionsBundle = YcShareElement.buildOptionsBundle(_mActivity, MeFragment.this); startActivity(intent, optionsBundle); } if (v == customLayout_collection) { startActivity(CustomViewActivity.class); } if (v == customLayoutAddress) { startActivity(MyAddressActivity.class); } if (v == customLayoutSignIn) { startActivity(SignInActivity.class); } if (v == customLayout_wee_video) { ARouter.getInstance().build(ARouterPath.WEE_VIDEO_MAIN_ACTIVITY).navigation(); } if (v == tv_set_constellation) { ConstellationSelectDialog selectDialog = new ConstellationSelectDialog(_mActivity, null); selectDialog.setMyOnItemClickListener(new ConstellationSelectDialog.MyOnItemClickListener() { @Override public void getSelectType(String s) { UserInfo userInfo = UserHelper.getUserInfo(_mActivity); userInfo.setConstellation(s); SPUtils.setSharedStringData(_mActivity, SharePConstant.KEY_USER_INFO_DATA, GsonUtil.GsonString(userInfo)); getUserLuckData(); } }); selectDialog.show(); } } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @Override public ShareElementInfo[] getShareElements() { return new ShareElementInfo[]{new ShareElementInfo(ivMeHead, new TextViewStateSaver())}; } @Subscribe(threadMode = ThreadMode.MAIN) public void onReceiveEvent(EventEntity event) { if (SnowConstant.EVENT_UPDATE_USER_HEAD.equals(event.getEvent())) { GlideApp.with(_mActivity) .load(UserHelper.getUserInfo(_mActivity).getHeadImageUrl()) .into(ivMeHead); } if (SnowConstant.EVENT_UPDATE_USER_SNAK.equals(event.getEvent())) { tv_user_nick.setText(UserHelper.getUserInfo(_mActivity).getNick()); } } @Override public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { int height = DisplayUtil.dip2px(170); if (scrollY <= 0) { me_title_bar.setTitle(""); me_title_bar.setBackgroundColor(Color.argb((int) 0, 44, 44, 44));//AGB由相关工具获得,或者美工提供 } else if (scrollY > 0 && scrollY <= height) { float scale = (float) scrollY / height; float alpha = (255 * scale); me_title_bar.setBackgroundColor(Color.argb((int) alpha, 44, 44, 44)); me_title_bar.setTitleColor(Color.argb((int) alpha, 255, 255, 255)); me_title_bar.setTitle(UserHelper.getUserInfo(_mActivity).getNick()); } else { me_title_bar.setTitle(UserHelper.getUserInfo(_mActivity).getNick()); me_title_bar.setBackgroundColor(Color.argb((int) 255, 44, 44, 44)); } } }
package com.bowlong.objpool; import com.bowlong.io.ByteInStream; public class ByteInPool extends AbstractQueueObjPool<ByteInStream> { public static final ByteInPool POOL = new ByteInPool(); public static final ByteInStream borrowObject(byte[] buf) { ByteInStream r2 = POOL.borrow(); r2.setBytes(buf); return r2; } public ByteInPool() { } public ByteInPool(int num) { for (int i = 0; i < num; i++) { returnObj(createObj()); } } public static final void returnObject(ByteInStream obj) { POOL.returnObj(obj); } @Override public final ByteInStream createObj() { ByteInStream is = new ByteInStream(new byte[8]); is.pool = this; // close it return to pool return is; } @Override public final ByteInStream resetObj(ByteInStream obj) { obj.reset(); return obj; } @Override public final ByteInStream destoryObj(ByteInStream obj) { obj.pool = null; return obj; } }
package services; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import model.Training; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.transform.AliasToEntityMapResultTransformer; import db.HibernateUtil; @SuppressWarnings("unchecked") public class TrainingRequestService { @SuppressWarnings("unchecked") public static List<Map<String, Object>> getLookupTraining(String empno) { List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); Session s = HibernateUtil.getSessionFactory().openSession(); SQLQuery q = s.createSQLQuery("exec SPE_AvailableTraining @UserId= :empNo"); q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); q.setString("empNo", empno); try { result = q.list(); } catch (Exception e) { e.printStackTrace(); } finally { s.close(); } return result; } public static String validate(Training training, String empNo) { // membuka koneksi Session s = HibernateUtil.getSessionFactory().openSession(); // membuat query dengan native sql SQLQuery sql = s.createSQLQuery("EXEC [dbo].[SPE_ValidationTrainingRequest] " + "@UserId = :emno, " + "@TrainingId = :trainingId, " + "@Remarks = :remark"); // memasang paramater sql.setString("emno", empNo); sql.setString("trainingId", training.getTrainingID()); sql.setString("remark", training.getRemark()); // untuk menjalankan query select gunakan q.list() String result = (String) sql.list().get(0); // menutup koneksi s.close(); return result; } public static void sentRequest(Training training, String empNo, String reqId, Session s) { SQLQuery q = s.createSQLQuery("Exec [SPE_SaveTrainingRequest] " + "@UserId =:empNo" + ",@RequestID =:requestId" + ",@TrainingId =:trainingId" + ",@Amount =:Amount" + ",@Remarks =:remark"); q.setString("empNo", empNo); q.setString("requestId", reqId); q.setBigDecimal("Amount", training.getAmount()); q.setString("trainingId", training.getTrainingID()); q.setString("remark", training.getRemark()); q.executeUpdate(); } public static String approveSingleRequest(String reqId) { String result = ""; Session s = HibernateUtil.getSessionFactory().openSession(); try { s.beginTransaction(); SQLQuery q = s.createSQLQuery("exec SPE_ProcessTrainingRequest " + "@RequestID =:reqId"); q.setString("reqId", reqId); q.executeUpdate(); s.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); result = e.getCause() != null ? e.getCause().getMessage() : e.toString(); s.getTransaction().rollback(); } finally { s.close(); } return result; } @SuppressWarnings("rawtypes") public static Training getTrainingbyrequestID(String reqId) { Map<String, Object> map; Training result = null; Session s = HibernateUtil.getSessionFactory().openSession(); SQLQuery q = s.createSQLQuery("exec [SPE_ViewTrainingRequest] " + "@RequestID=:reqId"); q.setString("reqId", reqId); q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); List tmpList = q.list(); if (tmpList != null && tmpList.size() > 0 && tmpList.get(0) != null) { result = new Training(); map = (Map<String, Object>) tmpList.get(0); result.convertFromMap(map); } s.close(); return result; } public static String getTrainingDesc(String trainingID) { // TODO Auto-generated method stub String result = ""; Session s = HibernateUtil.getSessionFactory().openSession(); SQLQuery q = s.createSQLQuery("select TrainingDesc from T_TrainingParm where TrainingId=:TrainingId"); q.setString("TrainingId", trainingID); try { result = (String) q.list().get(0); } catch (Exception e) { e.printStackTrace(); } finally { s.close(); } return result; } public static List<Map<String, String>> getListAvailableTraining(String empNo) { List<Map<String, String>> result = new ArrayList<Map<String, String>>(); Session s = HibernateUtil.getSessionFactory().openSession(); SQLQuery q = s.createSQLQuery("exec SPE_AvailableTraining @UserId= :empNo"); q.setString("empNo", empNo); q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); try { result = q.list(); } catch (Exception e) { e.printStackTrace(); } finally { s.close(); } return result; } }
/** * */ package simplejava.nio.channel; /** * @title ChannelsTest */ public class ChannelsTest { /** * 封装io包成为nio类的工具类:java.nio.channels.Channels */ public static void main(String[] args) { // TODO Auto-generated method stub } }
package test_strutturali; import static org.junit.Assert.*; import java.util.Calendar; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import sistema.*; public class PersonaTest { Persona p; static Calendar birthday; @BeforeClass public static void setUpBeforeClass() throws Exception { birthday = Calendar.getInstance(); birthday.set(1980, 0, 1); } @Before public void setUp() throws Exception { p = new Persona("Luca", "Rossi", "RSSLCU80A01D969P", birthday); } @Test public void testConstructor() { assertNotNull(p); assertEquals("Luca", p.getNome()); assertEquals("Rossi", p.getCognome()); assertEquals("RSSLCU80A01D969P", p.getCodiceFiscale()); assertEquals(birthday, p.getDataNascita()); } @Test public void testPrint() { p.print(); p = new Persona("Luca", "Rossi", "RSSLCU80A01D969P", null); p.print(); } }
package com.dais.controller.system; import com.common.pojo.ResultModel; import com.dais.controller.BaseController; import com.dais.model.SysUser; import com.dais.service.SystemUserService; import com.dais.utils.StringUtils; import com.dais.utils.Utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Enumeration; /** * @author xxp * @version 2017- 09- 09 10:01 * @description * @copyright www.zhgtrade.com */ @Controller public class AdminController extends BaseController { @Autowired private SystemUserService systemUserService; @RequestMapping(value = "/index", method = RequestMethod.GET) public String getIndexPage() { return "/index"; } /** * 登录页面 * * @return */ @RequestMapping(value = "/login", method = RequestMethod.GET) public String getLoginPage() { return "/login"; } /** * 接收ajax登录请求 * HttpSession * @return */ @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public ResultModel Login(HttpServletRequest request, SysUser user) { return systemUserService.doCheckLogin(user, request); } @RequestMapping(value = "/updatepassword", method = RequestMethod.POST) @ResponseBody public ResultModel updatepassword(String newpassword,String oldpassword,int id) { return systemUserService.updatepassword(newpassword,oldpassword,id); } /** * 生成验证码 * * @param request * @param * @throws IOException */ @RequestMapping(value = "/loginout") public String logout(HttpServletRequest request) throws IOException { // 生成验证码,放入session中 HttpSession session = request.getSession(); Enumeration<String> names = session.getAttributeNames(); while(names != null && names.hasMoreElements()){ session.removeAttribute(names.nextElement()); } return "/login"; } @RequestMapping(value = "/system/adminlist",method = RequestMethod.GET) public String getAdminPage() { return "/system/adminlist"; } @RequestMapping("/system/getAdminlist") @ResponseBody public ResultModel getAdminList(HttpServletRequest request,int start,int limit,String search) { return systemUserService.getAdminList(request,start, limit, search); } @RequestMapping("/system/save") @ResponseBody public ResultModel save(@RequestBody SysUser sysUser,HttpServletRequest request) { SysUser user = (SysUser)request.getSession().getAttribute("user_info"); if(user == null){ return ResultModel.build(500,"数据异常"); } int roleid = user.getRoleid(); if(roleid > sysUser.getRoleid()){ return ResultModel.build(402,"权限不足"); } sysUser.setLogintime(Utils.getTimestamp()); if(StringUtils.isEmpty(user.getName())){ sysUser.setCreateuser(user.getUsername()); }else{ sysUser.setCreateuser(user.getName()); } if(sysUser.getRoleid() == 2){ sysUser.setRolename("管理员"); }else{ sysUser.setRolename("普通用户"); } return systemUserService.save(sysUser); } @RequestMapping("/system/delete") @ResponseBody public ResultModel delete(int id) { return systemUserService.delete(id); } }
package com.wqt.service; import com.wqt.dto.Film; import java.util.List; public interface IFilmService { public List<Film> selectAll(); public String insert(Film film); }
import java.util.Scanner; // class scanner public class TriangleDemo { public static void main(String[] args) { double height,base; //create a Scanner object Scanner sc = new Scanner(System.in); // Create a Triangle object. Triangle tri = new Triangle(); // Prompt user to input value for height and base System.out.print("Enter value for Height : "); height = sc.nextDouble(); System.out.print("Enter value for Base : "); base = sc.nextDouble(); //Set the height and base (use mutator) tri.set(height,base); // Display the height, base and area (use accessor) System.out.println("The pyramid's height is "+ tri.getHeight()); System.out.println("The pyramid's base is "+ tri.getBase()); System.out.println("The pyramid's area is "+ tri.getArea()); } }
package org.houstondragonacademy.archer.services; import org.houstondragonacademy.archer.dao.entity.Account; import org.springframework.security.oauth2.provider.ClientDetailsService; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public interface AccountService extends ClientDetailsService { Mono<Account> createAccount(Account account); Mono<Account> updateAccount(Account account, String id); Flux<Account> findAll(); Mono<Account> findOne(String id); Mono<Account> findByEmailAddress(String email); Mono<Boolean> delete(String id); }
package com.tencent.mm.plugin.gcm.modelgcm; import com.tencent.mm.ab.l; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.plugin.gcm.modelgcm.c.a; public final class e extends l implements k { private q dJM; private com.tencent.mm.ab.e diJ = null; private String khr = null; private int uin = 0; public e(String str, int i) { this.khr = str; this.uin = i; } public final int a(com.tencent.mm.network.e eVar, com.tencent.mm.ab.e eVar2) { this.diJ = eVar2; this.dJM = new a(); ((a) this.dJM).uin = this.uin; ((a) this.dJM.KV()).khn.qZb = this.khr; return a(eVar, this.dJM, this); } public final int getType() { return 623; } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { this.diJ.a(i2, i3, str, this); } }
package com.aleks.pia.dao; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestParam; import com.aleks.pia.entity.Proizvod; @CrossOrigin("http://localhost:4200") @RepositoryRestResource(collectionResourceRel = "proizvodi", path = "proizvodi") public interface ProizvodRepository extends JpaRepository<Proizvod, Long>{ public Page<Proizvod> findByNazivContaining(@RequestParam("name") String name, Pageable pageable); //izgenerise upit na foru SELECT * FROM Product p //WHERE p.name LIKE CONCAT('%', :name, '%') public Page<Proizvod> findByKategorija(@RequestParam("kategorija") String kategorija, Pageable pageable); public Page<Proizvod> findByPreduzeceId(@RequestParam("id") Long id, Pageable pageable); }
package com.lolRiver.river.controllers.converters; import com.fasterxml.jackson.databind.ObjectMapper; import com.lolRiver.achimala.leaguelib.models.LeagueSummoner; import com.lolRiver.river.models.LolUser; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * @author mxia (mxia@lolRiver.com) * 10/5/13 */ @Component public class LeagueSummonerToLolUserConverter { private static final Logger LOGGER = Logger.getLogger(LeagueSummonerToLolUserConverter.class.getName()); private static ObjectMapper mapper = new ObjectMapper(); public LolUser convert(LeagueSummoner leagueSummoner) { if (leagueSummoner == null) { return null; } LolUser lolUser = new LolUser(); lolUser.setId(leagueSummoner.getId()); lolUser.setUserName(leagueSummoner.getName()); if (leagueSummoner.getServer() == null) { LOGGER.error("LeagueSummoner has null region: " + leagueSummoner); } lolUser.setRegion(leagueSummoner.getServer() == null ? "" : leagueSummoner.getServer().name()); List<String> invalidFields = invalidFieldsForLolUser(lolUser); if (!invalidFields.isEmpty()) { LOGGER.error("invalid fields from converting leagueSummoner to lolUser. invalidFields: " + invalidFields + " " + "LolUser: " + lolUser + " leagueSummoner: " + leagueSummoner); throw new RuntimeException(); } return lolUser; } private List<String> invalidFieldsForLolUser(LolUser lolUser) { List<String> list = new ArrayList<String>(); String invalidId = lolUser.invalidIdField(); if (invalidId != null) { list.add(invalidId); } String invalidUsername = lolUser.invalidUsername(); if (invalidUsername != null) { list.add(invalidUsername); } String invalidRegion = lolUser.invalidRegion(); if (invalidRegion != null) { list.add(invalidRegion); } String invalidStreamerName = lolUser.invalidStreamerName(); if (invalidStreamerName != null) { list.add(invalidStreamerName); } return list; } }
package com.tencent.mm.plugin.wenote.ui.nativenote.b; import android.content.res.Resources; import android.support.v7.widget.RecyclerView.t; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.g.a.kp; import com.tencent.mm.plugin.wenote.model.a.b; import com.tencent.mm.plugin.wenote.model.a.n; import com.tencent.mm.plugin.wenote.model.nativenote.c.e; import com.tencent.mm.plugin.wenote.model.nativenote.manager.WXRTEditText; import com.tencent.mm.plugin.wenote.model.nativenote.manager.c; import com.tencent.mm.plugin.wenote.model.nativenote.manager.k; import com.tencent.mm.sdk.platformtools.x; public abstract class h extends a { public static float qvC = Resources.getSystem().getDisplayMetrics().density; public static int qvD = Resources.getSystem().getDisplayMetrics().widthPixels; public static int qvE = ((int) ((40.0f * qvC) + 0.5f)); public ImageView bOA; public LinearLayout eRj; public OnClickListener jXR = new OnClickListener() { public final void onClick(View view) { if (h.this.qtF.cai() != null) { x.e("Micromsg.NoteOtherItemHolder", "click item , now is editing, quit it"); return; } if (h.this.qtF.qrC == 2) { h.this.qtF.qrp.caU().bZy(); h.this.qtF.cal(); } int gm = ((t) view.getTag()).gm(); kp kpVar = new kp(); if (c.bZD().Bv(gm) == null) { x.e("Micromsg.NoteOtherItemHolder", "click not response, null == NoteDataManager.getMgr().get(position),position is %d,datalist size = %d", new Object[]{Integer.valueOf(gm), Integer.valueOf(c.bZD().size())}); } else if (com.tencent.mm.plugin.wenote.model.c.bZb().qnC == null) { x.e("Micromsg.NoteOtherItemHolder", "getWnNoteBase is null"); } else { x.i("Micromsg.NoteOtherItemHolder", "click item, type is %d", new Object[]{Integer.valueOf(c.bZD().Bv(gm).getType())}); kpVar.bUP.bUR = ((n) c.bZD().Bv(gm)).qpc; kpVar.bUP.context = view.getContext(); kpVar.bUP.type = 1; com.tencent.mm.plugin.wenote.model.c.bZb().qnC.b(kpVar); } } }; public LinearLayout qvA; public LinearLayout qvB; public WXRTEditText qvo; public WXRTEditText qvp; public LinearLayout qvq; public TextView qvr; public TextView qvs; public ImageView qvt; public View qvu; public LinearLayout qvv; public LinearLayout qvw; public LinearLayout qvx; public LinearLayout qvy; public LinearLayout qvz; public h(View view, k kVar) { super(view, kVar); this.bOA = (ImageView) view.findViewById(R.h.edit_imageView); this.qvu = view.findViewById(R.h.video_click_area); this.qvq = (LinearLayout) view.findViewById(R.h.note_card_ll); this.eRj = (LinearLayout) view.findViewById(R.h.note_voice_ll); this.qvr = (TextView) view.findViewById(R.h.note_card_title); this.qvs = (TextView) view.findViewById(R.h.note_card_detail); this.qvt = (ImageView) view.findViewById(R.h.note_card_icon); this.qvr.setTextSize(16.0f); this.qvs.setTextSize(12.0f); this.qvv = (LinearLayout) view.findViewById(R.h.note_split_ll); this.qvv.setVisibility(8); this.qvx = (LinearLayout) view.findViewById(R.h.note_reminder_ll); this.qvx.setVisibility(8); this.qvy = (LinearLayout) view.findViewById(R.h.note_bottom_logo_ll); this.qvy.setVisibility(8); this.qvz = (LinearLayout) view.findViewById(R.h.other_cover_view); this.qvz.setBackgroundColor(1347529272); this.qvz.setVisibility(8); this.qvz.setOnClickListener(new 1(this)); this.qvA = (LinearLayout) view.findViewById(R.h.other_up_cover_view); this.qvA.setBackgroundColor(1347529272); this.qvA.setVisibility(4); this.qvB = (LinearLayout) view.findViewById(R.h.other_down_cover_view); this.qvB.setBackgroundColor(1347529272); this.qvB.setVisibility(4); this.qvw = (LinearLayout) view.findViewById(R.h.edit_view_ll); LayoutParams layoutParams = (LayoutParams) this.qvw.getLayoutParams(); layoutParams.width = qvD - qvE; layoutParams.height = -2; this.qvw.setLayoutParams(layoutParams); this.qvp = (WXRTEditText) view.findViewById(R.h.btnNext); this.qvo = (WXRTEditText) view.findViewById(R.h.btnPrev); ((LinearLayout) view.findViewById(R.h.btnNextLL)).setOnClickListener(new OnClickListener() { public final void onClick(View view) { h.this.qvp.bZZ(); h.this.qvp.requestFocus(); } }); ((LinearLayout) view.findViewById(R.h.btnPrevLL)).setOnClickListener(new 3(this)); this.qvp.setEditTextType(2); this.qvo.setEditTextType(1); this.qvo.qqL = this; this.qvp.qqL = this; if (!(kVar.qrC == 2 && this.qtF.qrD)) { this.qvp.setKeyListener(null); this.qvp.setEnabled(false); this.qvp.setFocusable(false); this.qvo.setKeyListener(null); this.qvo.setEnabled(false); this.qvo.setFocusable(false); } this.qtF.o(this.qvo); this.qtF.o(this.qvp); } public void a(b bVar, int i, int i2) { x.i("Micromsg.NoteOtherItemHolder", "ImageItemHolder position is " + gl()); this.qvo.setPosInDataList(i); this.qvp.setPosInDataList(i); if (e.isEnabled()) { e.cap().a(this.qvz, this.qvA, this.qvB, i); } bVar.qoK = this.qvo; bVar.qoL = this.qvp; bVar.qoM = null; if (!bVar.qoH) { if (this.qvo.hasFocus()) { this.qvo.clearFocus(); } if (this.qvp.hasFocus()) { this.qvp.clearFocus(); } } else if (bVar.qoN) { this.qvo.requestFocus(); } else { this.qvp.requestFocus(); } if (this.qvq.getVisibility() != 0) { return; } if (bVar.qoO) { this.qvq.setBackgroundResource(R.g.wenote_basecard_pressed_bg); } else { this.qvq.setBackgroundResource(R.g.wenote_basecard_bg); } } }
package com.tencent.mm.plugin.luckymoney.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.plugin.report.service.h; class LuckyMoneyIndexUI$3 implements OnClickListener { final /* synthetic */ LuckyMoneyIndexUI kVs; LuckyMoneyIndexUI$3(LuckyMoneyIndexUI luckyMoneyIndexUI) { this.kVs = luckyMoneyIndexUI; } public final void onClick(View view) { h.mEJ.h(11701, Integer.valueOf(3), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(2)); LuckyMoneyIndexUI.a(this.kVs, 1); } }
package com.xuecheng.manage_course.dao; import com.xuecheng.framework.domain.course.ext.CategoryNode; 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; @SpringBootTest @RunWith(SpringRunner.class) public class CategoryMapperTest { @Autowired private CategoryMapper categoryMapper; @Test public void testSelectList() { //CategoryNode categoryNode = categoryMapper.selectList(); CategoryNode categoryNodes = categoryMapper.selectList(); System.out.println(categoryNodes); } }
package com.atguigu.eduorder.controller; import com.atguigu.commonutils.JwtUtils; import com.atguigu.commonutils.R; import com.atguigu.eduorder.client.EduClient; import com.atguigu.eduorder.client.UcenterClient; import com.atguigu.eduorder.entity.TOrder; import com.atguigu.eduorder.service.TOrderService; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import io.jsonwebtoken.Jwt; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; /** * <p> * 订单 前端控制器 * </p> * * @author shine * @since 2021-07-20 */ @RestController @CrossOrigin @RequestMapping("/eduorder/torder") public class TOrderController { @Autowired private TOrderService orderService; @ApiOperation("1-生成订单信息,创建订单返回订单号") @PostMapping("createOrder/{courseId}") public R saveOrder(@PathVariable String courseId, HttpServletRequest request){ String memberId = JwtUtils.getMemberIdByJwtToken(request); String orderNo = orderService.createOrders(courseId, memberId); return R.ok().data("orderId", orderNo); } @ApiOperation("2-根据订单id查询订单信息") @GetMapping("getOrderInfo/{orderId}") public R getOrderInfo(@PathVariable String orderId){ QueryWrapper<TOrder> wrapper = new QueryWrapper<TOrder>(); wrapper.eq("order_no", orderId); TOrder order = orderService.getOne(wrapper); return R.ok().data("order", order); } }
/* * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with SAP Hybris. */ package com.cnk.travelogix.ccintegrationfacade.dto; import java.util.HashMap; import java.util.Map; import com.cnk.travelogix.ccintegrationfacade.enums.CCIntegrationConstant; /** * The Class CCIntegrationDto. */ public class CCIntegrationDto { /** The req res map. */ final Map<CCIntegrationConstant, Object> reqResMap = new HashMap<CCIntegrationConstant, Object>(); /** * Instantiates a new CC integration dto. * * @param reqObj * the req obj */ public CCIntegrationDto(final Object reqObj) { reqResMap.put(CCIntegrationConstant.REQ, reqObj); } /** * Adds the req. * * @param value * the value */ public void addReq(final Object value) { if (value != null) { reqResMap.put(CCIntegrationConstant.REQ, value); } } /** * Gets the req. * * @return the req */ public Object getReq() { return reqResMap.get(CCIntegrationConstant.REQ); } }
package com.example.magazine_irailson.activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.example.magazine_irailson.R; import com.example.magazine_irailson.config.ConfiguracaoFirebase; import com.example.magazine_irailson.model.Usuario; import com.example.magazine_irailson.util.Util; import com.google.firebase.FirebaseNetworkException; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException; import com.google.firebase.auth.FirebaseAuthUserCollisionException; import com.google.firebase.auth.FirebaseAuthWeakPasswordException; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import java.util.Objects; import studio.carbonylgroup.textfieldboxes.ExtendedEditText; public class CadastroUsuarioActivity extends AppCompatActivity { private ExtendedEditText editNomeUsuario; private ExtendedEditText editEmailUsuario; private ExtendedEditText editSenhaUsuario; private Button btCadastrar; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastro_usuario); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_24dp); toolbar.setTitle(getString(R.string.cadastrar_usuario)); setSupportActionBar(toolbar); editNomeUsuario = findViewById(R.id.edit_nome_usuario); editEmailUsuario = findViewById(R.id.edit_email_usuario); editSenhaUsuario = findViewById(R.id.edit_senha_usuario); btCadastrar = findViewById(R.id.bt_cadastrar); btCadastrar.setOnClickListener(view -> validarCampos()); } private void validarCampos() { boolean resultado; if (resultado = Util.isCampoVazio(editNomeUsuario.getText().toString())) { editNomeUsuario.setError(getString(R.string.preencha_nome)); editNomeUsuario.requestFocus(); } else if (resultado = Util.isCampoVazio(editEmailUsuario.getText().toString())) { editEmailUsuario.setError(getString(R.string.preencha_email)); editEmailUsuario.requestFocus(); } else if (resultado = Util.isCampoVazio(editSenhaUsuario.getText().toString()) || (editSenhaUsuario.getText().toString().length() < 8)) { editSenhaUsuario.setError(getString(R.string.preencha_os_dados_senha)); editSenhaUsuario.requestFocus(); } String nome = editNomeUsuario.getText().toString(); String email = editEmailUsuario.getText().toString(); String senha = editSenhaUsuario.getText().toString(); if (!resultado) cadastrarUsuario(nome, email, senha); } private void cadastrarUsuario(final String nome, final String email, final String senha) { progressDialog = Util.mostrarProgressDialog(this, "Cadastrando..."); FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao(); autenticacao.createUserWithEmailAndPassword( email, senha ).addOnCompleteListener(CadastroUsuarioActivity.this, task -> { if (task.isSuccessful()) { FirebaseUser usuarioFirebase = task.getResult().getUser(); String identificadorUsuario = usuarioFirebase.getUid(); Usuario usuario = new Usuario(); usuario.setId(identificadorUsuario); usuario.setNome(nome); usuario.setEmail(email); usuario.setSenha(senha); //Salvar no Firebase DatabaseReference referenciaFirebase = ConfiguracaoFirebase.getFirebase(); referenciaFirebase.child("usuarios").child(identificadorUsuario).setValue(usuario); Util.mostrarMensagen( CadastroUsuarioActivity.this, "Sucesso ao cadastrar!"); progressDialog.dismiss(); abrirLogin(); } else { progressDialog.dismiss(); String erroExcecao; try { throw Objects.requireNonNull(task.getException()); } catch (FirebaseAuthWeakPasswordException e) { erroExcecao = "A Senha deve conter carácteres, letras e números!"; } catch (FirebaseAuthInvalidCredentialsException e) { erroExcecao = "O E-mail digitado é inválido, digite um novo E-mail!"; } catch (FirebaseAuthUserCollisionException e) { erroExcecao = "Esse E-mail já está em uso!"; } catch (FirebaseNetworkException e) { erroExcecao = "Não há conexão com a internet!"; } catch (Exception e) { erroExcecao = "Ao efetuar o cadastro!"; e.printStackTrace(); } Util.mostrarMensagen( CadastroUsuarioActivity.this, "Erro: " + erroExcecao); } }); } private void abrirLogin() { Intent intent = new Intent(CadastroUsuarioActivity.this, LoginActivity.class); startActivity(intent); finish(); } }
package com.tencent.mm.g.a; public final class i$a { public int scene = 0; }
//$Id$ package main; import repository.UserMovieRepository; import services.MovieService; import services.UserService; import valueobjects.Rating; public class TestFile { private UserService userService; private MovieService movieService; public TestFile() { this.movieService = new MovieService(); this.userService = new UserService(); } public void addMovie() { movieService.addMovie("Don", 2006); movieService.addMovie("Tiger", 2008); movieService.addMovie("Padmaavat", 2006); movieService.addMovie("Lunchbox", 2021); movieService.addMovie("Guru", 2006); movieService.addMovie("Metro", 2006); } public void addUser() { userService.addUser("SRK"); userService.addUser("Salman"); userService.addUser("Deepika"); } public void addReviews() { userService.addReview(userService.getUser("SRK"), movieService.getMovie("Don"), new Rating(2)); userService.addReview(userService.getUser("SRK"), movieService.getMovie("Padmaavat"), new Rating(5)); userService.addReview(userService.getUser("Salman"), movieService.getMovie("Don"), new Rating(5)); userService.addReview(userService.getUser("Deepika"), movieService.getMovie("Don"), new Rating(9)); userService.addReview(userService.getUser("Deepika"), movieService.getMovie("Guru"), new Rating(6)); try { userService.addReview(userService.getUser("SRK"), movieService.getMovie("Don"), new Rating(10)); } catch (Exception e) { System.err.println(e.getMessage()); } userService.addReview(userService.getUser("Deepika"), movieService.getMovie("Lunchbox"), new Rating(5)); userService.addReview(userService.getUser("SRK"), movieService.getMovie("Tiger"), new Rating(5)); userService.addReview(userService.getUser("SRK"), movieService.getMovie("Metro"), new Rating(7)); } public void topInYear(){ System.out.println(movieService.getTopMovies(2006, 1)); //Critics userService.getTopCriticsMovie(1); } public void getTopMovieByAverage() { System.out.println(userService.getTopMovieByAverage(2006)); } }
package collage; import java.util.concurrent.LinkedBlockingQueue; import com.xuggle.xuggler.IContainer; import com.xuggle.xuggler.IPacket; import com.xuggle.xuggler.IStream; import com.xuggle.xuggler.IStreamCoder; public class BufferedIPacketFileInputStream extends IPacketCodableInputStream { private int maxBufferSize = -1; private IPacketWorkerThread workerThread = null; private String filename = "Name me"; private IStream[] streams = null; private IStreamCoder[] decoders = null; private IStreamCoder[] encoders = null; private IContainer container = null; public BufferedIPacketFileInputStream(String filename, int maxPacketBufferSize) { this.filename = filename; this.maxBufferSize = maxPacketBufferSize; this.packets = new LinkedBlockingQueue<IPacket>(maxPacketBufferSize); setupInputPacketStream(); } public BufferedIPacketFileInputStream(String filename) { this(filename, 100); } private void setupInputPacketStream() { // Create a Xuggler container object container = IContainer.make(); // Open up the container if (container.open(filename, IContainer.Type.READ, null) < 0) throw new IllegalArgumentException("could not open file: " + filename); // query how many streams the call to open found int numStreams = container.getNumStreams(); if (numStreams <= 0) throw new RuntimeException("No streams in input file: " + filename); streams = new IStream[numStreams]; decoders = new IStreamCoder[numStreams]; encoders = new IStreamCoder[numStreams]; // and iterate through the streams to find the first audio stream for(int i = 0; i < numStreams; i++) { IStream stream = container.getStream(i); IStreamCoder decoder = stream.getStreamCoder(); IStreamCoder encoder = IStreamCoder.make(IStreamCoder.Direction.ENCODING, decoder); if (encoder.open(null, null) < 0) System.err.println("Error opening encoder"); streams[i] = stream; decoders[i] = decoder; encoders[i] = encoder; } } private class IPacketWorkerThread extends Thread { public void run() { IPacket packet = IPacket.make(); while(container.readNextPacket(packet) >= 0) { try { packets.put(packet); } catch (InterruptedException e) { throw new RuntimeException("interrupted while adding new packet to queue"); } packet = IPacket.make(); } finish(); isDoneLoading = true; } } protected void cleanup() { if (container != null) container.close(); } public void start() { if (isStarted) return; isStarted = true; workerThread = new IPacketWorkerThread(); workerThread.start(); } public void close() { if (isInterrupted || isDone) return; isInterrupted = true; isDone = true; workerThread.interrupt(); cleanup(); } protected void finish() { if (isDone) return; isDone = true; cleanup(); } public IContainer getContainer() { return container; } public int getMaxBufferSize() { return maxBufferSize; } public float getFullness() { return packets.size()/maxBufferSize*100; } public IStreamCoder getStreamDecoder(int index) { return decoders[index]; } public IStreamCoder getStreamDecoder(IPacket packet) { return decoders[packet.getStreamIndex()]; } public IStreamCoder getStreamEncoder(int index) { return encoders[index]; } public IStreamCoder getStreamEncoder(IPacket packet) { return encoders[packet.getStreamIndex()]; } public int getNumStreams() { return streams.length; } public IStream getStream(int index) { return streams[index]; } public IStream getStream(IPacket packet) { return streams[packet.getStreamIndex()]; } }
package rent.common.projection; import org.springframework.data.rest.core.config.Projection; import rent.common.entity.TariffEntity; import java.util.List; @Projection(types = {TariffEntity.class}) public interface TariffBasic extends AbstractBasic { String getName(); ServiceBasic getService(); List<TariffValueBasic> getValues(); }
package com.xindq.yilan.activity.screen; import org.junit.Test; public class DatasClientTest { @Test public void onMessage(){ // Set<String> set=new HashSet<>(); // set.add("1"); // set.add("6"); // set.add("11"); // DatasClient datasClient = new DatasClient("ws://115.159.33.231:8888/datas",set); // datasClient.connect(); // new WebSocketClient(URI.create("ws://115.159.33.231:8888/datas")) { // // @Override // public void onOpen(ServerHandshake handshakedata) { // System.out.println("onOpen"); // send("[1]"); // } // // @Override // public void onMessage(String message) { // System.out.println(message); // } // // @Override // public void onClose(int code, String reason, boolean remote) { // System.out.println("onClose"); // } // // @Override // public void onError(Exception ex) { // System.out.println("onError"); // } // }.connect(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.example.android.inventoryapp; import android.app.LoaderManager; import android.content.ContentValues; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.support.v4.app.NavUtils; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import com.example.android.inventoryapp.data.StorageContract.ProductsEntry; public class ProductActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{ private static final String TAG = ProductActivity.class.getSimpleName(); private boolean mProductHasChanged = false; Uri uri; int isUri; private static final int URL_LOADER = 0; // EditText field to enter the product's name private EditText mProductNameEditText; // EditText field to enter the product's price private EditText mProductPriceEditText; // EditText field to enter the product's quantity private EditText mProductQuantityEditText; // EditText field to enter the product's supplier name private EditText mSupplierNameEditText; // EditText field to enter the product's supplier phone number private EditText mSupplierPhoneNumberEditText; private Button mOrderButton; private ImageButton mIncreaseQuantityButton; private ImageButton mDecreaseQuantityButton; int quantity; // Listens for any user touches on a View, implying that they are modifying // the view, and change the mProductHasChanged boolean to true. private View.OnTouchListener mTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mProductHasChanged = true; return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product); // Find all relevant views that we will need to read user input from mProductNameEditText = findViewById(R.id.edit_product_name); mProductPriceEditText = findViewById(R.id.edit_product_price); mProductQuantityEditText = findViewById(R.id.edit_quantity); mSupplierNameEditText = findViewById(R.id.edit_supplier_name); mSupplierPhoneNumberEditText = findViewById(R.id.edit_supplier_phone_number); mOrderButton = findViewById(R.id.button_order); mIncreaseQuantityButton = findViewById(R.id.b_quantity_increase); mDecreaseQuantityButton = findViewById(R.id.b_quantity_decrease); // set onTouchListener on that views mProductNameEditText.setOnTouchListener(mTouchListener); mProductPriceEditText.setOnTouchListener(mTouchListener); mProductQuantityEditText.setOnTouchListener(mTouchListener); mSupplierNameEditText.setOnTouchListener(mTouchListener); mSupplierPhoneNumberEditText.setOnTouchListener(mTouchListener); mIncreaseQuantityButton.setOnTouchListener(mTouchListener); mDecreaseQuantityButton.setOnTouchListener(mTouchListener); uri = getIntent().getData(); if (uri == null) { isUri = 0; setTitle("Add Product"); mOrderButton.setVisibility(View.GONE); } else { isUri = 1; setTitle("Edit Product"); // initialize Loader getLoaderManager().initLoader(URL_LOADER, null, this); } mIncreaseQuantityButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { quantity = Integer.parseInt(mProductQuantityEditText.getText().toString()); quantity += 1; mProductQuantityEditText.setText(String.valueOf(quantity)); } }); mDecreaseQuantityButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { quantity = Integer.parseInt(mProductQuantityEditText.getText().toString()); if(quantity == 0){ String toastText = getString(R.string.positive_quantity); Toast toast = Toast.makeText(ProductActivity.this, toastText, Toast.LENGTH_SHORT); toast.show(); } else { quantity -= 1; mProductQuantityEditText.setText(String.valueOf(quantity)); } } }); mOrderButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_DIAL); sendIntent.setData(Uri.parse("tel:" + mSupplierPhoneNumberEditText.getText().toString())); startActivity(sendIntent); } }); } // Create the menu options @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_editor, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ // Respond to a click on the "Save" menu option case R.id.action_save: boolean positiveValidationData = dataValidation(); if(positiveValidationData){ saveProduct(); } return true; // Respond to a click on the "delete" menu option case R.id.action_delete: showDeleteConfirmationDialog(); return true; // Respond to a click on the "Up" arrow button in the app bar case android.R.id.home: Log.i(TAG, "onOptionsItemSelected >> mProductHasChanged = " + mProductHasChanged); // If the product hasn't changed, continue with navigating up to parent activity if(!mProductHasChanged){ NavUtils.navigateUpFromSameTask(ProductActivity.this); return true; } // if there are unsaved changes, setup a dialog to warn the user. // Create a click listener to handle the user confirming that // changes should be discarded. DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // User clicked "Discard" button, navigate to parent activity. NavUtils.navigateUpFromSameTask(ProductActivity.this); } }; // Show a dialog that notifies the user they have unsaved changes showUnsavedChangesDialog(discardButtonClickListener); return true; } return super.onOptionsItemSelected(item); } private void showUnsavedChangesDialog( DialogInterface.OnClickListener discardButtonClickListener) { // Create an AlertDialog.Builder and set the message, and click listeners // for the positive and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.unsaved_changes_dialog_msg); builder.setPositiveButton(R.string.discard, discardButtonClickListener); builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Keep editing" button, so dismiss the dialog // and continue editing the pet. if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } public boolean dataValidation(){ String productName = mProductNameEditText.getText().toString().trim(); String supplierName = mSupplierNameEditText.getText().toString().trim(); String supplierPhoneNumber = mSupplierPhoneNumberEditText.getText().toString().trim(); if(TextUtils.isEmpty(productName)){ Toast.makeText(this, R.string.warn_product, Toast.LENGTH_SHORT).show(); } else if(TextUtils.isEmpty(mProductPriceEditText.getText().toString())){ Toast.makeText(this, R.string.warn_price, Toast.LENGTH_SHORT).show(); } else if(TextUtils.isEmpty(supplierName)){ Toast.makeText(this, R.string.warn_supplier, Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(supplierPhoneNumber)){ Toast.makeText(this, R.string.warn_supplier_phone, Toast.LENGTH_SHORT).show(); } return !TextUtils.isEmpty(productName) && !TextUtils.isEmpty(supplierName) && !TextUtils.isEmpty(supplierPhoneNumber) && !TextUtils.isEmpty(mProductPriceEditText.getText().toString()); } public void saveProduct(){ String productName = mProductNameEditText.getText().toString().trim(); int productPrice = Integer.parseInt(mProductPriceEditText.getText().toString()); int productQuantity = Integer.parseInt(mProductQuantityEditText.getText().toString()); String supplierName = mSupplierNameEditText.getText().toString().trim(); String supplierPhoneNumber = mSupplierPhoneNumberEditText.getText().toString().trim(); ContentValues values = new ContentValues(); values.put(ProductsEntry.COLUMN_PRODUCT_NAME, productName); values.put(ProductsEntry.COLUMN_PRICE, productPrice); values.put(ProductsEntry.COLUMN_QUANTITY, productQuantity); values.put(ProductsEntry.COLUMN_SUPPLIER_NAME, supplierName); values.put(ProductsEntry.COLUMN_PHONE_NUMBER, supplierPhoneNumber); switch (isUri){ case 0: Uri insertState = getContentResolver().insert(ProductsEntry.CONTENT_URI, values); if (insertState == null) { String toastText = getString(R.string.error_saving_product); Toast toast = Toast.makeText(this, toastText, Toast.LENGTH_SHORT); toast.show(); } else { String toastText = getString(R.string.product_saved); Toast toast = Toast.makeText(this, toastText, Toast.LENGTH_LONG); toast.show(); } break; case 1: int updateState = getContentResolver().update(uri, values, null, null); Log.i(TAG, "saveProduct >> updateState = " + updateState); if (updateState == 0) { String toastText = getString(R.string.error_update_product); Toast toast = Toast.makeText(this, toastText, Toast.LENGTH_SHORT); toast.show(); } else { String toastText = getString(R.string.update_product); Toast toast = Toast.makeText(this, toastText, Toast.LENGTH_LONG); toast.show(); } break; } finish(); } public void deleteProduct(){ int rowsDeleted = getContentResolver().delete(uri, null, null); if(rowsDeleted != 0 ){ String toastText = getString(R.string.editor_delete_product_successful); Toast toast = Toast.makeText(this, toastText, Toast.LENGTH_SHORT); toast.show(); } else { String toastText = getString(R.string.editor_delete_product_error); Toast toast = Toast.makeText(this, toastText, Toast.LENGTH_SHORT); toast.show(); } finish(); } private void showDeleteConfirmationDialog() { // Create an AlertDialog.Builder and set the message, and click listeners // for the postivie and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.delete_dialog_msg); builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Delete" button, so delete the product. deleteProduct(); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Cancel" button, so dismiss the dialog // and continue editing the product. if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } @Override public void onBackPressed() { // If the product hasn't changed, continue with handling back button press if (!mProductHasChanged) { super.onBackPressed(); return; } // If there are unsaved changes, setup a dialog to warn the user. // Create a click listener to handle the user confirming that changes should be discarded. DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // User clicked "Discard" button, close the current activity. finish(); } }; // Show dialog that there are unsaved changes showUnsavedChangesDialog(discardButtonClickListener); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String[] projection = { ProductsEntry._ID, ProductsEntry.COLUMN_PRODUCT_NAME, ProductsEntry.COLUMN_PRICE, ProductsEntry.COLUMN_QUANTITY, ProductsEntry.COLUMN_SUPPLIER_NAME, ProductsEntry.COLUMN_PHONE_NUMBER }; return new CursorLoader(this, uri, projection, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if(data.moveToFirst()){ String indexProductName = data.getString(data.getColumnIndex(ProductsEntry.COLUMN_PRODUCT_NAME)); int indexProductPrice = data.getInt(data.getColumnIndex(ProductsEntry.COLUMN_PRICE)); int indexProductQuantity = data.getInt(data.getColumnIndex(ProductsEntry.COLUMN_QUANTITY)); String indexSupplierName = data.getString(data.getColumnIndex(ProductsEntry.COLUMN_SUPPLIER_NAME)); String indexSupplierPhoneNumber = data.getString(data.getColumnIndex(ProductsEntry.COLUMN_PHONE_NUMBER)); mProductNameEditText.setText(indexProductName); mProductPriceEditText.setText(Integer.toString(indexProductPrice)); mProductQuantityEditText.setText(Integer.toString(indexProductQuantity)); mSupplierNameEditText.setText(indexSupplierName); mSupplierPhoneNumberEditText.setText(indexSupplierPhoneNumber); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mProductNameEditText.setText(null); mProductPriceEditText.setText(null); mProductQuantityEditText.setText(null); mSupplierNameEditText.setText(null); mSupplierPhoneNumberEditText.setText(null); } }
package com.auction.dao.message; import com.auction.dao.AbstractDao; import com.auction.dao.user.UserDao; import com.auction.entity.Message; import com.auction.entity.User; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import java.util.List; @Repository("messageDao") public class MessageDaoImpl extends AbstractDao<Integer, Message> implements MessageDao { public Message findById(Integer id) { return getByKey(id); } public void saveMessage(Message message) { persist(message); } public void deleteMessageId(Integer id) { Query query = getSession().createSQLQuery("delete from Message where id = :id"); query.setInteger("id", id); query.executeUpdate(); } @SuppressWarnings("unchecked") public List<Message> findAllMessages() { Criteria criteria = createEntityCriteria(); return (List<Message>) criteria.list(); } public Message findMessageByLogin(String login) { Criteria criteria = createEntityCriteria(); criteria.add(Restrictions.eq("login", login)); return (Message) criteria.uniqueResult() ; } }
package com.laurenelder.aquapharm; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.ActionBar.TabListener; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends Activity implements TabListener, MainFragment.mainInterface, LocationListener { String tag = "MAIN ACTIVITY"; Context context; Intent buildIntent; FileManager fileManager; FragmentManager fragMgr; Fragment mainFrag; LocationManager locMgr; Location loc; boolean switched; Double cap; URL url = null; Integer apiNum = 0; String modifiedDate; String latit; String longit; ActionBar actionBar; Double annualLowAverage = 0.0; Double annualHighAverage = 0.0; Double winterLowAverage = 0.0; Double winterHighAverage = 0.0; Double springLowAverage = 0.0; Double springHighAverage = 0.0; Double summerLowAverage = 0.0; Double summerHighAverage = 0.0; Double fallLowAverage = 0.0; Double fallHighAverage = 0.0; List <Containers> containerList = new ArrayList<Containers>(); List <Weather> weatherInfo = new ArrayList<Weather>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); context = this; switched = false; buildIntent = this.getIntent(); if (buildIntent.hasExtra("annualLowAverage")) { annualLowAverage = buildIntent.getDoubleExtra("annualLowAverage", annualLowAverage); annualHighAverage = buildIntent.getDoubleExtra("annualHighAverage", annualHighAverage); winterLowAverage = buildIntent.getDoubleExtra("winterLowAverage", winterLowAverage); winterHighAverage = buildIntent.getDoubleExtra("winterHighAverage", winterHighAverage); springLowAverage = buildIntent.getDoubleExtra("springLowAverage", springLowAverage); springHighAverage = buildIntent.getDoubleExtra("springHighAverage", springHighAverage); summerLowAverage = buildIntent.getDoubleExtra("summerLowAverage", summerLowAverage); summerHighAverage = buildIntent.getDoubleExtra("summerHighAverage", summerHighAverage); fallLowAverage = buildIntent.getDoubleExtra("fallLowAverage", fallLowAverage); fallHighAverage = buildIntent.getDoubleExtra("fallHighAverage", fallHighAverage); } // Setup FragmentManager to call methods in FormFragment fragMgr = getFragmentManager(); mainFrag = (MainFragment)fragMgr.findFragmentById(R.id.mainFrag); if(mainFrag == null) { mainFrag = new AddContainerFragment(); } // If temperature is already available add tabs right away. If not add tabs after API data is // returned. if (annualLowAverage == 0.0) { // Setup LocationManager for GPS updates locMgr = (LocationManager)getSystemService(LOCATION_SERVICE); locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, null); loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER); } else { actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); Tab actionBarTab = actionBar.newTab(); actionBarTab.setText(R.string.actionbar_buildsystem).setTabListener(this); actionBar.addTab(actionBarTab); actionBarTab = actionBar.newTab(); actionBarTab.setText(R.string.actionbar_fish).setTabListener(this); actionBar.addTab(actionBarTab); actionBarTab = actionBar.newTab(); actionBarTab.setText(R.string.actionbar_plants).setTabListener(this); actionBar.addTab(actionBarTab); actionBar.setSelectedNavigationItem(0); } checkForFile(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); menu.findItem(R.id.action_item_one).setEnabled(true).setVisible(true); menu.findItem(R.id.action_item_one).setIcon(R.drawable.ic_action_new); menu.findItem(R.id.action_item_two).setIcon(R.drawable.ic_action_about); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_item_one) { Intent addIntent = new Intent(context, AddContainerActivity.class); startActivityForResult(addIntent, 1); return true; } if (id == R.id.action_item_two) { new AboutDialog(); AboutDialog dialogFrag = AboutDialog.newInstance(context); dialogFrag.show(getFragmentManager(), "about_dialog"); return true; } return super.onOptionsItemSelected(item); } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub int tabIndex = tab.getPosition(); if (tabIndex == 0) { switched = true; } if (tabIndex == 1) { // switched = true; if (switched == true) { calculateTemps(); Intent fishIntent = new Intent(context, FishActivity.class); fishIntent.putExtra("annualLowAverage", annualLowAverage); fishIntent.putExtra("annualHighAverage", annualHighAverage); fishIntent.putExtra("winterLowAverage", winterLowAverage); fishIntent.putExtra("winterHighAverage", winterHighAverage); fishIntent.putExtra("springLowAverage", springLowAverage); fishIntent.putExtra("springHighAverage", springHighAverage); fishIntent.putExtra("summerLowAverage", summerLowAverage); fishIntent.putExtra("summerHighAverage", summerHighAverage); fishIntent.putExtra("fallLowAverage", fallLowAverage); fishIntent.putExtra("fallHighAverage", fallHighAverage); /* Log.i(tag, "Annual Average Low Temp: " + String.valueOf(annualLowAverage)); Log.i(tag, "Annual Average High Temp: " + String.valueOf(annualHighAverage)); Log.i(tag, "Winter Average Low Temp: " + String.valueOf(winterLowAverage)); Log.i(tag, "Winter Average High Temp: " + String.valueOf(winterHighAverage)); Log.i(tag, "Spring Average Low Temp: " + String.valueOf(springLowAverage)); Log.i(tag, "Spring Average High Temp: " + String.valueOf(springHighAverage)); Log.i(tag, "Summer Average Low Temp: " + String.valueOf(summerLowAverage)); Log.i(tag, "Summer Average High Temp: " + String.valueOf(summerHighAverage)); Log.i(tag, "Fall Average Low Temp: " + String.valueOf(fallLowAverage)); Log.i(tag, "Fall Average High Temp: " + String.valueOf(fallHighAverage));*/ startActivity(fishIntent); } } if (tabIndex == 2) { if (switched == true) { calculateTemps(); Intent plantsIntent = new Intent(context, PlantsActivity.class); plantsIntent.putExtra("annualLowAverage", annualLowAverage); plantsIntent.putExtra("annualHighAverage", annualHighAverage); plantsIntent.putExtra("winterLowAverage", winterLowAverage); plantsIntent.putExtra("winterHighAverage", winterHighAverage); plantsIntent.putExtra("springLowAverage", springLowAverage); plantsIntent.putExtra("springHighAverage", springHighAverage); plantsIntent.putExtra("summerLowAverage", summerLowAverage); plantsIntent.putExtra("summerHighAverage", summerHighAverage); plantsIntent.putExtra("fallLowAverage", fallLowAverage); plantsIntent.putExtra("fallHighAverage", fallHighAverage); startActivity(plantsIntent); } } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } @Override public void onBackPressed() { // TODO Auto-generated method stub } // Modify data depending on what result is returned from activity. protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (data.hasExtra("annualLowAverage")) { annualLowAverage = data.getDoubleExtra("annualLowAverage", annualLowAverage); annualHighAverage = data.getDoubleExtra("annualHighAverage", annualHighAverage); winterLowAverage = data.getDoubleExtra("winterLowAverage", winterLowAverage); winterHighAverage = data.getDoubleExtra("winterHighAverage", winterHighAverage); springLowAverage = data.getDoubleExtra("springLowAverage", springLowAverage); springHighAverage = data.getDoubleExtra("springHighAverage", springHighAverage); summerLowAverage = data.getDoubleExtra("summerLowAverage", summerLowAverage); summerHighAverage = data.getDoubleExtra("summerHighAverage", summerHighAverage); fallLowAverage = data.getDoubleExtra("fallLowAverage", fallLowAverage); fallHighAverage = data.getDoubleExtra("fallHighAverage", fallHighAverage); } if (resultCode == RESULT_OK) { if (requestCode == 1) { checkForFile(); } if (requestCode == 2) { String ctype = data.getExtras().getString("type").toString(); String clength = data.getExtras().getString("length").toString(); String cwidth = data.getExtras().getString("width").toString(); String cheight = data.getExtras().getString("height").toString(); String button = data.getExtras().getString("button").toString(); int position = data.getExtras().getInt("position"); // Log.i(tag, "requestCode 2 hit"); // Log.i(tag, containerList.toString()); if (button.matches("edit")) { Intent addIntent = new Intent(context, AddContainerActivity.class); addIntent.putExtra("type", ctype); addIntent.putExtra("length", clength); addIntent.putExtra("width", cwidth); addIntent.putExtra("height", cheight); addIntent.putExtra("spot", position); addIntent.putExtra("annualLowAverage", annualLowAverage); addIntent.putExtra("annualHighAverage", annualHighAverage); addIntent.putExtra("winterLowAverage", winterLowAverage); addIntent.putExtra("winterHighAverage", winterHighAverage); addIntent.putExtra("springLowAverage", springLowAverage); addIntent.putExtra("springHighAverage", springHighAverage); addIntent.putExtra("summerLowAverage", summerLowAverage); addIntent.putExtra("summerHighAverage", summerHighAverage); addIntent.putExtra("fallLowAverage", fallLowAverage); addIntent.putExtra("fallHighAverage", fallHighAverage); startActivityForResult(addIntent, 1); } if (button.matches("delete")) { // Log.i(tag, "Delete Hit" + "-" + spot.toString()); if (containerList.size() > 1) { containerList.remove(position); saveData(); } else { containerList.removeAll(containerList); File checkForFileExist = getBaseContext().getFileStreamPath(getResources() .getString(R.string.container_file_name)); if (checkForFileExist.exists()) { checkForFileExist.delete(); } ((MainFragment) mainFrag).clearList(); ((MainFragment) mainFrag).updateListView(); } } } } } public void startContainerActivity(int pos) { Intent containerIntent = new Intent(context, ContainerActivity.class); containerIntent.putExtra("type", containerList.get(pos).type); containerIntent.putExtra("length", containerList.get(pos).length); containerIntent.putExtra("width", containerList.get(pos).width); containerIntent.putExtra("height", containerList.get(pos).height); containerIntent.putExtra("position", pos); containerIntent.putExtra("annualLowAverage", annualLowAverage); containerIntent.putExtra("annualHighAverage", annualHighAverage); containerIntent.putExtra("winterLowAverage", winterLowAverage); containerIntent.putExtra("winterHighAverage", winterHighAverage); containerIntent.putExtra("springLowAverage", springLowAverage); containerIntent.putExtra("springHighAverage", springHighAverage); containerIntent.putExtra("summerLowAverage", summerLowAverage); containerIntent.putExtra("summerHighAverage", summerHighAverage); containerIntent.putExtra("fallLowAverage", fallLowAverage); containerIntent.putExtra("fallHighAverage", fallHighAverage); startActivityForResult(containerIntent, 2); } /* Check to see if the JSON file that stores the saved container list is * available. If it is read and parse file. */ public void checkForFile() { // Check for saved file and parse if file is available if (!containerList.isEmpty()) { containerList.removeAll(containerList); ((MainFragment) mainFrag).clearList(); } fileManager = FileManager.getInstance(); File checkForFile = getBaseContext().getFileStreamPath(getResources() .getString(R.string.container_file_name)); if (checkForFile.exists()) { String fileContent = fileManager.readFromFile(context, getResources() .getString(R.string.container_file_name), null); if (fileContent != null) { parseData(fileContent.toString(), "containers"); // Log.i(tag, fileContent.toString()); } } } /* parseData is passed in a raw string from saved file, parses, and calls * the setData method */ public void parseData (String rawData, String parseType) { JSONObject mainObject = null; try { mainObject = new JSONObject(rawData); // Log.i(tag, rawData); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (parseType.matches("containers")) { JSONArray subObject = null; try { if (mainObject != null) { subObject = mainObject.getJSONArray("containers"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i < subObject.length(); i++) { JSONObject dataObj = null; try { if (subObject != null) { dataObj = subObject.getJSONObject(i); String containerType = dataObj.getString("type"); String containerLength = dataObj.getString("length"); String containerWidth = dataObj.getString("width"); String containerHeight = dataObj.getString("height"); /* Log.i(tag, containerType.toString()); Log.i(tag, containerLength.toString()); Log.i(tag, containerWidth.toString()); Log.i(tag, containerHeight.toString());*/ setData(containerType, containerLength, containerWidth, containerHeight); ((MainFragment) mainFrag).addData(containerType, containerLength, containerWidth, containerHeight); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ((MainFragment) mainFrag).updateListView(); } if (parseType.matches("weather")) { JSONObject locationSubObject = null; JSONObject historySubObject = null; JSONObject historyDateSubObject = null; JSONArray observationsSubObject = null; JSONObject lowTempSubObject = null; JSONObject highTempSubObject = null; try { if (mainObject != null) { locationSubObject = mainObject.getJSONObject("location"); historySubObject = mainObject.getJSONObject("history"); historyDateSubObject = historySubObject.getJSONObject("date"); observationsSubObject = historySubObject.getJSONArray("observations"); lowTempSubObject = observationsSubObject.getJSONObject(0); highTempSubObject = observationsSubObject.getJSONObject(27); String location = locationSubObject.getString("city") + ", " + locationSubObject.getString("state"); String day = historyDateSubObject.getString("mday"); String month = historyDateSubObject.getString("mon"); String year = historyDateSubObject.getString("year"); String minTemp = lowTempSubObject.getString("tempi"); String maxTemp = highTempSubObject.getString("tempi"); setDataWeatherData(location, day, month, year, minTemp, maxTemp); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* setData is called at the end of the parseData method and saves each * JSON object to a custom object in the activity */ public boolean setData (String type, String length, String width, String height) { Containers newContainer = new Containers(type, length, width, height); containerList.add(newContainer); return true; } /* setData is called at the end of the parseData method and saves each * JSON object to a custom object in the activity */ public boolean setDataWeatherData (String thisLocation, String thisDay, String thisMonth, String thisYear, String thisLowTemp, String thisHighTemp) { apiNum++; Weather weatherData = new Weather(thisLocation, thisDay, thisMonth, thisYear, thisLowTemp, thisHighTemp); Log.i(tag, "Low Temp: " + thisLowTemp); Log.i(tag, "High Temp: " + thisHighTemp); weatherInfo.add(weatherData); if (apiNum < 8) { handleAPI(modifiedDate); } Log.i(tag, weatherInfo.toString()); addTabs(); return true; } /* getTotalCapacity method adds the capacity in gallons for each container and returns the * total of all of the containers together. */ public Double getTotalCapacity() { Double cap = 0.00; for (int q = 0; q < containerList.size(); q++) { Integer cuInches = Integer.parseInt(containerList.get(q).length) * Integer.parseInt(containerList.get(q).width) * Integer.parseInt(containerList.get(q).height); Log.i(tag, cuInches.toString()); Double cuFoot = cuInches / 1728.00; Double gallons = 7.48 * cuFoot; cap = cap + gallons; } return cap; } /* getContainerCapacity gets the capacity in gallons for each container in the list and * returns only the capacity of an individual container. */ public Double getContainerCapacity(int pos) { Integer cuInches = Integer.parseInt(containerList.get(pos).length) * Integer.parseInt(containerList.get(pos).width) * Integer.parseInt(containerList.get(pos).height); Log.i(tag, cuInches.toString()); Double cuFoot = cuInches / 1728.00; Double gallons = 7.48 * cuFoot; return gallons; } /* getTotalBedCapacity gets the capacity in gallons for each grow bed in the list and * returns the capacity of all grow beds together. */ public Double getTotalBedCapacity() { Double bedCapacity = 0.00; for (int x = 0; x < containerList.size(); x++) { if (containerList.get(x).type.matches("Grow Bed")) { Integer cuInches = Integer.parseInt(containerList.get(x).length) * Integer.parseInt(containerList.get(x).width) * Integer.parseInt(containerList.get(x).height); Log.i(tag, cuInches.toString()); Double cuFoot = cuInches / 1728.00; Double gallons = 7.48 * cuFoot; bedCapacity = bedCapacity + gallons; } } return bedCapacity; } /* saveData method is called by the action bar button. * This method builds a JSON file from the objects store within custom * objects and calls writeToFile to save the JSON file to the device. */ public void saveData() { String preJson = "{'containers':["; String contentJson = null; String postJson = "]}"; // Log.i(tag, "saveData method hit"); for (int i = 0; i < containerList.size(); i++) { if (i == 0) { contentJson = "{'type':" + "'" + containerList.get(i).type.toString() + "'" + "," + "'length':" + "'" + containerList.get(i).length.toString() + "'" + "," + "'width':" + "'" + containerList.get(i).width.toString() + "'" + "," + "'height':" + "'" + containerList.get(i).height.toString() + "'" + "}"; } else { contentJson = contentJson + "{'type':" + "'" + containerList.get(i).type.toString() + "'" + "," + "'length':" + "'" + containerList.get(i).length.toString() + "'" + "," + "'width':" + "'" + containerList.get(i).length.toString() + "'" + "," + "'height':" + "'" + containerList.get(i).height.toString() + "'" + "}"; } if (i != containerList.size() - 1) { contentJson = contentJson + ","; } } String fullJson = preJson + contentJson + postJson; // Log.i(tag, fullJson); fileManager.writeToFile(context, getResources().getString(R.string.container_file_name), fullJson); checkForFile(); } // Calls API with correct date and location public void handleAPI(String date) { if (loc != null) { // Check Network Connection and Show Error Notification if false if (checkConnection(context) == true) { getAPIdata data = new getAPIdata(); String formattedURL = null; if (apiNum == 0) { modifiedDate = date; String subDayStr = modifiedDate.substring(6, 8); Integer subDayNum = Integer.parseInt(subDayStr); Log.i(tag, "Day: " + subDayStr); String subMonStr = modifiedDate.substring(4, 6); Integer subMonNum = Integer.parseInt(subMonStr); Log.i(tag, "Month: " + subMonStr); String subYearStr = modifiedDate.substring(0, 4); Integer subYearNum = Integer.parseInt(subYearStr); if (subDayNum == 1) { if (subMonNum == 1) { subDayNum = 30; subMonNum = 12; subYearNum = subYearNum - 1; } else { subDayNum = 28; subMonNum = subMonNum - 1; } } else { subDayNum = subDayNum - 1; } if (subDayNum < 10) { subDayStr = "0" + subDayNum.toString(); } else { subDayStr = subDayNum.toString(); } if (subMonNum < 10) { subMonStr = "0" + subMonNum.toString(); } else { subMonStr = subMonNum.toString(); } subYearStr = subYearNum.toString(); formattedURL = context.getString(R.string.api_prehistory) + subYearStr + subMonStr + subDayStr + context.getString(R.string.api_precoord) + latit + "," + longit + context.getString(R.string.api_end); // Log.i(tag, formattedURL); modifiedDate = date; } else { String subDayStr = modifiedDate.substring(6, 8); Integer subDayNum = Integer.parseInt(subDayStr); Log.i(tag, "Day: " + subDayStr); String subMonStr = modifiedDate.substring(4, 6); Integer subMonNum = Integer.parseInt(subMonStr); Log.i(tag, "Month: " + subMonStr); String subYearStr = modifiedDate.substring(0, 4); Integer subyearNum = Integer.parseInt(subYearStr); Log.i(tag, "Year: " + subYearStr); if (apiNum == 1 || apiNum == 3 || apiNum == 5 || apiNum == 7) { if (subMonNum <= 2) { if (subMonNum == 1) { subMonNum = 11; } if (subMonNum == 2) { subMonNum = 12; } subyearNum = subyearNum - 1; } else { subMonNum = subMonNum - 2; } subDayNum = 15; } else { if (subMonNum == 1) { subMonNum = 12; subyearNum = subyearNum - 1; } else { subMonNum = subMonNum - 2; } subDayNum = 01; } if (subDayNum < 10) { subDayStr = "0" + subDayNum.toString(); } else { subDayStr = subDayNum.toString(); } if (subMonNum < 10) { subMonStr = "0" + subMonNum.toString(); } else { subMonStr = subMonNum.toString(); } modifiedDate = subyearNum.toString() + subMonStr + subDayStr; Log.i(tag, modifiedDate); formattedURL = context.getString(R.string.api_prehistory) + subyearNum.toString() + subMonStr + subDayStr + context.getString(R.string.api_precoord) + latit + "," + longit + context.getString(R.string.api_end); } try { url = new URL(formattedURL); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.i(tag, formattedURL); data.execute(formattedURL); } else { Toast.makeText(context, "No Internet Connection Available", Toast.LENGTH_SHORT).show(); Log.i(tag, "No Internet Connection"); } } } // Check Network Connection Method public Boolean checkConnection (Context context) { Boolean connected = false; ConnectivityManager connManag = (ConnectivityManager) context .getSystemService (Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfomation = connManag.getActiveNetworkInfo(); if (networkInfomation != null) { if (networkInfomation.isConnected()) { Log.i(tag, "Connection Type: " + networkInfomation.getTypeName() .toString()); connected = true; } } return connected; } // API Method public String getAPIresponse(URL url) { String apiResponse = ""; try { URLConnection apiConnection = url.openConnection(); BufferedInputStream bufferedInput = new BufferedInputStream(apiConnection .getInputStream()); byte[] contextByte = new byte[1024]; int bytesRead = 0; StringBuffer responseBuffer = new StringBuffer(); while ((bytesRead = bufferedInput.read(contextByte)) != -1) { apiResponse = new String(contextByte, 0, bytesRead); responseBuffer.append(apiResponse); } apiResponse = responseBuffer.toString(); // Log.i(tag, apiResponse); } catch (IOException e) { // TODO Auto-generated catch block Log.i(tag, "getAPIresponse - no data returned"); e.printStackTrace(); } // Log.i(tag, apiResponse.toString()); return apiResponse; } // API Class class getAPIdata extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); } @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub String APIresponseStr = ""; if (url != null) { APIresponseStr = getAPIresponse(url); return APIresponseStr; } else { return null; } } @Override protected void onPostExecute(String result) { // Log.i(tag, result); super.onPostExecute(result); // Log.i(tag, result); // Parse Methods Called based on which data is being entered after API has returned data parseData(result, "weather"); } } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub Log.i(tag, "Latitude: " + location.toString() + ", " + "Longitude: " + location.toString()); // Get current date Date date = new Date(); CharSequence currentDate = DateFormat.format("yyyyMMdd", date.getTime()); Log.i(tag, currentDate.toString()); latit = String.valueOf(location.getLatitude()); longit = String.valueOf(location.getLongitude()); handleAPI(currentDate.toString()); } // addTabs adds tabs after the API has returned data if weather data isn't already present. public void addTabs() { if (apiNum == 8) { actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); Tab actionBarTab = actionBar.newTab(); actionBarTab.setText(R.string.actionbar_buildsystem).setTabListener(this); actionBar.addTab(actionBarTab); actionBarTab = actionBar.newTab(); actionBarTab.setText(R.string.actionbar_fish).setTabListener(this); actionBar.addTab(actionBarTab); actionBarTab = actionBar.newTab(); actionBarTab.setText(R.string.actionbar_plants).setTabListener(this); actionBar.addTab(actionBarTab); actionBar.setSelectedNavigationItem(0); } } // calculateTemps calculates the average temp for all seasons as well as annually. public void calculateTemps() { ArrayList<Double> annualLowTemps = new ArrayList<Double>(); ArrayList<Double> annualHighTemps = new ArrayList<Double>(); ArrayList<Double> winterLowTemps = new ArrayList<Double>(); ArrayList<Double> winterHighTemps = new ArrayList<Double>(); ArrayList<Double> springLowTemps = new ArrayList<Double>(); ArrayList<Double> springHighTemps = new ArrayList<Double>(); ArrayList<Double> summerLowTemps = new ArrayList<Double>(); ArrayList<Double> summerHighTemps = new ArrayList<Double>(); ArrayList<Double> fallLowTemps = new ArrayList<Double>(); ArrayList<Double> fallHighTemps = new ArrayList<Double>(); if (!weatherInfo.isEmpty()) { for (int u = 0; u < weatherInfo.size(); u++) { Double lowTemp = 0.0; Double highTemp = 0.0; String lowTempStr = weatherInfo.get(u).lowTemp.toString(); String highTempStr = weatherInfo.get(u).highTemp.toString(); try { lowTemp = Double.parseDouble(lowTempStr); highTemp = Double.parseDouble(highTempStr); } catch(NumberFormatException nfe) { System.out.println("Could not parse " + nfe); } annualLowTemps.add(lowTemp); annualHighTemps.add(highTemp); if (weatherInfo.get(u).month.toString().matches("12") || weatherInfo.get(u).month.toString().matches("01") || weatherInfo.get(u).month.toString().matches("02")) { winterLowTemps.add(lowTemp); winterHighTemps.add(highTemp); } if (weatherInfo.get(u).month.toString().matches("03") || weatherInfo.get(u).month.toString().matches("04") || weatherInfo.get(u).month.toString().matches("05")) { springLowTemps.add(lowTemp); springHighTemps.add(highTemp); } if (weatherInfo.get(u).month.toString().matches("06") || weatherInfo.get(u).month.toString().matches("07") || weatherInfo.get(u).month.toString().matches("08")) { summerLowTemps.add(lowTemp); summerHighTemps.add(highTemp); } if (weatherInfo.get(u).month.toString().matches("09") || weatherInfo.get(u).month.toString().matches("10") || weatherInfo.get(u).month.toString().matches("11")) { fallLowTemps.add(lowTemp); fallHighTemps.add(highTemp); } } for (int t = 0; t < annualLowTemps.size(); t++) { annualLowAverage = annualLowAverage + annualLowTemps.get(t); annualHighAverage = annualHighAverage + annualHighTemps.get(t); } for (int q = 0; q < winterLowTemps.size(); q++) { winterLowAverage = winterLowAverage + winterLowTemps.get(q); winterHighAverage = winterHighAverage + winterHighTemps.get(q); } for (int w = 0; w < springLowTemps.size(); w++) { springLowAverage = springLowAverage + springLowTemps.get(w); springHighAverage = springHighAverage + springHighTemps.get(w); } for (int e = 0; e < summerLowTemps.size(); e++) { summerLowAverage = summerLowAverage + summerLowTemps.get(e); summerHighAverage = summerHighAverage + summerHighTemps.get(e); } for (int r = 0; r < fallLowTemps.size(); r++) { fallLowAverage = fallLowAverage + fallLowTemps.get(r); fallHighAverage = fallHighAverage + fallHighTemps.get(r); } Log.i(tag, annualLowTemps.toString()); Log.i(tag, annualHighTemps.toString()); Log.i(tag, winterLowTemps.toString()); Log.i(tag, winterHighTemps.toString()); Log.i(tag, springLowTemps.toString()); Log.i(tag, springHighTemps.toString()); Log.i(tag, summerLowTemps.toString()); Log.i(tag, summerHighTemps.toString()); Log.i(tag, fallLowTemps.toString()); Log.i(tag, fallHighTemps.toString()); annualLowAverage = annualLowAverage / annualLowTemps.size(); annualHighAverage = annualHighAverage / annualHighTemps.size(); winterLowAverage = winterLowAverage / winterLowTemps.size(); winterHighAverage = winterHighAverage / winterHighTemps.size(); springLowAverage = springLowAverage / springLowTemps.size(); springHighAverage = springHighAverage / springHighTemps.size(); summerLowAverage = summerLowAverage / summerLowTemps.size(); summerHighAverage = summerHighAverage / summerHighTemps.size(); fallLowAverage = fallLowAverage / fallLowTemps.size(); fallHighAverage = fallHighAverage / fallHighTemps.size(); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } }
package org.example.config; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DeprecatedHandlerProxyConfigurator implements ProxyConfigurator { @Override public Object replaceWithProxyIfNeeded(Object object, Class implClass) { if (!implClass.isAnnotationPresent(Deprecated.class)) { return object; } if (implClass.getInterfaces().length == 0) { String message = "--> cglib proxy: Run method with @Deprecated annotation!!!"; return Enhancer.create( implClass, (InvocationHandler) (proxy, method, args) -> getInvocationHander(object, method, args, message)); } String message = "--> dynamic proxy: Run method with @Deprecated annotation!!!"; return Proxy.newProxyInstance( implClass.getClassLoader(), implClass.getInterfaces(), (proxy, method, args) -> getInvocationHander(object, method, args, message)); } private Object getInvocationHander(Object object, Method method, Object[] args, String message) throws IllegalAccessException, InvocationTargetException { System.out.println(message); return method.invoke(object, args); } }
/*Longest Increasing Subsequence question: http://www.lintcode.com/en/problem/longest-increasing-subsequence/ answer: http://www.jiuzhang.com/solutions/longest-increasing-subsequence/ Given a sequence of integers, find the longest increasing subsequence (LIS). You code should return the length of the LIS. Example For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3 For [4, 2, 4, 5, 3, 7], the LIS is [4, 4, 5, 7], return 4 Challenge Time complexity O(n^2) or O(nlogn) Clarification What's the definition of longest increasing subsequence? * The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique. * https://en.wikipedia.org/wiki/Longest_common_subsequence_problem */ package sequenceDP; public class LongestIncreasingSubsequence { public static int longestincreasingsub(int[] nums){ if (nums == null || nums.length == 0){ return 0; } int n = nums.length; //1. state: maxlength[i] means the longest increasing subsequence ends with i. int[] maxlength = new int[n]; //2. initialization int max = 0; //3. function for (int i = 0; i < n; i++){ //initilazation, worst case, maxlength is 1 maxlength[i] = 1; //j is the previous element for (int j = 0; j < i; j++){ if (nums[j] <= nums[i]){ maxlength[i] = Math.max(maxlength[j] + 1, maxlength[i]); } } //important, maxlength[i] means the max length of the sequence ends with i, but we //need the max length of the whole array. if (maxlength[i] > max){ max = maxlength[i]; } } //4. answer return max; } public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = {5,4,1,2,3}; int[] nums1 = {4,2,4,5,3,7}; System.out.println(longestincreasingsub(nums)); //System.out.println(longestincreasingsub(nums1)); } }
import java.util.Scanner; import java.util.Stack; public class Random41 { public static int findLargestPossibleArea(int[] a) { Stack<Integer> s = new Stack<Integer>(); int n = a.length; int max = 0; int top; int m = -1; int i = 0; while (i < n) { if (s.empty() || a[s.peek()] <= a[i]) s.push(i++); else { top = s.peek(); s.pop(); m = a[top] * (s.empty() ? i : i - s.peek() - 1); if (max < m) max = m; } } while (s.empty() == false) { top = s.peek(); s.pop(); if(s.empty()) m = a[top]*i; else m = a[top]*(i-s.peek()-1); if (max < m) max = m; } return max; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter"); int t = scanner.nextInt(); while(t-->0) { int n = scanner.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i] = scanner.nextInt(); System.out.println(findLargestPossibleArea(arr)); } scanner.close(); } }
package org.sankozi.rogueland.model.effect; import org.sankozi.rogueland.model.Description; import org.sankozi.rogueland.model.GameObject; import org.sankozi.rogueland.model.Param; import java.util.Collections; import java.util.Map; /** * Base class of effects. Effect is an GameObject that changes parametrized * GameObjects like Destroyable, Actor or Player * * @author sankozi */ public abstract class Effect implements GameObject{ /** Null effect */ public static final Effect NULL = new Effect(-1f){ @Override public Description start(AccessManager manager) { return Description.EMPTY; } @Override public void end(AccessManager manager) {} @Override public String getObjectName() { return "none"; } @Override public Map<Param, Float> getDescriptionParameters(){ return Collections.emptyMap(); } }; protected final float finishTime; protected Effect(float finishTime) { this.finishTime = finishTime; } /** * Time at which this effect will end relative to start moment, * for permanent effects this method should return Float.POSITIVE_INFINITY * for instants should return 0f * @return */ public float getFinishTime(){ return finishTime; } /** * Makes changes to attached object * @param manager, not null * @return */ public abstract Description start(AccessManager manager); /** * Ends this Effect, implementing classes may undo changes made in start method * @param manager */ public abstract void end(AccessManager manager); /** * Return parameters that can be used to describe an effect * @return Map containing values of certain parameters, can be empty, never null */ public abstract Map<? extends Param, Float> getDescriptionParameters(); /** * If this Effect is based on parameters of attached GameObject this method * will be called when change in dependant values is detected. * * By default start method is called again. * * @param manager */ public void reload(EffectManager manager) { start(manager); } /** * Two effects are equal if they are same instances * @param obj * @return */ @Override public final boolean equals(Object obj) { return this == obj; } @Override public final int hashCode() { return super.hashCode(); } }
package com.monits.findbugs.jdk; import java.util.BitSet; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import javax.annotation.Nonnull; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.FieldInstruction; import org.apache.bcel.generic.GETFIELD; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionHandle; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.ba.BasicBlock; import edu.umd.cs.findbugs.ba.BasicBlock.InstructionIterator; import edu.umd.cs.findbugs.ba.CFG; import edu.umd.cs.findbugs.ba.CFGBuilderException; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.Edge; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; public class InconsistentHashCodeEqualsDetector extends BytecodeScanningDetector { private static final String HASH_CODE_METHOD_NAME = "hashCode"; private static final String EQUALS_METHOD_NAME = "equals"; private static final String EQUALS_SIGNATURE = "(Ljava/lang/Object;)Z"; private XMethodAndFields equalsFields; private XMethodAndFields hashCodeFields; private Map<String, XField> fieldNameToXField; private final BugReporter reporter; public InconsistentHashCodeEqualsDetector(@Nonnull final BugReporter reporter) { this.reporter = reporter; } @Override public void visitClassContext(final ClassContext classContext) { if (qualifiesForDetection(classContext)) { fieldNameToXField = populateNamesAndXFields(classContext); super.visitClassContext(classContext); if (!hashCodeFields.getFieldNames().equals(equalsFields.getFieldNames())) { reportBugs("HASHCHODE_HAS_MORE_FIELDS_THAN_EQUALS", HIGH_PRIORITY, hashCodeFields.getXMethod(), getFieldsDifference(hashCodeFields.getFieldNames(), equalsFields.getFieldNames())); reportBugs("EQUALS_HAS_MORE_FIELDS_THAN_HASHCODE", HIGH_PRIORITY, equalsFields.getXMethod(), getFieldsDifference(equalsFields.getFieldNames(), hashCodeFields.getFieldNames())); } equalsFields = null; hashCodeFields = null; fieldNameToXField = null; } } @Nonnull private Map<String, XField> populateNamesAndXFields(@Nonnull final ClassContext classContext) { final Map<String, XField> nameToXField = new HashMap<String, XField>(); for (final XField xField : classContext.getXClass().getXFields()) { if (!xField.isStatic() && !xField.isSynthetic()) { nameToXField.put(xField.getName(), xField); } } return nameToXField; } @Nonnull private Set<XField> getFieldsDifference(@Nonnull final Set<XField> comparable, @Nonnull final Set<XField> comparator) { final Set<XField> copyComparable = new HashSet<XField>(comparable); for (final XField xField : comparator) { copyComparable.remove(xField); } return copyComparable; } private boolean qualifiesForDetection(@Nonnull final ClassContext ctx) { int methodCounter = 0; for (final Method m : ctx.getMethodsInCallOrder()) { if (isEqualsMethod(m) || isHashCodeMethod(m)) { methodCounter++; } } // must be 2, hashCode and equals methods return methodCounter == 2; } private void reportBugs(@Nonnull final String bugType, @Nonnull final int priority, @Nonnull final XMethod method, @Nonnull final Set<XField> fields) { for (final XField xField : fields) { final BugInstance bug = new BugInstance(this, bugType, priority) .addClass(getClassContext().getClassDescriptor()) .addMethod(method) .addField(xField); reporter.reportBug(bug); } } @Override public void visitMethod(final Method method) { if (isEqualsMethod(method)) { equalsFields = new XMethodAndFields(getXMethod(), getMethodXFields(method)); } else if (isHashCodeMethod(method)) { hashCodeFields = new XMethodAndFields(getXMethod(), getMethodXFields(method)); } } private boolean isEqualsMethod(@Nonnull final Method method) { return EQUALS_METHOD_NAME.equals(method.getName()) && EQUALS_SIGNATURE.equals(method.getSignature()); } private boolean isHashCodeMethod(@Nonnull final Method method) { return HASH_CODE_METHOD_NAME.equals(method.getName()) && method.getArgumentTypes().length == 0; } @Nonnull private Set<XField> getMethodXFields(@Nonnull final Method method) { final Set<XField> xFields = new HashSet<XField>(); final CFG cfg; final ConstantPoolGen cpg; final BasicBlock bb; try { cfg = getClassContext().getCFG(method); cpg = cfg.getMethodGen().getConstantPool(); bb = cfg.getEntry(); } catch (final CFGBuilderException cbe) { return xFields; } final BitSet visitedBlock = new BitSet(); final Deque<BasicBlock> toBeProcessed = new LinkedList<BasicBlock>(); toBeProcessed.add(bb); while (!toBeProcessed.isEmpty()) { final BasicBlock currentBlock = toBeProcessed.removeFirst(); final InstructionIterator ii = currentBlock.instructionIterator(); while (ii.hasNext()) { final InstructionHandle ih = ii.next(); final Instruction ins = ih.getInstruction(); if (ins instanceof FieldInstruction) { final FieldInstruction fi = (FieldInstruction) ins; final String fieldName = fi.getFieldName(cpg); if (ins instanceof GETFIELD) { // TODO : Make sure we are actually using it to compute hashCode / equals final XField xField = fieldNameToXField.get(fieldName); if (null != xField) { // add field metadata xFields.add(xField); } } } // TODO : Check for INVOKESPECIAL / INVOKEVIRTUAL calling toString from other objects } // Get adjacent blocks final Iterator<Edge> oei = cfg.outgoingEdgeIterator(currentBlock); while (oei.hasNext()) { final Edge e = oei.next(); final BasicBlock cb = e.getTarget(); final int label = cb.getLabel(); // Avoid repeated blocks if (!visitedBlock.get(label)) { toBeProcessed.addLast(cb); visitedBlock.set(label); } } } return xFields; } private static final class XMethodAndFields { private final XMethod method; private final Set<XField> fieldNames; protected XMethodAndFields(@Nonnull final XMethod method, @Nonnull final Set<XField> fieldNames) { this.method = method; this.fieldNames = fieldNames; } @Nonnull public XMethod getXMethod() { return method; } @Nonnull public Set<XField> getFieldNames() { return fieldNames; } } }
package proc; import log.LogSetting; import javax.servlet.http.HttpSession; import java.util.Map; import java.util.Timer; import java.util.logging.Logger; /** * Created by wenc on 2017/4/28. * 这里是投票阶段,计时10s,接收每位玩家的投票信息,然后将结果暂时存储 */ public class VoteProc extends Proc { private static Logger logger = LogSetting.loadSetting("分配角色阶段"); /** 当前阶段的持续时间 */ private long time=10000; @Override public void run() { GameProc.timer.schedule(new VoteInfoProc(), time); } }
package com.cognitive.newswizard.service.repository; import java.util.List; import com.cognitive.newswizard.service.repository.projection.CountRawFeedEntryByPeriodProjection; public interface RawFeedEntryAggregationRepository { List<CountRawFeedEntryByPeriodProjection> countRawFeedEntryByPeriod(final Long start, final Long end); }
package com.example.myreadproject8.greendao.entity; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Transient; import java.io.Serializable; /** * created by ycq on 2021/4/24 0024 * describe:背诵区内容 */ @Entity public class Recite implements Serializable { @Transient//手动定义serialVersionUID,避免InvalidClassException异常,不写入数据表 private static final long serialVersionUID = 1L; @Id Long id;//id String reciteT; String reciteContent; String Author; String bookName; long addDate; //背诵次数 int reciteNum; boolean firstRecite; boolean secondRecite; boolean thirdRecite; boolean fourthRecite; boolean fifthRecite; boolean sixthRecite; boolean seventhRecite; long sortCode; int reciteNums; int reciteIndex; @Generated(hash = 1307617523) public Recite(Long id, String reciteT, String reciteContent, String Author, String bookName, long addDate, int reciteNum, boolean firstRecite, boolean secondRecite, boolean thirdRecite, boolean fourthRecite, boolean fifthRecite, boolean sixthRecite, boolean seventhRecite, long sortCode, int reciteNums, int reciteIndex) { this.id = id; this.reciteT = reciteT; this.reciteContent = reciteContent; this.Author = Author; this.bookName = bookName; this.addDate = addDate; this.reciteNum = reciteNum; this.firstRecite = firstRecite; this.secondRecite = secondRecite; this.thirdRecite = thirdRecite; this.fourthRecite = fourthRecite; this.fifthRecite = fifthRecite; this.sixthRecite = sixthRecite; this.seventhRecite = seventhRecite; this.sortCode = sortCode; this.reciteNums = reciteNums; this.reciteIndex = reciteIndex; } @Generated(hash = 278849458) public Recite() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getReciteT() { return this.reciteT; } public void setReciteT(String reciteT) { this.reciteT = reciteT; } public String getReciteContent() { return this.reciteContent; } public void setReciteContent(String reciteContent) { this.reciteContent = reciteContent; } public long getAddDate() { return this.addDate; } public void setAddDate(long addDate) { this.addDate = addDate; } public int getReciteNum() { return this.reciteNum; } public void setReciteNum(int reciteNum) { this.reciteNum = reciteNum; } public boolean getFirstRecite() { return this.firstRecite; } public void setFirstRecite(boolean firstRecite) { this.firstRecite = firstRecite; } public boolean getSecondRecite() { return this.secondRecite; } public void setSecondRecite(boolean secondRecite) { this.secondRecite = secondRecite; } public boolean getThirdRecite() { return this.thirdRecite; } public void setThirdRecite(boolean thirdRecite) { this.thirdRecite = thirdRecite; } public boolean getFourthRecite() { return this.fourthRecite; } public void setFourthRecite(boolean fourthRecite) { this.fourthRecite = fourthRecite; } public boolean getFifthRecite() { return this.fifthRecite; } public void setFifthRecite(boolean fifthRecite) { this.fifthRecite = fifthRecite; } public long getSortCode() { return this.sortCode; } public void setSortCode(long sortCode) { this.sortCode = sortCode; } public int getReciteNums() { return this.reciteNums; } public void setReciteNums(int reciteNums) { this.reciteNums = reciteNums; } public boolean getSixthRecite() { return this.sixthRecite; } public void setSixthRecite(boolean sixthRecite) { this.sixthRecite = sixthRecite; } public boolean getSeventhRecite() { return this.seventhRecite; } public void setSeventhRecite(boolean seventhRecite) { this.seventhRecite = seventhRecite; } public String getAuthor() { return this.Author; } public void setAuthor(String Author) { this.Author = Author; } public String getBookName() { return this.bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public int getReciteIndex() { return this.reciteIndex; } public void setReciteIndex(int reciteIndex) { this.reciteIndex = reciteIndex; } }
package com.tencent.mm.plugin.appbrand.dynamic; import android.os.Bundle; import com.tencent.mm.ipcinvoker.a; import com.tencent.mm.ipcinvoker.c; import com.tencent.mm.sdk.platformtools.x; class a$e implements a<Bundle, Bundle> { private a$e() { } public final /* synthetic */ void a(Object obj, c cVar) { c su = d.aeQ().su(((Bundle) obj).getString("id")); if (su == null) { x.e("MicroMsg.IPCInvoke_OnResume", "get DynamicPageViewIPCProxy(id : %s) return null.", new Object[]{r0}); return; } b.o(new 1(this, su)); } }
package test; import java.util.List; import monitor.Farm; import monitor.Image; import monitor.ImageBean; import monitor.Monitorpoint; import org.junit.Test; import static org.junit.Assert.*; public class ImageBeanTest { ImageBean imageBean = new ImageBean(); public ImageBeanTest() { } /* * test loadFarms function of ImageBean */ @Test public void testLoadFarms() { List<Farm> farms = imageBean.loadFarms(); assertTrue(farms.size() > 0); assertEquals(farms.get(0).getFarmname(), "Test Farm"); } /* * test getMonitorPoints function of ImageBean */ @Test public void testLoadMonitorPoints() { imageBean.loadMonitorpoints(); List<Monitorpoint> monitorPoints = imageBean.getMonitorPoints(); assertTrue(monitorPoints.size() > 0); assertEquals(monitorPoints.get(0).getMonitorPointName(), "Test Monitor Point"); } /* * test getMonitorPointImages function of ImageBean */ @Test public void testGetMonitorPointImages() { imageBean.setSelectedMonitorPointId("2"); imageBean.getMonitorPointImages(); List<Image> images = imageBean.getImages(); assertTrue(images.size() > 0); assertFalse(images.get(0).getPath().equals("")); } }
package ch.fhnw.edu.cpib.scanner.keywords; import ch.fhnw.edu.cpib.scanner.Base; import ch.fhnw.edu.cpib.scanner.enumerations.Mechmodes; import ch.fhnw.edu.cpib.scanner.enumerations.Terminals; public class Mechmode extends Base { private final Mechmodes mechmode; public Mechmode(Mechmodes mechmode) { super(Terminals.MECHMODE); this.mechmode = mechmode; } public Mechmodes getMechmode() { return mechmode; } public String toString() { return "(" + super.toString() + ", " + getMechmode().toString() + ")"; } }
package gcdemos; import java.util.Scanner; public class wiledemo { public static void main(String[] args) { String response; do { System.out.println("enter somthing to herar it echo!"); Scanner scnr =new Scanner(System.in); String echo = scnr.nextLine(); System.out.println(echo); System.out.println("do you want to continue?"); response = scnr.next(); } while (response.equalsIgnoreCase("yes")); System.out.println("See ya!"); } }
package edu.mayo.cts2.framework.webapp.rest.query; import java.util.Set; import edu.mayo.cts2.framework.model.command.ResolvedFilter; import edu.mayo.cts2.framework.model.command.ResolvedReadContext; import edu.mayo.cts2.framework.model.service.core.Query; import edu.mayo.cts2.framework.service.command.restriction.EntityDescriptionQueryServiceRestrictions; import edu.mayo.cts2.framework.service.profile.BaseQueryService; import edu.mayo.cts2.framework.service.profile.entitydescription.EntitiesFromAssociationsQuery; import edu.mayo.cts2.framework.service.profile.entitydescription.EntityDescriptionQuery; import edu.mayo.cts2.framework.webapp.rest.resolver.FilterResolver; import edu.mayo.cts2.framework.webapp.rest.resolver.ReadContextResolver; public class EntityQueryBuilder extends AbstractResourceQueryBuilder<EntityQueryBuilder, EntityDescriptionQuery> { private EntityDescriptionQueryServiceRestrictions restrictions; private EntitiesFromAssociationsQuery entitiesFromAssociationsQuery; public EntityQueryBuilder( BaseQueryService baseQueryService, FilterResolver filterResolver, ReadContextResolver readContextResolver) { super(baseQueryService, filterResolver, readContextResolver); } public EntityQueryBuilder addRestrictions(EntityDescriptionQueryServiceRestrictions restrictions){ this.restrictions = restrictions; return this.getThis(); } public EntityQueryBuilder addAssociationRestrictions(EntitiesFromAssociationsQuery restrictions){ this.entitiesFromAssociationsQuery = restrictions; return this.getThis(); } @Override protected EntityQueryBuilder getThis() { return this; } @Override public EntityDescriptionQuery build() { final DefaultResourceQuery query = new DefaultResourceQuery(); return new EntityDescriptionQuery(){ @Override public Query getQuery() { return query.getQuery(); } @Override public Set<ResolvedFilter> getFilterComponent() { return query.getFilterComponent(); } @Override public ResolvedReadContext getReadContext() { return query.getReadContext(); } @Override public EntityDescriptionQueryServiceRestrictions getRestrictions() { return restrictions; } @Override public EntitiesFromAssociationsQuery getEntitiesFromAssociationsQuery() { return entitiesFromAssociationsQuery; } }; } }
package com.scnuweb.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.scnuweb.entity.User; import com.scnuweb.util.StaticVar; public class LoginFilter implements Filter{ private String excludedPages[] ; private String redirectBaseUrl; private boolean isValid; @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest resq, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub if(!isValid) { chain.doFilter(resq, resp); return; } HttpServletResponse response = (HttpServletResponse) resp; HttpServletRequest request = (HttpServletRequest) resq; String requestPath = request.getServletPath(); for(String excludedPage:excludedPages) { if(excludedPage.equals(requestPath)) { chain.doFilter(resq, resp); return; } } User user = (User)request.getSession().getAttribute("currentUser"); if(user==null) { response.sendRedirect(redirectBaseUrl+"login.html"); } else { if(user.getUserType()==StaticVar.USER_TYPE_ADMIN) { if(!requestPath.startsWith("/admin/"))response.sendRedirect(redirectBaseUrl+"admin/index.html"); else chain.doFilter(resq, resp); } else if(user.getUserType()==StaticVar.USER_TYPE_CANDIDATE){ if(requestPath.startsWith("/exam/"))chain.doFilter(resq, resp); else if(!requestPath.startsWith("/candidate/"))response.sendRedirect(redirectBaseUrl+"candidate/index.html"); else chain.doFilter(resq, resp); } } } @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub excludedPages = filterConfig.getInitParameter("excludedPages").split(","); redirectBaseUrl = filterConfig.getInitParameter("redirectBaseUrl"); isValid = Boolean.parseBoolean(filterConfig.getInitParameter("isValid")); } }
package com.bozhong.lhdataaccess.application; import com.bozhong.lhdataaccess.client.common.constants.ServiceErrorEnum; /** * 上下文的返回结果 * * @author bin * @create 2018-04-27 下午5:17 **/ public class Result <T> { private static final long serialVersionUID = -6667401724585745605L; private boolean success = true; private ServiceErrorEnum serviceError; private T module; public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public ServiceErrorEnum getServiceError() { return serviceError; } public void setServiceError(ServiceErrorEnum serviceError) { this.success=false; this.serviceError = serviceError; } public T getModule() { return module; } public void setModule(T module) { this.module = module; } }
package com.hesoyam.pharmacy.pharmacy.model; import com.hesoyam.pharmacy.util.DateTimeRange; import javax.persistence.*; import javax.validation.constraints.Min; import java.util.Objects; @Entity public class InventoryItemPrice { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) protected Long id; @Column(nullable = false) @Min(0) protected double price; @Embedded protected DateTimeRange validThrough; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public DateTimeRange getValidThrough() { return validThrough; } public void setValidThrough(DateTimeRange validThrough) { this.validThrough = validThrough; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InventoryItemPrice)) return false; InventoryItemPrice itemPrice = (InventoryItemPrice) o; return Objects.equals(getId(), itemPrice.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } public boolean isConflictingWith(InventoryItemPrice newInventoryItemPrice) { return this.validThrough.overlaps(newInventoryItemPrice.getValidThrough()); } }
/* * 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 ai; import PriorityQueue.PQHeap; import ai.Node; import java.util.ArrayList; import java.util.Collection; import junit.framework.Assert; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * * @author oskar */ public class PQHeapTest { Node node_1; Node node_2; Node node_3; Node node_4; Node node_5; Node node_6; ArrayList<Node> nodes; public PQHeapTest() { this.nodes = new ArrayList<>(); } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { this.node_1 = mock(Node.class); this.node_2 = mock(Node.class); this.node_3 = mock(Node.class); this.node_4 = mock(Node.class); this.node_5 = mock(Node.class); this.node_6 = mock(Node.class); when(node_1.getFinalCost()).thenReturn(100); when(node_2.getFinalCost()).thenReturn(90); when(node_3.getFinalCost()).thenReturn(80); when(node_4.getFinalCost()).thenReturn(70); when(node_5.getFinalCost()).thenReturn(60); when(node_6.getFinalCost()).thenReturn(50); this.nodes.add(this.node_1); this.nodes.add(this.node_2); this.nodes.add(this.node_3); this.nodes.add(this.node_4); this.nodes.add(this.node_5); this.nodes.add(this.node_6); } private PQHeap insertAll(){ PQHeap pqHeap = new PQHeap(6); for(Node node : this.nodes) pqHeap.insert(node); return pqHeap; } @After public void tearDown() { } /** * Test of isEmpty method, of class PQHeap. */ @Test public void testIsEmpty() { PQHeap pqHeap = new PQHeap(10); Assert.assertTrue(pqHeap.isEmpty()); pqHeap = this.insertAll(); Assert.assertFalse(pqHeap.isEmpty()); } /** * Test of getHeapSize method, of class PQHeap. */ @Test public void testGetHeapSize() { PQHeap pqHeap = this.insertAll(); Assert.assertEquals(pqHeap.getHeapSize(), 6); // as 6 nodes is in the heap } /** * Test of extractMin method, of class PQHeap. */ @Test public void testExtractMin() { PQHeap pqHeap = this.insertAll(); Node min = mock(Node.class); when(min.getFinalCost()).thenReturn(Integer.MAX_VALUE); for(Node node : this.nodes){ if(node.getFinalCost() < min.getFinalCost()) min = node; } Assert.assertEquals(pqHeap.extractMin(), min); } /** * Test of remove method, of class PQHeap. */ @Test public void testRemove() { PQHeap pqHeap = this.insertAll(); Assert.assertTrue(pqHeap.contains(node_1)); pqHeap.remove(node_1); Assert.assertFalse(pqHeap.contains(node_1)); } /** * Test of contains method, of class PQHeap. */ @Test public void testContains() { PQHeap pqHeap = this.insertAll(); Assert.assertTrue(pqHeap.contains(this.nodes.get(0))); } /** * Test of insert method, of class PQHeap. */ @Test public void testInsert() { Node node = new Node(10, 10); PQHeap pqHeap = new PQHeap(10); Assert.assertFalse(pqHeap.contains(node)); pqHeap.insert(node); Assert.assertTrue(pqHeap.contains(node)); } }
import java.io.BufferedReader; import java.math.BigInteger; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author CappyHoding */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n; BigInteger res = new BigInteger("0"); n = sc.nextInt(); for(int i=0 ;i<n;i++){ String bil = sc.next(); BigInteger a = new BigInteger(bil); res = res.add(a); } String last = Integer.toString(n); BigInteger asd = new BigInteger(last); res = res.add(asd); System.out.println(res); } }
package com.cnk.travelogix.crm.facade; /* * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with SAP Hybris. */ import com.cnk.travelogix.sap.crm.integration.mapping.dto.CRMCustReplicationWSRequest; import com.cnk.travelogix.sap.crm.integration.mapping.dto.CRMCustReplicationWSResponse; import de.hybris.platform.commerceservices.customer.DuplicateUidException; /** * */ public interface CRMCustomerFacade { public CRMCustReplicationWSResponse createUpdateUser(final CRMCustReplicationWSRequest crmCustReplicationWSRequest) throws DuplicateUidException; }
public class Main { public static void main(String[] args) { Square square = new Square(3); System.out.println(square.getPerimeter()); square.setSide(1); System.out.println(square.getPerimeter()); System.out.println(square.toString()); } }
package chapter07; import java.util.Scanner; public class Exercise07_01 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("enter the number of students:"); int numberOfStudents = input.nextInt(); int[] numberOfPoints = new int[numberOfStudents]; for (int i = 0; i < numberOfPoints.length; i++) { System.out.println("enter " + numberOfStudents + " scores:"); numberOfPoints[i] = input.nextInt(); } printGrade(numberOfPoints, findHighestScore(numberOfPoints)); } private static int findHighestScore(int[] numberOfPoints) { int max = 0; for (int i = 0; i < numberOfPoints.length; i++) { max = max >= numberOfPoints[i] ? max : numberOfPoints[i]; } return max; } private static void printGrade(int[] numberOfPoints, int max) { for (int i = 0; i < numberOfPoints.length; i++) { if (numberOfPoints[i] >= max - 10) { System.out.println("Student " + i + " score is " + numberOfPoints[i] + " and grade is A"); } else if (numberOfPoints[i] >= max - 20) { System.out.println("Student " + i + " score is " + numberOfPoints[i] + " and grade is B"); } else if (numberOfPoints[i] >= max - 30) { System.out.println("Student " + i + " score is " + numberOfPoints[i] + " and grade is C"); } else if (numberOfPoints[i] >= max - 40) { System.out.println("Student " + i + " score is " + numberOfPoints[i] + " and grade is D"); } else { System.out.println("Student " + i + " score is " + numberOfPoints[i] + " and grade is F"); } } } }
package com.mideas.rpg.v2.command; import com.mideas.rpg.v2.connection.ConnectionManager; import com.mideas.rpg.v2.connection.PacketID; import com.mideas.rpg.v2.files.logs.LogsMgr; import com.mideas.rpg.v2.hud.RealmListFrame; import com.mideas.rpg.v2.hud.SelectScreen; public class CommandLoginRealm extends Command { @Override public void read() { short packetId = ConnectionManager.getWorldServerConnection().readShort(); if (packetId == PacketID.LOGIN_REALM_SUCCESS) { System.out.println("LOGIN:LOGIN_REALM_SUCCESS"); ConnectionManager.setIsLoggedOnWorldServer(true); ConnectionManager.setWorldServer(RealmListFrame.getSelectedRealm()); SelectScreen.getAlert().setText("Loading characters..."); CommandSelectScreenLoadCharacters.write(); LogsMgr.writeConnectionLog("Connection to world server accepted."); //SelectScreen.setRealmScreenActive(false); } else if (packetId == PacketID.LOGIN_REALM_DOESNT_ACCEPT_CONNECTION) { LogsMgr.writeConnectionLog("Connection to world server failed, server is closed."); } } }
/* * created 14.03.2005 * * $Id: TableComponentEditPolicy.java 3 2005-11-02 03:04:20Z csell $ */ package com.byterefinery.rmbench.editpolicies; import org.eclipse.gef.commands.Command; import org.eclipse.gef.editpolicies.ComponentEditPolicy; import org.eclipse.gef.requests.GroupRequest; import com.byterefinery.rmbench.editparts.DiagramEditPart; import com.byterefinery.rmbench.editparts.TableEditPart; import com.byterefinery.rmbench.operations.CommandAdapter; import com.byterefinery.rmbench.operations.DeleteTableOperation; /** * table component policy. Provides a delete command only. Not used because * {@link com.byterefinery.rmbench.actions.DeleteAction} does not use policies * * @author cse */ public class TableComponentEditPolicy extends ComponentEditPolicy { protected Command createDeleteCommand(GroupRequest request) { TableEditPart tablePart = (TableEditPart) getHost(); DiagramEditPart diagramPart = (DiagramEditPart)tablePart.getParent(); return new CommandAdapter( new DeleteTableOperation(diagramPart.getDiagram(), tablePart.getDTable())); } }
package com.gmail.ivanytskyy.vitaliy.annotation; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /* * LessonIntervalFormatValidator class. Used as a validator for properties of LessonInterval objects * @author Vitaliy Ivanytskyy */ public class LessonIntervalFormatValidator implements ConstraintValidator<LessonIntervalFormat, String>{ @Override public void initialize(LessonIntervalFormat constraintAnnotation) {} @Override public boolean isValid(String value, ConstraintValidatorContext context) { if(value == null || value.length() != 5){ return false; } String[] inputData = value.split("[.]"); if(inputData.length == 2){ int[] inputDataAsNumber = new int[2]; for(int i = 0; i < inputData.length; i++){ try{ inputDataAsNumber[i] = Integer.parseInt(inputData[i]); }catch(NumberFormatException nfe){ return false; } } int hour = inputDataAsNumber[0]; //System.out.println("hour " + hour); int minutes = inputDataAsNumber[1]; //System.out.println("minutes " + minutes); if(hour < 0 || hour > 24 || minutes < 0 || minutes > 59 || (hour == 24 && minutes > 0)){ return false; }else{ return true; } }else{ return false; } } }
package com.fabio.dropbox.repository; import com.fabio.dropbox.util.FileHashEntity; import org.springframework.data.repository.CrudRepository; public interface FileHashRepository extends CrudRepository<FileHashEntity, Integer> { }
package handsOn; public interface WebElements { public String strURL = "www.google.com"; public String strGmail = "//a[@data-pid='23']"; //public String strSignin = " //input[@aria-label = 'Email or phone']"; public String strSign = "//a[@ga-event-action='sign in']"; public String[] strArrCheck = {"hi","heloo","bye","Thanks"}; ///for practice public String strUrlA = "https://www.bing.com"; public String strTextbox = "//input[@type='search']"; public String strBingSearch = "//input[@id=\"sb_form_q\"]"; public String strImage = "//li[@id=\'images\']"; }
package com.hadoop.twitterhadoop.all.domain; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; public final class CONSTANTS { public static String jar_path = "jars/"; public static String output_path = "out/"; public static String output_name = "part-r-00000"; public static String full_output_path_hdfs = output_path+ output_name; public static String most_likes = jar_path + "mp-likes.jar"; public static String most_rts = jar_path + "mp-retweets.jar"; public static String most_reps = jar_path + "mp-replies.jar"; public static String most_times = jar_path + "mp-time.jar"; public static String length = jar_path + "mp-length.jar"; public static String dataset_path = "datasets/"; public static String default_dataset_path = dataset_path + "tweets.sample.csv"; public static Boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win"); }
package com.tdd.model; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author teyyub */ public class QueenTest { private Queen instance; public QueenTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { instance = new Queen(); } @After public void tearDown() { } /** * Test of getColor method, of class Queen. */ @Test public void createQueen() { Queen whiteQueen = Queen.createQueen("WHITE"); assertEquals("WHITE", whiteQueen.getColor()); assertEquals("q", whiteQueen.getRepresentation()); Queen blackQueen = Queen.createQueen("BLACK"); assertEquals("BLACK", blackQueen.getColor()); assertEquals("Q", blackQueen.getRepresentation()); assertEquals(9, whiteQueen.getValue()); assertEquals(9, blackQueen.getValue()); } }
package lists.linkedList.doublyLinkedList; public class Main { public static void main(String[] args) { Employee nishant = new Employee("Nishant", "Singh", 1); Employee prashant = new Employee("Prashant", "Singh", 2); Employee vinay = new Employee("Vinay", "Singh", 3); Employee anand = new Employee("Anand", "Singh", 4); EmployeeDoublyLinkedList employeeDoublyLinkedList= new EmployeeDoublyLinkedList(); //add elements to the front of LL System.out.println("add to front"); employeeDoublyLinkedList.addToFront(nishant); employeeDoublyLinkedList.addToFront(prashant); employeeDoublyLinkedList.addToFront(vinay); employeeDoublyLinkedList.addToFront(anand); employeeDoublyLinkedList.printList(); employeeDoublyLinkedList.getSize(); //add elements to the back of LL System.out.println("\nadd to back"); employeeDoublyLinkedList.addToEnd(nishant); employeeDoublyLinkedList.addToEnd(prashant); employeeDoublyLinkedList.addToEnd(vinay); employeeDoublyLinkedList.addToEnd(anand); employeeDoublyLinkedList.printList(); employeeDoublyLinkedList.getSize(); // remove elements from the front of the LL System.out.println("\nremoving elements from front"); employeeDoublyLinkedList.removeFromFront(); employeeDoublyLinkedList.removeFromFront(); employeeDoublyLinkedList.removeFromFront(); employeeDoublyLinkedList.removeFromFront(); employeeDoublyLinkedList.removeFromFront(); employeeDoublyLinkedList.printList(); employeeDoublyLinkedList.getSize(); // remove elements from the Back of the LL System.out.println("\nremoving elements from back"); employeeDoublyLinkedList.removeFromEnd(); employeeDoublyLinkedList.removeFromEnd(); employeeDoublyLinkedList.removeFromEnd(); employeeDoublyLinkedList.removeFromEnd(); employeeDoublyLinkedList.printList(); employeeDoublyLinkedList.getSize(); } }
package renderEngine; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; public class Fullscreen { private static boolean fullscreen = false; public static void setFullscreen() { try { Display.setDisplayModeAndFullscreen(Display.getDesktopDisplayMode()); } catch (LWJGLException e) { e.printStackTrace(); } fullscreen = true; } public static void setFullscreenOff() { try { Display.setFullscreen(false); } catch (LWJGLException e) { e.printStackTrace(); } fullscreen = false; } public static boolean isFullscreen() { return fullscreen; } }
package ftry.backand.first_comp.cofferorderer.BL.Rutiner; import android.content.Context; import java.io.Serializable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import ftry.backand.first_comp.cofferorderer.DAL.HttpRequestor; /** * Created by User on 4/15/2016. */ public class RutineUpdater implements Serializable { private RutineRunner mRutinner; public void StartRutine(HttpRequestor requestor,Context context) { mRutinner=new RutineRunner(requestor,context); ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleAtFixedRate(mRutinner, 0, 3, TimeUnit.SECONDS); } }
package model; public interface AccessBackDAO { public abstract AccessBackBean getAcess(String bigWave); public abstract AccessBackBean changePass(String bigWave, byte[] newPassKey); public abstract AccessBackBean insert(String bigWave, byte[] passKey); }
package isden.mois.magellanlauncher; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.preference.PreferenceManager; import android.support.v4.util.Pair; import isden.mois.magellanlauncher.helpers.DBBooks; import isden.mois.magellanlauncher.holders.BookTime; import isden.mois.magellanlauncher.holders.HistoryDetail; import isden.mois.magellanlauncher.utils.DateKt; import java.io.File; import java.util.*; public class Onyx { private static final String CONTENT_URI = "content://com.onyx.android.sdk.OnyxCmsProvider/"; public static Metadata getCurrentBook(Context ctx) { Cursor c = ctx.getContentResolver().query( Uri.parse(CONTENT_URI + "current_book"), null, null, null, null ); return parseBook(ctx, c); } public static Metadata getBook(Context ctx, String MD5) { Cursor c = ctx.getContentResolver().query( Uri.parse(CONTENT_URI + "book"), null, null, new String[]{MD5}, null ); return parseBook(ctx, c); } private static Metadata parseBook(Context ctx, Cursor c) { Metadata metadata = null; if (c != null) { if (c.moveToFirst()) { metadata = new Metadata(); metadata.md5 = c.getString(c.getColumnIndex("MD5")); metadata.title = c.getString(c.getColumnIndex("Title")); metadata.author = c.getString(c.getColumnIndex("Authors")); metadata.thumbnail = c.getString(c.getColumnIndex("Thumbnail")); metadata.filePath = c.getString(c.getColumnIndex("Location")); String progress = c.getString(c.getColumnIndex("Progress")); if (progress != null && progress.contains("/")) { String[] progressData = progress.split("/"); metadata.progress = Integer.parseInt(progressData[0]); metadata.size = Integer.parseInt(progressData[1]); } } c.close(); } if (metadata != null) { Pair<BookTime, Integer> details = getBookDetails(ctx, metadata.md5); metadata.time = details.first; metadata.readPages = details.second; } return metadata; } public static Pair<BookTime, Integer> getBookDetails(Context ctx, String MD5) { ArrayList<int[]> speeds = new ArrayList<>(); int lastProgress = 0; BookTime bookTime = new BookTime(); bookTime.totalTime = 0; bookTime.currentTime = 0; String[] progressData = null; Cursor c = getHistoryCursor(ctx, MD5); if (c != null) { try { while (c.moveToNext()) { long time = c.getLong(c.getColumnIndex("Time")); String progress = c.getString(c.getColumnIndex("Progress")); if (progress.contains("/")) { progressData = progress.split("/"); int currentProgress = Integer.parseInt(progressData[0]); // Если начал читать заново. if (currentProgress < lastProgress) { int totalProgress = Integer.parseInt(progressData[1]); int currentPercent = 100 * currentProgress / totalProgress; int previousPercent = 100 * lastProgress / totalProgress; int diffPercent = previousPercent - currentPercent; if (currentPercent < 20 && diffPercent > 20) { bookTime.currentTime = 0; speeds = new ArrayList<>(); lastProgress = 0; } } bookTime.totalTime += time; bookTime.currentTime += time; int speed; if (currentProgress != lastProgress) { speed = (int) (time / (currentProgress - lastProgress)); } else { speed = 0; } // Если были пропущены главы. if (currentProgress > lastProgress && speed > 10000 && speed < 100000) { speeds.add(new int[]{speed, currentProgress - lastProgress}); } lastProgress = currentProgress; } } } finally { c.close(); } } long bookWeight = 0; double bookPages = 0; for (int[] speedTime : speeds) { bookWeight += (long) speedTime[0] * speedTime[1]; bookPages += speedTime[1]; } bookTime.speed = bookWeight / bookPages; return new Pair<>(bookTime, (int) Math.round(bookPages)); } public static String getTotalTime(Context ctx) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); String limit = prefs.getString("history_clean_limit", "20000"); Cursor c = ctx.getContentResolver().query( Uri.parse(CONTENT_URI + "library_history"), new String[]{"SUM(EndTime - StartTime) AS Time"}, "(EndTime - StartTime) > " + limit, null, null ); if (c != null) { if (c.moveToFirst()) { long totalTime = c.getLong(0); return DateKt.formatHumanTime(totalTime); } c.close(); } return "0"; } public static void cleanDirtyHistory(Context ctx) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); String limit = prefs.getString("history_clean_limit", "20000"); ctx.getContentResolver().delete( Uri.parse(CONTENT_URI + "library_history"), "(EndTime - StartTime) < " + limit, null ); } public static List<Metadata> getLastDownloaded(Context ctx, int limit) { Cursor c = ctx.getContentResolver().query( Uri.parse(CONTENT_URI + "last_downloaded"), null, null, null, String.valueOf(limit) ); List<Metadata> metadataList = new ArrayList<>(); if (c != null) { try { while (c.moveToNext()) { Metadata metadata = new Metadata(); metadata.author = c.getString(c.getColumnIndex("Authors")); metadata.title = c.getString(c.getColumnIndex("Title")); metadata.filePath = c.getString(c.getColumnIndex("Location")); metadata.thumbnail = c.getString(c.getColumnIndex("Thumbnail")); metadataList.add(metadata); } } finally { c.close(); } } return metadataList; } public static Cursor getHistoryCursor(Context ctx, String MD5) { if (MD5 == null) { return null; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); String limit = prefs.getString("history_clean_limit", "20000"); return ctx.getContentResolver().query( Uri.parse(CONTENT_URI + "library_history"), new String[]{"StartTime", "(EndTime - StartTime) AS Time", "Progress"}, "Progress <> \"5/5\" AND MD5 = ? AND (EndTime - StartTime) > " + limit, new String[]{MD5}, "StartTime" ); } }
package com.x.service; import java.util.Map; /** * @Description: TODO * * @author chenkangming * @version V1.0 * @Date 2014-7-11下午11:03:38 */ public interface SysConfigService { Map<String,String> getSysConfig(); }
/** * @author Anthony Danilchenko * @program NameAndAdress.java * @programDescription Get user info and concatenate it and print it out * @date Sept. 24 2013 */ import java.util.Scanner; public class NameAndAddress { /** * @param args */ public static void main(String[] args) { //declare variables String firstN, lastN, street, town, state, fullN; String fullAdd; int houseNum, ZIP; Scanner reader = new Scanner(System.in); //get the users name System.out.println("What is your name?"); firstN = reader.nextLine(); // get the users last name System.out.println("Thank you, now your last name:"); lastN = reader.nextLine(); // get a full name together fullN = firstN + " " + lastN; //get the users house number System.out.println("House numbah?"); houseNum = reader.nextInt(); reader.nextLine(); //get the street name System.out.println("Along with your street name!"); street = reader.nextLine(); // get the town System.out.println("Almost hacked into your house just need the town"); town = reader.nextLine(); // get the state System.out.println("The two letters for your state as well:"); state = reader.nextLine(); // get the ZIP code System.out.println("Finally your Zip code for your ''surprise''!"); ZIP = reader.nextInt(); // put together the info fullAdd = street +" "+ town +", "+ state; // print out all of the info System.out.println(fullN); System.out.println(houseNum +" "+ fullAdd +" "+ ZIP); } }
package service; import dao.UserDao; import daoImp.UserDaoImp; import model.Person; import model.User; public class UserService { private UserDao dao = new UserDaoImp(); public User login(String username,String password) { return dao.login(username, password); } public Person getPerson(String ssn, int type) { return dao.getPerson(ssn, type); } public int addCourseToPerson(String ssn, String sectionno) { return dao.addCourseToPerson(ssn, sectionno); } }
package model; public class ActivememBean { String email; String name; String age; String gender; String addr; String profilepicture; String whoami; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public String getProfilepicture() { return profilepicture; } public void setProfilepicture(String profilepicture) { this.profilepicture = profilepicture; } public String getWhoami() { return whoami; } public void setWhoami(String whoami) { this.whoami = whoami; } }
package com.ayantsoft.Selenium.webpage; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.Color; public class HandlingPrograms { public static void main(String[] args) { // TODO Auto-generated method stub //handling alert boxes WebDriver driver = new FirefoxDriver(); String baseUrl = "http://localhost:8081/crudWithSpring"; driver.get(baseUrl); //Alert box releated opreations // Switching to Alert WebElement btn1 = driver.findElement(By.id("btn1")); btn1.click(); Alert alert = driver.switchTo().alert(); // Setting alert message. driver.switchTo().alert(); // Capturing alert message. String alertMessage= driver.switchTo().alert().getText(); // Displaying alert message System.out.println(alertMessage); //mouse releated opreations WebElement st1 = driver.findElement(By.id("st1")); /*Actions builder = new Actions(driver); Action mouseOverHome = builder .moveToElement(st1) .build(); String bgColor = st1.getCssValue("background-color"); bgColor = st1.getCssValue("background-color"); System.out.println("Before hover: " + bgColor); mouseOverHome.perform(); bgColor = st1.getCssValue("background-color"); System.out.println("After hover: " + bgColor); String hex = Color.fromString(bgColor).asHex(); System.out.println(hex);*/ //performing key and mouse events /* Actions builder = new Actions(driver); Action seriesOfActions = builder .moveToElement(st1) .click() .keyDown(st1, Keys.SHIFT) .sendKeys(st1, "hello") .keyUp(st1, Keys.SHIFT) .doubleClick(st1) .contextClick() .build(); seriesOfActions.perform() ;*/ } }
package com.hcl.dmu.utils; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import org.hibernate.Session; import org.hibernate.query.Query; import org.springframework.stereotype.Service; import com.hcl.dmu.reg.dao.AbstractDAO; @Service @Transactional public class RecordCountUtility<obj> extends AbstractDAO{ public Long getRecordCount(Object obj) { Session session = null; Long recordCount = null; try { session = getSession(); CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<Object> crt2 = cb.createQuery(Object.class); Root<obj> root2 = (Root<obj>) crt2.from(obj.getClass()); crt2.select(cb.count(root2)); //Finding the total count of records Query query2 = session.createQuery(crt2); recordCount = (Long) query2.getSingleResult(); } catch(Exception e) { e.printStackTrace(); } return recordCount; } }
package com.algaworks.ecommerce.mapeamentoavancado; import com.algaworks.ecommerce.EntityManagerTest; import com.algaworks.ecommerce.FileUploader; import com.algaworks.ecommerce.model.Cliente; import com.algaworks.ecommerce.model.NotaFiscal; import com.algaworks.ecommerce.model.Pedido; import com.algaworks.ecommerce.model.Produto; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.math.BigDecimal; import java.util.Date; import java.util.List; public class SalvandoArquivosTest extends EntityManagerTest { @Test public void salvaXmlNotaFiscal() { Pedido pedido = entityManager.find(Pedido.class, 1); NotaFiscal notaFiscal = new NotaFiscal(); notaFiscal.setPedido(pedido); notaFiscal.setDataEmissao(new Date()); notaFiscal.setXml(FileUploader.carregarArquivo("/nota-fiscal.xml")); entityManager.getTransaction().begin(); entityManager.persist(notaFiscal); entityManager.getTransaction().commit(); entityManager.clear(); NotaFiscal notaFiscalVerificacao = entityManager.find(NotaFiscal.class, notaFiscal.getId()); Assert.assertNotNull("Nota fiscal é nula", notaFiscalVerificacao.getXml()); Assert.assertTrue("XML da nota fiscal não tem bytes salvos", notaFiscalVerificacao.getXml().length > 0); } @Test public void salvaFotoProduto() { Produto produto = new Produto(); produto.setNome("Kindle new paper"); produto.setDescricao("Ótimo para leitura"); produto.setPreco(new BigDecimal(750)); produto.setTags(List.of("Eletrônicos", "Leitura")); produto.setFoto(FileUploader.carregarArquivo("/kindle.jpg")); entityManager.getTransaction().begin(); entityManager.persist(produto); entityManager.getTransaction().commit(); entityManager.clear(); Produto produtoVerificacao = entityManager.find(Produto.class, produto.getId()); Assert.assertNotNull("Produto é nulo", produtoVerificacao.getFoto()); Assert.assertTrue("Foto do produto não tem bytes salvos", produtoVerificacao.getFoto().length > 0); } }
import java.util.Scanner; class PatternW{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Enter number of rows"); int n = sc.nextByte(); int x=n; for(int i=1;i<=n;i++){ for(int j=1;j<2*n;j++){ if(j==1||j==n*2-1||j==x||j==2*n-x) System.out.print("*"); else System.out.print(" "); } System.out.println(); x--; } } }
package com.tencent.mm.plugin.sns.ui; import com.tencent.mm.plugin.sns.ui.SnsOnlineVideoActivity.7; import com.tencent.mm.ui.widget.a.d$a; class SnsOnlineVideoActivity$7$1 implements d$a { final /* synthetic */ 7 nZm; SnsOnlineVideoActivity$7$1(7 7) { this.nZm = 7; } public final void onDismiss() { SnsOnlineVideoActivity.a(this.nZm.nZl, null); } }
package com.ojas.es.entity; import java.util.List; public class CandidateSearchResponse { private Integer totalPages; private Integer totalRecords; private List<Candidate> candidates; public Integer getTotalPages() { return totalPages; } public void setTotalPages(Integer totalPages) { this.totalPages = totalPages; } public Integer getTotalRecords() { return totalRecords; } public void setTotalRecords(Integer totalRecords) { this.totalRecords = totalRecords; } public List<Candidate> getCandidates() { return candidates; } public void setCandidates(List<Candidate> candidates) { this.candidates = candidates; } }
package pro.eddiecache.kits.lateral; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import pro.eddiecache.core.CacheInfo; import pro.eddiecache.core.CacheStatus; import pro.eddiecache.core.DaemonCacheServiceRemote; import pro.eddiecache.core.model.ICacheElement; import pro.eddiecache.core.model.ICacheServiceRemote; import pro.eddiecache.core.model.IDaemon; import pro.eddiecache.core.stats.IStats; import pro.eddiecache.core.stats.Stats; import pro.eddiecache.kits.AbstractKitCacheEvent; import pro.eddiecache.kits.KitCacheAttributes; public class LateralCache<K, V> extends AbstractKitCacheEvent<K, V> { private static final Log log = LogFactory.getLog(LateralCache.class); private final ILateralCacheAttributes lateralCacheAttributes; private ICacheServiceRemote<K, V> lateralCacheService; private LateralCacheMonitor monitor; public LateralCache(ILateralCacheAttributes cattr, ICacheServiceRemote<K, V> lateral, LateralCacheMonitor monitor) { super(cattr.getCacheName()); this.lateralCacheAttributes = cattr; this.lateralCacheService = lateral; this.monitor = monitor; } public LateralCache(ILateralCacheAttributes cattr) { super(cattr.getCacheName()); this.lateralCacheAttributes = cattr; } @Override protected void processUpdate(ICacheElement<K, V> ce) throws IOException { try { if (ce != null) { if (log.isDebugEnabled()) { log.debug("Update: lateral = [" + lateralCacheService + "], " + "CacheInfo.listenerId = " + CacheInfo.listenerId); } lateralCacheService.update(ce, CacheInfo.listenerId); } } catch (IOException ex) { handleException(ex, "Fail to put [" + ce.getKey() + "] to " + ce.getCacheName() + "@" + lateralCacheAttributes); } } @Override protected ICacheElement<K, V> processGet(K key) throws IOException { ICacheElement<K, V> obj = null; if (this.lateralCacheAttributes.getPutOnlyMode()) { return null; } try { obj = lateralCacheService.get(getCacheName(), key); } catch (Exception e) { log.error(e); handleException(e, "Fail to get [" + key + "] from " + lateralCacheAttributes.getCacheName() + "@" + lateralCacheAttributes); } return obj; } @Override protected Map<K, ICacheElement<K, V>> processGetMatching(String pattern) throws IOException { if (this.lateralCacheAttributes.getPutOnlyMode()) { return Collections.emptyMap(); } try { return lateralCacheService.getMatching(getCacheName(), pattern); } catch (IOException e) { log.error(e); handleException(e, "Fail to getMatching [" + pattern + "] from " + lateralCacheAttributes.getCacheName() + "@" + lateralCacheAttributes); return Collections.emptyMap(); } } @Override protected Map<K, ICacheElement<K, V>> processGetMultiple(Set<K> keys) throws IOException { Map<K, ICacheElement<K, V>> elements = new HashMap<K, ICacheElement<K, V>>(); if (keys != null && !keys.isEmpty()) { for (K key : keys) { ICacheElement<K, V> element = get(key); if (element != null) { elements.put(key, element); } } } return elements; } @Override public Set<K> getKeySet() throws IOException { try { return lateralCacheService.getKeySet(getCacheName()); } catch (IOException ex) { handleException(ex, "Fail to get key set from " + lateralCacheAttributes.getCacheName() + "@" + lateralCacheAttributes); } return Collections.emptySet(); } @Override protected boolean processRemove(K key) throws IOException { if (log.isDebugEnabled()) { log.debug("Remove key:" + key); } try { lateralCacheService.remove(getCacheName(), key, CacheInfo.listenerId); } catch (IOException ex) { handleException(ex, "Fail to remove " + key + " from " + lateralCacheAttributes.getCacheName() + "@" + lateralCacheAttributes); } return false; } @Override protected void processRemoveAll() throws IOException { try { lateralCacheService.removeAll(getCacheName(), CacheInfo.listenerId); } catch (IOException ex) { handleException(ex, "Fail to remove all from " + lateralCacheAttributes.getCacheName() + "@" + lateralCacheAttributes); } } @Override protected void processDispose() throws IOException { try { lateralCacheService.dispose(this.lateralCacheAttributes.getCacheName()); } catch (IOException ex) { log.error("Couldn't dispose", ex); handleException(ex, "fail to dispose " + lateralCacheAttributes.getCacheName()); } } @Override public CacheStatus getStatus() { return this.lateralCacheService instanceof IDaemon ? CacheStatus.ERROR : CacheStatus.ALIVE; } @Override public int getSize() { return 0; } @Override public CacheType getCacheType() { return CacheType.LATERAL_CACHE; } private void handleException(Exception ex, String msg) throws IOException { lateralCacheService = new DaemonCacheServiceRemote<K, V>(lateralCacheAttributes.getDaemonQueueMaxSize()); monitor.notifyError(); if (ex instanceof IOException) { throw (IOException) ex; } throw new IOException(ex.getMessage()); } public void fixCache(ICacheServiceRemote<K, V> restoredLateral) { if (this.lateralCacheService != null && this.lateralCacheService instanceof DaemonCacheServiceRemote) { DaemonCacheServiceRemote<K, V> daemon = (DaemonCacheServiceRemote<K, V>) this.lateralCacheService; this.lateralCacheService = restoredLateral; try { daemon.spreadEvents(restoredLateral); } catch (Exception e) { try { handleException(e, "Problem in spreading events from DaemonCacheServiceRemote to new Lateral Service."); } catch (IOException ignored) { } } } else { this.lateralCacheService = restoredLateral; } } @Override public String getStats() { return ""; } @Override public KitCacheAttributes getKitCacheAttributes() { return lateralCacheAttributes; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\n LateralCache ") .append("\n Cache Name [").append(lateralCacheAttributes.getCacheName()).append("]") .append("\n cattr = [").append(lateralCacheAttributes).append("]"); return sb.toString(); } @Override public String getEventLoggerExtraInfo() { return null; } @Override public IStats getStatistics() { IStats stats = new Stats(); stats.setTypeName("LateralCache"); return stats; } }
package com.esprit.lyricsplus; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.WindowManager; import android.widget.TextView; import com.esprit.lyricsplus.entities.Record; import com.esprit.lyricsplus.entities.Song; public class LyricsActivity extends Activity { public static Context mAppContext; Song song ; Record record ; TextView textLyrics , textSong , textArtiste ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lyrics); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); textLyrics = (TextView) findViewById(R.id.lyrics) ; textSong = (TextView) findViewById(R.id.song_name) ; textArtiste = (TextView) findViewById(R.id.artist_name) ; song = (Song) getIntent().getSerializableExtra("song"); record = (Record) getIntent().getSerializableExtra("record"); mAppContext= getApplicationContext(); if(song == null) { System.out.println(record.getLyrics()); System.out.println(record.toString()); if(record.getLyrics().equals("null")) { textLyrics.setText("No Lyrics for this Song"); } else { textLyrics.setText(record.getLyrics()); } textArtiste.setText(record.getUser().getFullname()); textSong.setText(record.getTitle()); } else { textLyrics.setText(song.getLyrics()); textArtiste.setText(song.getSinger().getName()); textSong.setText(song.getTitle()); } DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int width = dm.widthPixels ; int height= dm.heightPixels ; getWindow().setLayout(width,height); } }
/** * aBoy.com Inc. * Copyright (c) 2004-2012 All Rights Reserved. */ package com.github.obullxl.lang.enums; /** * 枚举基类 * * @author obullxl@gmail.com * @version $Id: EnumBase.java, 2012-8-18 下午8:25:49 Exp $ */ public interface EnumBase { /** * 枚举ID */ public int id(); /** * 枚举名称 */ public String name(); /** * 枚举代码 */ public String code(); /** * 枚举描述 */ public String desp(); }
package com.shopify.api.pantos; import java.util.Map; import org.codehaus.jettison.json.JSONException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import lombok.extern.slf4j.Slf4j; @Controller @Slf4j public class PantosAPIController { @Autowired PantosService pantosService; // @RequestMapping(value = "/api/pantos/tracking", method = RequestMethod.POST, consumes="text/plain") /// @RequestBody // @RequestMapping(value = "/api/pantos/tracking", method = RequestMethod.POST) @RequestMapping(value = "/api/pantos/tracking", method = RequestMethod.POST, consumes="application/x-www-form-urlencoded") @ResponseBody public String tracking( @RequestHeader Map<String,String> headers, @RequestParam Map<String, String> map ) { String ifData = (String) map.get("ifdata"); log.info("tracking START 2 : "+ifData); String resultString = null; try { String userId = ""; String userPwd = ""; // String userId = headers.get("bizptrid"); // String userPwd = headers.get("bizptrpw"); resultString = pantosService.updateTracking(ifData, userId, userPwd); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); log.error("tracking error : "+ifData); } log.info("tracking END : "+ifData); return resultString; } }
package com.avogine.junkyard.io.event; public interface MouseScrollInputListener extends InputListener { public void mouseScrolled(MouseScrollInputEvent event); }
package ua.babiy.online_store.service; import ua.babiy.online_store.entity.User; import java.util.List; import java.util.Optional; public interface UserService { boolean saveNewUser(User user); List<User> findAll(); Optional<User> findById(Long userId); void delete(User user); void blockUser(Long userId); void unblockUser(Long userId); void updateUser(User user, String firstName, String lastName, String password); }
package jFrontd.Classes; import Classes.FileManager; import Classes.Globals; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; /** * @author Joseph Stevens */ public class Folder { //variables private final File ConfigDir = new File(Globals.Home+Globals.Separator+".jFrontd"); private final File FolderDir = new File(ConfigDir+Globals.Separator+"Folders"); private String newline = Globals.Newline; private int ID; private String Name; private String Path; private String SystemIcon; private String GameIcon; private int EmuID; private boolean showExtensions; private boolean mameROMs; private boolean hideUnsupportedFiletypes; private boolean goodmerged; //directory variables private BigInteger MD5; private String[] FileList; private String[] DisplayedList; public Folder(int i){ ID = i; ReadFile(); } public Folder(String Name, String Path, int EmuID, boolean showExtensions, boolean mameROMs, boolean hideUnsupportedFiletypes, boolean goodmerged, String SystemIcon, String GameIcon) { ID = FolderDir.list().length; this.Name = Name; this.Path = Path; this.EmuID = EmuID; this.showExtensions = showExtensions; this.mameROMs = mameROMs; this.hideUnsupportedFiletypes = hideUnsupportedFiletypes; this.goodmerged = goodmerged; this.SystemIcon = SystemIcon; this.GameIcon = GameIcon; //write new file MakeNewFile(); } //creates CRC, FileList, and RealList public void LoadDirectory(){ //create array of files in directory File Directory = new File(Path); FileList = Directory.list(); Arrays.sort(FileList); //create byte array of FileList int ByteArrayLength = 0; for(int i=0;i<FileList.length;i++){ ByteArrayLength += FileList[i].length(); } byte[] ByteArray = new byte[ByteArrayLength]; //populate byte array for(int i=0;i<FileList.length;i++){ byte[] buffer = FileList[i].getBytes(); for(int j=0;j<buffer.length;j++){ ByteArray[i+j] = buffer[j]; } } //create new MD5 BigInteger newMD5; try { MessageDigest MD = MessageDigest.getInstance("MD5"); MD.update(ByteArray); newMD5 = new BigInteger(MD.digest()); System.out.println(newMD5); } catch (NoSuchAlgorithmException ex) { Globals.ShowError(ex); } //compare new MD5 with old MD5, if there is a change, create new lists } private void MakeNewFile(){ //create the file variable File newfile = new File(FolderDir+Globals.Separator+ID); //If the file exists, delete it, and remake it, because it shouldn't. if (newfile.exists()){ try { newfile.delete(); newfile.createNewFile(); } catch (IOException ex) { Globals.ShowError(ex); } } //save new information to the file UpdateFile(); } private void ReadFile(){ //read the information from the file FileReader fr = null; try { File newfile = new File(FolderDir + Globals.Separator + ID); if (!newfile.exists()) { Globals.ShowError("You've hit a bug!", "You've hit a bug, please contact the author: Folder File does not exist.\nskiffain@gmail.com"); return; } //read in variables fr = new FileReader(newfile); BufferedReader br = new BufferedReader(fr); Name = br.readLine(); Path = br.readLine(); EmuID = Integer.parseInt(br.readLine()); showExtensions = Boolean.valueOf(br.readLine()); mameROMs = Boolean.valueOf(br.readLine()); hideUnsupportedFiletypes = Boolean.valueOf(br.readLine()); goodmerged = Boolean.valueOf(br.readLine()); SystemIcon = br.readLine(); GameIcon = br.readLine(); br.close(); } catch (Exception ex) { Globals.ShowError(ex); } } //deletes the current folder file, renames the others to fall in line public void Delete(){ //put the reminder files into an array int DirLength = FolderDir.list().length; File newfiles[] = new File[DirLength]; for(int i=0;i<DirLength;i++) newfiles[i] = new File(FolderDir+Globals.Separator+i); //delete the current reminder File todelete = new File(FolderDir+Globals.Separator+ID); todelete.delete(); //move all of the ones past the deleted file to -1 for(int i=ID+1;i<DirLength;i++) newfiles[i].renameTo(newfiles[i-1]); } //saves new information to file private void UpdateFile(){ try { //update the file File oldfile = new File(FolderDir + Globals.Separator + ID); oldfile.delete(); oldfile.createNewFile(); //save new information to the file FileWriter fw = new FileWriter(oldfile); fw.write(Name); fw.write(newline); fw.write(Path); fw.write(newline); fw.write(String.valueOf(EmuID)); fw.write(newline); fw.write(String.valueOf(showExtensions)); fw.write(newline); fw.write(String.valueOf(mameROMs)); fw.write(newline); fw.write(String.valueOf(hideUnsupportedFiletypes)); fw.write(newline); fw.write(String.valueOf(goodmerged)); fw.write(newline); fw.write(String.valueOf(SystemIcon)); fw.write(newline); fw.write(String.valueOf(GameIcon)); fw.close(); } catch (IOException ex) { Globals.ShowError(ex); } } //moves the folder ID/Filename to one previous public void MoveUp(){ if(ID==0){ //already at the top return; } //this method will change the filename/ID so that it moves up in the displayed lists File ThisFavorite = new File(FolderDir+Globals.Separator+ID); File Temp = new File(ConfigDir+Globals.Separator+"TempFile"); File PrevFavorite = new File(FolderDir+Globals.Separator+(ID-1)); //move files around FileManager.MoveFile(PrevFavorite, Temp); FileManager.MoveFile(ThisFavorite, PrevFavorite); FileManager.MoveFile(Temp, ThisFavorite); } //moves the folder ID/Filename to the next public void MoveDown(){ if(ID==(FolderDir.list().length-1)){ //already at the bottom return; } //this method will change the filename/ID so that it moves up in the displayed lists File ThisFavorite = new File(FolderDir+Globals.Separator+ID); File Temp = new File(ConfigDir+Globals.Separator+"TempFile"); File PrevFavorite = new File(FolderDir+Globals.Separator+(ID+1)); //move files around FileManager.MoveFile(PrevFavorite, Temp); FileManager.MoveFile(ThisFavorite, PrevFavorite); FileManager.MoveFile(Temp, ThisFavorite); } //changes the folder ID/Filename public void MoveTo(int newID){ if(newID < 0){ //you can't move it past the firs }else if(newID >= FolderDir.list().length){ //you can't move it past the last }else if(newID == ID+1){ //just use move down MoveDown(); }else if (newID == ID-1){ //just use move up MoveUp(); }else{ //move it to the selected ID //put the current in a temporary file File Temp = new File(ConfigDir+Globals.Separator+"TempFile"); File ThisFavorite = new File(FolderDir+Globals.Separator+ID); File NewFavorite = new File(FolderDir+Globals.Separator+newID); //create all files File[] AllFiles = new File[FolderDir.list().length]; for(int i=0;i<AllFiles.length;i++){ AllFiles[i] = new File(FolderDir+Globals.Separator+i); } //move ID to temporary file FileManager.MoveFile(ThisFavorite, Temp); //decide if we are moving forwards or backwards if(ID > newID){ //moving it backwards //SO, move from newID, to one before the current ID, forwards //move first file on its own for(int i=(ID-1);i>=newID;i--){ FileManager.MoveFile(AllFiles[i], AllFiles[i+1]); } //move temp file into newID FileManager.MoveFile(Temp, AllFiles[newID]); }else if(ID < newID){ //moving it forwards //SO, move from newID, to one after the current ID, backwards //move first file on its own for(int i=(ID+1);i<=newID;i++){ FileManager.MoveFile(AllFiles[i], AllFiles[i-1]); } //move temp file into newID FileManager.MoveFile(Temp, NewFavorite); } } } //set/get methods public String getName(){ return Name; } public String getPath(){ return Path; } public int getEmu(){ return EmuID; } public boolean getShowExtensions(){ return showExtensions; } public boolean getMameROMs(){ return mameROMs; } public boolean getHideUnsupportedFiletypes(){ return hideUnsupportedFiletypes; } public boolean getGoodmerged(){ return goodmerged; } public String getGameIcon(){ return GameIcon; } public String getSystemIcon(){ return SystemIcon; } public void setPath(String tPath){ Path = tPath; UpdateFile(); } public void setEmu(int tEmu){ EmuID = tEmu; UpdateFile(); } public void setName(String tName){ Name = tName; UpdateFile(); } public void setShowExtensions(boolean showExtensions){ this.showExtensions = showExtensions; UpdateFile(); } public void setMameROMs(boolean mameROMs){ this.mameROMs = mameROMs; UpdateFile(); } public void setHideUnsupportedFiletypes(boolean hideUnsupportedFiletypes){ this.hideUnsupportedFiletypes = hideUnsupportedFiletypes; UpdateFile(); } public void setGoodmerged( boolean goodmerged){ this.goodmerged = goodmerged; UpdateFile(); } public void setGameIcon(String Icon){ this.GameIcon = Icon; UpdateFile(); } public void setSystemIcon(String Icon){ this.SystemIcon = Icon; UpdateFile(); } }
/* * 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 Gestion.utils; import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Image; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BarcodeQRCode; import com.itextpdf.text.pdf.PdfWriter; import java.awt.Desktop; import java.awt.print.PrinterJob; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; import javax.print.PrintService; import javax.print.PrintServiceLookup; import org.jpedal.PdfDecoder; import org.jpedal.objects.PrinterOptions; /** * * @author christian */ public class GenerateFacture { public GenerateFacture(){ super(); } /** * ligneFac 1 = num du magasin * ligneFac 0 = num facture * ligneFac 2 = logo de l'entreprise * ligneFac 3 = Nom de l'entreprise * ligneFac 4 = BP de l'entreprise * ligneFac 5 = email de l'entreprise * ligneFac 6 = tel de l'entreprise * ligneFac 7 = devise * ligneFac (i) = NomProduit PrixUnitaie X Qte = Prixtotale(i) * ligneFac (n-6) = TOTAL = Prixtotale * ligneFac (n-5) = TVA = 150 FCFA * ligneFac (n-4) = Net a payer = Prixtotale+tva * ligneFac (n-3) = avancement * ligneFac (n-2) = reste a payer * ligneFac (n-1) = NomVendeur = nomduvendeur * ligneFac (n) = NomClient = nomduClient * @param ligneFac */ @SuppressWarnings({"UseSpecificCatch", "CallToPrintStackTrace", "empty-statement"}) public static void PrintPDF(ArrayList<String> ligneFac){ //ici on doit deja inserer l'entete des données. int height = 800; int width = 300; int dim = 15; String nomMaga = (String)ligneFac.get(1); String NrFacture = (String)ligneFac.get(0); String nomFichier = "Documents/Factures/FKCTicket_" + NrFacture + ".pdf"; int dimensionCourante = 0; dimensionCourante = height + dim*(ligneFac.size() - 6); // preparation ticket Document document = new Document(new Rectangle(width, dimensionCourante)); document.addTitle(nomMaga); document.setMargins(4,2, 0, 0); try { PdfWriter.getInstance(document, new FileOutputStream(nomFichier)); document.open(); // Insertion du logo de la companie Image image1 = Image.getInstance((String)ligneFac.get(2)); image1.setAlignment(Image.ALIGN_TOP); image1.setAlignment(Image.ALIGN_CENTER); image1.scalePercent(70, 70); document.add(image1); // definition du style des caracteres Font font1 = new Font(Font.FontFamily.TIMES_ROMAN , 11); Font font2 = new Font(Font.FontFamily.COURIER , 10); // Font font3 = new Font(Font.FontFamily.TIMES_ROMAN, 10); //Font fontTicket = new Font(Font.FontFamily.TIMES_ROMAN, 10); Font fontTitre = new Font(Font.FontFamily.TIMES_ROMAN, 12); fontTitre.setStyle("bold"); Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 11,Font.BOLD); Paragraph GrandTitre = new Paragraph(nomMaga, catFont); GrandTitre.setAlignment(Element.ALIGN_CENTER); document.add(GrandTitre); document.add(new Phrase(" ")); document.add(new Paragraph((String)ligneFac.get(3), font1)); //document.add(new Paragraph(NrFacture, font2)); // date ici document.add(new Paragraph((String)ligneFac.get(4), font2)); document.add(new Paragraph((String)ligneFac.get(5), font2)); document.add(new Paragraph((String)ligneFac.get(6), font2)); document.add(new Phrase(" ")); String ma = null; String date = Calendar.getInstance().getTime().toString(); //String affichageMatches[] = new String[this.listPariMatches.size()]; for(int i= 8; i < ligneFac.size()-7; i++){ // Jeu: 10256 - 24/05/2015 16:30\n Manchester – Queens Park Rangers\n Score(1-2) Mi-Temps, cote: 1.55" ma = (String)ligneFac.get(i); document.add(new Paragraph( ma,font1)); } document.add(new Paragraph("*****************************************************",font1)); for(int i= ligneFac.size()-7; i < ligneFac.size(); i++){ ma = (String)ligneFac.get(i); document.add(new Paragraph( ma,font1)); } document.add(new Paragraph("*****************************************************",font1)); document.add(new Paragraph("------ "+date+" ------",font2)); document.add(new Paragraph("--------------------------------------------------------------------------------",font1)); document.add(new Paragraph(""+ligneFac.get(7), font2)); document.add(new Paragraph("--------------------------------------------------------------------------------",font1)); document.add(new Paragraph(" ******* Logiciel fourni par FKC&Group *******", font2)); document.add(new Paragraph("************ Tel (+237)678-13-21-86 ************", font2)); //String m = Gestion.utils.Utils.CrypterUneChaine(ligneFac.get(0)+"_"+date,"SHA-256"); String m = "NUM FACTURE = "+ligneFac.get(0)+"\n" + ligneFac.get(ligneFac.size()-2)+"\n" + ligneFac.get(ligneFac.size()-1)+"\n" + ligneFac.get(ligneFac.size()-5)+"\n" + ligneFac.get(ligneFac.size()-4)+"\n" + ligneFac.get(ligneFac.size()-3)+"\n" + "Date de vente = "+date; BarcodeQRCode my_code = new BarcodeQRCode(m,150,150,null); Image image2 = my_code.getImage(); image2.setAlignment(Image.ALIGN_TOP); image2.setAlignment(Image.ALIGN_CENTER); image2.scalePercent(70, 70); document.add(image2); document.close(); try { Desktop.getDesktop().open(new File(nomFichier)); } catch (IOException ex) { Gestion.utils.Utils.addMessage("GenerateFacture:printPDF:fichier facture",true); } prinTicketPDF(nomFichier); }catch(Exception e){ e.printStackTrace(); }; } public static void prinTicketPDF(String url) { PrintService printService = PrintServiceLookup.lookupDefaultPrintService(); String fichierTicket = url; try{ // PrintService printService = PrintServiceLookup.lookupDefaultPrintService(); //Open & decode the pdf file PdfDecoder decode_pdf = new PdfDecoder(true); decode_pdf.openPdfFile(fichierTicket); //Get the total number of pages in the pdf file int pageCount = decode_pdf.getPageCount(); //set to print all pages decode_pdf.setPagePrintRange(1, pageCount); //Auto-rotate and scale flag decode_pdf.setPrintAutoRotateAndCenter(false); // Are we printing the current area only decode_pdf.setPrintCurrentView(false); //set mode - see org.jpedal.objects.contstants.PrinterOptions for all values //the pdf file already is in the desired format. So turn off scaling decode_pdf.setPrintPageScalingMode(PrinterOptions.PAGE_SCALING_NONE); //by default scaling will center on page as well. decode_pdf.setCenterOnScaling(false); //flag if we use paper size or PDF size. //Use PDF size as it already has the desired paper size decode_pdf.setUsePDFPaperSize(false); //setup print job and objects PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintService(printService); //setup Java Print Service (JPS) to use JPedal printJob.setPageable(decode_pdf); //Print the file to the desired printer printJob.print(); }catch(Exception e){ System.out.println("Erreur: "+e.toString());} } }
package Domain; import Domain.Effetti.Effetto; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.*; /** * Created by Michele on 04/06/2017. */ public class TesseraScomunicaTest { TesseraScomunica tesseraScomunica; @Before public void setUp() throws Exception { tesseraScomunica = new TesseraScomunica("id", 1, new ArrayList<>()); assertEquals("id", tesseraScomunica.Nome); assertEquals(1, tesseraScomunica.Periodo); assertEquals(0, tesseraScomunica.getCostoRisorse().getLegno()); assertEquals(0, tesseraScomunica.getCostoRisorse().getPietra()); assertEquals(0, tesseraScomunica.getCostoRisorse().getServi()); assertEquals(0, tesseraScomunica.getCostoRisorse().getMonete()); assertNull(tesseraScomunica.getEffettoImmediato()); assertNotNull(tesseraScomunica.getEffettoPermanente()); } @Test public void assegnaGiocatore() throws Exception { Giocatore giocatore = new Giocatore(); tesseraScomunica.AssegnaGiocatore(giocatore); assertEquals(1, giocatore.CarteScomunica.size()); } @Test public void getTipoCarta() throws Exception { assertEquals(TipoCarta.Scomunica, tesseraScomunica.getTipoCarta()); } }
package com.takshine.wxcrm.service.impl; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.takshine.core.service.CRMService; import com.takshine.wxcrm.base.common.Constants; import com.takshine.wxcrm.base.model.BaseModel; import com.takshine.wxcrm.base.services.BaseServiceImpl; import com.takshine.wxcrm.base.util.PropertiesUtil; import com.takshine.wxcrm.base.util.StringUtils; import com.takshine.wxcrm.base.util.cache.RedisCacheUtil; import com.takshine.wxcrm.domain.Activity; import com.takshine.wxcrm.domain.Group; import com.takshine.wxcrm.domain.Subscribe; import com.takshine.wxcrm.service.Group2ZjrmService; @Service("group2ZjrmService") public class Group2ZjrmServiceImpl extends BaseServiceImpl implements Group2ZjrmService { private static Logger log = Logger.getLogger(Group2ZjrmServiceImpl.class.getName()); @Autowired @Qualifier("cRMService") private CRMService cRMService; public BaseModel initObj() { // TODO Auto-generated method stub return null; } public static final String GROUP_PUBLIC_LIST="GROUP_PUBLIC_LIST"; public static final String GROUP_DETAIL="GROUP_DETAIL"; public List<Group> getPublicGroupList(String openId) throws Exception { List<Group> returnList=new ArrayList<Group>(); List<Group> list =this.getPublicGroupList(); if(list==null||list.size()<1){ return null; } Subscribe sub= new Subscribe(); sub.setOpenId(openId); sub.setType("group"); sub.setPagecounts(1000); sub.setCurrpages(0); List<Subscribe> sublist= getSqlSession().selectList("subscribeSql.findSubscribeList", sub); for(Group group:list){ for(Subscribe subObj:sublist){ if(group.getId().equals(subObj.getFeedid())){ group.setRssId(subObj.getId()); sublist.remove(subObj); break; } } returnList.add(group); } return returnList; } public List<Group> getPublicGroupList() throws Exception { List<Group> list=new ArrayList<Group>(); if(RedisCacheUtil.checkKeyExisted(this.GROUP_PUBLIC_LIST)){ list=(ArrayList<Group>) RedisCacheUtil.get(this.GROUP_PUBLIC_LIST); }else{ String url = PropertiesUtil.getAppContext("zjsso.url")+"/out/group/public_list"; log.info("getPublicGroupList url => url is : " + url); String rst = cRMService.getWxService().getWxHttpConUtil().postJsonData(url,"", "", Constants.INVOKE_MULITY); log.info("getPublicGroupList rst => rst is : " + rst); //做空判断 if(null == rst || "".equals(rst)) return null; //解析JSON数据 JSONArray jsonObject = JSONArray.fromObject(rst); list = (ArrayList<Group>)JSONArray.toCollection(jsonObject,Group.class); RedisCacheUtil.set(this.GROUP_PUBLIC_LIST, list); } return list; } public Group getGroupDetail(String groupId) throws Exception { Group group=null; if(RedisCacheUtil.checkKeyExisted(this.GROUP_DETAIL+"_"+groupId)){ group=(Group) RedisCacheUtil.get(this.GROUP_DETAIL+"_"+groupId); } if(group==null){ String url = PropertiesUtil.getAppContext("zjsso.url")+"/out/group/activity_list/"+groupId; log.info("getPublicGroupList url => url is : " + url); String rst = cRMService.getWxService().getWxHttpConUtil().postJsonData(url,"", "", Constants.INVOKE_MULITY); log.info("getPublicGroupList rst => rst is : " + rst); //做空判断 if(null == rst || "".equals(rst)) return null; //解析JSON数据 JSONArray jsonStr = JSONArray.fromObject(rst); JSONObject jsonObject=jsonStr.optJSONObject(0); if(!jsonObject.containsKey("errcode")){ group=new Group(); group.setId(groupId); group.setName(jsonObject.getString("name")); group.setLogo(jsonObject.getString("logo")); JSONArray jsonArray = jsonObject.getJSONArray("groupActivitys"); if(null != jsonArray && jsonArray.size()>0){ ArrayList<Activity> IdList = new ArrayList<Activity>(); ArrayList<Activity> activityList = new ArrayList<Activity>(); JSONObject jsonObject1 = null; for(int i=0;i<jsonArray.size();i++){ Activity ac = new Activity(); jsonObject1 = jsonArray.getJSONObject(i); ac.setRowid(jsonObject1.getString("activityId")); IdList.add(ac); } activityList=this.getActivity(IdList);//通过Id列表查询活动详情列表 group.setList(activityList); } RedisCacheUtil.set(this.GROUP_DETAIL+"_"+groupId, group,3600); } } return group; } public ArrayList<Activity> getActivity(ArrayList<Activity> idList){ String url = PropertiesUtil.getAppContext("zjmarketing.url")+"/activity/synclistbyidlist"; log.info("getActivity url => url is : " + url); String respStr = cRMService.getWxService().getWxHttpConUtil().postJsonData(url,"", JSONArray.fromObject(idList).toString(), Constants.INVOKE_MULITY); log.info("getActivity respStr => respStr is : " + respStr); ArrayList<Activity> list=new ArrayList<Activity>(); if(StringUtils.isNotNullOrEmptyStr(respStr)){ JSONArray jsonArray = JSONArray.fromObject(respStr); for(int i=0;i<jsonArray.size();i++){ Activity act = new Activity(); JSONObject jsonObject = jsonArray.getJSONObject(i); act.setRowid(jsonObject.getString("id")); act.setDeadline(jsonObject.getString("end_date")); act.setStartdate(jsonObject.getString("start_date")); act.setTitle(jsonObject.getString("title")); act.setDesc(jsonObject.getString("content")); act.setPlace(jsonObject.getString("place")); act.setImagename(jsonObject.getString("logo")); act.setType(jsonObject.getString("type")); list.add(act); } } return list; } }
package listaExericicos8_parte2; import java.util.ArrayList; import java.util.Collection; import java.util.Scanner; public class exercicio3 { public static void main(String[] args) { Scanner leia = new Scanner(System.in); Collection<String> produtosEstoque = new ArrayList(); Collection<String> produtosAdicionadosEstoque = new ArrayList(); Collection<String> produtosRemovidosEstoque = new ArrayList(); char opcaoAdicionar, opcaoContinuar, opcaoRemover; produtosEstoque.add("Balde"); produtosEstoque.add("Desinfetante"); produtosEstoque.add("Detergente"); produtosEstoque.add("Esponja"); produtosEstoque.add("Sab„o neutro"); produtosEstoque.add("Vassoura"); System.out.printf("Lista de produtos: %s",produtosEstoque); System.out.print("\n\nDeseja adicionar produtos ao estoque S/N: "); opcaoAdicionar = leia.next().toUpperCase().charAt(0); if (opcaoAdicionar == 'S') { do { System.out.print("Digite o nome do produto que deseja adicionar: "); produtosAdicionadosEstoque.add(leia.next()); System.out.print("\nDeseja adicionar mais produtos S/N: "); opcaoContinuar = leia.next().toUpperCase().charAt(0); } while (opcaoContinuar == 'S'); } System.out.printf("\nLista de produtos Adicionados: %s",produtosAdicionadosEstoque); produtosEstoque.addAll(produtosAdicionadosEstoque); System.out.printf("\nLista de produtos Atualizada: %s",produtosEstoque); produtosEstoque.remove("Sab„o neutro"); System.out.print("\n\nDeseja remover produtos do estoque S/N: "); opcaoRemover = leia.next().toUpperCase().charAt(0); if (opcaoRemover == 'S') { do { System.out.print("Digite o nome do produto que deseja remover: "); produtosRemovidosEstoque.add(leia.next()); System.out.print("\nDeseja remover mais produtos S/N: "); opcaoContinuar = leia.next().toUpperCase().charAt(0); } while (opcaoContinuar == 'S'); } System.out.printf("\nLista de produtos Removidos: %s",produtosRemovidosEstoque); produtosEstoque.removeAll(produtosRemovidosEstoque); System.out.println("\nLista de produtos Atualizada:"); for (String produto : produtosEstoque) { System.out.printf("%s\n",produto); } } }
/* * @Author : fengzhi * @date : 2019 - 04 - 21 13 : 31 * @Description : */ package nowcoder_leetcode; public class p_10 { }
package tp.ia.caperucita; import frsf.cidisi.faia.agent.search.GoalTest; import frsf.cidisi.faia.state.AgentState; public class ObjetivoCaperucitaRoja extends GoalTest { @Override public boolean isGoalState(AgentState agentState) { EstadoAgenteCaperucitaRoja estadoAgenteCaperucitaRoja = (EstadoAgenteCaperucitaRoja) agentState; if (estadoAgenteCaperucitaRoja.getX() != estadoAgenteCaperucitaRoja.getSalidaX()) return false; if (estadoAgenteCaperucitaRoja.getY() != estadoAgenteCaperucitaRoja.getSalidaY()) return false; return true; } }
package com.tencent.tencentmap.mapsdk.a; import android.content.Context; import android.graphics.Bitmap; public class no { private final String a = "marker_default.png"; private int b = -1; private int c = -1; private String d = ""; private String e = ""; private String f = ""; private float g = -1.0f; private Bitmap h = null; private String i = null; public no(int i) { this.b = i; } public String a() { return this.i; } private String b(Bitmap bitmap) { String obj = bitmap.toString(); if (obj == null) { obj = ""; } obj = obj.replace("android.graphics.Bitmap", ""); int width = bitmap.getWidth(); int height = bitmap.getHeight(); return (obj + "@" + bitmap.hashCode() + "@" + width + "@" + height + "@" + bitmap.getRowBytes()) + "@" + bitmap.getPixel(width / 2, height / 2); } public Bitmap a(Context context) { if (this.h != null) { this.i = b(this.h); return this.h; } else if (context == null) { return null; } else { switch (this.b) { case 1: this.i = "res_" + this.c; if (kh.u != null) { this.h = kh.u.a(this.i); } if (this.h == null) { this.h = kh.a(context, this.c); if (!(kh.u == null || this.h == null)) { kh.u.a(this.i, this.h); break; } } break; case 2: this.i = "asset_" + this.d; if (kh.u != null) { this.h = kh.u.a(this.i); } if (this.h == null) { this.h = kh.c(context, this.d); if (this.h == null) { this.h = kh.b(context, this.d); if (this.h != null) { this.h = kh.b(this.h); } } if (!(kh.u == null || this.h == null)) { kh.u.a(this.i, this.h); break; } } break; case 3: this.i = "file_" + this.e; if (kh.u != null) { this.h = kh.u.a(this.i); } if (this.h == null) { this.h = kh.a(context, this.e); break; } break; case 4: this.i = "path_" + this.f; if (kh.u != null) { this.h = kh.u.a(this.i); } if (this.h == null) { this.h = kh.b(this.f); if (!(kh.u == null || this.h == null)) { kh.u.a(this.i, this.h); break; } } break; case 5: this.i = "asset_marker_default.png"; if (kh.u != null) { this.h = kh.u.a(this.i); } if (this.h == null) { this.h = kh.b(context, "marker_default.png"); if (!(kh.u == null || this.h == null)) { kh.u.a(this.i, this.h); break; } } break; case 6: String a = a(this.g); if (a != null) { this.i = "asset_" + a; if (kh.u != null) { this.h = kh.u.a(this.i); } if (this.h == null) { this.h = kh.b(context, a); if (!(kh.u == null || this.h == null)) { kh.u.a(this.i, this.h); break; } } } break; } return this.h; } } private String a(float f) { if (f < 30.0f) { return "RED.png"; } if (f >= 30.0f && f < 60.0f) { return "ORANGE.png"; } if (f >= 60.0f && f < 120.0f) { return "YELLOW.png"; } if (f >= 120.0f && f < 180.0f) { return "GREEN.png"; } if (f >= 180.0f && f < 210.0f) { return "CYAN.png"; } if (f >= 210.0f && f < 240.0f) { return "AZURE.png"; } if (f >= 240.0f && f < 270.0f) { return "BLUE.png"; } if (f >= 270.0f && f < 300.0f) { return "VIOLET.png"; } if (f >= 300.0f && f < 330.0f) { return "MAGENTAV.png"; } if (f >= 330.0f) { return "ROSE.png"; } return null; } public void a(String str) { this.d = str; } public void a(Bitmap bitmap) { this.h = bitmap; } }
package com.liwei.activity; import java.lang.reflect.Type; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.ImageView; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.RequestParams; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest.HttpMethod; import com.liwei.adapter.MyStudentAdapter; import com.liwei.application.MyApplation; import com.liwei.model.bean.MyStudentBean; import com.liwei.teachsystem.R; import com.liwei.utils.ToastUtils; import com.liwei.utils.UrlUtils; public class MyStudentActivity extends Activity { private ListView lView; private String tno; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mystudent); MyApplation.setActivity(this); tno=getIntent().getStringExtra("tno"); initView(); } public void initView(){ ImageView close=(ImageView)findViewById(R.id.bjmgf_sdk_closeAboutBtnId); /** * 返回按钮 */ close.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); lView=(ListView) findViewById(R.id.mystudent); HttpUtils utils=new HttpUtils(); RequestParams params=new RequestParams(); params.addBodyParameter("tno",tno); utils.send(HttpMethod.POST, UrlUtils.url+"/MyStudentServlet",params, new RequestCallBack<String>() { @Override public void onFailure(HttpException arg0, String arg1) { ToastUtils.getToast(MyStudentActivity.this, "请求网络数据失败"); } @Override public void onSuccess(ResponseInfo<String> responseInfo) { String list=responseInfo.result; Gson gson=new Gson(); Type classOfT=new TypeToken<List<MyStudentBean>>(){}.getType(); List<MyStudentBean> list1=gson.fromJson(list, classOfT); MyStudentAdapter adapter =new MyStudentAdapter(MyStudentActivity.this, list1, tno); lView.setAdapter(adapter); adapter.notifyDataSetChanged(); ToastUtils.getToast(MyStudentActivity.this, "请求网络数据成功"); } }); } }
package c.t.m.g; public enum dg$b { Normal, Daemon, Single, Stop; static { Normal = new dg$b("Normal", 0); Daemon = new dg$b("Daemon", 1); Single = new dg$b("Single", 2); Stop = new dg$b("Stop", 3); dg$b[] dg_bArr = new dg$b[]{Normal, Daemon, Single, Stop}; } }
package JavaSem1.BattleShipRuzan; /** * Ship.java * @author: Ruzan Sasuri rps7183@g.rit.edu * @author: Akash Venkatachalam av2833@g.rit.edu * @author: Ghodratollah Aalipour ga5481@g.rit.edu * Id: $ Ship.java v1.0, 2016/11/07$ * Revision: First Revision */ public class Ship { private int xCoord, yCoord, len, left; private char orien; private String name; /** * Constructor for ship class * @param x x-coordinate * @param y y-coordinate * @param ln length * @param orn orientation * @param n name of the ship */ protected Ship( int x, int y, int ln, char orn, String n) { xCoord=x; yCoord=y; len=ln; orien=orn; left = len; name = n; } /** *Method to get the x co-ordinate of ship */ public int getxCoord() { return xCoord; } /** *Method to get the y co-ordinate of ship */ public int getyCoord() { return yCoord; } public int getLen() { return len; } /** *Method to get the orientation of the ship */ public char getOrien() { return orien; } public void decrLeft() { left--; } public String getName() { return name; } public int getLeft() { return this.left; } /*public static void main(String a[]) { Ship s = new Ship(1,1,2,'H',"Trial ship"); System.out.println(s.getLeft()); s.hit(1,1); System.out.println(s.getLeft()); s.hit(1,2); System.out.println(s.getLeft()); }*/ }
package com.linda.framework.rpc.client; import com.linda.framework.rpc.RemoteCall; import com.linda.framework.rpc.RemoteExecutor; import com.linda.framework.rpc.Service; import com.linda.framework.rpc.exception.RpcException; import com.linda.framework.rpc.net.AbstractRpcConnector; import com.linda.framework.rpc.net.AbstractRpcMultiConnectorImpl; import com.linda.framework.rpc.net.RpcCallListener; public class MultiClientRemoteExecutorImpl extends AbstractClientRemoteExecutor implements RemoteExecutor, RpcCallListener, Service { private AbstractRpcMultiConnectorImpl connector; public MultiClientRemoteExecutorImpl(AbstractRpcMultiConnectorImpl connector) { super(); connector.addRpcCallListener(this); this.connector = connector; } @Override public void startService() { connector.startService(); } @Override public void stopService() { connector.stopService(); } @Override public AbstractRpcConnector getRpcConnector(RemoteCall call) { AbstractRpcConnector resource = connector.getResource(); if (resource == null) { throw new RpcException("connection lost"); } return resource; } }